text
stringlengths
54
60.6k
<commit_before>#ifndef LONGEST_PALINDROME_HPP #define LONGEST_PALINDROME_HPP // https://leetcode.com/problems/longest-palindromic-substring/description/ // Given a string s, find the longest palindromic substring in s. // Solutions: // https://articles.leetcode.com/longest-palindromic-substring-part-i/ // https://articles.leetcode.com/longest-palindromic-substring-part-ii/ #include <string> namespace LongestPalindrome { class Solution { public: std::string longestPalindrome(std::string s) { const int strSize = static_cast<int>(s.size()); // Start and end indexes of the longest palindrom int start = 0, end = 0; // Iterate over string. On each iteration we choose new (next) letter // as possible center of palindrom for (int i = 0; i < strSize; ++i) { // Check if current letter is central letter of palindrom // (length of palindrom is odd - 'aba') int len1 = expandAroundCenter(s, i, i); // Check if center of palindrom is between current and next // letters (length of palindrim is even - 'abba') int len2 = expandAroundCenter(s, i, i + 1); // Update start and end indexes of the longest palindrom int len = std::max(len1, len2); if (len > end - start) { start = i - (len - 1) / 2; end = i + len / 2; } } return s.substr(static_cast<size_t>(start), static_cast<size_t>(end + 1 - start)); } private: int expandAroundCenter(const std::string& s, const int& left, const int& right) { // 'left' and 'right' are possible indexes of the center of the // palindrom. Because palindrom is symmetric about its center, // we will try to move from the center to the palindrom borders // (variables L and R) at the same time. We will stop when letters // on the borders of palindrom will not be the same. // Do not forget to check at each step that our borders are within // the string!!! int L = left, R = right; const int strSize = static_cast<int>(s.size()); while (L >= 0 && R < strSize && s.at(static_cast<size_t>(L)) == s.at(static_cast<size_t>(R))) { L--; R++; } return R - L - 1; } }; } #endif // LONGEST_PALINDROME_HPP <commit_msg>Refactoring for longest palindrome: use size_t instead of ints<commit_after>#ifndef LONGEST_PALINDROME_HPP #define LONGEST_PALINDROME_HPP // https://leetcode.com/problems/longest-palindromic-substring/description/ // Given a string s, find the longest palindromic substring in s. // Solutions: // https://articles.leetcode.com/longest-palindromic-substring-part-i/ // https://articles.leetcode.com/longest-palindromic-substring-part-ii/ #include <string> namespace LongestPalindrome { class Solution { public: std::string longestPalindrome(const std::string& s) { if (s.size() < 2) { return s; } // Start and end indexes of the longest palindrom size_t start = 0, end = 0; // Iterate over string. On each iteration we choose new (next) letter // as possible center of palindrom for (size_t i = 0; i < s.size(); ++i) { // Check if current letter is central letter of palindrom // (length of palindrom is odd - 'aba') size_t lenOddPalindrome = expandAroundCenter(s, i, i); // Check if center of palindrom is between current and next // letters (length of palindrim is even - 'abba') size_t lenEvenPalindrome = expandAroundCenter(s, i, i + 1); // Update start and end indexes of the longest palindrom size_t len = std::max(lenOddPalindrome, lenEvenPalindrome); if (len > end - start) { start = i - (len - 1) / 2; end = i + len / 2; } } return s.substr(start, (end + 1 - start)); } private: size_t expandAroundCenter(const std::string& s, size_t left, size_t right) { // 'left' and 'right' are possible indexes of the center of the // palindrom. Because palindrom is symmetric about its center, // we will try to move from the center to the palindrom borders // (variables L and R) at the same time. We will stop when letters // on the borders of palindrom will not be the same. // Do not forget to check at each step that our borders are within // the string!!! size_t length = 0; while (right < s.size() && s.at(left) == s.at(right)) { length = right - left + 1; if (left == 0 || right == s.size() - 1) { break; } left--; right++; } return length; } }; } #endif // LONGEST_PALINDROME_HPP <|endoftext|>
<commit_before>#include "std.h" #include "process.h" #include "outputmgr.h" /** * Global process-synchronization variables. */ // Global process limit. static nat procLimit = 1; // Global active processes. static ProcMap alive; // Global lock for 'alive'. static Lock aliveLock; // Global lock for waiting on processes. static Lock waitLock; // System-specific waiting logic. Returns the process id that terminated. static void systemWaitProc(ProcId &proc, int &result); // Wait for any process we're monitoring to terminate, and handle that event. // Assumes that 'waitLock' is taken when called. void waitProc() { ProcId exited; int result; systemWaitProc(exited, result); Process *p = null; { Lock::Guard z(aliveLock); ProcMap::const_iterator i = alive.find(exited); if (i == alive.end()) return; p = i->second; alive.erase(i); } if (!p) return; p->result = result; p->finished = true; if (p->owner) p->owner->terminated(exited, result); } Process::Process(const Path &file, const vector<String> &args, const Path &cwd, const Env *env) : file(file), args(args), cwd(cwd), env(env), process(invalidProc), owner(null), outPipe(noPipe), errPipe(noPipe), result(0), finished(false) {} int Process::wait() { while (!finished) { Lock::Guard z(waitLock); // Double-check the condition after we manage to take the lock! if (finished) break; waitProc(); } process = invalidProc; return result; } #ifdef WINDOWS const ProcId invalidProc = INVALID_HANDLE_VALUE; bool Process::spawn(bool manage, OutputState *state) { ostringstream cmdline; cmdline << file; for (nat i = 0; i < args.size(); i++) cmdline << ' ' << args[i]; DEBUG("Running " << cmdline.str(), VERBOSE); STARTUPINFO si; zeroMem(si); si.cb = sizeof(STARTUPINFO); si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.dwFlags |= STARTF_USESTDHANDLES; if (manage) { Pipe readStderr, writeStderr; createPipe(readStderr, writeStderr, true); si.hStdError = writeStderr; errPipe = readStderr; OutputMgr::addError(readStderr, state); Pipe readStdout, writeStdout; createPipe(readStdout, writeStdout, true); si.hStdOutput = writeStdout; outPipe = readStdout; OutputMgr::add(readStdout, state); } else { si.hStdError = GetStdHandle(STD_ERROR_HANDLE); si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); } PROCESS_INFORMATION pi; zeroMem(pi); BOOL ok = CreateProcess(toS(file).c_str(), (char *)cmdline.str().c_str(), NULL, NULL, TRUE, CREATE_SUSPENDED, env ? env->data() : NULL, toS(cwd).c_str(), &si, &pi); if (!ok) { WARNING("Failed to launch " << file); process = invalidProc; return false; } process = pi.hProcess; { Lock::Guard z(aliveLock); alive.insert(make_pair(process, this)); } // Start the process! ResumeThread(pi.hThread); CloseHandle(pi.hThread); if (manage) { CloseHandle(si.hStdError); CloseHandle(si.hStdOutput); } return true; } Process::~Process() { if (process != invalidProc) { { Lock::Guard z(aliveLock); alive.erase(process); } CloseHandle(process); if (outPipe != noPipe) OutputMgr::remove(outPipe); if (errPipe != noPipe) OutputMgr::remove(errPipe); } } static String getEnv(const char *name) { char buf[512] = { 0 }; GetEnvironmentVariable(name, buf, 512); return buf; } Process *shellProcess(const String &command, const Path &cwd, const Env *env) { String shell = getEnv("ComSpec"); vector<String> args; args.push_back("/S"); args.push_back("/C"); args.push_back("\"" + command + "\""); return new Process(Path(shell), args, cwd, env); } static void systemWaitProc(ProcId &proc, int &code) { nat size = 0; ProcId *ids = null; { Lock::Guard z(aliveLock); ids = new ProcId[alive.size()]; for (ProcMap::const_iterator i = alive.begin(), end = alive.end(); i != end; ++i) { if (!i->second->terminated()) ids[size++] = i->first; } } DWORD result = WaitForMultipleObjects(size, ids, FALSE, INFINITE); nat id = 0; if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + size) { id = result - WAIT_OBJECT_0; } else if (result >= WAIT_ABANDONED_0 && result < WAIT_ABANDONED_0 + size) { id = result - WAIT_ABANDONED_0; } else { WARNING("Failed to call WaitForMultipleObjects!"); exit(10); } proc = ids[id]; delete []ids; DWORD c = 1; GetExitCodeProcess(proc, &c); code = int(c); } #else #include <cstring> #include <unistd.h> #include <sys/wait.h> const ProcId invalidProc = 0; static char *createStr(const String &str) { char *n = new char[str.size() + 1]; memcpy(n, str.c_str(), str.size() + 1); return n; } bool Process::spawn(bool manage, OutputState *state) { nat argc = args.size() + 1; char **argv = new char *[argc + 1]; argv[0] = createStr(toS(file)); for (nat i = 0; i < args.size(); i++) { argv[i + 1] = createStr(args[i]); } argv[argc] = null; Pipe writeStderr, writeStdout; if (manage) { Pipe readStderr, readStdout; createPipe(readStderr, writeStderr, true); errPipe = readStderr; OutputMgr::addError(readStderr, state); createPipe(readStdout, writeStdout, true); outPipe = readStdout; OutputMgr::add(readStdout, state); } // Prepare everything so we do not have to do potential mallocs in the child. String wdStr = toS(cwd); const char *wdCStr = wdStr.c_str(); sigset_t waitFor; sigemptyset(&waitFor); sigaddset(&waitFor, SIGCONT); // Make sure we do not consume SIGCONT too early in the child. sigset_t oldMask; pthread_sigmask(SIG_BLOCK, &waitFor, &oldMask); pid_t child = fork(); if (child == 0) { if (chdir(wdCStr)) { perror("Failed to chdir: "); exit(1); } // Redirect stderr/stdout. if (manage) { close(STDERR_FILENO); dup2(writeStderr, STDERR_FILENO); close(writeStderr); close(STDOUT_FILENO); dup2(writeStdout, STDOUT_FILENO); close(writeStdout); } // Wait until our parent is ready... int signal; do { if (sigwait(&waitFor, &signal)) { perror("Sigwait: "); exit(4); } } while (signal != SIGCONT); if (env) { execve(argv[0], argv, (char **)env->data()); } else { execv(argv[0], argv); } perror("Failed to exec: "); exit(1); } // Restore mask. pthread_sigmask(SIG_SETMASK, &oldMask, null); process = child; { Lock::Guard z(aliveLock); alive.insert(make_pair(process, this)); } // Start child again. kill(child, SIGCONT); if (manage) { // Close our ends of the pipes. closePipe(writeStderr); closePipe(writeStdout); } // Clean up... for (nat i = 0; i < argc; i++) { delete []argv[i]; } delete []argv; return true; } Process::~Process() { // We can not clean up a child without doing 'wait'. We let the system clear this when mymake // exits. if (process != invalidProc) { { Lock::Guard z(aliveLock); alive.erase(process); } if (outPipe != noPipe) OutputMgr::remove(outPipe); if (errPipe != noPipe) OutputMgr::remove(errPipe); } } Process *shellProcess(const String &command, const Path &cwd, const Env *env) { vector<String> args; args.push_back("-c"); args.push_back(command); return new Process(Path("/bin/sh"), args, cwd, env); } static void systemWaitProc(ProcId &proc, int &result) { int status; do { proc = waitpid(-1, &status, 0); } while (!WIFEXITED(status)); result = WEXITSTATUS(status); } #endif ProcGroup::ProcGroup(nat limit, OutputState &state) : state(state), limit(limit), failed(false) { if (limit == 0) limit = 1; } ProcGroup::~ProcGroup() { Lock::Guard z(aliveLock); for (ProcMap::iterator i = our.begin(), end = our.end(); i != end; ++i) { alive.erase(i->first); delete i->second; } } void ProcGroup::setLimit(nat l) { if (l >= 1) procLimit = l; } bool ProcGroup::canSpawn() { Lock::Guard z(aliveLock); return alive.size() < procLimit && our.size() < limit; } bool ProcGroup::spawn(Process *p) { if (failed) { delete p; return false; } p->owner = this; // Wait until there is room for more... while (!canSpawn() && !failed) { Lock::Guard z(waitLock); // Double check... if (canSpawn() || failed) break; waitProc(); } if (failed) { delete p; return false; } p->spawn(true, &state); our.insert(make_pair(p->process, p)); // Make the output look more logical to the user when running on one thread. if (limit == 1 || procLimit == 1) { return wait(); } return true; } bool ProcGroup::wait() { while (!failed) { { Lock::Guard z(aliveLock); if (our.empty()) break; } Lock::Guard z(waitLock); if (failed) break; { Lock::Guard z(aliveLock); if (our.empty()) break; } waitProc(); } return !failed; } void ProcGroup::terminated(ProcId id, int result) { ProcMap::iterator i = our.find(id); if (i == our.end()) return; if (result != 0) failed = true; delete i->second; our.erase(i); } int exec(const Path &binary, const vector<String> &args, const Path &cwd, const Env *env) { Process p(binary, args, cwd, env); if (!p.spawn()) return 1; return p.wait(); } // Run a command through a shell. int shellExec(const String &command, const Path &cwd, const Env *env) { Process *p = shellProcess(command, cwd, env); int r = 1; if (p->spawn()) r = p->wait(); delete p; return r; } <commit_msg>Properly handle crashes in spawned processes on UNIX.<commit_after>#include "std.h" #include "process.h" #include "outputmgr.h" /** * Global process-synchronization variables. */ // Global process limit. static nat procLimit = 1; // Global active processes. static ProcMap alive; // Global lock for 'alive'. static Lock aliveLock; // Global lock for waiting on processes. static Lock waitLock; // System-specific waiting logic. Returns the process id that terminated. static void systemWaitProc(ProcId &proc, int &result); // Wait for any process we're monitoring to terminate, and handle that event. // Assumes that 'waitLock' is taken when called. void waitProc() { ProcId exited; int result; systemWaitProc(exited, result); Process *p = null; { Lock::Guard z(aliveLock); ProcMap::const_iterator i = alive.find(exited); if (i == alive.end()) return; p = i->second; alive.erase(i); } if (!p) return; p->result = result; p->finished = true; if (p->owner) p->owner->terminated(exited, result); } Process::Process(const Path &file, const vector<String> &args, const Path &cwd, const Env *env) : file(file), args(args), cwd(cwd), env(env), process(invalidProc), owner(null), outPipe(noPipe), errPipe(noPipe), result(0), finished(false) {} int Process::wait() { while (!finished) { Lock::Guard z(waitLock); // Double-check the condition after we manage to take the lock! if (finished) break; waitProc(); } process = invalidProc; return result; } #ifdef WINDOWS const ProcId invalidProc = INVALID_HANDLE_VALUE; bool Process::spawn(bool manage, OutputState *state) { ostringstream cmdline; cmdline << file; for (nat i = 0; i < args.size(); i++) cmdline << ' ' << args[i]; DEBUG("Running " << cmdline.str(), VERBOSE); STARTUPINFO si; zeroMem(si); si.cb = sizeof(STARTUPINFO); si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.dwFlags |= STARTF_USESTDHANDLES; if (manage) { Pipe readStderr, writeStderr; createPipe(readStderr, writeStderr, true); si.hStdError = writeStderr; errPipe = readStderr; OutputMgr::addError(readStderr, state); Pipe readStdout, writeStdout; createPipe(readStdout, writeStdout, true); si.hStdOutput = writeStdout; outPipe = readStdout; OutputMgr::add(readStdout, state); } else { si.hStdError = GetStdHandle(STD_ERROR_HANDLE); si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); } PROCESS_INFORMATION pi; zeroMem(pi); BOOL ok = CreateProcess(toS(file).c_str(), (char *)cmdline.str().c_str(), NULL, NULL, TRUE, CREATE_SUSPENDED, env ? env->data() : NULL, toS(cwd).c_str(), &si, &pi); if (!ok) { WARNING("Failed to launch " << file); process = invalidProc; return false; } process = pi.hProcess; { Lock::Guard z(aliveLock); alive.insert(make_pair(process, this)); } // Start the process! ResumeThread(pi.hThread); CloseHandle(pi.hThread); if (manage) { CloseHandle(si.hStdError); CloseHandle(si.hStdOutput); } return true; } Process::~Process() { if (process != invalidProc) { { Lock::Guard z(aliveLock); alive.erase(process); } CloseHandle(process); if (outPipe != noPipe) OutputMgr::remove(outPipe); if (errPipe != noPipe) OutputMgr::remove(errPipe); } } static String getEnv(const char *name) { char buf[512] = { 0 }; GetEnvironmentVariable(name, buf, 512); return buf; } Process *shellProcess(const String &command, const Path &cwd, const Env *env) { String shell = getEnv("ComSpec"); vector<String> args; args.push_back("/S"); args.push_back("/C"); args.push_back("\"" + command + "\""); return new Process(Path(shell), args, cwd, env); } static void systemWaitProc(ProcId &proc, int &code) { nat size = 0; ProcId *ids = null; { Lock::Guard z(aliveLock); ids = new ProcId[alive.size()]; for (ProcMap::const_iterator i = alive.begin(), end = alive.end(); i != end; ++i) { if (!i->second->terminated()) ids[size++] = i->first; } } DWORD result = WaitForMultipleObjects(size, ids, FALSE, INFINITE); nat id = 0; if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + size) { id = result - WAIT_OBJECT_0; } else if (result >= WAIT_ABANDONED_0 && result < WAIT_ABANDONED_0 + size) { id = result - WAIT_ABANDONED_0; } else { WARNING("Failed to call WaitForMultipleObjects!"); exit(10); } proc = ids[id]; delete []ids; DWORD c = 1; GetExitCodeProcess(proc, &c); code = int(c); } #else #include <cstring> #include <unistd.h> #include <sys/wait.h> const ProcId invalidProc = 0; static char *createStr(const String &str) { char *n = new char[str.size() + 1]; memcpy(n, str.c_str(), str.size() + 1); return n; } bool Process::spawn(bool manage, OutputState *state) { nat argc = args.size() + 1; char **argv = new char *[argc + 1]; argv[0] = createStr(toS(file)); for (nat i = 0; i < args.size(); i++) { argv[i + 1] = createStr(args[i]); } argv[argc] = null; Pipe writeStderr, writeStdout; if (manage) { Pipe readStderr, readStdout; createPipe(readStderr, writeStderr, true); errPipe = readStderr; OutputMgr::addError(readStderr, state); createPipe(readStdout, writeStdout, true); outPipe = readStdout; OutputMgr::add(readStdout, state); } // Prepare everything so we do not have to do potential mallocs in the child. String wdStr = toS(cwd); const char *wdCStr = wdStr.c_str(); sigset_t waitFor; sigemptyset(&waitFor); sigaddset(&waitFor, SIGCONT); // Make sure we do not consume SIGCONT too early in the child. sigset_t oldMask; pthread_sigmask(SIG_BLOCK, &waitFor, &oldMask); pid_t child = fork(); if (child == 0) { if (chdir(wdCStr)) { perror("Failed to chdir: "); exit(1); } // Redirect stderr/stdout. if (manage) { close(STDERR_FILENO); dup2(writeStderr, STDERR_FILENO); close(writeStderr); close(STDOUT_FILENO); dup2(writeStdout, STDOUT_FILENO); close(writeStdout); } // Wait until our parent is ready... int signal; do { if (sigwait(&waitFor, &signal)) { perror("Sigwait: "); exit(4); } } while (signal != SIGCONT); if (env) { execve(argv[0], argv, (char **)env->data()); } else { execv(argv[0], argv); } perror("Failed to exec: "); exit(1); } // Restore mask. pthread_sigmask(SIG_SETMASK, &oldMask, null); process = child; { Lock::Guard z(aliveLock); alive.insert(make_pair(process, this)); } // Start child again. kill(child, SIGCONT); if (manage) { // Close our ends of the pipes. closePipe(writeStderr); closePipe(writeStdout); } // Clean up... for (nat i = 0; i < argc; i++) { delete []argv[i]; } delete []argv; return true; } Process::~Process() { // We can not clean up a child without doing 'wait'. We let the system clear this when mymake // exits. if (process != invalidProc) { { Lock::Guard z(aliveLock); alive.erase(process); } if (outPipe != noPipe) OutputMgr::remove(outPipe); if (errPipe != noPipe) OutputMgr::remove(errPipe); } } Process *shellProcess(const String &command, const Path &cwd, const Env *env) { vector<String> args; args.push_back("-c"); args.push_back(command); return new Process(Path("/bin/sh"), args, cwd, env); } static void systemWaitProc(ProcId &proc, int &result) { while (true) { int status; proc = waitpid(-1, &status, 0); if (proc < 0) { perror("waitpid: "); continue; } if (WIFEXITED(status)) { result = WEXITSTATUS(status); break; } else if (WIFSIGNALED(status)) { result = -WTERMSIG(status); break; } } } #endif ProcGroup::ProcGroup(nat limit, OutputState &state) : state(state), limit(limit), failed(false) { if (limit == 0) limit = 1; } ProcGroup::~ProcGroup() { Lock::Guard z(aliveLock); for (ProcMap::iterator i = our.begin(), end = our.end(); i != end; ++i) { alive.erase(i->first); delete i->second; } } void ProcGroup::setLimit(nat l) { if (l >= 1) procLimit = l; } bool ProcGroup::canSpawn() { Lock::Guard z(aliveLock); return alive.size() < procLimit && our.size() < limit; } bool ProcGroup::spawn(Process *p) { if (failed) { delete p; return false; } p->owner = this; // Wait until there is room for more... while (!canSpawn() && !failed) { Lock::Guard z(waitLock); // Double check... if (canSpawn() || failed) break; waitProc(); } if (failed) { delete p; return false; } p->spawn(true, &state); our.insert(make_pair(p->process, p)); // Make the output look more logical to the user when running on one thread. if (limit == 1 || procLimit == 1) { return wait(); } return true; } bool ProcGroup::wait() { while (!failed) { { Lock::Guard z(aliveLock); if (our.empty()) break; } Lock::Guard z(waitLock); if (failed) break; { Lock::Guard z(aliveLock); if (our.empty()) break; } waitProc(); } return !failed; } void ProcGroup::terminated(ProcId id, int result) { ProcMap::iterator i = our.find(id); if (i == our.end()) return; if (result != 0) failed = true; delete i->second; our.erase(i); } int exec(const Path &binary, const vector<String> &args, const Path &cwd, const Env *env) { Process p(binary, args, cwd, env); if (!p.spawn()) return 1; return p.wait(); } // Run a command through a shell. int shellExec(const String &command, const Path &cwd, const Env *env) { Process *p = shellProcess(command, cwd, env); int r = 1; if (p->spawn()) r = p->wait(); delete p; return r; } <|endoftext|>
<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */ /** * Copyright (C) 2013 Regents of the University of California. * @author: Alexander Afanasyev <alexander.afanasyev@ucla.edu> * @author: Zhenkai Zhu <zhenkai@cs.ucla.edu> * See COPYING for copyright and distribution information. */ #ifndef NDN_LOGGING_HPP #define NDN_LOGGING_HPP #include <ndn-cpp//common.hpp> #ifdef NDN_CPP_HAVE_LOG4CXX #include <log4cxx/logger.h> #define MEMBER_LOGGER \ static log4cxx::LoggerPtr staticModuleLogger; #define INIT_MEMBER_LOGGER(className,name) \ log4cxx::LoggerPtr className::staticModuleLogger = log4cxx::Logger::getLogger (name); #define INIT_LOGGER(name) \ static log4cxx::LoggerPtr staticModuleLogger = log4cxx::Logger::getLogger (name); #define _LOG_DEBUG(x) \ LOG4CXX_DEBUG(staticModuleLogger, x); #define _LOG_TRACE(x) \ LOG4CXX_TRACE(staticModuleLogger, x); #define _LOG_FUNCTION(x) \ LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "(" << x << ")"); #define _LOG_FUNCTION_NOARGS \ LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "()"); #define _LOG_ERROR(x) \ LOG4CXX_ERROR(staticModuleLogger, x); #define _LOG_ERROR_COND(cond,x) \ if (cond) { _LOG_ERROR(x) } #define _LOG_DEBUG_COND(cond,x) \ if (cond) { _LOG_DEBUG(x) } void INIT_LOGGERS (); #else // else NDN_CPP_HAVE_LOG4CXX #define INIT_LOGGER(name) #define _LOG_FUNCTION(x) #define _LOG_FUNCTION_NOARGS #define _LOG_TRACE(x) #define INIT_LOGGERS(x) #define _LOG_ERROR(x) #define _LOG_ERROR_COND(cond,x) #define _LOG_DEBUG_COND(cond,x) #define MEMBER_LOGGER #define INIT_MEMBER_LOGGER(className,name) #ifdef _DEBUG #include <sys/time.h> #include <iostream> #define _LOG_DEBUG(x) \ { time_t now = time(0); std::string s = std::string(ctime(&now)); std::clog << s.substr(0, s.size() - 1) << " " << x << std::endl; } #else #define _LOG_DEBUG(x) #endif #endif // NDN_CPP_HAVE_LOG4CXX #endif <commit_msg>util: Fix typo on logging.hpp for include common.hpp.<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */ /** * Copyright (C) 2013 Regents of the University of California. * @author: Alexander Afanasyev <alexander.afanasyev@ucla.edu> * @author: Zhenkai Zhu <zhenkai@cs.ucla.edu> * See COPYING for copyright and distribution information. */ #ifndef NDN_LOGGING_HPP #define NDN_LOGGING_HPP #include <ndn-cpp/common.hpp> #ifdef NDN_CPP_HAVE_LOG4CXX #include <log4cxx/logger.h> #define MEMBER_LOGGER \ static log4cxx::LoggerPtr staticModuleLogger; #define INIT_MEMBER_LOGGER(className,name) \ log4cxx::LoggerPtr className::staticModuleLogger = log4cxx::Logger::getLogger (name); #define INIT_LOGGER(name) \ static log4cxx::LoggerPtr staticModuleLogger = log4cxx::Logger::getLogger (name); #define _LOG_DEBUG(x) \ LOG4CXX_DEBUG(staticModuleLogger, x); #define _LOG_TRACE(x) \ LOG4CXX_TRACE(staticModuleLogger, x); #define _LOG_FUNCTION(x) \ LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "(" << x << ")"); #define _LOG_FUNCTION_NOARGS \ LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "()"); #define _LOG_ERROR(x) \ LOG4CXX_ERROR(staticModuleLogger, x); #define _LOG_ERROR_COND(cond,x) \ if (cond) { _LOG_ERROR(x) } #define _LOG_DEBUG_COND(cond,x) \ if (cond) { _LOG_DEBUG(x) } void INIT_LOGGERS (); #else // else NDN_CPP_HAVE_LOG4CXX #define INIT_LOGGER(name) #define _LOG_FUNCTION(x) #define _LOG_FUNCTION_NOARGS #define _LOG_TRACE(x) #define INIT_LOGGERS(x) #define _LOG_ERROR(x) #define _LOG_ERROR_COND(cond,x) #define _LOG_DEBUG_COND(cond,x) #define MEMBER_LOGGER #define INIT_MEMBER_LOGGER(className,name) #ifdef _DEBUG #include <sys/time.h> #include <iostream> #define _LOG_DEBUG(x) \ { time_t now = time(0); std::string s = std::string(ctime(&now)); std::clog << s.substr(0, s.size() - 1) << " " << x << std::endl; } #else #define _LOG_DEBUG(x) #endif #endif // NDN_CPP_HAVE_LOG4CXX #endif <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "embeddedapp.h" #include <server/server.h> #include <Cutelyst/Context> #include <Cutelyst/Response> #include <QMessageBox> #include <QNetworkReply> #include <QNetworkAccessManager> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , m_server(new Cutelyst::Server{this}) , m_app(new EmbeddedApp{m_server}) , m_nam(new QNetworkAccessManager{this}) , m_serverReceivedHeaders(new QStandardItemModel{this}) , m_clientReceivedHeaders(new QStandardItemModel{this}) { ui->setupUi(this); ui->serverReceivedHeaders->setModel(m_serverReceivedHeaders); ui->clientReceivedHeaders->setModel(m_clientReceivedHeaders); connect(ui->serverPortSB, &QSpinBox::valueChanged, this, &MainWindow::updateUrl); connect(ui->clientSendPB, &QPushButton::clicked, this, &MainWindow::clientSend); connect(ui->serverListenPB, &QPushButton::clicked, this, &MainWindow::listenClicked); connect(ui->serverStopListenPB, &QPushButton::clicked, this, [=] { ui->serverStopListenPB->setEnabled(false); m_server->stop(); }); connect(m_server, &Cutelyst::Server::ready, this, [=] { ui->serverStopListenPB->setEnabled(true); }); connect(m_server, &Cutelyst::Server::stopped, this, [=] { ui->serverListenPB->setEnabled(true); }); connect(m_server, &Cutelyst::Server::errorOccured, this, [=] (const QString &message) { ui->serverListenPB->setEnabled(true); ui->serverStopListenPB->setEnabled(false); QMessageBox::critical(this, tr("Failed to start server"), message); }); connect(m_app, &EmbeddedApp::indexCalled, this, &MainWindow::indexCalled); updateUrl(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::clientSend() { QString path = ui->clientPathLE->text(); if (!path.startsWith(QLatin1Char('/'))) { path.prepend(QLatin1Char('/')); } QUrl url(QLatin1String("http://localhost:") + QString::number(ui->serverPortSB->value()) + path); QNetworkRequest request(url); QNetworkReply *reply = m_nam->sendCustomRequest(request, ui->clientMethodLE->currentText().toLatin1(), ui->clientBodyPTE->toPlainText().toUtf8()); connect(reply, &QNetworkReply::finished, this, [=] { reply->deleteLater(); ui->clientSendPB->setEnabled(true); const QByteArray body = reply->readAll(); ui->clientResponsePTE->setPlainText(QString::fromUtf8(body)); int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QString statusReason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); qDebug() << "client finished" << body.size() << status << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute); ui->clientResponseLE->setText(QString::number(status) + QLatin1String(" - ") + statusReason); m_clientReceivedHeaders->clear(); for (auto &header : reply->rawHeaderPairs()) { qDebug() << "client " << header.first << header.second; auto keyItem = new QStandardItem(QString::fromLatin1(header.first)); auto valueItem = new QStandardItem(QString::fromLatin1(header.second)); m_clientReceivedHeaders->appendRow({ keyItem, valueItem, }); } }); ui->clientSendPB->setEnabled(false); } void MainWindow::listenClicked() { ui->serverListenPB->setEnabled(false); const QString address = QLatin1String("localhost:") + QString::number(ui->serverPortSB->value()); m_server->setHttpSocket({ address }); m_server->start(m_app); } void MainWindow::indexCalled(Cutelyst::Context *c) { qDebug() << "indexCalled" << ui->serverResponsePTE->toPlainText().toUtf8().size(); // Request ui->serverMethodLE->setText(c->request()->method()); ui->serverPathLE->setText(c->request()->path()); if (c->request()->body()) { ui->serverBodyPTE->setPlainText(QString::fromUtf8(c->request()->body()->readAll())); } else { ui->serverBodyPTE->clear(); } m_serverReceivedHeaders->clear(); const auto headersData = c->request()->headers().data(); auto hIt = headersData.begin(); while (hIt != headersData.end()) { auto keyItem = new QStandardItem(hIt.key()); auto valueItem = new QStandardItem(hIt.value()); m_serverReceivedHeaders->appendRow({ keyItem, valueItem, }); ++hIt; } // Response c->response()->setStatus(ui->serverStatusSB->value()); c->response()->setBody(ui->serverResponsePTE->toPlainText().toUtf8()); } void MainWindow::updateUrl() { const QString url = QLatin1String("http://localhost:") + QString::number(ui->serverPortSB->value()); ui->serverL->setText(tr("Server: <a href=\"%1\">%1</a>").arg(url)); } <commit_msg>Fix example connect<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "embeddedapp.h" #include <server/server.h> #include <Cutelyst/Context> #include <Cutelyst/Response> #include <QMessageBox> #include <QNetworkReply> #include <QNetworkAccessManager> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , m_server(new Cutelyst::Server{this}) , m_app(new EmbeddedApp{m_server}) , m_nam(new QNetworkAccessManager{this}) , m_serverReceivedHeaders(new QStandardItemModel{this}) , m_clientReceivedHeaders(new QStandardItemModel{this}) { ui->setupUi(this); ui->serverReceivedHeaders->setModel(m_serverReceivedHeaders); ui->clientReceivedHeaders->setModel(m_clientReceivedHeaders); connect(ui->serverPortSB, &QSpinBox::valueChanged, this, [=] { updateUrl(); }); connect(ui->clientSendPB, &QPushButton::clicked, this, &MainWindow::clientSend); connect(ui->serverListenPB, &QPushButton::clicked, this, &MainWindow::listenClicked); connect(ui->serverStopListenPB, &QPushButton::clicked, this, [=] { ui->serverStopListenPB->setEnabled(false); m_server->stop(); }); connect(m_server, &Cutelyst::Server::ready, this, [=] { ui->serverStopListenPB->setEnabled(true); }); connect(m_server, &Cutelyst::Server::stopped, this, [=] { ui->serverListenPB->setEnabled(true); }); connect(m_server, &Cutelyst::Server::errorOccured, this, [=] (const QString &message) { ui->serverListenPB->setEnabled(true); ui->serverStopListenPB->setEnabled(false); QMessageBox::critical(this, tr("Failed to start server"), message); }); connect(m_app, &EmbeddedApp::indexCalled, this, &MainWindow::indexCalled); updateUrl(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::clientSend() { QString path = ui->clientPathLE->text(); if (!path.startsWith(QLatin1Char('/'))) { path.prepend(QLatin1Char('/')); } QUrl url(QLatin1String("http://localhost:") + QString::number(ui->serverPortSB->value()) + path); QNetworkRequest request(url); QNetworkReply *reply = m_nam->sendCustomRequest(request, ui->clientMethodLE->currentText().toLatin1(), ui->clientBodyPTE->toPlainText().toUtf8()); connect(reply, &QNetworkReply::finished, this, [=] { reply->deleteLater(); ui->clientSendPB->setEnabled(true); const QByteArray body = reply->readAll(); ui->clientResponsePTE->setPlainText(QString::fromUtf8(body)); int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QString statusReason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); qDebug() << "client finished" << body.size() << status << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute); ui->clientResponseLE->setText(QString::number(status) + QLatin1String(" - ") + statusReason); m_clientReceivedHeaders->clear(); for (auto &header : reply->rawHeaderPairs()) { qDebug() << "client " << header.first << header.second; auto keyItem = new QStandardItem(QString::fromLatin1(header.first)); auto valueItem = new QStandardItem(QString::fromLatin1(header.second)); m_clientReceivedHeaders->appendRow({ keyItem, valueItem, }); } }); ui->clientSendPB->setEnabled(false); } void MainWindow::listenClicked() { ui->serverListenPB->setEnabled(false); const QString address = QLatin1String("localhost:") + QString::number(ui->serverPortSB->value()); m_server->setHttpSocket({ address }); m_server->start(m_app); } void MainWindow::indexCalled(Cutelyst::Context *c) { qDebug() << "indexCalled" << ui->serverResponsePTE->toPlainText().toUtf8().size(); // Request ui->serverMethodLE->setText(c->request()->method()); ui->serverPathLE->setText(c->request()->path()); if (c->request()->body()) { ui->serverBodyPTE->setPlainText(QString::fromUtf8(c->request()->body()->readAll())); } else { ui->serverBodyPTE->clear(); } m_serverReceivedHeaders->clear(); const auto headersData = c->request()->headers().data(); auto hIt = headersData.begin(); while (hIt != headersData.end()) { auto keyItem = new QStandardItem(hIt.key()); auto valueItem = new QStandardItem(hIt.value()); m_serverReceivedHeaders->appendRow({ keyItem, valueItem, }); ++hIt; } // Response c->response()->setStatus(ui->serverStatusSB->value()); c->response()->setBody(ui->serverResponsePTE->toPlainText().toUtf8()); } void MainWindow::updateUrl() { const QString url = QLatin1String("http://localhost:") + QString::number(ui->serverPortSB->value()); ui->serverL->setText(tr("Server: <a href=\"%1\">%1</a>").arg(url)); } <|endoftext|>
<commit_before>#include <string> #include "caffe2/core/init.h" #include "caffe2/core/operator.h" #include "caffe2/proto/caffe2.pb.h" #include "caffe2/utils/proto_utils.h" #include "caffe2/utils/string_utils.h" #include "caffe2/core/logging.h" CAFFE2_DEFINE_string(net, "", "The given net to benchmark."); CAFFE2_DEFINE_string(init_net, "", "The given net to initialize any parameters."); CAFFE2_DEFINE_string(input, "", "Input that is needed for running the network. If " "multiple input needed, use comma separated string."); CAFFE2_DEFINE_string(input_file, "", "Input file that contain the serialized protobuf for " "the input blobs. If multiple input needed, use comma " "separated string. Must have the same number of items " "as input does."); CAFFE2_DEFINE_string(input_dims, "", "Alternate to input_files, if all inputs are simple " "float TensorCPUs, specify the dimension using comma " "separated numbers. If multiple input needed, use " "semicolon to separate the dimension of different " "tensors."); CAFFE2_DEFINE_string(output, "", "Output that should be dumped after the execution " "finishes. If multiple outputs are needed, use comma " "separated string. If you want to dump everything, pass " "'*' as the output value."); CAFFE2_DEFINE_string(output_folder, "", "The folder that the output should be written to. This " "folder must already exist in the file system."); CAFFE2_DEFINE_int(warmup, 0, "The number of iterations to warm up."); CAFFE2_DEFINE_int(iter, 10, "The number of iterations to run."); CAFFE2_DEFINE_bool(run_individual, false, "Whether to benchmark individual operators."); using std::string; using std::unique_ptr; using std::vector; int main(int argc, char** argv) { caffe2::GlobalInit(&argc, &argv); unique_ptr<caffe2::Workspace> workspace(new caffe2::Workspace()); // Run initialization network. caffe2::NetDef net_def; CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_init_net, &net_def)); CAFFE_ENFORCE(workspace->RunNetOnce(net_def)); // Load input. if (caffe2::FLAGS_input.size()) { vector<string> input_names = caffe2::split(',', caffe2::FLAGS_input); if (caffe2::FLAGS_input_file.size()) { vector<string> input_files = caffe2::split(',', caffe2::FLAGS_input_file); CAFFE_ENFORCE_EQ( input_names.size(), input_files.size(), "Input name and file should have the same number."); for (int i = 0; i < input_names.size(); ++i) { caffe2::BlobProto blob_proto; CAFFE_ENFORCE(caffe2::ReadProtoFromFile(input_files[i], &blob_proto)); workspace->CreateBlob(input_names[i])->Deserialize(blob_proto); } } else if (caffe2::FLAGS_input_dims.size()) { vector<string> input_dims_list = caffe2::split(';', caffe2::FLAGS_input_dims); CAFFE_ENFORCE_EQ( input_names.size(), input_dims_list.size(), "Input name and dims should have the same number of items."); for (int i = 0; i < input_names.size(); ++i) { vector<string> input_dims_str = caffe2::split(',', input_dims_list[i]); vector<int> input_dims; for (const string& s : input_dims_str) { input_dims.push_back(caffe2::stoi(s)); } caffe2::TensorCPU* tensor = workspace->GetBlob(input_names[i])->GetMutable<caffe2::TensorCPU>(); tensor->Reshape(input_dims); tensor->mutable_data<float>(); } } else { CAFFE_THROW("You requested input tensors, but neither input_file nor " "input_dims is set."); } } // Run main network. CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_net, &net_def)); caffe2::NetBase* net = workspace->CreateNet(net_def); CHECK_NOTNULL(net); net->TEST_Benchmark( caffe2::FLAGS_warmup, caffe2::FLAGS_iter, caffe2::FLAGS_run_individual); string output_prefix = caffe2::FLAGS_output_folder.size() ? caffe2::FLAGS_output_folder + "/" : ""; if (caffe2::FLAGS_output.size()) { vector<string> output_names = caffe2::split(',', caffe2::FLAGS_output); if (caffe2::FLAGS_output == "*") { output_names = workspace->Blobs(); } for (const string& name : output_names) { CAFFE_ENFORCE( workspace->HasBlob(name), "You requested a non-existing blob: ", name); string serialized = workspace->GetBlob(name)->Serialize(name); string output_filename = output_prefix + name; caffe2::WriteStringToFile(serialized, output_filename.c_str()); } } return 0; } <commit_msg>Use Resize instead of reshape in speed_benchmark<commit_after>#include <string> #include "caffe2/core/init.h" #include "caffe2/core/operator.h" #include "caffe2/proto/caffe2.pb.h" #include "caffe2/utils/proto_utils.h" #include "caffe2/utils/string_utils.h" #include "caffe2/core/logging.h" CAFFE2_DEFINE_string(net, "", "The given net to benchmark."); CAFFE2_DEFINE_string(init_net, "", "The given net to initialize any parameters."); CAFFE2_DEFINE_string(input, "", "Input that is needed for running the network. If " "multiple input needed, use comma separated string."); CAFFE2_DEFINE_string(input_file, "", "Input file that contain the serialized protobuf for " "the input blobs. If multiple input needed, use comma " "separated string. Must have the same number of items " "as input does."); CAFFE2_DEFINE_string(input_dims, "", "Alternate to input_files, if all inputs are simple " "float TensorCPUs, specify the dimension using comma " "separated numbers. If multiple input needed, use " "semicolon to separate the dimension of different " "tensors."); CAFFE2_DEFINE_string(output, "", "Output that should be dumped after the execution " "finishes. If multiple outputs are needed, use comma " "separated string. If you want to dump everything, pass " "'*' as the output value."); CAFFE2_DEFINE_string(output_folder, "", "The folder that the output should be written to. This " "folder must already exist in the file system."); CAFFE2_DEFINE_int(warmup, 0, "The number of iterations to warm up."); CAFFE2_DEFINE_int(iter, 10, "The number of iterations to run."); CAFFE2_DEFINE_bool(run_individual, false, "Whether to benchmark individual operators."); using std::string; using std::unique_ptr; using std::vector; int main(int argc, char** argv) { caffe2::GlobalInit(&argc, &argv); unique_ptr<caffe2::Workspace> workspace(new caffe2::Workspace()); // Run initialization network. caffe2::NetDef net_def; CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_init_net, &net_def)); CAFFE_ENFORCE(workspace->RunNetOnce(net_def)); // Load input. if (caffe2::FLAGS_input.size()) { vector<string> input_names = caffe2::split(',', caffe2::FLAGS_input); if (caffe2::FLAGS_input_file.size()) { vector<string> input_files = caffe2::split(',', caffe2::FLAGS_input_file); CAFFE_ENFORCE_EQ( input_names.size(), input_files.size(), "Input name and file should have the same number."); for (int i = 0; i < input_names.size(); ++i) { caffe2::BlobProto blob_proto; CAFFE_ENFORCE(caffe2::ReadProtoFromFile(input_files[i], &blob_proto)); workspace->CreateBlob(input_names[i])->Deserialize(blob_proto); } } else if (caffe2::FLAGS_input_dims.size()) { vector<string> input_dims_list = caffe2::split(';', caffe2::FLAGS_input_dims); CAFFE_ENFORCE_EQ( input_names.size(), input_dims_list.size(), "Input name and dims should have the same number of items."); for (int i = 0; i < input_names.size(); ++i) { vector<string> input_dims_str = caffe2::split(',', input_dims_list[i]); vector<int> input_dims; for (const string& s : input_dims_str) { input_dims.push_back(caffe2::stoi(s)); } caffe2::TensorCPU* tensor = workspace->GetBlob(input_names[i])->GetMutable<caffe2::TensorCPU>(); tensor->Resize(input_dims); tensor->mutable_data<float>(); } } else { CAFFE_THROW("You requested input tensors, but neither input_file nor " "input_dims is set."); } } // Run main network. CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_net, &net_def)); caffe2::NetBase* net = workspace->CreateNet(net_def); CHECK_NOTNULL(net); net->TEST_Benchmark( caffe2::FLAGS_warmup, caffe2::FLAGS_iter, caffe2::FLAGS_run_individual); string output_prefix = caffe2::FLAGS_output_folder.size() ? caffe2::FLAGS_output_folder + "/" : ""; if (caffe2::FLAGS_output.size()) { vector<string> output_names = caffe2::split(',', caffe2::FLAGS_output); if (caffe2::FLAGS_output == "*") { output_names = workspace->Blobs(); } for (const string& name : output_names) { CAFFE_ENFORCE( workspace->HasBlob(name), "You requested a non-existing blob: ", name); string serialized = workspace->GetBlob(name)->Serialize(name); string output_filename = output_prefix + name; caffe2::WriteStringToFile(serialized, output_filename.c_str()); } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cachedbitmap.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-17 03:29:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_canvas.hxx" #include <canvas/debug.hxx> #include "cachedbitmap.hxx" #include "repainttarget.hxx" #include <com/sun/star/rendering/RepaintResult.hpp> #include <com/sun/star/rendering/XPolyPolygon2D.hpp> #include <basegfx/matrix/b2dhommatrix.hxx> #include <basegfx/tools/canvastools.hxx> using namespace ::com::sun::star; namespace vclcanvas { CachedBitmap::CachedBitmap( const GraphicObjectSharedPtr& rGraphicObject, const ::Point& rPoint, const ::Size& rSize, const GraphicAttr& rAttr, const rendering::ViewState& rUsedViewState, const uno::Reference< rendering::XCanvas >& rTarget ) : CachedPrimitiveBase( rUsedViewState, rTarget, true ), mpGraphicObject( rGraphicObject ), maPoint( rPoint ), maSize( rSize ), maAttributes( rAttr ) { } void SAL_CALL CachedBitmap::disposing() { ::osl::MutexGuard aGuard( m_aMutex ); mpGraphicObject.reset(); CachedPrimitiveBase::disposing(); } ::sal_Int8 CachedBitmap::doRedraw( const rendering::ViewState& rNewState, const rendering::ViewState& rOldState, const uno::Reference< rendering::XCanvas >& rTargetCanvas, bool bSameViewTransform ) { (void)rNewState; (void)rOldState; ENSURE_AND_THROW( bSameViewTransform, "CachedBitmap::doRedraw(): base called with changed view transform " "(told otherwise during construction)" ); RepaintTarget* pTarget = dynamic_cast< RepaintTarget* >(rTargetCanvas.get()); ENSURE_AND_THROW( pTarget, "CachedBitmap::redraw(): cannot cast target to RepaintTarget" ); if( !pTarget->repaint( mpGraphicObject, maPoint, maSize, maAttributes ) ) { // target failed to repaint return rendering::RepaintResult::FAILED; } return rendering::RepaintResult::REDRAWN; } } <commit_msg>INTEGRATION: CWS thbpp9_SRC680 (1.6.70); FILE MERGED 2007/10/17 21:14:36 thb 1.6.70.1: #i82485# Carry clips along, also for XCachedPrimitive repaints<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cachedbitmap.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-11-01 14:40:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_canvas.hxx" #include <canvas/debug.hxx> #include "cachedbitmap.hxx" #include "repainttarget.hxx" #include <com/sun/star/rendering/RepaintResult.hpp> #include <com/sun/star/rendering/XPolyPolygon2D.hpp> #include <basegfx/matrix/b2dhommatrix.hxx> #include <basegfx/tools/canvastools.hxx> using namespace ::com::sun::star; namespace vclcanvas { CachedBitmap::CachedBitmap( const GraphicObjectSharedPtr& rGraphicObject, const ::Point& rPoint, const ::Size& rSize, const GraphicAttr& rAttr, const rendering::ViewState& rUsedViewState, const rendering::RenderState& rUsedRenderState, const uno::Reference< rendering::XCanvas >& rTarget ) : CachedPrimitiveBase( rUsedViewState, rTarget, true ), mpGraphicObject( rGraphicObject ), maRenderState(rUsedRenderState), maPoint( rPoint ), maSize( rSize ), maAttributes( rAttr ) { } void SAL_CALL CachedBitmap::disposing() { ::osl::MutexGuard aGuard( m_aMutex ); mpGraphicObject.reset(); CachedPrimitiveBase::disposing(); } ::sal_Int8 CachedBitmap::doRedraw( const rendering::ViewState& rNewState, const rendering::ViewState& rOldState, const uno::Reference< rendering::XCanvas >& rTargetCanvas, bool bSameViewTransform ) { ENSURE_AND_THROW( bSameViewTransform, "CachedBitmap::doRedraw(): base called with changed view transform " "(told otherwise during construction)" ); // TODO(P1): Could adapt to modified clips as well if( rNewState.Clip != rOldState.Clip ) return rendering::RepaintResult::FAILED; RepaintTarget* pTarget = dynamic_cast< RepaintTarget* >(rTargetCanvas.get()); ENSURE_AND_THROW( pTarget, "CachedBitmap::redraw(): cannot cast target to RepaintTarget" ); if( !pTarget->repaint( mpGraphicObject, rNewState, maRenderState, maPoint, maSize, maAttributes ) ) { // target failed to repaint return rendering::RepaintResult::FAILED; } return rendering::RepaintResult::REDRAWN; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: spritecanvas.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: thb $ $Date: 2004-03-18 10:38:44 $ * * 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 _VCLCANVAS_SPRITECANVAS_HXX_ #define _VCLCANVAS_SPRITECANVAS_HXX_ #include <memory> #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _CPPUHELPER_COMPBASE4_HXX_ #include <cppuhelper/compbase4.hxx> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX #include <comphelper/uno3.hxx> #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICENAME_HPP_ #include <com/sun/star/lang/XServiceName.hpp> #endif #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif #ifndef _DRAFTS_COM_SUN_STAR_RENDERING_XSPRITECANVAS_HPP_ #include <drafts/com/sun/star/rendering/XSpriteCanvas.hpp> #endif #include <canvas/vclwrapper.hxx> #include "redrawmanager.hxx" #include "spritesurface.hxx" #include "outdevprovider.hxx" #include "canvasbase.hxx" #include "impltools.hxx" class OutputDevice; class Point; namespace com { namespace sun { namespace star { namespace uno { class XComponentContext; class RuntimeException; } } } } class Window; namespace vclcanvas { typedef ::cppu::WeakComponentImplHelper4< ::drafts::com::sun::star::rendering::XSpriteCanvas, ::com::sun::star::lang::XInitialization, ::com::sun::star::lang::XServiceInfo, ::com::sun::star::lang::XServiceName > SpriteCanvas_Base; class SpriteCanvas : public ::comphelper::OBaseMutex, public SpriteSurface, public OutDevProvider, public SpriteCanvas_Base { public: typedef ::rtl::Reference< SpriteCanvas > ImplRef; SpriteCanvas( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext ); // XInterface // Need to implement that, because OutDevProvide comes with an // unimplemented version of XInterface. // Forwarding the XInterface implementation to the // cppu::ImplHelper templated base, which does the refcounting and // queryInterface for us: Classname Base doing refcount and handling queryInterface // | | // V V DECLARE_UNO3_AGG_DEFAULTS( SpriteCanvas, SpriteCanvas_Base ); // XCanvas virtual void SAL_CALL drawPoint( const ::drafts::com::sun::star::geometry::RealPoint2D& aPoint, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL drawLine( const ::drafts::com::sun::star::geometry::RealPoint2D& aStartPoint, const ::drafts::com::sun::star::geometry::RealPoint2D& aEndPoint, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL drawBezier( const ::drafts::com::sun::star::geometry::RealBezierSegment2D& aBezierSegment, const ::drafts::com::sun::star::geometry::RealPoint2D& aEndPoint, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL drawPolyPolygon( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL strokePolyPolygon( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, const ::drafts::com::sun::star::rendering::StrokeAttributes& strokeAttributes ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL strokeTexturedPolyPolygon( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, const ::com::sun::star::uno::Sequence< ::drafts::com::sun::star::rendering::Texture >& textures, const ::drafts::com::sun::star::rendering::StrokeAttributes& strokeAttributes ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL strokeTextureMappedPolyPolygon( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, const ::com::sun::star::uno::Sequence< ::drafts::com::sun::star::rendering::Texture >& textures, const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::geometry::XMapping2D >& xMapping, const ::drafts::com::sun::star::rendering::StrokeAttributes& strokeAttributes ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D > SAL_CALL queryStrokeShapes( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, const ::drafts::com::sun::star::rendering::StrokeAttributes& strokeAttributes ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL fillPolyPolygon( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL fillTexturedPolyPolygon( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, const ::com::sun::star::uno::Sequence< ::drafts::com::sun::star::rendering::Texture >& textures ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL fillTextureMappedPolyPolygon( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D >& xPolyPolygon, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, const ::com::sun::star::uno::Sequence< ::drafts::com::sun::star::rendering::Texture >& textures, const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::geometry::XMapping2D >& xMapping ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCanvasFont > SAL_CALL queryFont( const ::drafts::com::sun::star::rendering::FontRequest& fontRequest ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL drawText( const ::drafts::com::sun::star::rendering::StringContext& text, const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCanvasFont >& xFont, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, sal_Int8 textDirection ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL drawOffsettedText( const ::drafts::com::sun::star::rendering::StringContext& text, const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCanvasFont >& xFont, const ::com::sun::star::uno::Sequence< double >& offsets, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, sal_Int8 textDirection ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCachedPrimitive > SAL_CALL drawBitmap( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XBitmap >& xBitmap, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XGraphicDevice > SAL_CALL getDevice() throw (::com::sun::star::uno::RuntimeException); // XBitmapCanvas (only providing, not implementing the // interface. Also note subtle method parameter differences) virtual void SAL_CALL copyRect( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XBitmapCanvas >& sourceCanvas, const ::drafts::com::sun::star::geometry::RealRectangle2D& sourceRect, const ::drafts::com::sun::star::rendering::ViewState& sourceViewState, const ::drafts::com::sun::star::rendering::RenderState& sourceRenderState, const ::drafts::com::sun::star::geometry::RealRectangle2D& destRect, const ::drafts::com::sun::star::rendering::ViewState& destViewState, const ::drafts::com::sun::star::rendering::RenderState& destRenderState ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // XSpriteCanvas virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromAnimation( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XAnimation >& animation ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromBitmaps( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XBitmap > >& animationBitmaps, sal_Int16 interpolationMode ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCustomSprite > SAL_CALL createCustomSprite( const ::drafts::com::sun::star::geometry::RealSize2D& spriteSize ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XSprite > SAL_CALL createClonedSprite( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XSprite >& original ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL updateScreen() throw (::com::sun::star::uno::RuntimeException); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw( ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ); // XServiceName virtual ::rtl::OUString SAL_CALL getServiceName( ) throw (::com::sun::star::uno::RuntimeException); // factory static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext ) throw ( ::com::sun::star::uno::Exception ); // SpriteSurface virtual void showSprite( const Sprite::ImplRef& sprite ); virtual void hideSprite( const Sprite::ImplRef& sprite ); virtual void moveSprite( const Sprite::ImplRef& sprite, const Point& rOldPos, const Point& rNewPos ); virtual void updateSprite( const Sprite::ImplRef& sprite, const Point& rPos, const Rectangle& rUpdateArea ); // OutDevProvider virtual OutputDevice& getOutDev(); virtual const OutputDevice& getOutDev() const; protected: ~SpriteCanvas(); // we're a ref-counted UNO class. _We_ destroy ourselves. private: // default: disabled copy/assignment SpriteCanvas(const SpriteCanvas&); SpriteCanvas& operator=( const SpriteCanvas& ); void checkOurState(); // throws OutDevProvider::ImplRef getImplRef(); // TODO: Lifetime issue. Cannot control pointer validity over // object lifetime, since we're a UNO component Window* mpOutputWindow; // for the screen output ::canvas::vcltools::VCLObject<VirtualDevice> maVDev; // for the back-buffer ::std::auto_ptr< RedrawManager > mpRedrawManager; // handles smooth screen updates for us CanvasBase maCanvasHelper; // for the basic canvas implementation }; } #endif <commit_msg>INTEGRATION: CWS presentationengine01 (1.2.2); FILE MERGED 2004/11/17 17:00:33 thb 1.2.2.7: #118514# Canvas module reorg 2004/08/27 18:46:18 thb 1.2.2.6: #110496# Adapted to recent canvas API changes (XSpriteCanvas::updateScreen and sprite clip semantics 2004/08/02 17:51:00 thb 1.2.2.5: #110496# Adapted to recent XCanvas API changes, streamlined and factored out common code with directxcanvas 2004/07/20 19:23:57 thb 1.2.2.4: #110496# Removed self-references to various interface implementations, along the lines, factored out common base implementation for all c++ canvases 2004/05/27 20:51:25 thb 1.2.2.3: #110496# Added classification code to all TODO/HACK/FIXME comments. There are four categories: - code quality (C) - performance (P) - missing functionality (F) - and missing/incomplete error handling (E)<commit_after>/************************************************************************* * * $RCSfile: spritecanvas.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-11-26 17:15:43 $ * * 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 _VCLCANVAS_SPRITECANVAS_HXX_ #define _VCLCANVAS_SPRITECANVAS_HXX_ #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICENAME_HPP_ #include <com/sun/star/lang/XServiceName.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_RENDERING_XSPRITECANVAS_HPP_ #include <drafts/com/sun/star/rendering/XSpriteCanvas.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_RENDERING_XINTEGERBITMAP_HPP_ #include <drafts/com/sun/star/rendering/XIntegerBitmap.hpp> #endif #ifndef _CPPUHELPER_COMPBASE5_HXX_ #include <cppuhelper/compbase5.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif #include <canvas/vclwrapper.hxx> #include <canvas/bitmapcanvasbase.hxx> #include <memory> #include "redrawmanager.hxx" #include "spritesurface.hxx" #include "canvashelper.hxx" #include "backbuffer.hxx" #include "impltools.hxx" class OutputDevice; class Point; namespace com { namespace sun { namespace star { namespace uno { class XComponentContext; class RuntimeException; } } } } namespace vclcanvas { typedef ::cppu::WeakComponentImplHelper5< ::drafts::com::sun::star::rendering::XSpriteCanvas, ::drafts::com::sun::star::rendering::XIntegerBitmap, ::com::sun::star::lang::XInitialization, ::com::sun::star::lang::XServiceInfo, ::com::sun::star::lang::XServiceName > CanvasBase_Base; typedef ::canvas::internal::BitmapCanvasBase< CanvasBase_Base, CanvasHelper, tools::LocalGuard > SpriteCanvas_Base; class SpriteCanvas : public SpriteCanvas_Base, public SpriteSurface { public: typedef ::rtl::Reference< SpriteCanvas > ImplRef; SpriteCanvas( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext ); /// Dispose all internal references virtual void SAL_CALL disposing(); // XSpriteCanvas virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromAnimation( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XAnimation >& animation ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromBitmaps( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XBitmap > >& animationBitmaps, sal_Int8 interpolationMode ) throw (::com::sun::star::lang::IllegalArgumentException, ::drafts::com::sun::star::rendering::VolatileContentDestroyedException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCustomSprite > SAL_CALL createCustomSprite( const ::drafts::com::sun::star::geometry::RealSize2D& spriteSize ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XSprite > SAL_CALL createClonedSprite( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XSprite >& original ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL updateScreen( sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw( ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ); // XServiceName virtual ::rtl::OUString SAL_CALL getServiceName( ) throw (::com::sun::star::uno::RuntimeException); // factory static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext ) throw ( ::com::sun::star::uno::Exception ); // SpriteSurface virtual void showSprite( const Sprite::ImplRef& sprite ); virtual void hideSprite( const Sprite::ImplRef& sprite ); virtual void moveSprite( const Sprite::ImplRef& sprite, const Point& rOldPos, const Point& rNewPos ); virtual void updateSprite( const Sprite::ImplRef& sprite, const Point& rPos, const Rectangle& rUpdateArea ); protected: ~SpriteCanvas(); // we're a ref-counted UNO class. _We_ destroy ourselves. private: // default: disabled copy/assignment SpriteCanvas(const SpriteCanvas&); SpriteCanvas& operator=( const SpriteCanvas& ); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxComponentContext; WindowGraphicDevice::ImplRef mxDevice; BackBufferSharedPtr mpBackBuffer; ::std::auto_ptr< RedrawManager > mpRedrawManager; // handles smooth screen updates for us }; } #endif <|endoftext|>
<commit_before>#ifndef RBX_CODE_RESOURCE #define RBX_CODE_RESOURCE namespace rubinius { class CodeManager; class VM; class State; class CodeResource { bool mark_; bool detached_; public: CodeResource() : mark_(false) , detached_(false) {} virtual ~CodeResource() { }; virtual void cleanup(State* state, CodeManager* cm) = 0; virtual int size() { return 0; } virtual const char* kind() { return "resource"; } bool marked() const { return mark_ ; } void set_mark() { mark_ = true; } void clear_mark() { mark_ = false; } bool detached() const { return detached_; } void set_detached() { detached_ = true; } }; } #endif <commit_msg>We always create a code resource as marked initially<commit_after>#ifndef RBX_CODE_RESOURCE #define RBX_CODE_RESOURCE namespace rubinius { class CodeManager; class VM; class State; class CodeResource { bool mark_; bool detached_; public: CodeResource() : mark_(true) , detached_(false) {} virtual ~CodeResource() { }; virtual void cleanup(State* state, CodeManager* cm) = 0; virtual int size() { return 0; } virtual const char* kind() { return "resource"; } bool marked() const { return mark_ ; } void set_mark() { mark_ = true; } void clear_mark() { mark_ = false; } bool detached() const { return detached_; } void set_detached() { detached_ = true; } }; } #endif <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: BodyActuator.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2014 Stanford University and the Authors * * Author(s): Soha Pouya, Michael Sherman * * * * 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include <OpenSim/Common/XMLDocument.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/SimbodyEngine/Body.h> #include "BodyActuator.h" using namespace OpenSim; using namespace std; using SimTK::Vec3; //============================================================================= // STATICS //============================================================================= //============================================================================= // CONSTRUCTORS //============================================================================= // Uses default (compiler-generated) destructor, copy constructor, copy // assignment operator. //_____________________________________________________________________________ /** * Also serves as default constructor. */ BodyActuator::BodyActuator() { setNull(); constructInfrastructure(); } //============================================================================= // CONSTRUCTION //============================================================================= //_____________________________________________________________________________ // Set the data members of this actuator to their null values. void BodyActuator::setNull() { setAuthors("Soha Pouya, Michael Sherman"); } //_____________________________________________________________________________ // Allocate and initialize properties. void BodyActuator::constructProperties() { } void BodyActuator::constructStructuralConnectors() { constructStructuralConnector<Body>("body"); } //============================================================================= // GET AND SET //============================================================================= //============================================================================== // COMPUTATIONS //============================================================================== //============================================================================== // APPLICATION //============================================================================== //_____________________________________________________________________________ /** * Apply the actuator force to BodyA and BodyB. */ void BodyActuator::computeForce(const SimTK::State& s, SimTK::Vector_<SimTK::SpatialVec>& bodyForces, SimTK::Vector& generalizedForces) const { const SimbodyEngine& engine = getModel().getSimbodyEngine(); //if (!getConnector<Body>("body").isConnected()) // printf("OH SHIT!!\n"); const Body& body = getConnector<Body>("body").getConnectee(); const SimTK::Vector& spatial = getControls(s); const Vec3 torqueVec_B(spatial[0],spatial[1],spatial[2]); const Vec3 forceVec_B(spatial[3],spatial[4],spatial[5]); Vec3 torqueVec_G, forceVec_G; engine.transform(s, body, torqueVec_B, engine.getGroundBody(), torqueVec_G); engine.transform(s, body, forceVec_B, engine.getGroundBody(), forceVec_G); applyTorque(s, body, torqueVec_G, bodyForces); applyForceToPoint(s, body, Vec3(0), forceVec_G, bodyForces); } //_____________________________________________________________________________ /** * Sets the actual Body reference _body */ void BodyActuator::connectToModel(Model& model) { Super::connectToModel(model); } <commit_msg>Fixed BodyActuator for getControls (no need to use reference)<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: BodyActuator.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2014 Stanford University and the Authors * * Author(s): Soha Pouya, Michael Sherman * * * * 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include <OpenSim/Common/XMLDocument.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/SimbodyEngine/Body.h> #include "BodyActuator.h" using namespace OpenSim; using namespace std; using SimTK::Vec3; //============================================================================= // STATICS //============================================================================= //============================================================================= // CONSTRUCTORS //============================================================================= // Uses default (compiler-generated) destructor, copy constructor, copy // assignment operator. //_____________________________________________________________________________ /** * Also serves as default constructor. */ BodyActuator::BodyActuator() { setNull(); constructInfrastructure(); } //============================================================================= // CONSTRUCTION //============================================================================= //_____________________________________________________________________________ // Set the data members of this actuator to their null values. void BodyActuator::setNull() { setAuthors("Soha Pouya, Michael Sherman"); } //_____________________________________________________________________________ // Allocate and initialize properties. void BodyActuator::constructProperties() { } void BodyActuator::constructStructuralConnectors() { constructStructuralConnector<Body>("body"); } //============================================================================= // GET AND SET //============================================================================= //============================================================================== // COMPUTATIONS //============================================================================== //============================================================================== // APPLICATION //============================================================================== //_____________________________________________________________________________ /** * Apply the actuator force to BodyA and BodyB. */ void BodyActuator::computeForce(const SimTK::State& s, SimTK::Vector_<SimTK::SpatialVec>& bodyForces, SimTK::Vector& generalizedForces) const { const SimbodyEngine& engine = getModel().getSimbodyEngine(); //if (!getConnector<Body>("body").isConnected()) // printf("OH SHIT!!\n"); const Body& body = getConnector<Body>("body").getConnectee(); const SimTK::Vector spatial = getControls(s); //spatial.dump("internal actuator controls."); const Vec3 torqueVec_B(spatial[0],spatial[1],spatial[2]); const Vec3 forceVec_B(spatial[3],spatial[4],spatial[5]); Vec3 torqueVec_G, forceVec_G; engine.transform(s, body, torqueVec_B, engine.getGroundBody(), torqueVec_G); engine.transform(s, body, forceVec_B, engine.getGroundBody(), forceVec_G); applyTorque(s, body, torqueVec_G, bodyForces); applyForceToPoint(s, body, Vec3(0), forceVec_G, bodyForces); } //_____________________________________________________________________________ /** * Sets the actual Body reference _body */ void BodyActuator::connectToModel(Model& model) { Super::connectToModel(model); } <|endoftext|>
<commit_before>// ForceReporter.cpp //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // AUTHOR: Ayman Habib //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /* Copyright (c) 2006 Stanford University * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 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; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) 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. */ //============================================================================= // INCLUDES //============================================================================= #include <iostream> #include <string> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/ForceSet.h> #include <OpenSim/Simulation/Model/ConstraintSet.h> #include "ForceReporter.h" using namespace OpenSim; using namespace std; //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Destructor. */ ForceReporter::~ForceReporter() { deleteStorage(); } //_____________________________________________________________________________ /** * Construct an ForceReporter object for recording the Forces exerted on a model during a simulation. * * @param aModel Model for which the Forces are to be recorded. */ ForceReporter::ForceReporter(Model *aModel) : Analysis(aModel), _forceStore(1000,"ModelForces"), _includeConstraintForces(_includeConstraintForcesProp.getValueBool()) { // NULL setNull(); // DESCRIPTION constructDescription(); // STORAGE allocateStorage(); } //_____________________________________________________________________________ /** * Construct an object from file. * * The object is constructed from the root element of the XML document. * The type of object is the tag name of the XML root element. * * @param aFileName File name of the document. */ ForceReporter::ForceReporter(const std::string &aFileName): Analysis(aFileName, false), _forceStore(1000,"ModelForces"), _includeConstraintForces(_includeConstraintForcesProp.getValueBool()) { setNull(); // Serialize from XML updateFromXMLDocument(); // DESCRIPTION constructDescription(); // STORAGE allocateStorage(); } // Copy constrctor and virtual copy //_____________________________________________________________________________ /** * Copy constructor. * */ ForceReporter::ForceReporter(const ForceReporter &aForceReporter): Analysis(aForceReporter), _forceStore(aForceReporter._forceStore), _includeConstraintForces(_includeConstraintForcesProp.getValueBool()) { setNull(); // COPY TYPE AND NAME *this = aForceReporter; } //_____________________________________________________________________________ /** * Clone * */ Object* ForceReporter::copy() const { ForceReporter *object = new ForceReporter(*this); return(object); } //============================================================================= // CONSTRUCTION METHODS //============================================================================= //_____________________________________________________________________________ /** * Set NULL values for all member variables. */ void ForceReporter::setNull() { // TYPE setType("ForceReporter"); // NAME setName("ForceReporter"); _includeConstraintForcesProp.setComment("Flag indicating whether to include forces due to constraints."); _includeConstraintForcesProp.setName("include_constraint_forces"); _includeConstraintForcesProp.setValue(false); _propertySet.append( &_includeConstraintForcesProp ); } //-------------------------------------------------------------------------- // OPERATORS //-------------------------------------------------------------------------- ForceReporter& ForceReporter::operator=(const ForceReporter &aForceReporter) { // BASE CLASS Analysis::operator=(aForceReporter); // STORAGE deleteStorage(); allocateStorage(); _includeConstraintForces = aForceReporter._includeConstraintForces; return (*this); } //_____________________________________________________________________________ /** * Set the model pointer for analysis. */ void ForceReporter::setModel(Model& aModel) { // BASE CLASS Analysis::setModel(aModel); } //_____________________________________________________________________________ /** * Allocate storage for the forces. */ void ForceReporter::allocateStorage() { // ACCELERATIONS _forceStore.setDescription(getDescription()); // Keep references o all storages in a list for uniform access from GUI _storageList.append(&_forceStore); _storageList.setMemoryOwner(false); } //----------------------------------------------------------------------------- // DESCRIPTION //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Construct the description for the ForceReporter files. */ void ForceReporter::constructDescription() { char descrip[1024]; strcpy(descrip,"\nThis file contains the forces exerted on a model "); strcat(descrip,"during a simulation.\n"); strcat(descrip,"\nA force is a generalized force, meaning that"); strcat(descrip," it can be either a force (N) or a torque (Nm).\n"); strcat(descrip,"\nUnits are S.I. units (second, meters, Newtons, ...)"); if(getInDegrees()) { strcat(descrip,"\nAngles are in degrees."); } else { strcat(descrip,"\nAngles are in radians."); } strcat(descrip,"\n\n"); setDescription(descrip); } //----------------------------------------------------------------------------- // COLUMN LABELS //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Construct the column labels for the ForceReporter storage files. */ void ForceReporter::constructColumnLabels(const SimTK::State& s) { if (_model) { // ASSIGN Array<string> columnLabels; columnLabels.append("time"); int nf=_model->getForceSet().getSize(); for(int i=0;i<nf;i++) { // If body force we need to record six values for torque+force // If muscle we record one scalar Force& f = _model->getForceSet().get(i); if (f.isDisabled(s)) continue; // Skip over disabled forces Array<string> forceLabels = f.getRecordLabels(); // If prescribed force we need to record point, columnLabels.append(forceLabels); } if(_includeConstraintForces){ int nc=_model->getConstraintSet().getSize(); for(int i=0;i<nc;i++) { Constraint& c = _model->getConstraintSet().get(i); if (c.isDisabled(s)) continue; // Skip over disabled constraints // Ask constraint how many columns and their names it reports Array<string> forceLabels = _model->getConstraintSet().get(i).getRecordLabels(); // If prescribed force we need to record point, columnLabels.append(forceLabels); } } _forceStore.setColumnLabels(columnLabels); } } //============================================================================= // DESTRUCTION METHODS //============================================================================= //_____________________________________________________________________________ /** * Delete storage objects. */ void ForceReporter::deleteStorage() { //if(_forceStore!=NULL) { delete _forceStore; _forceStore=NULL; } } //============================================================================= // ANALYSIS //============================================================================= //_____________________________________________________________________________ /** * Record the ForceReporter quantities. */ int ForceReporter::record(const SimTK::State& s) { if(_model==NULL) return(-1); // MAKE SURE ALL ForceReporter QUANTITIES ARE VALID _model->getMultibodySystem().realize(s, SimTK::Stage::Dynamics ); StateVector nextRow = StateVector(s.getTime()); // NUMBER OF Forces const ForceSet& forces = _model->getForceSet(); // This does not contain gravity int nf = forces.getSize(); for(int i=0;i<nf;i++) { // If body force we need to record six values for torque+force // If muscle we record one scalar OpenSim::Force& nextForce = (OpenSim::Force&)forces[i]; if (nextForce.isDisabled(s)) continue; Array<double> values = nextForce.getRecordValues(s); nextRow.getData().append(values); } if(_includeConstraintForces){ // NUMBER OF Constraints const ConstraintSet& constraints = _model->getConstraintSet(); // This does not contain gravity int nc = constraints.getSize(); for(int i=0;i<nc;i++) { OpenSim::Constraint& nextConstraint = (OpenSim::Constraint&)constraints[i]; if (nextConstraint.isDisabled(s)) continue; Array<double> values = nextConstraint.getRecordValues(s); nextRow.getData().append(values); } } _forceStore.append(nextRow); return(0); } //_____________________________________________________________________________ /** * This method is called at the beginning of an analysis so that any * necessary initializations may be performed. * * * This method should be overriden in the child class. It is * included here so that the child class will not have to implement it if it * is not necessary. * * @param state system State * @param aStep Step number of the integration. * * @return -1 on error, 0 otherwise. */ int ForceReporter:: begin(SimTK::State& s) { if(!proceed()) return(0); tidyForceNames(); // LABELS constructColumnLabels(s); // RESET STORAGE _forceStore.reset(s.getTime()); // RECORD int status = 0; if(_forceStore.getSize()<=0) { status = record(s); } return(status); } //_____________________________________________________________________________ /** * This method is called to perform the analysis. It can be called during * the execution of a forward integrations or after the integration by * feeding it the necessary data. * * When called during an integration, this method is meant to be called * * This method should be overriden in derived classes. It is * included here so that the derived class will not have to implement it if * it is not necessary. * * @param state System state * * @return -1 on error, 0 otherwise. */ int ForceReporter:: step(const SimTK::State& s, int stepNumber ) { if(!proceed( stepNumber )) return(0); record(s); return(0); } //_____________________________________________________________________________ /** * This method is called at the end of an analysis so that any * necessary finalizations may be performed. * * This method is meant to be called at the end of an integration * * This method should be overriden in the child class. It is * included here so that the child class will not have to implement it if it * is not necessary. * @param state System state * * @return -1 on error, 0 otherwise. */ int ForceReporter:: end(SimTK::State& s ) { if (!proceed()) return 0; record(s); return(0); } //============================================================================= // IO //============================================================================= //_____________________________________________________________________________ /** * Print results. * * The file names are constructed as * aDir + "/" + aBaseName + "_" + ComponentName + aExtension * * @param aDir Directory in which the results reside. * @param aBaseName Base file name. * @param aDT Desired time interval between adjacent storage vectors. Linear * interpolation is used to print the data out at the desired interval. * @param aExtension File extension. * * @return 0 on success, -1 on error. */ int ForceReporter:: printResults(const string &aBaseName,const string &aDir,double aDT, const string &aExtension) { if(!getOn()) { printf("ForceReporter.printResults: Off- not printing.\n"); return(0); } std::string prefix=aBaseName+"_"+getName()+"_"; Storage::printResult(&_forceStore, prefix+"forces", aDir, aDT, aExtension); return(0); } void ForceReporter::tidyForceNames() { OpenSim::Array<string> forceNames(""); const ForceSet& forces = _model->getForceSet(); // This does not contain gravity forces.getNames(forceNames); // Make sure names are unique and non-empty. If empty assign names AutoForcexxx int nf = forceNames.getSize(); for(int i=0; i<nf; i++){ int j=1; if (forceNames[i]==""){ bool validNameFound=false; char pad[100]; // Make up a candidate name sprintf(pad, "%s%d", forces.get(i).getType().c_str(), j++); while(!validNameFound){ validNameFound = (forceNames.findIndex(string(pad))== -1); if (!validNameFound){ sprintf(pad, "Force%d", j++); } } string newName(pad); _model->updForceSet()[i].setName(newName); cout << "Changing blank name for force to " << newName << endl; } } } <commit_msg>fixed small bug in ForceReporter.cpp when duplicate Force names are given: bug in tidyForceNames()<commit_after>// ForceReporter.cpp //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // AUTHOR: Ayman Habib //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /* Copyright (c) 2006 Stanford University * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 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; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) 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. */ //============================================================================= // INCLUDES //============================================================================= #include <iostream> #include <string> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/ForceSet.h> #include <OpenSim/Simulation/Model/ConstraintSet.h> #include "ForceReporter.h" using namespace OpenSim; using namespace std; //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Destructor. */ ForceReporter::~ForceReporter() { deleteStorage(); } //_____________________________________________________________________________ /** * Construct an ForceReporter object for recording the Forces exerted on a model during a simulation. * * @param aModel Model for which the Forces are to be recorded. */ ForceReporter::ForceReporter(Model *aModel) : Analysis(aModel), _forceStore(1000,"ModelForces"), _includeConstraintForces(_includeConstraintForcesProp.getValueBool()) { // NULL setNull(); // DESCRIPTION constructDescription(); // STORAGE allocateStorage(); } //_____________________________________________________________________________ /** * Construct an object from file. * * The object is constructed from the root element of the XML document. * The type of object is the tag name of the XML root element. * * @param aFileName File name of the document. */ ForceReporter::ForceReporter(const std::string &aFileName): Analysis(aFileName, false), _forceStore(1000,"ModelForces"), _includeConstraintForces(_includeConstraintForcesProp.getValueBool()) { setNull(); // Serialize from XML updateFromXMLDocument(); // DESCRIPTION constructDescription(); // STORAGE allocateStorage(); } // Copy constrctor and virtual copy //_____________________________________________________________________________ /** * Copy constructor. * */ ForceReporter::ForceReporter(const ForceReporter &aForceReporter): Analysis(aForceReporter), _forceStore(aForceReporter._forceStore), _includeConstraintForces(_includeConstraintForcesProp.getValueBool()) { setNull(); // COPY TYPE AND NAME *this = aForceReporter; } //_____________________________________________________________________________ /** * Clone * */ Object* ForceReporter::copy() const { ForceReporter *object = new ForceReporter(*this); return(object); } //============================================================================= // CONSTRUCTION METHODS //============================================================================= //_____________________________________________________________________________ /** * Set NULL values for all member variables. */ void ForceReporter::setNull() { // TYPE setType("ForceReporter"); // NAME setName("ForceReporter"); _includeConstraintForcesProp.setComment("Flag indicating whether to include forces due to constraints."); _includeConstraintForcesProp.setName("include_constraint_forces"); _includeConstraintForcesProp.setValue(false); _propertySet.append( &_includeConstraintForcesProp ); } //-------------------------------------------------------------------------- // OPERATORS //-------------------------------------------------------------------------- ForceReporter& ForceReporter::operator=(const ForceReporter &aForceReporter) { // BASE CLASS Analysis::operator=(aForceReporter); // STORAGE deleteStorage(); allocateStorage(); _includeConstraintForces = aForceReporter._includeConstraintForces; return (*this); } //_____________________________________________________________________________ /** * Set the model pointer for analysis. */ void ForceReporter::setModel(Model& aModel) { // BASE CLASS Analysis::setModel(aModel); } //_____________________________________________________________________________ /** * Allocate storage for the forces. */ void ForceReporter::allocateStorage() { // ACCELERATIONS _forceStore.setDescription(getDescription()); // Keep references o all storages in a list for uniform access from GUI _storageList.append(&_forceStore); _storageList.setMemoryOwner(false); } //----------------------------------------------------------------------------- // DESCRIPTION //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Construct the description for the ForceReporter files. */ void ForceReporter::constructDescription() { char descrip[1024]; strcpy(descrip,"\nThis file contains the forces exerted on a model "); strcat(descrip,"during a simulation.\n"); strcat(descrip,"\nA force is a generalized force, meaning that"); strcat(descrip," it can be either a force (N) or a torque (Nm).\n"); strcat(descrip,"\nUnits are S.I. units (second, meters, Newtons, ...)"); if(getInDegrees()) { strcat(descrip,"\nAngles are in degrees."); } else { strcat(descrip,"\nAngles are in radians."); } strcat(descrip,"\n\n"); setDescription(descrip); } //----------------------------------------------------------------------------- // COLUMN LABELS //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Construct the column labels for the ForceReporter storage files. */ void ForceReporter::constructColumnLabels(const SimTK::State& s) { if (_model) { // ASSIGN Array<string> columnLabels; columnLabels.append("time"); int nf=_model->getForceSet().getSize(); for(int i=0;i<nf;i++) { // If body force we need to record six values for torque+force // If muscle we record one scalar Force& f = _model->getForceSet().get(i); if (f.isDisabled(s)) continue; // Skip over disabled forces Array<string> forceLabels = f.getRecordLabels(); // If prescribed force we need to record point, columnLabels.append(forceLabels); } if(_includeConstraintForces){ int nc=_model->getConstraintSet().getSize(); for(int i=0;i<nc;i++) { Constraint& c = _model->getConstraintSet().get(i); if (c.isDisabled(s)) continue; // Skip over disabled constraints // Ask constraint how many columns and their names it reports Array<string> forceLabels = _model->getConstraintSet().get(i).getRecordLabels(); // If prescribed force we need to record point, columnLabels.append(forceLabels); } } _forceStore.setColumnLabels(columnLabels); } } //============================================================================= // DESTRUCTION METHODS //============================================================================= //_____________________________________________________________________________ /** * Delete storage objects. */ void ForceReporter::deleteStorage() { //if(_forceStore!=NULL) { delete _forceStore; _forceStore=NULL; } } //============================================================================= // ANALYSIS //============================================================================= //_____________________________________________________________________________ /** * Record the ForceReporter quantities. */ int ForceReporter::record(const SimTK::State& s) { if(_model==NULL) return(-1); // MAKE SURE ALL ForceReporter QUANTITIES ARE VALID _model->getMultibodySystem().realize(s, SimTK::Stage::Dynamics ); StateVector nextRow = StateVector(s.getTime()); // NUMBER OF Forces const ForceSet& forces = _model->getForceSet(); // This does not contain gravity int nf = forces.getSize(); for(int i=0;i<nf;i++) { // If body force we need to record six values for torque+force // If muscle we record one scalar OpenSim::Force& nextForce = (OpenSim::Force&)forces[i]; if (nextForce.isDisabled(s)) continue; Array<double> values = nextForce.getRecordValues(s); nextRow.getData().append(values); } if(_includeConstraintForces){ // NUMBER OF Constraints const ConstraintSet& constraints = _model->getConstraintSet(); // This does not contain gravity int nc = constraints.getSize(); for(int i=0;i<nc;i++) { OpenSim::Constraint& nextConstraint = (OpenSim::Constraint&)constraints[i]; if (nextConstraint.isDisabled(s)) continue; Array<double> values = nextConstraint.getRecordValues(s); nextRow.getData().append(values); } } _forceStore.append(nextRow); return(0); } //_____________________________________________________________________________ /** * This method is called at the beginning of an analysis so that any * necessary initializations may be performed. * * * This method should be overriden in the child class. It is * included here so that the child class will not have to implement it if it * is not necessary. * * @param state system State * @param aStep Step number of the integration. * * @return -1 on error, 0 otherwise. */ int ForceReporter:: begin(SimTK::State& s) { if(!proceed()) return(0); tidyForceNames(); // LABELS constructColumnLabels(s); // RESET STORAGE _forceStore.reset(s.getTime()); // RECORD int status = 0; if(_forceStore.getSize()<=0) { status = record(s); } return(status); } //_____________________________________________________________________________ /** * This method is called to perform the analysis. It can be called during * the execution of a forward integrations or after the integration by * feeding it the necessary data. * * When called during an integration, this method is meant to be called * * This method should be overriden in derived classes. It is * included here so that the derived class will not have to implement it if * it is not necessary. * * @param state System state * * @return -1 on error, 0 otherwise. */ int ForceReporter:: step(const SimTK::State& s, int stepNumber ) { if(!proceed( stepNumber )) return(0); record(s); return(0); } //_____________________________________________________________________________ /** * This method is called at the end of an analysis so that any * necessary finalizations may be performed. * * This method is meant to be called at the end of an integration * * This method should be overriden in the child class. It is * included here so that the child class will not have to implement it if it * is not necessary. * @param state System state * * @return -1 on error, 0 otherwise. */ int ForceReporter:: end(SimTK::State& s ) { if (!proceed()) return 0; record(s); return(0); } //============================================================================= // IO //============================================================================= //_____________________________________________________________________________ /** * Print results. * * The file names are constructed as * aDir + "/" + aBaseName + "_" + ComponentName + aExtension * * @param aDir Directory in which the results reside. * @param aBaseName Base file name. * @param aDT Desired time interval between adjacent storage vectors. Linear * interpolation is used to print the data out at the desired interval. * @param aExtension File extension. * * @return 0 on success, -1 on error. */ int ForceReporter:: printResults(const string &aBaseName,const string &aDir,double aDT, const string &aExtension) { if(!getOn()) { printf("ForceReporter.printResults: Off- not printing.\n"); return(0); } std::string prefix=aBaseName+"_"+getName()+"_"; Storage::printResult(&_forceStore, prefix+"forces", aDir, aDT, aExtension); return(0); } void ForceReporter::tidyForceNames() { OpenSim::Array<string> forceNames(""); const ForceSet& forces = _model->getForceSet(); // This does not contain gravity forces.getNames(forceNames); // Make sure names are unique and non-empty. If empty assign names AutoForcexxx int nf = forceNames.getSize(); for(int i=0; i<nf; i++){ int j=1; if (forceNames[i]==""){ bool validNameFound=false; char pad[100]; // Make up a candidate name sprintf(pad, "%s%d", forces.get(i).getType().c_str(), j++); while(!validNameFound){ validNameFound = (forceNames.findIndex(string(pad))== -1); if (!validNameFound){ sprintf(pad, "Force%d", j++); } } string newName(pad); _model->updForceSet()[i].setName(newName); forceNames.set(i, newName); cout << "Changing blank name for force to " << newName << endl; } } } <|endoftext|>
<commit_before>// programming_challenges_13.cpp: santiaago // Description: Australian Voting - Programming challenges 110108 #include <iostream> #include <vector> #include <sstream> #include <string> #include <map> #include <limits> using namespace std; typedef vector<string> CandidatesVector; typedef map<string, unsigned int> CandidatesVoteMap; typedef map<string, unsigned int> CandidatesPositionMap; typedef map<unsigned int, CandidatesVoteMap> VotingMap; typedef vector<unsigned int > VoteVector; typedef vector<VoteVector> VotesVector; typedef vector< CandidatesVector > WinnersByCaseVector; bool areCandidatesTied(const CandidatesVoteMap &candidates); void getLowestCandidates(const CandidatesVoteMap &candidates, CandidatesVector &lowest_candidates); string getHighestCandidateFromMap(const CandidatesVoteMap &candidates); string getHighestCandidateFromLowest(const unsigned int lowest_candidate, const VotesVector all_votes, VotingMap candidate_votes, const CandidatesVector candidates); void buildVoting(CandidatesVector &candidates, CandidatesPositionMap &candidates_position, VotingMap &candidate_votes, VotesVector &all_votes); void addWinners(CandidatesVector &winners, const VotesVector &all_votes, VotingMap &candidate_votes, const CandidatesPositionMap &map_candidate, const CandidatesVector &candidates); int main(){ cout << "Australian Voting" << endl; // ready number of cases. unsigned int num_cases(0); cin >> num_cases; // ready empty line. string line; getline (cin, line); WinnersByCaseVector winners(num_cases); // container to hold the winners of each case / election. while(num_cases > 0){ CandidatesVector candidates; // vector of candidate names. CandidatesPositionMap candidates_position; // map of each candidate position from 1st to nth. VotingMap candidate_votes; // map of all positions in current election, and for each position the number of votes of each candidate. VotesVector all_votes; // vector that has all votes in current election // fill all containers by reading the input stream. buildVoting(candidates, candidates_position, candidate_votes, all_votes); // append winners to collection based of the votes. addWinners(winners[winners.size() - num_cases], all_votes, candidate_votes, candidates_position, candidates); num_cases--; } // print winners, one by line, and a blank line per case. for(int i = 0; i < winners.size(); i++){ for(int j = 0; j < winners[i].size(); j++){ cout << winners[i][j] << endl; } if(i != winners.size() - 1){ cout << endl; } } } // Fill the containers based on the input stream. void buildVoting(CandidatesVector &candidates, CandidatesPositionMap &candidates_position, VotingMap &candidate_votes, VotesVector &all_votes){ unsigned int num_candidates(0); cin >> num_candidates; cin.ignore(); // read candidates string candidate; while( num_candidates > 0 && getline(cin, candidate, '\n')){ candidates.push_back(candidate); candidates_position[candidate] = candidates.size()-num_candidates + 1; num_candidates--; } // read up to 1000 lines string vote; unsigned int num_votes(0); while( num_votes < 1000){ getline(cin, vote, '\n'); if(vote.empty()) break; istringstream stm(vote); unsigned int index_candidate; VoteVector current_vote; while( stm >> index_candidate){ current_vote.push_back(index_candidate); } for(int i = 0; i < current_vote.size(); i++){ candidate_votes[i + 1][candidates[current_vote[i]-1]]++; } num_votes++; all_votes.push_back(current_vote); } } // Append winners to 'winners' vector based on votes. // Rules are as follows: // Initially only the first choices are counted, and if one candidate receives more than 50% of the vote then that candidate is elected. // However, if no candidate receives more than 50%, all candidates tied for the lowest number of votes are eliminated. // Ballots ranking these candidates first are recounted in favor of their highest-ranked non-eliminated candidate. // This process of eliminating the weakest candidates and counting their ballots in favor of the preferred non-eliminated candidate // continues until one candidate receives more than 50% of the vote, or until all remaining candidates are tied. void addWinners(CandidatesVector &winners, const VotesVector &all_votes, VotingMap &candidate_votes, const CandidatesPositionMap &candidates_position,const CandidatesVector &candidates){ double mayority = all_votes.size()/double(2.0); bool has_winner(false); while(!has_winner){ // look for candidate with mayority for(auto t : candidate_votes[1]){ if(t.second > mayority){ winners.push_back(t.first); has_winner = true; break; } } if(has_winner){ break; } // mayority not found, remove lowest candidate. // search for best candidate in votes where lowest candidate was first. // give lowest candidate the votes of the best candidate. if(!has_winner){ CandidatesVector lowest_candidates; getLowestCandidates(candidate_votes[1], lowest_candidates); if(lowest_candidates.size() < candidate_votes[1].size()){ for(auto lowest_candidate : lowest_candidates){ CandidatesPositionMap::const_iterator lowest = candidates_position.find(lowest_candidate); if(lowest == candidates_position.end()){ continue; } string highest_candidate = getHighestCandidateFromLowest(lowest->second, all_votes, candidate_votes, candidates); unsigned int votes_to_give = candidate_votes[1][lowest_candidate]; CandidatesVoteMap::iterator to_remove; to_remove = candidate_votes[1].find(lowest_candidate); if(to_remove == candidate_votes[1].end()){ continue; } candidate_votes[1].erase(to_remove); candidate_votes[1][highest_candidate] += votes_to_give; } } } // if candidates in first position are all tied, they are all winners. if(areCandidatesTied(candidate_votes[1])){ for(auto c : candidate_votes[1]){ winners.push_back(c.first); } has_winner = true; } } } // From a map of candidate votes, fill a vector with all the lowest candidates in map. void getLowestCandidates(const CandidatesVoteMap &candidates, CandidatesVector &lowest_candidates){ // get minimum vote unsigned int min(numeric_limits<int>::max()); for(auto c : candidates){ if(c.second < min){ min = c.second; } } // get candidate with minimum vote for(auto c: candidates){ if(c.second == min){ lowest_candidates.push_back(c.first); } } } // Based on the id of the lowest candidate: // Find the votes made to that candidates. // From those votes, find the best existing candidate other than the lowest. // Return that candidate. string getHighestCandidateFromLowest(const unsigned int lowest_candidate, const VotesVector all_votes, VotingMap candidate_votes, const CandidatesVector candidates){ string highest_candidate; // find all votes where the lowest_candidate was vote as 1st candidate and count 2nd votes. CandidatesVoteMap votes; for(int i = 0; i < all_votes.size(); i++){ if(all_votes[i][0] == lowest_candidate){ votes[candidates[all_votes[i][1] - 1]]++; } } bool found(false); while(!found){ highest_candidate = getHighestCandidateFromMap(votes); CandidatesVoteMap::iterator it; it = candidate_votes[1].find(highest_candidate); if(it != candidate_votes[1].cend()){ found = true; }else{ CandidatesVoteMap::iterator to_remove; to_remove = votes.find(highest_candidate); votes.erase(to_remove); } } return highest_candidate; } // From a map of candidate votes, return the candidate with the highest votes. string getHighestCandidateFromMap(const CandidatesVoteMap &candidates){ string highest_candidate; unsigned int max(0); for(auto c : candidates){ if(c.second > max){ max = c.second; highest_candidate = c.first; } } return highest_candidate; } // Determine whether all candidates are tied in votes or not based on the candidates votes. bool areCandidatesTied(const CandidatesVoteMap &candidates){ unsigned int value(-1); for(auto c : candidates){ if(value == -1){ value = c.second; } else { if(value != c.second){ return false; } } } return true; } <commit_msg>sumbit file now compiles prior to c++ 11<commit_after>// programming_challenges_13.cpp: santiaago // Description: Australian Voting - Programming challenges 110108 #include <iostream> #include <vector> #include <sstream> #include <string> #include <map> #include <limits> using namespace std; typedef vector<string> CandidatesVector; typedef map<string, unsigned int> CandidatesVoteMap; typedef map<string, unsigned int> CandidatesPositionMap; typedef map<unsigned int, CandidatesVoteMap> VotingMap; typedef vector<unsigned int > VoteVector; typedef vector<VoteVector> VotesVector; typedef vector< CandidatesVector > WinnersByCaseVector; bool areCandidatesTied(const CandidatesVoteMap &candidates); void getLowestCandidates(const CandidatesVoteMap &candidates, CandidatesVector &lowest_candidates); string getHighestCandidateFromMap(const CandidatesVoteMap &candidates); string getHighestCandidateFromLowest(const unsigned int lowest_candidate, const VotesVector all_votes, VotingMap candidate_votes, const CandidatesVector candidates); void buildVoting(CandidatesVector &candidates, CandidatesPositionMap &candidates_position, VotingMap &candidate_votes, VotesVector &all_votes); void addWinners(CandidatesVector &winners, const VotesVector &all_votes, VotingMap &candidate_votes, const CandidatesPositionMap &map_candidate, const CandidatesVector &candidates); int main(){ cout << "Australian Voting" << endl; // ready number of cases. unsigned int num_cases(0); cin >> num_cases; // ready empty line. string line; getline (cin, line); WinnersByCaseVector winners(num_cases); // container to hold the winners of each case / election. while(num_cases > 0){ CandidatesVector candidates; // vector of candidate names. CandidatesPositionMap candidates_position; // map of each candidate position from 1st to nth. VotingMap candidate_votes; // map of all positions in current election, and for each position the number of votes of each candidate. VotesVector all_votes; // vector that has all votes in current election // fill all containers by reading the input stream. buildVoting(candidates, candidates_position, candidate_votes, all_votes); // append winners to collection based of the votes. addWinners(winners[winners.size() - num_cases], all_votes, candidate_votes, candidates_position, candidates); num_cases--; } // print winners, one by line, and a blank line per case. for(int i = 0; i < winners.size(); i++){ for(int j = 0; j < winners[i].size(); j++){ cout << winners[i][j] << endl; } if(i != winners.size() - 1){ cout << endl; } } } // Fill the containers based on the input stream. void buildVoting(CandidatesVector &candidates, CandidatesPositionMap &candidates_position, VotingMap &candidate_votes, VotesVector &all_votes){ unsigned int num_candidates(0); cin >> num_candidates; cin.ignore(); // read candidates string candidate; while( num_candidates > 0 && getline(cin, candidate, '\n')){ candidates.push_back(candidate); candidates_position[candidate] = candidates.size()-num_candidates + 1; num_candidates--; } // read up to 1000 lines string vote; unsigned int num_votes(0); while( num_votes < 1000){ getline(cin, vote, '\n'); if(vote.empty()) break; istringstream stm(vote); unsigned int index_candidate; VoteVector current_vote; while( stm >> index_candidate){ current_vote.push_back(index_candidate); } for(int i = 0; i < current_vote.size(); i++){ candidate_votes[i + 1][candidates[current_vote[i]-1]]++; } num_votes++; all_votes.push_back(current_vote); } } // Append winners to 'winners' vector based on votes. // Rules are as follows: // Initially only the first choices are counted, and if one candidate receives more than 50% of the vote then that candidate is elected. // However, if no candidate receives more than 50%, all candidates tied for the lowest number of votes are eliminated. // Ballots ranking these candidates first are recounted in favor of their highest-ranked non-eliminated candidate. // This process of eliminating the weakest candidates and counting their ballots in favor of the preferred non-eliminated candidate // continues until one candidate receives more than 50% of the vote, or until all remaining candidates are tied. void addWinners(CandidatesVector &winners, const VotesVector &all_votes, VotingMap &candidate_votes, const CandidatesPositionMap &candidates_position,const CandidatesVector &candidates){ double mayority = all_votes.size()/double(2.0); bool has_winner(false); while(!has_winner){ // look for candidate with mayority for(CandidatesVoteMap::iterator c = candidate_votes[1].begin(); c != candidate_votes[1].end(); c++){ if(c->second > mayority){ winners.push_back(c->first); has_winner = true; break; } } if(has_winner){ break; } // mayority not found, remove lowest candidate. // search for best candidate in votes where lowest candidate was first. // give lowest candidate the votes of the best candidate. if(!has_winner){ CandidatesVector lowest_candidates; getLowestCandidates(candidate_votes[1], lowest_candidates); if(lowest_candidates.size() < candidate_votes[1].size()){ for(CandidatesVector::const_iterator lowest_candidate = lowest_candidates.begin(); lowest_candidate != lowest_candidates.end(); lowest_candidate++){ CandidatesPositionMap::const_iterator lowest = candidates_position.find(*lowest_candidate); if(lowest == candidates_position.end()){ continue; } string highest_candidate = getHighestCandidateFromLowest(lowest->second, all_votes, candidate_votes, candidates); unsigned int votes_to_give = candidate_votes[1][*lowest_candidate]; CandidatesVoteMap::iterator to_remove; to_remove = candidate_votes[1].find(*lowest_candidate); if(to_remove == candidate_votes[1].end()){ continue; } candidate_votes[1].erase(to_remove); candidate_votes[1][highest_candidate] += votes_to_give; } } } // if candidates in first position are all tied, they are all winners. if(areCandidatesTied(candidate_votes[1])){ for(CandidatesVoteMap::iterator c = candidate_votes[1].begin(); c != candidate_votes[1].end(); c++){ winners.push_back(c->first); } has_winner = true; } } } // From a map of candidate votes, fill a vector with all the lowest candidates in map. void getLowestCandidates(const CandidatesVoteMap &candidates, CandidatesVector &lowest_candidates){ // get minimum vote unsigned int min(numeric_limits<int>::max()); for(CandidatesVoteMap::const_iterator c = candidates.begin(); c != candidates.end(); c++){ if(c->second < min){ min = c->second; } } // get candidate with minimum vote for(CandidatesVoteMap::const_iterator c = candidates.begin(); c != candidates.end(); c++){ if(c->second == min){ lowest_candidates.push_back(c->first); } } } // Based on the id of the lowest candidate: // Find the votes made to that candidates. // From those votes, find the best existing candidate other than the lowest. // Return that candidate. string getHighestCandidateFromLowest(const unsigned int lowest_candidate, const VotesVector all_votes, VotingMap candidate_votes, const CandidatesVector candidates){ string highest_candidate; // find all votes where the lowest_candidate was vote as 1st candidate and count 2nd votes. CandidatesVoteMap votes; for(int i = 0; i < all_votes.size(); i++){ if(all_votes[i][0] == lowest_candidate){ votes[candidates[all_votes[i][1] - 1]]++; } } bool found(false); while(!found){ highest_candidate = getHighestCandidateFromMap(votes); CandidatesVoteMap::iterator it; it = candidate_votes[1].find(highest_candidate); if(it != candidate_votes[1].end()){ found = true; }else{ CandidatesVoteMap::iterator to_remove; to_remove = votes.find(highest_candidate); votes.erase(to_remove); } } return highest_candidate; } // From a map of candidate votes, return the candidate with the highest votes. string getHighestCandidateFromMap(const CandidatesVoteMap &candidates){ string highest_candidate; unsigned int max(0); for(CandidatesVoteMap::const_iterator c = candidates.begin(); c != candidates.end(); c++){ if(c->second > max){ max = c->second; highest_candidate = c->first; } } return highest_candidate; } // Determine whether all candidates are tied in votes or not based on the candidates votes. bool areCandidatesTied(const CandidatesVoteMap &candidates){ unsigned int value(-1); for(CandidatesVoteMap:: const_iterator c = candidates.begin(); c != candidates.end(); c++){ if(value == -1){ value = c->second; } else { if(value != c->second){ return false; } } } return true; } <|endoftext|>
<commit_before>#ifndef NMEA #define NMEA #include "GPS.hpp" #include <string> using namespace IGVC::Sensors; namespace nmea { //GPS funcs bool decodeGPRMC(const std::string& line, GPSState& state); bool decodeGPRMT(const std::string& line); bool decodeGPGGA(const std::string& line, GPSState& state); bool decodeGPGSA(const std::string& line); bool decodeGPGSV(const std::string& line); void decodeUTCTime(const std::string& val); double decodeLatitude(const std::string& val, const char hemi); double decodeLongitude(const std::string& val, const char hemi); } #endif <commit_msg>Added some basic documentation to nmea header.<commit_after>#ifndef NMEA #define NMEA #include "GPS.hpp" #include <string> using namespace IGVC::Sensors; /** * This namespace contains helper methods for interpreting messages received from devices following the nmea standard. */ namespace nmea { //GPS funcs bool decodeGPRMC(const std::string& line, GPSState& state); bool decodeGPRMT(const std::string& line); bool decodeGPGGA(const std::string& line, GPSState& state); bool decodeGPGSA(const std::string& line); bool decodeGPGSV(const std::string& line); void decodeUTCTime(const std::string& val); double decodeLatitude(const std::string& val, const char hemi); double decodeLongitude(const std::string& val, const char hemi); } #endif <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "FetchManager.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/V8ThrowException.h" #include "core/dom/ExceptionCode.h" #include "core/fetch/FetchUtils.h" #include "core/fileapi/Blob.h" #include "core/frame/csp/ContentSecurityPolicy.h" #include "core/loader/ThreadableLoader.h" #include "core/loader/ThreadableLoaderClient.h" #include "modules/serviceworkers/FetchRequestData.h" #include "modules/serviceworkers/Response.h" #include "modules/serviceworkers/ResponseInit.h" #include "platform/network/ResourceRequest.h" #include "platform/weborigin/SecurityOrigin.h" #include "public/platform/WebURLRequest.h" #include "wtf/HashSet.h" namespace blink { class FetchManager::Loader : public ThreadableLoaderClient { public: Loader(ExecutionContext*, FetchManager*, PassRefPtr<ScriptPromiseResolver>, const FetchRequestData*); ~Loader(); virtual void didReceiveResponse(unsigned long, const ResourceResponse&, PassOwnPtr<WebDataConsumerHandle>); virtual void didFinishLoading(unsigned long, double); virtual void didFail(const ResourceError&); virtual void didFailAccessControlCheck(const ResourceError&); virtual void didFailRedirectCheck(); virtual void didDownloadData(int); void start(); void cleanup(); private: void performBasicFetch(); void performNetworkError(const String& message); void performHTTPFetch(); void failed(const String& message); void notifyFinished(); ExecutionContext* m_executionContext; FetchManager* m_fetchManager; RefPtr<ScriptPromiseResolver> m_resolver; Persistent<FetchRequestData> m_request; RefPtr<ThreadableLoader> m_loader; ResourceResponse m_response; long long m_downloadedBlobLength; bool m_corsFlag; bool m_corsPreflightFlag; bool m_failed; }; FetchManager::Loader::Loader(ExecutionContext* executionContext, FetchManager* fetchManager, PassRefPtr<ScriptPromiseResolver> resolver, const FetchRequestData* request) : m_executionContext(executionContext) , m_fetchManager(fetchManager) , m_resolver(resolver) , m_request(request->createCopy()) , m_downloadedBlobLength(0) , m_corsFlag(false) , m_corsPreflightFlag(false) , m_failed(false) { } FetchManager::Loader::~Loader() { if (m_loader) m_loader->cancel(); } void FetchManager::Loader::didReceiveResponse(unsigned long, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle) { // FIXME: Use |handle|. ASSERT_UNUSED(handle, !handle); m_response = response; } void FetchManager::Loader::didFinishLoading(unsigned long, double) { if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped()) return; OwnPtr<BlobData> blobData = BlobData::create(); String filePath = m_response.downloadedFilePath(); if (!filePath.isEmpty() && m_downloadedBlobLength) { blobData->appendFile(filePath); blobData->setContentType(m_response.mimeType()); } FetchResponseData* response = FetchResponseData::create(); response->setStatus(m_response.httpStatusCode()); response->setStatusMessage(m_response.httpStatusText()); HTTPHeaderMap::const_iterator end = m_response.httpHeaderFields().end(); for (HTTPHeaderMap::const_iterator it = m_response.httpHeaderFields().begin(); it != end; ++it) { response->headerList()->append(it->key, it->value); } response->setBlobDataHandle(BlobDataHandle::create(blobData.release(), m_downloadedBlobLength)); response->setURL(m_request->url()); switch (m_request->tainting()) { case FetchRequestData::BasicTainting: response = response->createBasicFilteredResponse(); break; case FetchRequestData::CORSTainting: response = response->createCORSFilteredResponse(); break; case FetchRequestData::OpaqueTainting: response = response->createOpaqueFilteredResponse(); break; } m_resolver->resolve(Response::create(m_resolver->executionContext(), response)); notifyFinished(); } void FetchManager::Loader::didFail(const ResourceError& error) { failed("Fetch API cannot load " + error.failingURL() + ". " + error.localizedDescription()); } void FetchManager::Loader::didFailAccessControlCheck(const ResourceError& error) { failed("Fetch API cannot load " + error.failingURL() + ". " + error.localizedDescription()); } void FetchManager::Loader::didFailRedirectCheck() { failed("Fetch API cannot load " + m_request->url().string() + ". Redirects are not yet supported."); } void FetchManager::Loader::didDownloadData(int dataLength) { m_downloadedBlobLength += dataLength; } void FetchManager::Loader::start() { // "1. If |request|'s url contains a Known HSTS Host, modify it per the // requirements of the 'URI [sic] Loading and Port Mapping' chapter of HTTP // Strict Transport Security." // FIXME: Implement this. // "2. If |request|'s referrer is not none, set |request|'s referrer to the // result of invoking determine |request|'s referrer." // We set the referrer using workerGlobalScope's URL in // WorkerThreadableLoader. // "3. If |request|'s synchronous flag is unset and fetch is not invoked // recursively, run the remaining steps asynchronously." // We don't support synchronous flag. // "4. Let response be the value corresponding to the first matching // statement:" // "- should fetching |request| be blocked as mixed content returns blocked" // We do mixed content checking in ResourceFetcher. // "- should fetching |request| be blocked as content security returns // blocked" if (!ContentSecurityPolicy::shouldBypassMainWorld(m_executionContext) && !m_executionContext->contentSecurityPolicy()->allowConnectToSource(m_request->url())) { // "A network error." performNetworkError("Refused to connect to '" + m_request->url().elidedString() + "' because it violates the document's Content Security Policy."); return; } // "- |request|'s url's origin is |request|'s origin and the |CORS flag| is // unset" // "- |request|'s url's scheme is 'data' and |request|'s same-origin data // URL flag is set" // "- |request|'s url's scheme is 'about'" if ((SecurityOrigin::create(m_request->url())->isSameSchemeHostPort(m_request->origin().get()) && !m_corsFlag) || (m_request->url().protocolIsData() && m_request->sameOriginDataURLFlag()) || (m_request->url().protocolIsAbout())) { // "The result of performing a basic fetch using request." performBasicFetch(); return; } // "- |request|'s mode is |same-origin|" if (m_request->mode() == WebURLRequest::FetchRequestModeSameOrigin) { // "A network error." performNetworkError("Fetch API cannot load " + m_request->url().string() + ". Request mode is \"same-origin\" but the URL\'s origin is not same as the request origin " + m_request->origin()->toString() + "."); return; } // "- |request|'s mode is |no CORS|" if (m_request->mode() == WebURLRequest::FetchRequestModeNoCORS) { // "Set |request|'s response tainting to |opaque|." m_request->setResponseTainting(FetchRequestData::OpaqueTainting); // "The result of performing a basic fetch using |request|." performBasicFetch(); return; } // "- |request|'s url's scheme is not one of 'http' and 'https'" if (!m_request->url().protocolIsInHTTPFamily()) { // "A network error." performNetworkError("Fetch API cannot load " + m_request->url().string() + ". URL scheme must be \"http\" or \"https\" for CORS request."); return; } // "- |request|'s mode is |CORS-with-forced-preflight|. // "- |request|'s unsafe request flag is set and either |request|'s method // is not a simple method or a header in |request|'s header list is not a // simple header" if (m_request->mode() == WebURLRequest::FetchRequestModeCORSWithForcedPreflight || (m_request->unsafeRequestFlag() && (!FetchUtils::isSimpleMethod(m_request->method()) || m_request->headerList()->containsNonSimpleHeader()))) { // "Set |request|'s response tainting to |CORS|." m_request->setResponseTainting(FetchRequestData::CORSTainting); // "The result of performing an HTTP fetch using |request| with the // |CORS flag| and |CORS preflight flag| set." m_corsFlag = true; m_corsPreflightFlag = true; performHTTPFetch(); return; } // "- Otherwise // Set |request|'s response tainting to |CORS|." m_request->setResponseTainting(FetchRequestData::CORSTainting); // "The result of performing an HTTP fetch using |request| with the // |CORS flag| set." m_corsFlag = true; m_corsPreflightFlag = false; performHTTPFetch(); } void FetchManager::Loader::cleanup() { // Prevent notification m_fetchManager = 0; if (m_loader) { m_loader->cancel(); m_loader.clear(); } } void FetchManager::Loader::performBasicFetch() { // "To perform a basic fetch using |request|, switch on |request|'s url's // scheme, and run the associated steps:" if (m_request->url().protocolIsInHTTPFamily()) { // "Return the result of performing an HTTP fetch using |request|." m_corsFlag = false; m_corsPreflightFlag = false; performHTTPFetch(); } else { // FIXME: implement other protocols. performNetworkError("Fetch API cannot load " + m_request->url().string() + ". URL scheme \"" + m_request->url().protocol() + "\" is not supported."); } } void FetchManager::Loader::performNetworkError(const String& message) { failed(message); } void FetchManager::Loader::performHTTPFetch() { ASSERT(m_request->url().protocolIsInHTTPFamily()); // CORS preflight fetch procedure is implemented inside DocumentThreadableLoader. // "1. Let |HTTPRequest| be a copy of |request|, except that |HTTPRequest|'s // body is a tee of |request|'s body." // We use ResourceRequest class for HTTPRequest. // FIXME: Support body. ResourceRequest request(m_request->url()); request.setRequestContext(WebURLRequest::RequestContextFetch); request.setDownloadToFile(true); request.setHTTPMethod(m_request->method()); const Vector<OwnPtr<FetchHeaderList::Header> >& list = m_request->headerList()->list(); for (size_t i = 0; i < list.size(); ++i) { request.addHTTPHeaderField(AtomicString(list[i]->first), AtomicString(list[i]->second)); } if (m_request->method() != "GET" && m_request->method() != "HEAD") { RefPtr<BlobDataHandle> blobDataHandle = m_request->blobDataHandle(); if (blobDataHandle.get()) { RefPtr<FormData> httpBody(FormData::create()); httpBody->appendBlob(blobDataHandle->uuid(), blobDataHandle); request.setHTTPBody(httpBody); } } // "2. Append `Referer`/empty byte sequence, if |HTTPRequest|'s |referrer| // is none, and `Referer`/|HTTPRequest|'s referrer, serialized and utf-8 // encoded, otherwise, to HTTPRequest's header list. // We set the referrer using workerGlobalScope's URL in // WorkerThreadableLoader. // "3. Append `Host`, ..." // FIXME: Implement this when the spec is fixed. // "4.If |HTTPRequest|'s force Origin header flag is set, append `Origin`/ // |HTTPRequest|'s origin, serialized and utf-8 encoded, to |HTTPRequest|'s // header list." // We set Origin header in updateRequestForAccessControl() called from // DocumentThreadableLoader::makeCrossOriginAccessRequest // "5. Let |credentials flag| be set if either |HTTPRequest|'s credentials // mode is |include|, or |HTTPRequest|'s credentials mode is |same-origin| // and the |CORS flag| is unset, and unset otherwise. ResourceLoaderOptions resourceLoaderOptions; resourceLoaderOptions.dataBufferingPolicy = DoNotBufferData; if (m_request->credentials() == WebURLRequest::FetchCredentialsModeInclude || (m_request->credentials() == WebURLRequest::FetchCredentialsModeSameOrigin && !m_corsFlag)) { resourceLoaderOptions.allowCredentials = AllowStoredCredentials; } ThreadableLoaderOptions threadableLoaderOptions; threadableLoaderOptions.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(m_executionContext) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective; if (m_corsPreflightFlag) threadableLoaderOptions.preflightPolicy = ForcePreflight; if (m_corsFlag) threadableLoaderOptions.crossOriginRequestPolicy = UseAccessControl; else threadableLoaderOptions.crossOriginRequestPolicy = AllowCrossOriginRequests; m_loader = ThreadableLoader::create(*m_executionContext, this, request, threadableLoaderOptions, resourceLoaderOptions); } void FetchManager::Loader::failed(const String& message) { if (m_failed) return; if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped()) return; m_failed = true; ScriptState* state = m_resolver->scriptState(); ScriptState::Scope scope(state); m_resolver->reject(V8ThrowException::createTypeError(state->isolate(), message)); notifyFinished(); } void FetchManager::Loader::notifyFinished() { if (m_fetchManager) m_fetchManager->onLoaderFinished(this); } FetchManager::FetchManager(ExecutionContext* executionContext) : m_executionContext(executionContext) , m_isStopped(false) { } FetchManager::~FetchManager() { if (!m_isStopped) stop(); } ScriptPromise FetchManager::fetch(ScriptState* scriptState, const FetchRequestData* request) { RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); OwnPtr<Loader> ownLoader(adoptPtr(new Loader(m_executionContext, this, resolver.release(), request))); Loader* loader = m_loaders.add(ownLoader.release()).storedValue->get(); loader->start(); return promise; } void FetchManager::stop() { ASSERT(!m_isStopped); m_isStopped = true; for (auto& loader : m_loaders) { loader->cleanup(); } } void FetchManager::onLoaderFinished(Loader* loader) { m_loaders.remove(loader); } } // namespace blink <commit_msg>Speculative fix for Use-after-free in FetchManager.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "FetchManager.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/V8ThrowException.h" #include "core/dom/ExceptionCode.h" #include "core/fetch/FetchUtils.h" #include "core/fileapi/Blob.h" #include "core/frame/csp/ContentSecurityPolicy.h" #include "core/loader/ThreadableLoader.h" #include "core/loader/ThreadableLoaderClient.h" #include "modules/serviceworkers/FetchRequestData.h" #include "modules/serviceworkers/Response.h" #include "modules/serviceworkers/ResponseInit.h" #include "platform/network/ResourceRequest.h" #include "platform/weborigin/SecurityOrigin.h" #include "public/platform/WebURLRequest.h" #include "wtf/HashSet.h" namespace blink { class FetchManager::Loader : public ThreadableLoaderClient { public: Loader(ExecutionContext*, FetchManager*, PassRefPtr<ScriptPromiseResolver>, const FetchRequestData*); ~Loader(); virtual void didReceiveResponse(unsigned long, const ResourceResponse&, PassOwnPtr<WebDataConsumerHandle>); virtual void didFinishLoading(unsigned long, double); virtual void didFail(const ResourceError&); virtual void didFailAccessControlCheck(const ResourceError&); virtual void didFailRedirectCheck(); virtual void didDownloadData(int); void start(); void cleanup(); private: void performBasicFetch(); void performNetworkError(const String& message); void performHTTPFetch(); void failed(const String& message); void notifyFinished(); ExecutionContext* m_executionContext; FetchManager* m_fetchManager; RefPtr<ScriptPromiseResolver> m_resolver; Persistent<FetchRequestData> m_request; RefPtr<ThreadableLoader> m_loader; ResourceResponse m_response; long long m_downloadedBlobLength; bool m_corsFlag; bool m_corsPreflightFlag; bool m_failed; }; FetchManager::Loader::Loader(ExecutionContext* executionContext, FetchManager* fetchManager, PassRefPtr<ScriptPromiseResolver> resolver, const FetchRequestData* request) : m_executionContext(executionContext) , m_fetchManager(fetchManager) , m_resolver(resolver) , m_request(request->createCopy()) , m_downloadedBlobLength(0) , m_corsFlag(false) , m_corsPreflightFlag(false) , m_failed(false) { } FetchManager::Loader::~Loader() { if (m_loader) m_loader->cancel(); } void FetchManager::Loader::didReceiveResponse(unsigned long, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle) { // FIXME: Use |handle|. ASSERT_UNUSED(handle, !handle); m_response = response; } void FetchManager::Loader::didFinishLoading(unsigned long, double) { if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped()) return; OwnPtr<BlobData> blobData = BlobData::create(); String filePath = m_response.downloadedFilePath(); if (!filePath.isEmpty() && m_downloadedBlobLength) { blobData->appendFile(filePath); blobData->setContentType(m_response.mimeType()); } FetchResponseData* response = FetchResponseData::create(); response->setStatus(m_response.httpStatusCode()); response->setStatusMessage(m_response.httpStatusText()); HTTPHeaderMap::const_iterator end = m_response.httpHeaderFields().end(); for (HTTPHeaderMap::const_iterator it = m_response.httpHeaderFields().begin(); it != end; ++it) { response->headerList()->append(it->key, it->value); } response->setBlobDataHandle(BlobDataHandle::create(blobData.release(), m_downloadedBlobLength)); response->setURL(m_request->url()); switch (m_request->tainting()) { case FetchRequestData::BasicTainting: response = response->createBasicFilteredResponse(); break; case FetchRequestData::CORSTainting: response = response->createCORSFilteredResponse(); break; case FetchRequestData::OpaqueTainting: response = response->createOpaqueFilteredResponse(); break; } m_resolver->resolve(Response::create(m_resolver->executionContext(), response)); notifyFinished(); } void FetchManager::Loader::didFail(const ResourceError& error) { failed("Fetch API cannot load " + error.failingURL() + ". " + error.localizedDescription()); } void FetchManager::Loader::didFailAccessControlCheck(const ResourceError& error) { failed("Fetch API cannot load " + error.failingURL() + ". " + error.localizedDescription()); } void FetchManager::Loader::didFailRedirectCheck() { failed("Fetch API cannot load " + m_request->url().string() + ". Redirects are not yet supported."); } void FetchManager::Loader::didDownloadData(int dataLength) { m_downloadedBlobLength += dataLength; } void FetchManager::Loader::start() { // "1. If |request|'s url contains a Known HSTS Host, modify it per the // requirements of the 'URI [sic] Loading and Port Mapping' chapter of HTTP // Strict Transport Security." // FIXME: Implement this. // "2. If |request|'s referrer is not none, set |request|'s referrer to the // result of invoking determine |request|'s referrer." // We set the referrer using workerGlobalScope's URL in // WorkerThreadableLoader. // "3. If |request|'s synchronous flag is unset and fetch is not invoked // recursively, run the remaining steps asynchronously." // We don't support synchronous flag. // "4. Let response be the value corresponding to the first matching // statement:" // "- should fetching |request| be blocked as mixed content returns blocked" // We do mixed content checking in ResourceFetcher. // "- should fetching |request| be blocked as content security returns // blocked" if (!ContentSecurityPolicy::shouldBypassMainWorld(m_executionContext) && !m_executionContext->contentSecurityPolicy()->allowConnectToSource(m_request->url())) { // "A network error." performNetworkError("Refused to connect to '" + m_request->url().elidedString() + "' because it violates the document's Content Security Policy."); return; } // "- |request|'s url's origin is |request|'s origin and the |CORS flag| is // unset" // "- |request|'s url's scheme is 'data' and |request|'s same-origin data // URL flag is set" // "- |request|'s url's scheme is 'about'" if ((SecurityOrigin::create(m_request->url())->isSameSchemeHostPort(m_request->origin().get()) && !m_corsFlag) || (m_request->url().protocolIsData() && m_request->sameOriginDataURLFlag()) || (m_request->url().protocolIsAbout())) { // "The result of performing a basic fetch using request." performBasicFetch(); return; } // "- |request|'s mode is |same-origin|" if (m_request->mode() == WebURLRequest::FetchRequestModeSameOrigin) { // "A network error." performNetworkError("Fetch API cannot load " + m_request->url().string() + ". Request mode is \"same-origin\" but the URL\'s origin is not same as the request origin " + m_request->origin()->toString() + "."); return; } // "- |request|'s mode is |no CORS|" if (m_request->mode() == WebURLRequest::FetchRequestModeNoCORS) { // "Set |request|'s response tainting to |opaque|." m_request->setResponseTainting(FetchRequestData::OpaqueTainting); // "The result of performing a basic fetch using |request|." performBasicFetch(); return; } // "- |request|'s url's scheme is not one of 'http' and 'https'" if (!m_request->url().protocolIsInHTTPFamily()) { // "A network error." performNetworkError("Fetch API cannot load " + m_request->url().string() + ". URL scheme must be \"http\" or \"https\" for CORS request."); return; } // "- |request|'s mode is |CORS-with-forced-preflight|. // "- |request|'s unsafe request flag is set and either |request|'s method // is not a simple method or a header in |request|'s header list is not a // simple header" if (m_request->mode() == WebURLRequest::FetchRequestModeCORSWithForcedPreflight || (m_request->unsafeRequestFlag() && (!FetchUtils::isSimpleMethod(m_request->method()) || m_request->headerList()->containsNonSimpleHeader()))) { // "Set |request|'s response tainting to |CORS|." m_request->setResponseTainting(FetchRequestData::CORSTainting); // "The result of performing an HTTP fetch using |request| with the // |CORS flag| and |CORS preflight flag| set." m_corsFlag = true; m_corsPreflightFlag = true; performHTTPFetch(); return; } // "- Otherwise // Set |request|'s response tainting to |CORS|." m_request->setResponseTainting(FetchRequestData::CORSTainting); // "The result of performing an HTTP fetch using |request| with the // |CORS flag| set." m_corsFlag = true; m_corsPreflightFlag = false; performHTTPFetch(); } void FetchManager::Loader::cleanup() { // Prevent notification m_fetchManager = 0; if (m_loader) { m_loader->cancel(); m_loader.clear(); } } void FetchManager::Loader::performBasicFetch() { // "To perform a basic fetch using |request|, switch on |request|'s url's // scheme, and run the associated steps:" if (m_request->url().protocolIsInHTTPFamily()) { // "Return the result of performing an HTTP fetch using |request|." m_corsFlag = false; m_corsPreflightFlag = false; performHTTPFetch(); } else { // FIXME: implement other protocols. performNetworkError("Fetch API cannot load " + m_request->url().string() + ". URL scheme \"" + m_request->url().protocol() + "\" is not supported."); } } void FetchManager::Loader::performNetworkError(const String& message) { failed(message); } void FetchManager::Loader::performHTTPFetch() { ASSERT(m_request->url().protocolIsInHTTPFamily()); // CORS preflight fetch procedure is implemented inside DocumentThreadableLoader. // "1. Let |HTTPRequest| be a copy of |request|, except that |HTTPRequest|'s // body is a tee of |request|'s body." // We use ResourceRequest class for HTTPRequest. // FIXME: Support body. ResourceRequest request(m_request->url()); request.setRequestContext(WebURLRequest::RequestContextFetch); request.setDownloadToFile(true); request.setHTTPMethod(m_request->method()); const Vector<OwnPtr<FetchHeaderList::Header> >& list = m_request->headerList()->list(); for (size_t i = 0; i < list.size(); ++i) { request.addHTTPHeaderField(AtomicString(list[i]->first), AtomicString(list[i]->second)); } if (m_request->method() != "GET" && m_request->method() != "HEAD") { RefPtr<BlobDataHandle> blobDataHandle = m_request->blobDataHandle(); if (blobDataHandle.get()) { RefPtr<FormData> httpBody(FormData::create()); httpBody->appendBlob(blobDataHandle->uuid(), blobDataHandle); request.setHTTPBody(httpBody); } } // "2. Append `Referer`/empty byte sequence, if |HTTPRequest|'s |referrer| // is none, and `Referer`/|HTTPRequest|'s referrer, serialized and utf-8 // encoded, otherwise, to HTTPRequest's header list. // We set the referrer using workerGlobalScope's URL in // WorkerThreadableLoader. // "3. Append `Host`, ..." // FIXME: Implement this when the spec is fixed. // "4.If |HTTPRequest|'s force Origin header flag is set, append `Origin`/ // |HTTPRequest|'s origin, serialized and utf-8 encoded, to |HTTPRequest|'s // header list." // We set Origin header in updateRequestForAccessControl() called from // DocumentThreadableLoader::makeCrossOriginAccessRequest // "5. Let |credentials flag| be set if either |HTTPRequest|'s credentials // mode is |include|, or |HTTPRequest|'s credentials mode is |same-origin| // and the |CORS flag| is unset, and unset otherwise. ResourceLoaderOptions resourceLoaderOptions; resourceLoaderOptions.dataBufferingPolicy = DoNotBufferData; if (m_request->credentials() == WebURLRequest::FetchCredentialsModeInclude || (m_request->credentials() == WebURLRequest::FetchCredentialsModeSameOrigin && !m_corsFlag)) { resourceLoaderOptions.allowCredentials = AllowStoredCredentials; } ThreadableLoaderOptions threadableLoaderOptions; threadableLoaderOptions.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(m_executionContext) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective; if (m_corsPreflightFlag) threadableLoaderOptions.preflightPolicy = ForcePreflight; if (m_corsFlag) threadableLoaderOptions.crossOriginRequestPolicy = UseAccessControl; else threadableLoaderOptions.crossOriginRequestPolicy = AllowCrossOriginRequests; m_loader = ThreadableLoader::create(*m_executionContext, this, request, threadableLoaderOptions, resourceLoaderOptions); } void FetchManager::Loader::failed(const String& message) { if (m_failed) return; if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped()) return; m_failed = true; ScriptState* state = m_resolver->scriptState(); ScriptState::Scope scope(state); m_resolver->reject(V8ThrowException::createTypeError(state->isolate(), message)); notifyFinished(); } void FetchManager::Loader::notifyFinished() { if (m_fetchManager) m_fetchManager->onLoaderFinished(this); } FetchManager::FetchManager(ExecutionContext* executionContext) : m_executionContext(executionContext) , m_isStopped(false) { } FetchManager::~FetchManager() { if (!m_isStopped) stop(); } ScriptPromise FetchManager::fetch(ScriptState* scriptState, const FetchRequestData* request) { RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); OwnPtr<Loader> ownLoader(adoptPtr(new Loader(m_executionContext, this, resolver.release(), request))); Loader* loader = m_loaders.add(ownLoader.release()).storedValue->get(); loader->start(); return promise; } void FetchManager::stop() { ASSERT(!m_isStopped); m_isStopped = true; for (auto& loader : m_loaders) { loader->cleanup(); } } void FetchManager::onLoaderFinished(Loader* loader) { // We don't use remove here, becuase it may cause recursive deletion. OwnPtr<Loader> p = m_loaders.take(loader); } } // namespace blink <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkThreadedController.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkThreadedController.h" #include "vtkObjectFactory.h" #include "vtkDataSet.h" #include "vtkImageData.h" #include "vtkMultiThreader.h" #include "vtkOutputWindow.h" #include "vtkCriticalSection.h" #include "vtkSharedMemoryCommunicator.h" #ifdef VTK_USE_SPROC #include <sys/prctl.h> #endif static vtkSimpleCriticalSection vtkOutputWindowCritSect; // Output window which prints out the process id // with the error or warning messages class VTK_PARALLEL_EXPORT vtkThreadedControllerOutputWindow : public vtkOutputWindow { public: vtkTypeRevisionMacro(vtkThreadedControllerOutputWindow,vtkOutputWindow); void DisplayText(const char* t) { // Need to use critical section because the output window // is global. For the same reason, the process id has to // be obtained by calling GetGlobalController vtkOutputWindowCritSect.Lock(); vtkMultiProcessController* cont = vtkMultiProcessController::GetGlobalController(); if (cont) { cout << "Process id: " << cont->GetLocalProcessId() << " >> "; } cout << t; cout.flush(); vtkOutputWindowCritSect.Unlock(); } vtkThreadedControllerOutputWindow() { vtkObject* ret = vtkObjectFactory::CreateInstance("vtkThreadedControllerOutputWindow"); if (ret) ret->Delete(); } friend class vtkThreadedController; private: vtkThreadedControllerOutputWindow(const vtkThreadedControllerOutputWindow&); void operator=(const vtkThreadedControllerOutputWindow&); }; vtkCxxRevisionMacro(vtkThreadedControllerOutputWindow, "1.19"); vtkCxxRevisionMacro(vtkThreadedController, "1.19"); vtkStandardNewMacro(vtkThreadedController); void vtkThreadedController::CreateOutputWindow() { #if defined(VTK_USE_PTHREADS) || defined(VTK_USE_SPROC) || defined(VTK_USE_WIN32_THREADS) vtkThreadedControllerOutputWindow* window = new vtkThreadedControllerOutputWindow; this->OutputWindow = window; vtkOutputWindow::SetInstance(this->OutputWindow); #endif } //---------------------------------------------------------------------------- vtkThreadedController::vtkThreadedController() { this->LocalProcessId = 0; vtkMultiThreader::SetGlobalMaximumNumberOfThreads(0); this->MultiThreader = 0; this->NumberOfProcesses = 0; this->MultipleMethodFlag = 0; this->LastNumberOfProcesses = 0; this->Controllers = 0; this->OutputWindow = 0; } //---------------------------------------------------------------------------- vtkThreadedController::~vtkThreadedController() { if (this->MultiThreader) { this->MultiThreader->Delete(); } if(this->Communicator) { this->Communicator->Delete(); } this->NumberOfProcesses = 0; this->ResetControllers(); } //---------------------------------------------------------------------------- void vtkThreadedController::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if (this->MultiThreader) { os << indent << "MultiThreader:\n"; this->MultiThreader->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "MultiThreader: (none)\n"; } os << indent << "LocalProcessId: " << this->LocalProcessId << endl; os << indent << "Barrier in progress: " << (vtkThreadedController::IsBarrierInProgress ? "(yes)" : "(no)") << endl; os << indent << "Barrier counter: " << vtkThreadedController::Counter << endl; os << indent << "Last number of processes: " << this->LastNumberOfProcesses << endl; } //---------------------------------------------------------------------------- void vtkThreadedController::Initialize(int* vtkNotUsed(argc), char*** vtkNotUsed(argv)) { if ( !vtkThreadedController::BarrierLock ) { vtkThreadedController::BarrierLock = new vtkSimpleCriticalSection(1); } if ( !vtkThreadedController::BarrierInProgress) { vtkThreadedController::BarrierInProgress = new vtkSimpleCriticalSection; } } void vtkThreadedController::Finalize() { if (vtkThreadedController::BarrierLock) { vtkThreadedController::BarrierLock->Unlock(); } delete vtkThreadedController::BarrierLock; vtkThreadedController::BarrierLock = 0; delete vtkThreadedController::BarrierInProgress; vtkThreadedController::BarrierInProgress = 0; } void vtkThreadedController::ResetControllers() { int i; for(i=1; i < this->LastNumberOfProcesses; i++) { this->Controllers[i]->Delete(); } if (this->NumberOfProcesses == this->LastNumberOfProcesses) { return; } delete[] this->Controllers; if (this->NumberOfProcesses > 0 ) { this->Controllers = new vtkThreadedController*[this->NumberOfProcesses]; } } //---------------------------------------------------------------------------- // Called before threads are spawned to create the "process objecs". void vtkThreadedController::CreateProcessControllers() { // Delete previous controllers. this->ResetControllers(); // Create the controllers. // The original controller will be assigned thread 0. this->Controllers[0] = this; this->LocalProcessId = 0; // Create a new communicator. if (this->Communicator) { this->Communicator->Delete(); } this->Communicator = vtkSharedMemoryCommunicator::New(); ((vtkSharedMemoryCommunicator*)this->Communicator)->Initialize( this->NumberOfProcesses, this->ForceDeepCopy); this->RMICommunicator = this->Communicator; // Initialize the new controllers. for (int i = 1; i < this->NumberOfProcesses; ++i) { this->Controllers[i] = vtkThreadedController::New(); this->Controllers[i]->LocalProcessId = i; this->Controllers[i]->NumberOfProcesses = this->NumberOfProcesses; this->Controllers[i]->Communicator = ((vtkSharedMemoryCommunicator*)this->Communicator)->Communicators[i]; this->Controllers[i]->RMICommunicator = ((vtkSharedMemoryCommunicator*)this->RMICommunicator)->Communicators[i]; } // Stored in case someone changes the number of processes. // Needed to delete the controllers properly. this->LastNumberOfProcesses = this->NumberOfProcesses; } vtkSimpleCriticalSection vtkThreadedController::CounterLock; int vtkThreadedController::Counter; #ifdef VTK_USE_WIN32_THREADS HANDLE vtkThreadedController::BarrierEndedEvent = 0; HANDLE vtkThreadedController::NextThread = 0; #else //vtkSimpleCriticalSection vtkThreadedController::BarrierLock(1); //vtkSimpleCriticalSection vtkThreadedController::BarrierInProgress; vtkSimpleCriticalSection* vtkThreadedController::BarrierLock = 0; vtkSimpleCriticalSection* vtkThreadedController::BarrierInProgress = 0; #endif int vtkThreadedController::IsBarrierInProgress=0; void vtkThreadedController::Barrier() { if (this->NumberOfProcesses == 0) { return; } #ifndef VTK_USE_WIN32_THREADS if (!vtkThreadedController::BarrierLock || !vtkThreadedController::BarrierInProgress) { vtkErrorMacro("Barrier was called without initializing threads. " "Please call Initialize first. Skipping barrier."); return; } #endif vtkThreadedController::InitializeBarrier(); // If there was a barrier before this one, we need to // wait until that is cleaned up if (vtkThreadedController::IsBarrierInProgress) { vtkThreadedController::WaitForPreviousBarrierToEnd(); } #ifdef VTK_USE_WIN32_THREADS else { ResetEvent(vtkThreadedController::BarrierEndedEvent); } #endif // All processes increment the counter (which is initially 0) by 1 vtkThreadedController::CounterLock.Lock(); int count = ++vtkThreadedController::Counter; vtkThreadedController::CounterLock.Unlock(); if (count == this->NumberOfProcesses) { // If you are the last process, unlock the barrier vtkThreadedController::BarrierStarted(); vtkThreadedController::SignalNextThread(); } else { // If you are not the last process, wait until someone unlocks // the barrier vtkThreadedController::WaitForNextThread(); vtkThreadedController::CounterLock.Lock(); vtkThreadedController::Counter--; vtkThreadedController::CounterLock.Unlock(); if (vtkThreadedController::Counter == 1) { // If you are the last process to pass the barrier // Set the counter to 0 and leave the barrier locked vtkThreadedController::Counter = 0; // Barrier is over, another one can start vtkThreadedController::BarrierEnded(); } else { // unlock the barrier for the next guy vtkThreadedController::SignalNextThread(); } } } //---------------------------------------------------------------------------- VTK_THREAD_RETURN_TYPE vtkThreadedController::vtkThreadedControllerStart( void *arg ) { vtkMultiThreader::ThreadInfo* info = (vtkMultiThreader::ThreadInfo*)(arg); int threadId = info->ThreadID; vtkThreadedController *controller0 =(vtkThreadedController*)(info->UserData); controller0->Start(threadId); return VTK_THREAD_RETURN_VALUE; } //---------------------------------------------------------------------------- // We are going to try something new. We will pass the local controller // as the argument. void vtkThreadedController::Start(int threadId) { vtkThreadedController* localController = this->Controllers[threadId]; // Store threadId in a table. #ifdef VTK_USE_PTHREADS localController->ThreadId = pthread_self(); #elif defined VTK_USE_SPROC localController->ThreadId = PRDA->sys_prda.prda_sys.t_pid; #elif defined VTK_USE_WIN32_THREADS localController->ThreadId = GetCurrentThreadId(); #endif this->Barrier(); if (this->MultipleMethodFlag) { if (this->MultipleMethod[threadId]) { (this->MultipleMethod[threadId])(localController, this->MultipleData[threadId]); } else { vtkWarningMacro("MultipleMethod " << threadId << " not set"); } } else { if (this->SingleMethod) { (this->SingleMethod)(localController, this->SingleData); } else { vtkErrorMacro("SingleMethod not set"); } } } //---------------------------------------------------------------------------- // Execute the method set as the SingleMethod on NumberOfThreads threads. void vtkThreadedController::SingleMethodExecute() { if (!this->MultiThreader) { this->MultiThreader = vtkMultiThreader::New(); } this->CreateProcessControllers(); this->MultipleMethodFlag = 0; this->MultiThreader->SetSingleMethod(vtkThreadedControllerStart, (void*)this); this->MultiThreader->SetNumberOfThreads(this->NumberOfProcesses); // GLOBAL_CONTROLLER will be from thread0 always. // GetLocalController will translate to the local controller. vtkMultiProcessController::SetGlobalController(this); this->MultiThreader->SingleMethodExecute(); } //---------------------------------------------------------------------------- // Execute the methods set as the MultipleMethods. void vtkThreadedController::MultipleMethodExecute() { if (!this->MultiThreader) { this->MultiThreader = vtkMultiThreader::New(); } this->CreateProcessControllers(); this->MultipleMethodFlag = 1; this->MultiThreader->SetSingleMethod(vtkThreadedControllerStart, (void*)this); this->MultiThreader->SetNumberOfThreads(this->NumberOfProcesses); // GLOBAL_CONTROLLER will be from thread0 always. // GetLocalController will translate to the local controller. vtkMultiProcessController::SetGlobalController(this); this->MultiThreader->SingleMethodExecute(); } vtkMultiProcessController *vtkThreadedController::GetLocalController() { #ifdef VTK_USE_PTHREADS int idx; pthread_t pid = pthread_self(); for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pthread_equal(pid, this->Controllers[idx]->ThreadId)) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #elif defined VTK_USE_SPROC int idx; pid_t pid = PRDA->sys_prda.prda_sys.t_pid; for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pid == this->Controllers[idx]->ThreadId) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #elif defined VTK_USE_WIN32_THREADS int idx; DWORD pid = GetCurrentThreadId(); for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pid == this->Controllers[idx]->ThreadId) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #else vtkErrorMacro( "ThreadedController only works with windows api, pthreads or sproc"); return this; #endif } // Note that the Windows and Unix implementations of // these methods are completely different. This is because, // in Windows, if the same thread locks the same mutex/critical // section twice, it will not block. Therefore, this method // can not be used to make the threads wait until all of them // reach the barrier // If there was a barrier before this one, we need to // wait until that is cleaned up or bad things happen. void vtkThreadedController::WaitForPreviousBarrierToEnd() { #ifdef VTK_USE_WIN32_THREADS WaitForSingleObject(vtkThreadedController::BarrierEndedEvent, INFINITE); #else vtkThreadedController::BarrierInProgress->Lock(); vtkThreadedController::BarrierInProgress->Unlock(); #endif } void vtkThreadedController::BarrierStarted() { vtkThreadedController::IsBarrierInProgress = 1; #ifdef VTK_USE_WIN32_THREADS #else vtkThreadedController::BarrierInProgress->Lock(); #endif } // A new barrier can now start void vtkThreadedController::BarrierEnded() { vtkThreadedController::IsBarrierInProgress = 0; #ifdef VTK_USE_WIN32_THREADS SetEvent(vtkThreadedController::BarrierEndedEvent); #else vtkThreadedController::BarrierInProgress->Unlock(); #endif } // Tell the next guy that it is ok to continue with the barrier void vtkThreadedController::SignalNextThread() { #ifdef VTK_USE_WIN32_THREADS SetEvent(vtkThreadedController::NextThread); #else vtkThreadedController::BarrierLock->Unlock(); #endif } // Create the windows event necessary for waiting void vtkThreadedController::InitializeBarrier() { #ifdef VTK_USE_WIN32_THREADS if (!BarrierEndedEvent) { vtkThreadedController::BarrierEndedEvent = CreateEvent(0,FALSE,FALSE,0); vtkThreadedController::NextThread = CreateEvent(0,FALSE,FALSE,0); } #endif } // Wait until the previous thread says it's ok to continue void vtkThreadedController::WaitForNextThread() { #ifdef VTK_USE_WIN32_THREADS WaitForSingleObject(vtkThreadedController::NextThread,INFINITE); #else vtkThreadedController::BarrierLock->Lock(); #endif } <commit_msg>Left out a ifndef<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkThreadedController.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkThreadedController.h" #include "vtkObjectFactory.h" #include "vtkDataSet.h" #include "vtkImageData.h" #include "vtkMultiThreader.h" #include "vtkOutputWindow.h" #include "vtkCriticalSection.h" #include "vtkSharedMemoryCommunicator.h" #ifdef VTK_USE_SPROC #include <sys/prctl.h> #endif static vtkSimpleCriticalSection vtkOutputWindowCritSect; // Output window which prints out the process id // with the error or warning messages class VTK_PARALLEL_EXPORT vtkThreadedControllerOutputWindow : public vtkOutputWindow { public: vtkTypeRevisionMacro(vtkThreadedControllerOutputWindow,vtkOutputWindow); void DisplayText(const char* t) { // Need to use critical section because the output window // is global. For the same reason, the process id has to // be obtained by calling GetGlobalController vtkOutputWindowCritSect.Lock(); vtkMultiProcessController* cont = vtkMultiProcessController::GetGlobalController(); if (cont) { cout << "Process id: " << cont->GetLocalProcessId() << " >> "; } cout << t; cout.flush(); vtkOutputWindowCritSect.Unlock(); } vtkThreadedControllerOutputWindow() { vtkObject* ret = vtkObjectFactory::CreateInstance("vtkThreadedControllerOutputWindow"); if (ret) ret->Delete(); } friend class vtkThreadedController; private: vtkThreadedControllerOutputWindow(const vtkThreadedControllerOutputWindow&); void operator=(const vtkThreadedControllerOutputWindow&); }; vtkCxxRevisionMacro(vtkThreadedControllerOutputWindow, "1.20"); vtkCxxRevisionMacro(vtkThreadedController, "1.20"); vtkStandardNewMacro(vtkThreadedController); void vtkThreadedController::CreateOutputWindow() { #if defined(VTK_USE_PTHREADS) || defined(VTK_USE_SPROC) || defined(VTK_USE_WIN32_THREADS) vtkThreadedControllerOutputWindow* window = new vtkThreadedControllerOutputWindow; this->OutputWindow = window; vtkOutputWindow::SetInstance(this->OutputWindow); #endif } //---------------------------------------------------------------------------- vtkThreadedController::vtkThreadedController() { this->LocalProcessId = 0; vtkMultiThreader::SetGlobalMaximumNumberOfThreads(0); this->MultiThreader = 0; this->NumberOfProcesses = 0; this->MultipleMethodFlag = 0; this->LastNumberOfProcesses = 0; this->Controllers = 0; this->OutputWindow = 0; } //---------------------------------------------------------------------------- vtkThreadedController::~vtkThreadedController() { if (this->MultiThreader) { this->MultiThreader->Delete(); } if(this->Communicator) { this->Communicator->Delete(); } this->NumberOfProcesses = 0; this->ResetControllers(); } //---------------------------------------------------------------------------- void vtkThreadedController::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if (this->MultiThreader) { os << indent << "MultiThreader:\n"; this->MultiThreader->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "MultiThreader: (none)\n"; } os << indent << "LocalProcessId: " << this->LocalProcessId << endl; os << indent << "Barrier in progress: " << (vtkThreadedController::IsBarrierInProgress ? "(yes)" : "(no)") << endl; os << indent << "Barrier counter: " << vtkThreadedController::Counter << endl; os << indent << "Last number of processes: " << this->LastNumberOfProcesses << endl; } //---------------------------------------------------------------------------- void vtkThreadedController::Initialize(int* vtkNotUsed(argc), char*** vtkNotUsed(argv)) { #ifndef VTK_USE_WIN32_THREADS if ( !vtkThreadedController::BarrierLock ) { vtkThreadedController::BarrierLock = new vtkSimpleCriticalSection(1); } if ( !vtkThreadedController::BarrierInProgress) { vtkThreadedController::BarrierInProgress = new vtkSimpleCriticalSection; } #endif } void vtkThreadedController::Finalize() { #ifndef VTK_USE_WIN32_THREADS if (vtkThreadedController::BarrierLock) { vtkThreadedController::BarrierLock->Unlock(); } delete vtkThreadedController::BarrierLock; vtkThreadedController::BarrierLock = 0; delete vtkThreadedController::BarrierInProgress; vtkThreadedController::BarrierInProgress = 0; #endif } void vtkThreadedController::ResetControllers() { int i; for(i=1; i < this->LastNumberOfProcesses; i++) { this->Controllers[i]->Delete(); } if (this->NumberOfProcesses == this->LastNumberOfProcesses) { return; } delete[] this->Controllers; if (this->NumberOfProcesses > 0 ) { this->Controllers = new vtkThreadedController*[this->NumberOfProcesses]; } } //---------------------------------------------------------------------------- // Called before threads are spawned to create the "process objecs". void vtkThreadedController::CreateProcessControllers() { // Delete previous controllers. this->ResetControllers(); // Create the controllers. // The original controller will be assigned thread 0. this->Controllers[0] = this; this->LocalProcessId = 0; // Create a new communicator. if (this->Communicator) { this->Communicator->Delete(); } this->Communicator = vtkSharedMemoryCommunicator::New(); ((vtkSharedMemoryCommunicator*)this->Communicator)->Initialize( this->NumberOfProcesses, this->ForceDeepCopy); this->RMICommunicator = this->Communicator; // Initialize the new controllers. for (int i = 1; i < this->NumberOfProcesses; ++i) { this->Controllers[i] = vtkThreadedController::New(); this->Controllers[i]->LocalProcessId = i; this->Controllers[i]->NumberOfProcesses = this->NumberOfProcesses; this->Controllers[i]->Communicator = ((vtkSharedMemoryCommunicator*)this->Communicator)->Communicators[i]; this->Controllers[i]->RMICommunicator = ((vtkSharedMemoryCommunicator*)this->RMICommunicator)->Communicators[i]; } // Stored in case someone changes the number of processes. // Needed to delete the controllers properly. this->LastNumberOfProcesses = this->NumberOfProcesses; } vtkSimpleCriticalSection vtkThreadedController::CounterLock; int vtkThreadedController::Counter; #ifdef VTK_USE_WIN32_THREADS HANDLE vtkThreadedController::BarrierEndedEvent = 0; HANDLE vtkThreadedController::NextThread = 0; #else //vtkSimpleCriticalSection vtkThreadedController::BarrierLock(1); //vtkSimpleCriticalSection vtkThreadedController::BarrierInProgress; vtkSimpleCriticalSection* vtkThreadedController::BarrierLock = 0; vtkSimpleCriticalSection* vtkThreadedController::BarrierInProgress = 0; #endif int vtkThreadedController::IsBarrierInProgress=0; void vtkThreadedController::Barrier() { if (this->NumberOfProcesses == 0) { return; } #ifndef VTK_USE_WIN32_THREADS if (!vtkThreadedController::BarrierLock || !vtkThreadedController::BarrierInProgress) { vtkErrorMacro("Barrier was called without initializing threads. " "Please call Initialize first. Skipping barrier."); return; } #endif vtkThreadedController::InitializeBarrier(); // If there was a barrier before this one, we need to // wait until that is cleaned up if (vtkThreadedController::IsBarrierInProgress) { vtkThreadedController::WaitForPreviousBarrierToEnd(); } #ifdef VTK_USE_WIN32_THREADS else { ResetEvent(vtkThreadedController::BarrierEndedEvent); } #endif // All processes increment the counter (which is initially 0) by 1 vtkThreadedController::CounterLock.Lock(); int count = ++vtkThreadedController::Counter; vtkThreadedController::CounterLock.Unlock(); if (count == this->NumberOfProcesses) { // If you are the last process, unlock the barrier vtkThreadedController::BarrierStarted(); vtkThreadedController::SignalNextThread(); } else { // If you are not the last process, wait until someone unlocks // the barrier vtkThreadedController::WaitForNextThread(); vtkThreadedController::CounterLock.Lock(); vtkThreadedController::Counter--; vtkThreadedController::CounterLock.Unlock(); if (vtkThreadedController::Counter == 1) { // If you are the last process to pass the barrier // Set the counter to 0 and leave the barrier locked vtkThreadedController::Counter = 0; // Barrier is over, another one can start vtkThreadedController::BarrierEnded(); } else { // unlock the barrier for the next guy vtkThreadedController::SignalNextThread(); } } } //---------------------------------------------------------------------------- VTK_THREAD_RETURN_TYPE vtkThreadedController::vtkThreadedControllerStart( void *arg ) { vtkMultiThreader::ThreadInfo* info = (vtkMultiThreader::ThreadInfo*)(arg); int threadId = info->ThreadID; vtkThreadedController *controller0 =(vtkThreadedController*)(info->UserData); controller0->Start(threadId); return VTK_THREAD_RETURN_VALUE; } //---------------------------------------------------------------------------- // We are going to try something new. We will pass the local controller // as the argument. void vtkThreadedController::Start(int threadId) { vtkThreadedController* localController = this->Controllers[threadId]; // Store threadId in a table. #ifdef VTK_USE_PTHREADS localController->ThreadId = pthread_self(); #elif defined VTK_USE_SPROC localController->ThreadId = PRDA->sys_prda.prda_sys.t_pid; #elif defined VTK_USE_WIN32_THREADS localController->ThreadId = GetCurrentThreadId(); #endif this->Barrier(); if (this->MultipleMethodFlag) { if (this->MultipleMethod[threadId]) { (this->MultipleMethod[threadId])(localController, this->MultipleData[threadId]); } else { vtkWarningMacro("MultipleMethod " << threadId << " not set"); } } else { if (this->SingleMethod) { (this->SingleMethod)(localController, this->SingleData); } else { vtkErrorMacro("SingleMethod not set"); } } } //---------------------------------------------------------------------------- // Execute the method set as the SingleMethod on NumberOfThreads threads. void vtkThreadedController::SingleMethodExecute() { if (!this->MultiThreader) { this->MultiThreader = vtkMultiThreader::New(); } this->CreateProcessControllers(); this->MultipleMethodFlag = 0; this->MultiThreader->SetSingleMethod(vtkThreadedControllerStart, (void*)this); this->MultiThreader->SetNumberOfThreads(this->NumberOfProcesses); // GLOBAL_CONTROLLER will be from thread0 always. // GetLocalController will translate to the local controller. vtkMultiProcessController::SetGlobalController(this); this->MultiThreader->SingleMethodExecute(); } //---------------------------------------------------------------------------- // Execute the methods set as the MultipleMethods. void vtkThreadedController::MultipleMethodExecute() { if (!this->MultiThreader) { this->MultiThreader = vtkMultiThreader::New(); } this->CreateProcessControllers(); this->MultipleMethodFlag = 1; this->MultiThreader->SetSingleMethod(vtkThreadedControllerStart, (void*)this); this->MultiThreader->SetNumberOfThreads(this->NumberOfProcesses); // GLOBAL_CONTROLLER will be from thread0 always. // GetLocalController will translate to the local controller. vtkMultiProcessController::SetGlobalController(this); this->MultiThreader->SingleMethodExecute(); } vtkMultiProcessController *vtkThreadedController::GetLocalController() { #ifdef VTK_USE_PTHREADS int idx; pthread_t pid = pthread_self(); for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pthread_equal(pid, this->Controllers[idx]->ThreadId)) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #elif defined VTK_USE_SPROC int idx; pid_t pid = PRDA->sys_prda.prda_sys.t_pid; for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pid == this->Controllers[idx]->ThreadId) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #elif defined VTK_USE_WIN32_THREADS int idx; DWORD pid = GetCurrentThreadId(); for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pid == this->Controllers[idx]->ThreadId) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #else vtkErrorMacro( "ThreadedController only works with windows api, pthreads or sproc"); return this; #endif } // Note that the Windows and Unix implementations of // these methods are completely different. This is because, // in Windows, if the same thread locks the same mutex/critical // section twice, it will not block. Therefore, this method // can not be used to make the threads wait until all of them // reach the barrier // If there was a barrier before this one, we need to // wait until that is cleaned up or bad things happen. void vtkThreadedController::WaitForPreviousBarrierToEnd() { #ifdef VTK_USE_WIN32_THREADS WaitForSingleObject(vtkThreadedController::BarrierEndedEvent, INFINITE); #else vtkThreadedController::BarrierInProgress->Lock(); vtkThreadedController::BarrierInProgress->Unlock(); #endif } void vtkThreadedController::BarrierStarted() { vtkThreadedController::IsBarrierInProgress = 1; #ifdef VTK_USE_WIN32_THREADS #else vtkThreadedController::BarrierInProgress->Lock(); #endif } // A new barrier can now start void vtkThreadedController::BarrierEnded() { vtkThreadedController::IsBarrierInProgress = 0; #ifdef VTK_USE_WIN32_THREADS SetEvent(vtkThreadedController::BarrierEndedEvent); #else vtkThreadedController::BarrierInProgress->Unlock(); #endif } // Tell the next guy that it is ok to continue with the barrier void vtkThreadedController::SignalNextThread() { #ifdef VTK_USE_WIN32_THREADS SetEvent(vtkThreadedController::NextThread); #else vtkThreadedController::BarrierLock->Unlock(); #endif } // Create the windows event necessary for waiting void vtkThreadedController::InitializeBarrier() { #ifdef VTK_USE_WIN32_THREADS if (!BarrierEndedEvent) { vtkThreadedController::BarrierEndedEvent = CreateEvent(0,FALSE,FALSE,0); vtkThreadedController::NextThread = CreateEvent(0,FALSE,FALSE,0); } #endif } // Wait until the previous thread says it's ok to continue void vtkThreadedController::WaitForNextThread() { #ifdef VTK_USE_WIN32_THREADS WaitForSingleObject(vtkThreadedController::NextThread,INFINITE); #else vtkThreadedController::BarrierLock->Lock(); #endif } <|endoftext|>
<commit_before>//===- unittest/Tooling/RecursiveASTVisitorTest.cpp -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "TestVisitor.h" #include <stack> using namespace clang; namespace { class LambdaExprVisitor : public ExpectedLocationVisitor<LambdaExprVisitor> { public: bool VisitLambdaExpr(LambdaExpr *Lambda) { PendingBodies.push(Lambda); Match("", Lambda->getIntroducerRange().getBegin()); return true; } /// For each call to VisitLambdaExpr, we expect a subsequent call (with /// proper nesting) to TraverseLambdaBody. bool TraverseLambdaBody(LambdaExpr *Lambda) { EXPECT_FALSE(PendingBodies.empty()); EXPECT_EQ(PendingBodies.top(), Lambda); PendingBodies.pop(); return TraverseStmt(Lambda->getBody()); } /// Determine whether TraverseLambdaBody has been called for every call to /// VisitLambdaExpr. bool allBodiesHaveBeenTraversed() const { return PendingBodies.empty(); } private: std::stack<LambdaExpr *> PendingBodies; }; TEST(RecursiveASTVisitor, VisitsLambdaExpr) { LambdaExprVisitor Visitor; Visitor.ExpectMatch("", 1, 12); EXPECT_TRUE(Visitor.runOver("void f() { []{ return; }(); }", LambdaExprVisitor::Lang_CXX11)); } TEST(RecursiveASTVisitor, TraverseLambdaBodyCanBeOverridden) { LambdaExprVisitor Visitor; EXPECT_TRUE(Visitor.runOver("void f() { []{ return; }(); }", LambdaExprVisitor::Lang_CXX11)); EXPECT_TRUE(Visitor.allBodiesHaveBeenTraversed()); } // Matches the (optional) capture-default of a lambda-introducer. class LambdaDefaultCaptureVisitor : public ExpectedLocationVisitor<LambdaDefaultCaptureVisitor> { public: bool VisitLambdaExpr(LambdaExpr *Lambda) { if (Lambda->getCaptureDefault() != LCD_None) { Match("", Lambda->getCaptureDefaultLoc()); } return true; } }; TEST(RecursiveASTVisitor, HasCaptureDefaultLoc) { LambdaDefaultCaptureVisitor Visitor; Visitor.ExpectMatch("", 1, 20); EXPECT_TRUE(Visitor.runOver("void f() { int a; [=]{a;}; }", LambdaDefaultCaptureVisitor::Lang_CXX11)); } // Checks for lambda classes that are not marked as implicitly-generated. // (There should be none.) class ClassVisitor : public ExpectedLocationVisitor<ClassVisitor> { public: ClassVisitor() : SawNonImplicitLambdaClass(false) {} bool VisitCXXRecordDecl(CXXRecordDecl* record) { if (record->isLambda() && !record->isImplicit()) SawNonImplicitLambdaClass = true; return true; } bool sawOnlyImplicitLambdaClasses() const { return !SawNonImplicitLambdaClass; } private: bool SawNonImplicitLambdaClass; }; TEST(RecursiveASTVisitor, LambdaClosureTypesAreImplicit) { ClassVisitor Visitor; EXPECT_TRUE(Visitor.runOver("auto lambda = []{};", ClassVisitor::Lang_CXX11)); EXPECT_TRUE(Visitor.sawOnlyImplicitLambdaClasses()); } // Check to ensure that attributes and expressions within them are being // visited. class AttrVisitor : public ExpectedLocationVisitor<AttrVisitor> { public: bool VisitMemberExpr(MemberExpr *ME) { Match(ME->getMemberDecl()->getNameAsString(), ME->getLocStart()); return true; } bool VisitAttr(Attr *A) { Match("Attr", A->getLocation()); return true; } bool VisitGuardedByAttr(GuardedByAttr *A) { Match("guarded_by", A->getLocation()); return true; } }; TEST(RecursiveASTVisitor, AttributesAreVisited) { AttrVisitor Visitor; Visitor.ExpectMatch("Attr", 4, 24); Visitor.ExpectMatch("guarded_by", 4, 24); Visitor.ExpectMatch("mu1", 4, 35); Visitor.ExpectMatch("Attr", 5, 29); Visitor.ExpectMatch("mu1", 5, 54); Visitor.ExpectMatch("mu2", 5, 59); EXPECT_TRUE(Visitor.runOver( "class Foo {\n" " int mu1;\n" " int mu2;\n" " int a __attribute__((guarded_by(mu1)));\n" " void bar() __attribute__((exclusive_locks_required(mu1, mu2)));\n" "};\n")); } } // end anonymous namespace <commit_msg>Replace some tabs with spaces.<commit_after>//===- unittest/Tooling/RecursiveASTVisitorTest.cpp -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "TestVisitor.h" #include <stack> using namespace clang; namespace { class LambdaExprVisitor : public ExpectedLocationVisitor<LambdaExprVisitor> { public: bool VisitLambdaExpr(LambdaExpr *Lambda) { PendingBodies.push(Lambda); Match("", Lambda->getIntroducerRange().getBegin()); return true; } /// For each call to VisitLambdaExpr, we expect a subsequent call (with /// proper nesting) to TraverseLambdaBody. bool TraverseLambdaBody(LambdaExpr *Lambda) { EXPECT_FALSE(PendingBodies.empty()); EXPECT_EQ(PendingBodies.top(), Lambda); PendingBodies.pop(); return TraverseStmt(Lambda->getBody()); } /// Determine whether TraverseLambdaBody has been called for every call to /// VisitLambdaExpr. bool allBodiesHaveBeenTraversed() const { return PendingBodies.empty(); } private: std::stack<LambdaExpr *> PendingBodies; }; TEST(RecursiveASTVisitor, VisitsLambdaExpr) { LambdaExprVisitor Visitor; Visitor.ExpectMatch("", 1, 12); EXPECT_TRUE(Visitor.runOver("void f() { []{ return; }(); }", LambdaExprVisitor::Lang_CXX11)); } TEST(RecursiveASTVisitor, TraverseLambdaBodyCanBeOverridden) { LambdaExprVisitor Visitor; EXPECT_TRUE(Visitor.runOver("void f() { []{ return; }(); }", LambdaExprVisitor::Lang_CXX11)); EXPECT_TRUE(Visitor.allBodiesHaveBeenTraversed()); } // Matches the (optional) capture-default of a lambda-introducer. class LambdaDefaultCaptureVisitor : public ExpectedLocationVisitor<LambdaDefaultCaptureVisitor> { public: bool VisitLambdaExpr(LambdaExpr *Lambda) { if (Lambda->getCaptureDefault() != LCD_None) { Match("", Lambda->getCaptureDefaultLoc()); } return true; } }; TEST(RecursiveASTVisitor, HasCaptureDefaultLoc) { LambdaDefaultCaptureVisitor Visitor; Visitor.ExpectMatch("", 1, 20); EXPECT_TRUE(Visitor.runOver("void f() { int a; [=]{a;}; }", LambdaDefaultCaptureVisitor::Lang_CXX11)); } // Checks for lambda classes that are not marked as implicitly-generated. // (There should be none.) class ClassVisitor : public ExpectedLocationVisitor<ClassVisitor> { public: ClassVisitor() : SawNonImplicitLambdaClass(false) {} bool VisitCXXRecordDecl(CXXRecordDecl* record) { if (record->isLambda() && !record->isImplicit()) SawNonImplicitLambdaClass = true; return true; } bool sawOnlyImplicitLambdaClasses() const { return !SawNonImplicitLambdaClass; } private: bool SawNonImplicitLambdaClass; }; TEST(RecursiveASTVisitor, LambdaClosureTypesAreImplicit) { ClassVisitor Visitor; EXPECT_TRUE(Visitor.runOver("auto lambda = []{};", ClassVisitor::Lang_CXX11)); EXPECT_TRUE(Visitor.sawOnlyImplicitLambdaClasses()); } // Check to ensure that attributes and expressions within them are being // visited. class AttrVisitor : public ExpectedLocationVisitor<AttrVisitor> { public: bool VisitMemberExpr(MemberExpr *ME) { Match(ME->getMemberDecl()->getNameAsString(), ME->getLocStart()); return true; } bool VisitAttr(Attr *A) { Match("Attr", A->getLocation()); return true; } bool VisitGuardedByAttr(GuardedByAttr *A) { Match("guarded_by", A->getLocation()); return true; } }; TEST(RecursiveASTVisitor, AttributesAreVisited) { AttrVisitor Visitor; Visitor.ExpectMatch("Attr", 4, 24); Visitor.ExpectMatch("guarded_by", 4, 24); Visitor.ExpectMatch("mu1", 4, 35); Visitor.ExpectMatch("Attr", 5, 29); Visitor.ExpectMatch("mu1", 5, 54); Visitor.ExpectMatch("mu2", 5, 59); EXPECT_TRUE(Visitor.runOver( "class Foo {\n" " int mu1;\n" " int mu2;\n" " int a __attribute__((guarded_by(mu1)));\n" " void bar() __attribute__((exclusive_locks_required(mu1, mu2)));\n" "};\n")); } } // end anonymous namespace <|endoftext|>
<commit_before>#include "SolidMechanics.h" template<> InputParameters validParams<SolidMechanics>() { InputParameters params= validParams<PorousMedia>(); params.addParam<Real>("thermal_expansion",1.0e-6,"thermal expansion coefficient (1/K)"); params.addParam<Real>("youngs_modulus",1.50e10,"in Pascal") ; params.addParam<Real>("poissons_ratio",0.2,"dimensionless"); params.addParam<Real>("biot_coeff",0.0,"dimensionless"); params.addParam<Real>("t_ref",293.15,"initial temperature"); return params; } SolidMechanics::SolidMechanics(const std::string & name, MooseSystem & moose_system, InputParameters parameters) :PorousMedia(name, moose_system, parameters), _has_temp(isCoupled("temperature")), _grad_temp (_has_temp ? coupledGradient("temperature") : _grad_zero), _temperature(_has_temp ? coupledValue("temperature") : _zero), _has_x_disp(isCoupled("x_disp")), _grad_x_disp(_has_x_disp ? coupledGradient("x_disp") : _grad_zero), _has_y_disp(isCoupled("y_disp")), _grad_y_disp(_has_y_disp ? coupledGradient("y_disp") : _grad_zero), _has_z_disp(isCoupled("z_disp")), _grad_z_disp(_has_z_disp ? coupledGradient("z_disp") : _grad_zero), _input_thermal_expansion(getParam<Real>("thermal_expansion")), _input_youngs_modulus(getParam<Real>("youngs_modulus")), _input_poissons_ratio(getParam<Real>("poissons_ratio")), _input_biot_coeff(getParam<Real>("biot_coeff")), _input_t_ref(getParam<Real>("t_ref")), //declare material properties _thermal_strain(declareProperty<Real>("thermal_strain")), _alpha(declareProperty<Real>("alpha")), _youngs_modulus(declareProperty<Real>("youngs_modulus")), _poissons_ratio(declareProperty<Real>("poissons_ratio")), _biot_coeff(declareProperty<Real>("biot_coeff")), _strain_normal_vector(declareProperty<RealVectorValue>("strain_normal_vector")), _strain_shear_vector (declareProperty<RealVectorValue>("strain_shear_vector")), _stress_normal_vector(declareProperty<RealVectorValue>("stress_normal_vector")), _stress_shear_vector (declareProperty<RealVectorValue>("stress_shear_vector")) { } void SolidMechanics::computeProperties() { PorousMedia::computeProperties(); for(unsigned int qp=0; qp<_n_qpoints; qp++) { _alpha[qp] = _input_thermal_expansion; if(_has_temp) _thermal_strain[qp] = _input_thermal_expansion*(_temperature[qp] - _input_t_ref); else _thermal_strain[qp] = 0.0; _youngs_modulus[qp] = _input_youngs_modulus; _poissons_ratio[qp] = _input_poissons_ratio; _biot_coeff[qp] = _input_biot_coeff; if (_has_x_disp && _has_y_disp) { _E = _youngs_modulus[qp]; _nu = _poissons_ratio[qp]; _c1 = _E*(1.-_nu)/(1.+_nu)/(1.-2.*_nu); _c2 = _nu/(1.-_nu); _c3 = 0.5*(1.-2.*_nu)/(1.-_nu); _strain_normal_vector[qp](0) = _grad_x_disp[qp](0); //s_xx _strain_normal_vector[qp](1) = _grad_y_disp[qp](1); //s_yy if (_dim == 3) _strain_normal_vector[qp](2) = _grad_z_disp[qp](2); //s_zz _strain_shear_vector[qp](0) = 0.5*(_grad_x_disp[qp](1)+_grad_y_disp[qp](0)); // s_xy if (_dim == 3) { _strain_shear_vector[qp](1) = 0.5*(_grad_x_disp[qp](2)+_grad_z_disp[qp](0)); // s_xz _strain_shear_vector[qp](2) = 0.5*(_grad_y_disp[qp](2)+_grad_z_disp[qp](1)); // s_yz } _stress_normal_vector[qp](0) = _c1*_strain_normal_vector[qp](0)+_c1*_c2*_strain_normal_vector[qp](1)+_c1*_c2*_strain_normal_vector[qp](2); //tau_xx _stress_normal_vector[qp](1) = _c1*_c2*_strain_normal_vector[qp](0)+_c1*_strain_normal_vector[qp](1)+_c1*_c2*_strain_normal_vector[qp](2); //tau_yy if (_dim == 3) _stress_normal_vector[qp](2) = _c1*_c2*_strain_normal_vector[qp](0)+_c1*_c2*_strain_normal_vector[qp](1)+_c1*_strain_normal_vector[qp](2); //tau_zz _stress_shear_vector[qp](0) = _c1*_c3*2.0*_strain_shear_vector[qp](0); //tau_xy if (_dim == 3) { _stress_shear_vector[qp](1) = _c1*_c3*2.0*_strain_shear_vector[qp](1); //tau_xz _stress_shear_vector[qp](2) = _c1*_c3*2.0*_strain_shear_vector[qp](2); //tau_yz } } } } <commit_msg>modify solid mechanics kermel coupleing<commit_after>#include "SolidMechanics.h" template<> InputParameters validParams<SolidMechanics>() { InputParameters params= validParams<PorousMedia>(); params.addParam<Real>("thermal_expansion",1.0e-6,"thermal expansion coefficient (1/K)"); params.addParam<Real>("youngs_modulus",1.50e10,"in Pascal") ; params.addParam<Real>("poissons_ratio",0.2,"dimensionless"); params.addParam<Real>("biot_coeff",0.0,"dimensionless"); params.addParam<Real>("t_ref",293.15,"initial temperature"); params.addCoupledVar("temperature", "TODO: add description");//Hai forgot this // params.addCoupledVar("pressure", "TODO: add description");//Hai forgot this return params; } SolidMechanics::SolidMechanics(const std::string & name, MooseSystem & moose_system, InputParameters parameters) :PorousMedia(name, moose_system, parameters), _has_temp(isCoupled("temperature")), _grad_temp (_has_temp ? coupledGradient("temperature") : _grad_zero), _temperature(_has_temp ? coupledValue("temperature") : _zero), _has_x_disp(isCoupled("x_disp")), _grad_x_disp(_has_x_disp ? coupledGradient("x_disp") : _grad_zero), _has_y_disp(isCoupled("y_disp")), _grad_y_disp(_has_y_disp ? coupledGradient("y_disp") : _grad_zero), _has_z_disp(isCoupled("z_disp")), _grad_z_disp(_has_z_disp ? coupledGradient("z_disp") : _grad_zero), _input_thermal_expansion(getParam<Real>("thermal_expansion")), _input_youngs_modulus(getParam<Real>("youngs_modulus")), _input_poissons_ratio(getParam<Real>("poissons_ratio")), _input_biot_coeff(getParam<Real>("biot_coeff")), _input_t_ref(getParam<Real>("t_ref")), //declare material properties _thermal_strain(declareProperty<Real>("thermal_strain")), _alpha(declareProperty<Real>("alpha")), _youngs_modulus(declareProperty<Real>("youngs_modulus")), _poissons_ratio(declareProperty<Real>("poissons_ratio")), _biot_coeff(declareProperty<Real>("biot_coeff")), _strain_normal_vector(declareProperty<RealVectorValue>("strain_normal_vector")), _strain_shear_vector (declareProperty<RealVectorValue>("strain_shear_vector")), _stress_normal_vector(declareProperty<RealVectorValue>("stress_normal_vector")), _stress_shear_vector (declareProperty<RealVectorValue>("stress_shear_vector")) { } void SolidMechanics::computeProperties() { PorousMedia::computeProperties(); for(unsigned int qp=0; qp<_n_qpoints; qp++) { _alpha[qp] = _input_thermal_expansion; if(_has_temp) _thermal_strain[qp] = _input_thermal_expansion*(_temperature[qp] - _input_t_ref); else _thermal_strain[qp] = 0.0; _youngs_modulus[qp] = _input_youngs_modulus; _poissons_ratio[qp] = _input_poissons_ratio; _biot_coeff[qp] = _input_biot_coeff; if (_has_x_disp && _has_y_disp) { _E = _youngs_modulus[qp]; _nu = _poissons_ratio[qp]; _c1 = _E*(1.-_nu)/(1.+_nu)/(1.-2.*_nu); _c2 = _nu/(1.-_nu); _c3 = 0.5*(1.-2.*_nu)/(1.-_nu); _strain_normal_vector[qp](0) = _grad_x_disp[qp](0); //s_xx _strain_normal_vector[qp](1) = _grad_y_disp[qp](1); //s_yy if (_dim == 3) _strain_normal_vector[qp](2) = _grad_z_disp[qp](2); //s_zz _strain_shear_vector[qp](0) = 0.5*(_grad_x_disp[qp](1)+_grad_y_disp[qp](0)); // s_xy if (_dim == 3) { _strain_shear_vector[qp](1) = 0.5*(_grad_x_disp[qp](2)+_grad_z_disp[qp](0)); // s_xz _strain_shear_vector[qp](2) = 0.5*(_grad_y_disp[qp](2)+_grad_z_disp[qp](1)); // s_yz } _stress_normal_vector[qp](0) = _c1*_strain_normal_vector[qp](0)+_c1*_c2*_strain_normal_vector[qp](1)+_c1*_c2*_strain_normal_vector[qp](2); //tau_xx _stress_normal_vector[qp](1) = _c1*_c2*_strain_normal_vector[qp](0)+_c1*_strain_normal_vector[qp](1)+_c1*_c2*_strain_normal_vector[qp](2); //tau_yy if (_dim == 3) _stress_normal_vector[qp](2) = _c1*_c2*_strain_normal_vector[qp](0)+_c1*_c2*_strain_normal_vector[qp](1)+_c1*_strain_normal_vector[qp](2); //tau_zz _stress_shear_vector[qp](0) = _c1*_c3*2.0*_strain_shear_vector[qp](0); //tau_xy if (_dim == 3) { _stress_shear_vector[qp](1) = _c1*_c3*2.0*_strain_shear_vector[qp](1); //tau_xz _stress_shear_vector[qp](2) = _c1*_c3*2.0*_strain_shear_vector[qp](2); //tau_yz } } } } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/testapp.h> #include <vbench/test/all.h> #include <vespa/vespalib/util/slaveproc.h> #include <vespa/vespalib/net/crypto_engine.h> #include <vespa/vespalib/net/tls/tls_crypto_engine.h> #include <vespa/vespalib/test/make_tls_options_for_testing.h> #include <vespa/vespalib/portal/portal.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> using namespace vbench; using vespalib::SlaveProc; using InputReader = vespalib::InputReader; using OutputWriter = vespalib::OutputWriter; using Portal = vespalib::Portal; auto null_crypto = std::make_shared<vespalib::NullCryptoEngine>(); auto tls_opts = vespalib::test::make_tls_options_for_testing(); auto tls_crypto = std::make_shared<vespalib::TlsCryptoEngine>(tls_opts); void write_file(const vespalib::string &file_name, const vespalib::string &content) { int fd = creat(file_name.c_str(), 0600); ASSERT_TRUE(fd >= 0); ssize_t res = write(fd, content.data(), content.size()); ASSERT_EQUAL(res, ssize_t(content.size())); int res2 = close(fd); ASSERT_EQUAL(res2, 0); } TEST("vbench usage") { std::string out; EXPECT_FALSE(SlaveProc::run("../../apps/vbench/vbench_app", out)); fprintf(stderr, "%s\n", out.c_str()); } struct MyGet : vespalib::Portal::GetHandler { std::atomic<size_t> cnt; void get(vespalib::Portal::GetRequest request) override { ++cnt; request.respond_with_content("text/plain", "data"); }; }; struct Servers { MyGet my_get; MyGet my_tls_get; Portal::SP portal; Portal::SP tls_portal; Portal::Token::UP root; Portal::Token::UP tls_root; Servers() : my_get(), my_tls_get(), portal(Portal::create(null_crypto, 0)), tls_portal(Portal::create(tls_crypto, 0)), root(portal->bind("/", my_get)), tls_root(tls_portal->bind("/", my_tls_get)) { write_file("ca_certs.pem", tls_opts.ca_certs_pem()); write_file("certs.pem", tls_opts.cert_chain_pem()); write_file("test.key", tls_opts.private_key_pem()); } }; TEST_MT_F("run vbench", 2, Servers()) { if (thread_id == 0) { std::string out; EXPECT_TRUE(SlaveProc::run(strfmt("sed 's/_LOCAL_PORT_/%d/' vbench.cfg.template > vbench.cfg", f1.portal->listen_port()).c_str())); EXPECT_TRUE(SlaveProc::run("../../apps/vbench/vbench_app run vbench.cfg 2> vbench.out", out)); fprintf(stderr, "null crypto: %s\n", out.c_str()); EXPECT_GREATER(f1.my_get.cnt, 10u); } else { std::string tls_out; EXPECT_TRUE(SlaveProc::run(strfmt("sed 's/_LOCAL_PORT_/%d/' vbench.tls.cfg.template > vbench.tls.cfg", f1.tls_portal->listen_port()).c_str())); EXPECT_TRUE(SlaveProc::run("../../apps/vbench/vbench_app run vbench.tls.cfg 2> vbench.tls.out", tls_out)); fprintf(stderr, "tls crypto: %s\n", tls_out.c_str()); EXPECT_GREATER(f1.my_tls_get.cnt, 10u); } } TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); } <commit_msg>overwrite private key with garbage after test is run<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/testapp.h> #include <vbench/test/all.h> #include <vespa/vespalib/util/slaveproc.h> #include <vespa/vespalib/net/crypto_engine.h> #include <vespa/vespalib/net/tls/tls_crypto_engine.h> #include <vespa/vespalib/test/make_tls_options_for_testing.h> #include <vespa/vespalib/portal/portal.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> using namespace vbench; using vespalib::SlaveProc; using InputReader = vespalib::InputReader; using OutputWriter = vespalib::OutputWriter; using Portal = vespalib::Portal; auto null_crypto = std::make_shared<vespalib::NullCryptoEngine>(); auto tls_opts = vespalib::test::make_tls_options_for_testing(); auto tls_crypto = std::make_shared<vespalib::TlsCryptoEngine>(tls_opts); void write_file(const vespalib::string &file_name, const vespalib::string &content) { int fd = creat(file_name.c_str(), 0600); ASSERT_TRUE(fd >= 0); ssize_t res = write(fd, content.data(), content.size()); ASSERT_EQUAL(res, ssize_t(content.size())); int res2 = close(fd); ASSERT_EQUAL(res2, 0); } TEST("vbench usage") { std::string out; EXPECT_FALSE(SlaveProc::run("../../apps/vbench/vbench_app", out)); fprintf(stderr, "%s\n", out.c_str()); } struct MyGet : vespalib::Portal::GetHandler { std::atomic<size_t> cnt; void get(vespalib::Portal::GetRequest request) override { ++cnt; request.respond_with_content("text/plain", "data"); }; }; struct Servers { MyGet my_get; MyGet my_tls_get; Portal::SP portal; Portal::SP tls_portal; Portal::Token::UP root; Portal::Token::UP tls_root; Servers() : my_get(), my_tls_get(), portal(Portal::create(null_crypto, 0)), tls_portal(Portal::create(tls_crypto, 0)), root(portal->bind("/", my_get)), tls_root(tls_portal->bind("/", my_tls_get)) { write_file("ca_certs.pem", tls_opts.ca_certs_pem()); write_file("certs.pem", tls_opts.cert_chain_pem()); write_file("test.key", tls_opts.private_key_pem()); } ~Servers() { write_file("test.key", "garbage\n"); } }; TEST_MT_F("run vbench", 2, Servers()) { if (thread_id == 0) { std::string out; EXPECT_TRUE(SlaveProc::run(strfmt("sed 's/_LOCAL_PORT_/%d/' vbench.cfg.template > vbench.cfg", f1.portal->listen_port()).c_str())); EXPECT_TRUE(SlaveProc::run("../../apps/vbench/vbench_app run vbench.cfg 2> vbench.out", out)); fprintf(stderr, "null crypto: %s\n", out.c_str()); EXPECT_GREATER(f1.my_get.cnt, 10u); } else { std::string tls_out; EXPECT_TRUE(SlaveProc::run(strfmt("sed 's/_LOCAL_PORT_/%d/' vbench.tls.cfg.template > vbench.tls.cfg", f1.tls_portal->listen_port()).c_str())); EXPECT_TRUE(SlaveProc::run("../../apps/vbench/vbench_app run vbench.tls.cfg 2> vbench.tls.out", tls_out)); fprintf(stderr, "tls crypto: %s\n", tls_out.c_str()); EXPECT_GREATER(f1.my_tls_get.cnt, 10u); } } TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Tasks/SimpleTasks/IncludeTask.hpp> namespace Hearthstonepp::SimpleTasks { TaskID IncludeTask::GetTaskID() const { return TaskID::INCLUDE; } std::vector<Entity*> IncludeTask::GetEntities(EntityType entityType, Player& player) { std::vector<Entity*> entities; switch (entityType) { case EntityType::HERO: entities.emplace_back(player.GetHero()); break; case EntityType::FRIENDS: for (auto& minion : player.GetField()) { entities.emplace_back(minion); } entities.emplace_back(player.GetHero()); break; case EntityType::ENEMIES: for (auto& minion : player.GetOpponent().GetField()) { entities.emplace_back(minion); } entities.emplace_back(player.GetOpponent().GetHero()); break; default: throw std::exception("Not implemented"); } return entities; } MetaData IncludeTask::Impl(Player&) { return MetaData::INCLUDE_SUCCESS; } } // namespace Hearthstonepp::SimpleTasks <commit_msg>fix: Correct compile error on Linux and macOS<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Tasks/SimpleTasks/IncludeTask.hpp> #include <stdexcept> namespace Hearthstonepp::SimpleTasks { TaskID IncludeTask::GetTaskID() const { return TaskID::INCLUDE; } std::vector<Entity*> IncludeTask::GetEntities(EntityType entityType, Player& player) { std::vector<Entity*> entities; switch (entityType) { case EntityType::HERO: entities.emplace_back(player.GetHero()); break; case EntityType::FRIENDS: for (auto& minion : player.GetField()) { entities.emplace_back(minion); } entities.emplace_back(player.GetHero()); break; case EntityType::ENEMIES: for (auto& minion : player.GetOpponent().GetField()) { entities.emplace_back(minion); } entities.emplace_back(player.GetOpponent().GetHero()); break; default: throw std::domain_error("Invalid entity type"); } return entities; } MetaData IncludeTask::Impl(Player&) { return MetaData::INCLUDE_SUCCESS; } } // namespace Hearthstonepp::SimpleTasks <|endoftext|>
<commit_before>//Copyright (c) 2013 Christopher Johnstone(meson800) //The MIT License - See ../../../LICENSE for more info #include "StateSaver.h" HINSTANCE StateSaver::hDLL = 0; INT_PTR CALLBACK StateSaver::DlgProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { case WM_INITDIALOG: //get size of window, and create list box to fill it RECT rect; if (GetWindowRect(hWnd, &rect)) { int width = rect.right - rect.left; int height = rect.bottom - rect.top; HWND hListBox = CreateWindowEx(WS_EX_CLIENTEDGE , "listbox", "status_listbox" , WS_CHILD | WS_VISIBLE | ES_AUTOVSCROLL , 0, 0, width, height , hWnd, NULL, hDLL, NULL); *((HWND*)lParam) = hListBox; } return true; case WM_CLOSE: EndDialog(hWnd, wParam); return true; default: return false; } } void StateSaver::updateDialog() { if (recordedEvents.size() == 0) { //we're done with the dialog!!! oapiCloseDialog(hDlg); int result; EndDialog(hDlg, (WPARAM)(&result)); } } bool StateSaver::handleEventBlocking(Event ev) { for (unsigned int i = 0; i < ranges.size(); i++) { if (ev.id > ranges[i].first && ev.id < ranges[i].second) { //record that sucker! currentEvents[ev.id] = ev.state; //see if it matches one of our recorded events //iterate over map eventPairMapIterator itr = recordedEvents.begin(); while (itr != recordedEvents.end()) { //check if the id and state are the same if (itr->second.first == ev.id && itr->second.second == ev.state) { fprintf(Log::returnLogHandle(), "[StateSaver]-Handled and Blocked event, id=%i\tstate=%i\n", (ev.id), (ev.state)); //delete from listbox int item_id = SendMessage(listbox, LB_FINDSTRINGEXACT, -1, (LPARAM)(itr->first.c_str())); if (item_id != LB_ERR) SendMessage(listbox, LB_DELETESTRING, item_id, NULL); else Log::println("[StateSaver]-Couldn't delete string out of listbox!"); //delete from map itr = recordedEvents.erase(itr); updateDialog(); //return true, we handled it return true; } else { itr++; } } updateDialog(); } } return false; } void StateSaver::load(const char * key, const char * value) { //load ranges if (strcmp(key, "range") == 0) { int first, second; if (sscanf(value, " %i %i", &first, &second) == 2) ranges.push_back(std::make_pair(first, second)); } //load mapping if (strcmp(key, "mapping") == 0) { int map_key; char map_value [256]; if (sscanf(value, " %i %s", &map_key, map_value) == 2) eventToNameMapping[map_key] = std::string(map_value); } } void StateSaver::loadScenarioState(FILEHANDLE scenario) { createListbox(); //listbox = (HWND)oapiGetDialogContext(hDlg); char * line; while (oapiReadScenario_nextline(scenario, line)) { //load the recorded event and add to listbox int ev_id, ev_state; if (sscanf(line, "%i %i", &ev_id, &ev_state) == 2) { std::string item_name; //see if there is an easy name for the event if (eventToNameMapping.count(ev_id) != 0) { //just add the easy name to the listbox SendMessage(listbox, LB_ADDSTRING, NULL, (LPARAM)eventToNameMapping[ev_id].c_str()); item_name = eventToNameMapping[ev_id]; } else { //no easy name :( char idToString[100]; sprintf(idToString, "%d", ev_id); SendMessage(listbox, LB_ADDSTRING, NULL, (LPARAM)idToString); item_name = idToString; } //add to recorded events recordedEvents[item_name] = std::make_pair(ev_id, ev_state); updateDialog(); } } updateDialog(); } void StateSaver::saveScenarioState(FILEHANDLE scenario) { for (eventMapIterator it = currentEvents.begin(); it != currentEvents.end(); it++) { char lineToWrite[100]; sprintf(lineToWrite, "%i %i", it->first, it->second); oapiWriteLine(scenario, lineToWrite); } } void StateSaver::createListbox() { hDlg = oapiOpenDialog(hDLL, IDD_STATE, &(StateSaver::DlgProc), (void *)(&listbox)); }<commit_msg>Added check to return true when a event is recieved with the wrong state, correct id<commit_after>//Copyright (c) 2013 Christopher Johnstone(meson800) //The MIT License - See ../../../LICENSE for more info #include "StateSaver.h" HINSTANCE StateSaver::hDLL = 0; INT_PTR CALLBACK StateSaver::DlgProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { case WM_INITDIALOG: //get size of window, and create list box to fill it RECT rect; if (GetWindowRect(hWnd, &rect)) { int width = rect.right - rect.left; int height = rect.bottom - rect.top; HWND hListBox = CreateWindowEx(WS_EX_CLIENTEDGE , "listbox", "status_listbox" , WS_CHILD | WS_VISIBLE | ES_AUTOVSCROLL , 0, 0, width, height , hWnd, NULL, hDLL, NULL); *((HWND*)lParam) = hListBox; } return true; case WM_CLOSE: EndDialog(hWnd, wParam); return true; default: return false; } } void StateSaver::updateDialog() { if (recordedEvents.size() == 0) { //we're done with the dialog!!! oapiCloseDialog(hDlg); int result; EndDialog(hDlg, (WPARAM)(&result)); } } bool StateSaver::handleEventBlocking(Event ev) { for (unsigned int i = 0; i < ranges.size(); i++) { if (ev.id > ranges[i].first && ev.id < ranges[i].second) { //record that sucker! currentEvents[ev.id] = ev.state; //see if it matches one of our recorded events //iterate over map eventPairMapIterator itr = recordedEvents.begin(); while (itr != recordedEvents.end()) { //check if the id and state are the same if (itr->second.first == ev.id && itr->second.second == ev.state) { fprintf(Log::returnLogHandle(), "[StateSaver]-Handled and Blocked event, id=%i\tstate=%i\n", (ev.id), (ev.state)); //delete from listbox int item_id = SendMessage(listbox, LB_FINDSTRINGEXACT, -1, (LPARAM)(itr->first.c_str())); if (item_id != LB_ERR) SendMessage(listbox, LB_DELETESTRING, item_id, NULL); else Log::println("[StateSaver]-Couldn't delete string out of listbox!"); //delete from map itr = recordedEvents.erase(itr); updateDialog(); //return true, we handled it return true; } else { //to make sure "bad" events are blocked, return true if the id is the same if (itr->second.first == ev.id) return true; itr++; } } updateDialog(); } } return false; } void StateSaver::load(const char * key, const char * value) { //load ranges if (strcmp(key, "range") == 0) { int first, second; if (sscanf(value, " %i %i", &first, &second) == 2) ranges.push_back(std::make_pair(first, second)); } //load mapping if (strcmp(key, "mapping") == 0) { int map_key; char map_value [256]; if (sscanf(value, " %i %s", &map_key, map_value) == 2) eventToNameMapping[map_key] = std::string(map_value); } } void StateSaver::loadScenarioState(FILEHANDLE scenario) { createListbox(); //listbox = (HWND)oapiGetDialogContext(hDlg); char * line; while (oapiReadScenario_nextline(scenario, line)) { //load the recorded event and add to listbox int ev_id, ev_state; if (sscanf(line, "%i %i", &ev_id, &ev_state) == 2) { std::string item_name; //see if there is an easy name for the event if (eventToNameMapping.count(ev_id) != 0) { //just add the easy name to the listbox SendMessage(listbox, LB_ADDSTRING, NULL, (LPARAM)eventToNameMapping[ev_id].c_str()); item_name = eventToNameMapping[ev_id]; } else { //no easy name :( char idToString[100]; sprintf(idToString, "%d", ev_id); SendMessage(listbox, LB_ADDSTRING, NULL, (LPARAM)idToString); item_name = idToString; } //add to recorded events recordedEvents[item_name] = std::make_pair(ev_id, ev_state); updateDialog(); } } updateDialog(); } void StateSaver::saveScenarioState(FILEHANDLE scenario) { for (eventMapIterator it = currentEvents.begin(); it != currentEvents.end(); it++) { char lineToWrite[100]; sprintf(lineToWrite, "%i %i", it->first, it->second); oapiWriteLine(scenario, lineToWrite); } } void StateSaver::createListbox() { hDlg = oapiOpenDialog(hDLL, IDD_STATE, &(StateSaver::DlgProc), (void *)(&listbox)); }<|endoftext|>
<commit_before>// Copyright 2008, 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 "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/browser/save_package.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" const std::wstring kTestDir = L"save_page"; class SavePageTest : public UITest { protected: SavePageTest() : UITest() {} void CheckFile(const std::wstring& client_file, const std::wstring& server_file, bool check_equal) { bool exist = false; for (int i = 0; i < 20; ++i) { if (file_util::PathExists(client_file)) { exist = true; break; } Sleep(kWaitForActionMaxMsec / 20); } EXPECT_TRUE(exist); if (check_equal) { std::wstring server_file_name; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &server_file_name)); server_file_name += L"\\" + kTestDir + L"\\" + server_file; ASSERT_TRUE(file_util::PathExists(server_file_name)); EXPECT_PRED2(file_util::ContentsEqual, client_file, server_file_name); } EXPECT_TRUE(DieFileDie(client_file, false)); } virtual void SetUp() { UITest::SetUp(); EXPECT_TRUE(file_util::CreateNewTempDirectory(L"", &save_dir_)); save_dir_ += file_util::kPathSeparator; } std::wstring save_dir_; }; // bug 1306067 TEST_F(SavePageTest, DISABLED_SaveHTMLOnly) { std::wstring file_name = L"a.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"a_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(full_file_name, file_name, true); EXPECT_FALSE(file_util::PathExists(dir)); } TEST_F(SavePageTest, SaveCompleteHTML) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"b_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_COMPLETE_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(dir, true)); } TEST_F(SavePageTest, NoSave) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"c_files"; scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(GURL(L"about:blank"))); WaitUntilTabCount(1); EXPECT_FALSE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get())); } <commit_msg>Enable back SavePageTest.SaveHTMLOnly since it was mostly failing on Windows 2000 and add debugging information to know how SavePageTest.SaveCompleteHTML is failing.<commit_after>// Copyright 2008, 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 "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/browser/save_package.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" const std::wstring kTestDir = L"save_page"; class SavePageTest : public UITest { protected: SavePageTest() : UITest() {} void CheckFile(const std::wstring& client_file, const std::wstring& server_file, bool check_equal) { bool exist = false; for (int i = 0; i < 20; ++i) { if (file_util::PathExists(client_file)) { exist = true; break; } Sleep(kWaitForActionMaxMsec / 20); } EXPECT_TRUE(exist); if (check_equal) { std::wstring server_file_name; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &server_file_name)); server_file_name += L"\\" + kTestDir + L"\\" + server_file; ASSERT_TRUE(file_util::PathExists(server_file_name)); int64 client_file_size = 0; int64 server_file_size = 0; EXPECT_TRUE(file_util::GetFileSize(client_file, &client_file_size)); EXPECT_TRUE(file_util::GetFileSize(server_file_name, &server_file_size)); EXPECT_EQ(client_file_size, server_file_size); EXPECT_PRED2(file_util::ContentsEqual, client_file, server_file_name); } EXPECT_TRUE(DieFileDie(client_file, false)); } virtual void SetUp() { UITest::SetUp(); EXPECT_TRUE(file_util::CreateNewTempDirectory(L"", &save_dir_)); save_dir_ += file_util::kPathSeparator; } std::wstring save_dir_; }; TEST_F(SavePageTest, SaveHTMLOnly) { std::wstring file_name = L"a.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"a_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(full_file_name, file_name, true); EXPECT_FALSE(file_util::PathExists(dir)); } TEST_F(SavePageTest, SaveCompleteHTML) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"b_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_COMPLETE_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(dir, true)); } TEST_F(SavePageTest, NoSave) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"c_files"; scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(GURL(L"about:blank"))); WaitUntilTabCount(1); EXPECT_FALSE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get())); } <|endoftext|>
<commit_before>/************************************************************************* * Copyright (c) 2013 eProsima. All rights reserved. * * This copy of FastCdr is licensed to you under the terms described in the * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution. * *************************************************************************/ /* * StatelessTest.cpp * * Created on: Feb 26, 2014 * Author: Gonzalo Rodriguez Canosa * email: gonzalorodriguez@eprosima.com * grcanosa@gmail.com */ #include <stdio.h> #include <string> #include <iostream> #include <iomanip> #include <bitset> #include <cstdint> // #include "eprosimartps/Participant.h" #include "eprosimartps/dds/Publisher.h" #include "eprosimartps/dds/Subscriber.h" #include "eprosimartps/dds/DomainParticipant.h" #include "eprosimartps/common/colors.h" #include "eprosimartps/dds/ParameterList.h" #include "eprosimartps/utils/RTPSLog.h" #include "eprosimartps/dds/DDSTopicDataType.h" #include "eprosimartps/reader/RTPSListener.h" using namespace eprosima; using namespace dds; using namespace rtps; using namespace std; #define IPTEST1 23 #define IPTEST2 25 #define IPTEST3 27 #define IPTESTWIN 11 #define WR 1 //Writer 1, Reader 2 #if defined(__LITTLE_ENDIAN__) const Endianness_t DEFAULT_ENDIAN = LITTLEEND; #elif defined (__BIG_ENDIAN__) const Endianness_t DEFAULT_ENDIAN = BIGEND; #endif #if defined(_WIN32) #define COPYSTR strcpy_s #else #define COPYSTR strcpy #endif typedef struct TestType{ char name[6]; //KEY int32_t value; double price; TestType() { value = -1; price = 0; strcpy(name,"UNDEF"); } void print() { cout << "Name: "; printf("%s",name); cout << " |Value: "<< value; cout << " |Price: "<< price; cout << endl; } }TestType; class TestTypeDataType:public DDSTopicDataType { public: TestTypeDataType() { m_topicDataTypeName = "TestType"; m_typeSize = 6+4+sizeof(double); m_isGetKeyDefined = true; }; ~TestTypeDataType(){}; bool serialize(void*data,SerializedPayload_t* payload); bool deserialize(SerializedPayload_t* payload,void * data); bool getKey(void*data,InstanceHandle_t* ihandle); }; //Funciones de serializacion y deserializacion para el ejemplo bool TestTypeDataType::serialize(void*data,SerializedPayload_t* payload) { payload->length = sizeof(TestType); payload->encapsulation = CDR_LE; if(payload->data !=NULL) free(payload->data); payload->data = (octet*)malloc(payload->length); memcpy(payload->data,data,payload->length); return true; } bool TestTypeDataType::deserialize(SerializedPayload_t* payload,void * data) { //cout << "Deserializando length: " << payload->length << endl; memcpy(data,payload->data,payload->length); return true; } bool TestTypeDataType::getKey(void*data,InstanceHandle_t* handle) { TestType* tp = (TestType*)data; handle->value[0] = 0; handle->value[1] = 0; handle->value[2] = 0; handle->value[3] = 5; //length of string in CDR BE handle->value[4] = tp->name[0]; handle->value[5] = tp->name[1]; handle->value[6] = tp->name[2]; handle->value[7] = tp->name[3]; handle->value[8] = tp->name[4]; for(uint8_t i=9;i<16;i++) handle->value[i] = 0; return true; } class TestTypeListener: public RTPSListener{ public: TestTypeListener(){}; ~TestTypeListener(){}; void newMessageCallback() { cout <<"New Message"<<endl; } }; int main(int argc, char** argv) { RTPSLog::setVerbosity(RTPSLog::EPROSIMA_INFO_VERBOSITY_LEVEL); int type; if(argc > 1) { RTPSLog::Info << "Parsing arguments: " << argv[1] << endl; RTPSLog::printInfo(); if(strcmp(argv[1],"1")==0) type = 1; else if(strcmp(argv[1],"2")==0) type = 2; else if(strcmp(argv[1],"3")==0) type = 3; } else type = WR; TestTypeDataType TestTypeData; DomainParticipant::registerType((DDSTopicDataType*)&TestTypeData); ParticipantParams_t PParam; PParam.defaultSendPort = 10042; PParam.m_useSimpleParticipantDiscovery = false; Participant* p = DomainParticipant::createParticipant(PParam); switch(type) { case 1: { WriterParams_t WParam; WParam.historySize = 20; WParam.topicKind = WITH_KEY; WParam.topicDataType = "TestType"; WParam.topicName = "Test_topic"; Publisher* pub1 = DomainParticipant::createPublisher(p,WParam); Publisher* pub2 = DomainParticipant::createPublisher(p,WParam); ReaderParams_t Rparam; Rparam.historySize = 50; Rparam.topicDataType = std::string("TestType"); Rparam.topicName = std::string("Test_topic"); Rparam.topicKind = NO_KEY; Locator_t loc; loc.kind = 1; loc.port = 10469; Rparam.unicastLocatorList.push_back(loc); //Listen in the 10469 port Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam); loc.set_IP4_address(192,168,1,IPTEST2); pub1->addReaderLocator(loc,true); pub2->addReaderLocator(loc,true); TestType tp1,tp2,tp_in; COPYSTR(tp1.name,"Obje1"); COPYSTR(tp2.name,"Obje2"); tp1.value = 0; tp1.price = 1.3; tp2.value = 0; tp2.price = -1.3; int n; cout << "Enter number to start: "; cin >> n; for(uint i = 0;i<10;i++) { tp1.value++; tp1.price *= (i+1); tp2.value++; tp2.price *= (i+1); pub1->write((void*)&tp1); pub2->write((void*)&tp2); if(pub1->getHistory_n() >= 0.8*WParam.historySize) pub1->removeMinSeqChange(); if(pub2->getHistory_n() >= 0.8*WParam.historySize) pub2->removeMinSeqChange(); if(i==8) { pub1->dispose((void*)&tp1); pub1->unregister((void*)&tp1); pub2->dispose((void*)&tp2); pub2->unregister((void*)&tp2); COPYSTR(tp1.name,"Obje3"); tp1.value = 0; tp1.price = 1.5; COPYSTR(tp2.name,"Obje4"); tp2.value = 0; tp2.price = 1.5; } if(sub->getHistory_n() >= 0.8*Rparam.historySize) { cout << "Taking all from subscriber" <<endl; std::vector<void*> data_vec; sub->takeAllCache(&data_vec); for(unsigned int i=0;i<data_vec.size();i++) ((TestType*)data_vec[i])->print(); cout << "Subscriber History has now: " << sub->getHistory_n() << " elements "<<endl; } } cout << "Sleeping 2 seconds"<<endl; sleep(3); while(sub->readMinSeqUnreadCache((void*)&tp_in)) { tp_in.print(); tp_in.value = -111; } break; } case 2: { ReaderParams_t Rparam; Rparam.historySize = 50; Rparam.topicDataType = std::string("TestType"); Rparam.topicName = std::string("Test_topic"); Rparam.topicKind = WITH_KEY; Locator_t loc; loc.kind = 1; loc.port = 10469; Rparam.unicastLocatorList.push_back(loc); //Listen in port 10469 Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam); TestTypeListener listener; sub->assignListener((RTPSListener*)&listener); WriterParams_t WParam; WParam.historySize = 50; WParam.topicKind = NO_KEY; WParam.topicDataType = "TestType"; WParam.topicName = "Test_topic"; Publisher* pub1 = DomainParticipant::createPublisher(p,WParam); loc.set_IP4_address(192,168,1,IPTEST1); pub1->addReaderLocator(loc,false); while(1) { cout << "Blocking until new message arrives " << endl; sub->blockUntilNewMessage(); cout << "After new message block " << sub->getHistory_n() << endl; TestType tp; while(sub->readMinSeqUnreadCache((void*)&tp)) { tp.print(); pub1->write((void*)&tp); } cout << "Read: " << sub->getReadElements_n() <<" from History: "<<sub->getHistory_n()<< endl; if(sub->getHistory_n() >= 0.5*Rparam.historySize) { cout << "Taking all" <<endl; std::vector<void*> data_vec; sub->takeAllCache(&data_vec); for(unsigned int i=0;i<data_vec.size();i++) ((TestType*)data_vec[i])->print(); cout << "History has now: " << sub->getHistory_n() << " elements "; cout << " and is FUll?: " << sub->isHistoryFull() << endl; } } break; } default: break; } cout << "Enter numer "<< endl; int n; cin >> n; DomainParticipant::stopAll(); return 0; } <commit_msg>statelessTest ready<commit_after>/************************************************************************* * Copyright (c) 2013 eProsima. All rights reserved. * * This copy of FastCdr is licensed to you under the terms described in the * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution. * *************************************************************************/ /* * StatelessTest.cpp * * Created on: Feb 26, 2014 * Author: Gonzalo Rodriguez Canosa * email: gonzalorodriguez@eprosima.com * grcanosa@gmail.com */ #include <stdio.h> #include <string> #include <iostream> #include <iomanip> #include <bitset> #include <cstdint> // #include "eprosimartps/Participant.h" #include "eprosimartps/dds/Publisher.h" #include "eprosimartps/dds/Subscriber.h" #include "eprosimartps/dds/DomainParticipant.h" #include "eprosimartps/common/colors.h" #include "eprosimartps/dds/ParameterList.h" #include "eprosimartps/utils/RTPSLog.h" #include "eprosimartps/dds/DDSTopicDataType.h" #include "eprosimartps/reader/RTPSListener.h" using namespace eprosima; using namespace dds; using namespace rtps; using namespace std; #define IPTEST1 23 #define IPTEST2 25 #define IPTEST3 27 #define IPTESTWIN 11 #define WR 1 //Writer 1, Reader 2 #if defined(__LITTLE_ENDIAN__) const Endianness_t DEFAULT_ENDIAN = LITTLEEND; #elif defined (__BIG_ENDIAN__) const Endianness_t DEFAULT_ENDIAN = BIGEND; #endif #if defined(_WIN32) #define COPYSTR strcpy_s #else #define COPYSTR strcpy #endif typedef struct TestType{ char name[6]; //KEY int32_t value; double price; TestType() { value = -1; price = 0; strcpy(name,"UNDEF"); } void print() { cout << "Name: "; printf("%s",name); cout << " |Value: "<< value; cout << " |Price: "<< price; cout << endl; } }TestType; class TestTypeDataType:public DDSTopicDataType { public: TestTypeDataType() { m_topicDataTypeName = "TestType"; m_typeSize = 6+4+sizeof(double); m_isGetKeyDefined = true; }; ~TestTypeDataType(){}; bool serialize(void*data,SerializedPayload_t* payload); bool deserialize(SerializedPayload_t* payload,void * data); bool getKey(void*data,InstanceHandle_t* ihandle); }; //Funciones de serializacion y deserializacion para el ejemplo bool TestTypeDataType::serialize(void*data,SerializedPayload_t* payload) { payload->length = sizeof(TestType); payload->encapsulation = CDR_LE; if(payload->data !=NULL) free(payload->data); payload->data = (octet*)malloc(payload->length); memcpy(payload->data,data,payload->length); return true; } bool TestTypeDataType::deserialize(SerializedPayload_t* payload,void * data) { //cout << "Deserializando length: " << payload->length << endl; memcpy(data,payload->data,payload->length); return true; } bool TestTypeDataType::getKey(void*data,InstanceHandle_t* handle) { TestType* tp = (TestType*)data; handle->value[0] = 0; handle->value[1] = 0; handle->value[2] = 0; handle->value[3] = 5; //length of string in CDR BE handle->value[4] = tp->name[0]; handle->value[5] = tp->name[1]; handle->value[6] = tp->name[2]; handle->value[7] = tp->name[3]; handle->value[8] = tp->name[4]; for(uint8_t i=9;i<16;i++) handle->value[i] = 0; return true; } class TestTypeListener: public RTPSListener{ public: TestTypeListener(){}; ~TestTypeListener(){}; void newMessageCallback() { cout <<"New Message"<<endl; } }; int main(int argc, char** argv) { RTPSLog::setVerbosity(RTPSLog::EPROSIMA_INFO_VERBOSITY_LEVEL); int type; if(argc > 1) { RTPSLog::Info << "Parsing arguments: " << argv[1] << endl; RTPSLog::printInfo(); if(strcmp(argv[1],"1")==0) type = 1; else if(strcmp(argv[1],"2")==0) type = 2; else if(strcmp(argv[1],"3")==0) type = 3; } else type = WR; TestTypeDataType TestTypeData; DomainParticipant::registerType((DDSTopicDataType*)&TestTypeData); ParticipantParams_t PParam; PParam.defaultSendPort = 10042; PParam.m_useSimpleParticipantDiscovery = false; Participant* p = DomainParticipant::createParticipant(PParam); switch(type) { case 1: { WriterParams_t WParam; WParam.historySize = 20; WParam.topicKind = WITH_KEY; WParam.topicDataType = "TestType"; WParam.topicName = "Test_topic"; Publisher* pub1 = DomainParticipant::createPublisher(p,WParam); Publisher* pub2 = DomainParticipant::createPublisher(p,WParam); ReaderParams_t Rparam; Rparam.historySize = 50; Rparam.topicDataType = std::string("TestType"); Rparam.topicName = std::string("Test_topic"); Rparam.topicKind = NO_KEY; Locator_t loc; loc.kind = 1; loc.port = 10469; Rparam.unicastLocatorList.push_back(loc); //Listen in the 10469 port Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam); loc.set_IP4_address(192,168,1,IPTEST2); pub1->addReaderLocator(loc,true); pub2->addReaderLocator(loc,true); TestType tp1,tp2,tp_in; COPYSTR(tp1.name,"Obje1"); COPYSTR(tp2.name,"Obje2"); tp1.value = 0; tp1.price = 1.3; tp2.value = 0; tp2.price = -1.3; int n; cout << "Enter number to start: "; cin >> n; for(uint i = 0;i<10;i++) { tp1.value++; tp1.price *= (i+1); tp2.value++; tp2.price *= (i+1); pub1->write((void*)&tp1); pub2->write((void*)&tp2); if(pub1->getHistory_n() >= 0.8*WParam.historySize) pub1->removeMinSeqChange(); if(pub2->getHistory_n() >= 0.8*WParam.historySize) pub2->removeMinSeqChange(); if(i==8) { pub1->dispose((void*)&tp1); pub1->unregister((void*)&tp1); pub2->dispose((void*)&tp2); pub2->unregister((void*)&tp2); COPYSTR(tp1.name,"Obje3"); tp1.value = 0; tp1.price = 1.5; COPYSTR(tp2.name,"Obje4"); tp2.value = 0; tp2.price = 1.5; } if(sub->getHistory_n() >= 0.8*Rparam.historySize) { cout << "Taking all from subscriber" <<endl; std::vector<void*> data_vec; sub->takeAllCache(&data_vec); for(unsigned int i=0;i<data_vec.size();i++) ((TestType*)data_vec[i])->print(); cout << "Subscriber History has now: " << sub->getHistory_n() << " elements "<<endl; } } cout << "Sleeping 3 seconds"<<endl; sleep(3); while(sub->readMinSeqUnreadCache((void*)&tp_in)) { tp_in.print(); tp_in.value = -111; } break; } case 2: { ReaderParams_t Rparam; Rparam.historySize = 50; Rparam.topicDataType = std::string("TestType"); Rparam.topicName = std::string("Test_topic"); Rparam.topicKind = WITH_KEY; Locator_t loc; loc.kind = 1; loc.port = 10469; Rparam.unicastLocatorList.push_back(loc); //Listen in port 10469 Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam); TestTypeListener listener; sub->assignListener((RTPSListener*)&listener); WriterParams_t WParam; WParam.historySize = 50; WParam.topicKind = NO_KEY; WParam.topicDataType = "TestType"; WParam.topicName = "Test_topic"; Publisher* pub1 = DomainParticipant::createPublisher(p,WParam); loc.set_IP4_address(192,168,1,IPTEST1); pub1->addReaderLocator(loc,false); while(1) { cout << "Blocking until new message arrives " << endl; sub->blockUntilNewMessage(); cout << "After new message block " << sub->getHistory_n() << endl; TestType tp; while(sub->readMinSeqUnreadCache((void*)&tp)) { tp.print(); pub1->write((void*)&tp); tp.value = -1; tp.price = 0; COPYSTR(tp.name,"UNDEF"); } cout << "Read: " << sub->getReadElements_n() <<" from History: "<<sub->getHistory_n()<< endl; if(sub->getHistory_n() >= 0.5*Rparam.historySize) { cout << "Taking all" <<endl; std::vector<void*> data_vec; sub->takeAllCache(&data_vec); for(unsigned int i=0;i<data_vec.size();i++) ((TestType*)data_vec[i])->print(); cout << "History has now: " << sub->getHistory_n() << " elements "; cout << " and is FUll?: " << sub->isHistoryFull() << endl; } } break; } default: break; } cout << "Enter numer "<< endl; int n; cin >> n; DomainParticipant::stopAll(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLProjectedPolyDataRayBounder.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Lisa Sobierajski Avila who developed this class. Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkOpenGLProjectedPolyDataRayBounder.h" #include "vtkNew2VolumeRenderer.h" // Description: // Construct a new vtkOpenGLProjectedPolyDataRayBounder. The depth range // buffer is initially NULL and no display list has been created vtkOpenGLProjectedPolyDataRayBounder::vtkOpenGLProjectedPolyDataRayBounder() { this->DisplayList = 0; this->DepthRangeBuffer = NULL; } // Description: // Destruct the vtkOpenGLProjectedPolyDataRayBounder. Free the // DepthRangeBuffer if necessary vtkOpenGLProjectedPolyDataRayBounder::~vtkOpenGLProjectedPolyDataRayBounder() { if ( this->DepthRangeBuffer ) delete this->DepthRangeBuffer; } // Description: // Create a display list from the polygons contained in pdata. // Lines and vertices are ignored, polys and strips are used. void vtkOpenGLProjectedPolyDataRayBounder::Build( vtkPolyData *pdata ) { vtkCellArray *polys; vtkCellArray *strips; vtkPoints *points; int *pts, npts; int current_num_vertices = -1; int i; polys = pdata->GetPolys(); points = pdata->GetPoints(); strips = pdata->GetStrips(); if ( !glIsList( this->DisplayList ) ) this->DisplayList = glGenLists( 1 ); glNewList( this->DisplayList, GL_COMPILE ); for ( polys->InitTraversal(); polys->GetNextCell( npts, pts ); ) { // If we are doing a different number of vertices, or if this // is a polygon, then end what we were doing and begin again if ( current_num_vertices != npts || npts > 4 ) { // Unless of course this is our first time through - then we // don't want to end if ( current_num_vertices != -1 ) glEnd(); // How many vertices do we have? if ( npts == 3 ) glBegin( GL_TRIANGLES ); else if ( npts == 4 ) glBegin( GL_QUADS ); else glBegin( GL_POLYGON ); } // Draw the vertices for ( i = 0; i < npts; i++ ) glVertex3fv( points->GetPoint( pts[i] ) ); current_num_vertices = npts; } glEnd(); for ( strips->InitTraversal(); strips->GetNextCell( npts, pts ); ) { glBegin( GL_TRIANGLE_STRIP ); // Draw the vertices for ( i = 0; i < npts; i++ ) glVertex3fv( points->GetPoint( pts[i] ) ); glEnd(); } glEndList(); } // Description: // Draw the display list and create the depth range buffer. // // Known problem: // camera clipping planes (near/far) may clip the projected // geometry resulting in incorrect results. float *vtkOpenGLProjectedPolyDataRayBounder::Draw( vtkRenderer *ren, vtkMatrix4x4 *position_matrix ) { GLboolean lighting_on; int size[2]; float *near_buffer, *far_buffer; vtkTransform *transform; vtkMatrix4x4 *matrix; float ren_aspect[2], aspect, range[2]; float *ray_ptr; float *near_ptr, *far_ptr; float *range_ptr; vtkNew2VolumeRenderer *volren; float z_numerator, z_denom_mult, z_denom_add; float zfactor; int i, j; GLint current_viewport[4]; volren = (vtkNew2VolumeRenderer *) ren->GetNewVolumeRenderer(); // Create some objects that we will need later transform = vtkTransform::New(); matrix = vtkMatrix4x4::New(); // The size of the view rays is the size of the image we are creating ((vtkNew2VolumeRenderer *) (ren->GetNewVolumeRenderer()))->GetViewRaysSize( size ); // This should be fixed - I should not be off in someone else's viewport // if there are more than one of them... glGetIntegerv( GL_VIEWPORT, (GLint *) current_viewport ); glPushAttrib(GL_VIEWPORT_BIT); glViewport( current_viewport[0], current_viewport[1], (GLsizei) size[0], (GLsizei) size[1] ); // Create the near buffer storage near_buffer = new float[ size[0] * size[1] ]; // Create the far buffer storage far_buffer = new float[ size[0] * size[1] ]; if ( this->DepthRangeBuffer ) delete this->DepthRangeBuffer; this->DepthRangeBuffer = new float[ size[0] * size[1] * 2 ]; // Save previous lighting state, and turn lighting off glGetBooleanv( GL_LIGHTING, &lighting_on ); glDisable( GL_LIGHTING ); // Put the volume's matrix on the stack position_matrix->Transpose(); glPushMatrix(); glMultMatrixf( (*position_matrix)[0] ); // Do the far buffer glDepthFunc( GL_GREATER ); glClearColor( (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0) ); glClearDepth( (GLclampd)(0.0) ); glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); glCallList( this->DisplayList ); glReadPixels( 0, 0, size[0], size[1], GL_DEPTH_COMPONENT, GL_FLOAT, far_buffer ); // Do the near buffer glDepthFunc( GL_LESS ); glClearColor( (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0) ); glClearDepth( (GLclampd)(1.0) ); glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); glCallList( this->DisplayList ); glReadPixels( (GLint) 0, (GLint) 0, (GLsizei) size[0], (GLsizei) size[1], GL_DEPTH_COMPONENT, GL_FLOAT, near_buffer ); // Clean up glPopMatrix(); glDepthFunc( GL_LEQUAL ); if ( lighting_on ) glEnable( GL_LIGHTING ); glPopAttrib(); near_ptr = near_buffer; far_ptr = far_buffer; range_ptr = this->DepthRangeBuffer; if( ren->GetActiveCamera()->GetParallelProjection() ) { // Get the aspect ratio of the renderer ren->GetAspect( ren_aspect ); aspect = ren_aspect[0]/ren_aspect[1]; // Get the clipping range of the active camera ren->GetActiveCamera()->GetClippingRange( range ); // Create the perspective matrix for the camera. This will be used // to decode z values, so we will need to inverted transform->SetMatrix( ren->GetActiveCamera()->GetPerspectiveTransform( aspect, 0, 1 ) ); transform->Inverse(); // To speed things up, we pull the matrix out of the transform. // This way, we can decode z values faster since we know which elements // of the matrix are important, and which are zero. transform->GetMatrix( *matrix ); // Just checking that our assumptions are correct. This code should // be removed after the debugging phase is complete if( this->Debug ) { if ( matrix->Element[3][0] || matrix->Element[3][1] || matrix->Element[3][2] || matrix->Element[2][3] || (matrix->Element[3][3] != 1.0) ) { vtkErrorMacro( << "Oh no! They aren't 0 like they're supposed to be!"); cout << *transform; } } // These are the important elements of the matrix. We will decode // z values by : ((zbuffer value)*znum3) zfactor = -(matrix->Element[2][2]); for ( j = 0; j < size[1]; j++ ) for ( i = 0; i < size[0]; i++ ) { if ( *near_ptr < 1.0 ) { *(range_ptr++) = ((*(near_ptr++))*2.0 -1.0) * zfactor; *(range_ptr++) = ((*( far_ptr++))*2.0 -1.0) * zfactor; } else { *(range_ptr++) = -1.0; *(range_ptr++) = -1.0; near_ptr++; far_ptr++; } } } else { // Get the aspect ratio of the renderer ren->GetAspect( ren_aspect ); aspect = ren_aspect[0]/ren_aspect[1]; // Get the clipping range of the active camera ren->GetActiveCamera()->GetClippingRange( range ); // Create the perspective matrix for the camera. This will be used // to decode z values, so we will need to invert it transform->SetMatrix( ren->GetActiveCamera()->GetPerspectiveTransform( aspect, 0, 1 ) ); transform->Inverse(); // To speed things up, we pull the matrix out of the transform. // This way, we can decode z values faster since we know which elements // of the matrix are important, and which are zero. transform->GetMatrix( *matrix ); // Just checking that our assumptions are correct. This code should // be removed after the debugging phase is complete if( this->Debug ) { if ( matrix->Element[2][0] || matrix->Element[2][1] || matrix->Element[3][0] || matrix->Element[3][1] || matrix->Element[2][2] ) vtkErrorMacro( << "Oh no! They aren't 0 like they're supposed to be!"); } // These are the important elements of the matrix. We will decode // z values by taking the znum1 and dividing by the zbuffer z value times // zdenom1 plus zdenom2. z_numerator = matrix->Element[2][3]; z_denom_mult = matrix->Element[3][2]; z_denom_add = matrix->Element[3][3]; ray_ptr = volren->GetPerspectiveViewRays(); ray_ptr += 2; for ( j = 0; j < size[1]; j++ ) for ( i = 0; i < size[0]; i++ ) { if ( *near_ptr < 1.0 ) { *(range_ptr++) = (-z_numerator / ( ((*(near_ptr++))*2.0 -1.0) * z_denom_mult + z_denom_add )) / (-(*ray_ptr)); *(range_ptr++) = (-z_numerator / ( ((*(far_ptr++))*2.0 -1.0) * z_denom_mult + z_denom_add )) / (-(*ray_ptr)); ray_ptr += 3; } else { *(range_ptr++) = -1.0; *(range_ptr++) = -1.0; near_ptr++; far_ptr++; ray_ptr += 3; } } } delete near_buffer; delete far_buffer; // Delete the objects we created transform->Delete(); matrix->Delete(); return ( this->DepthRangeBuffer ); } // Description: // Print the vtkOpenGLProjectedPolyDataRayBounder void vtkOpenGLProjectedPolyDataRayBounder::PrintSelf(ostream& os, vtkIndent indent) { vtkProjectedPolyDataRayBounder::PrintSelf(os,indent); } <commit_msg>Changes for replacement of vtkNewVolumeRenderer with vtkRayCaster<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLProjectedPolyDataRayBounder.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Lisa Sobierajski Avila who developed this class. Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkOpenGLProjectedPolyDataRayBounder.h" #include "vtkRenderer.h" #include "vtkRayCaster.h" // Description: // Construct a new vtkOpenGLProjectedPolyDataRayBounder. The depth range // buffer is initially NULL and no display list has been created vtkOpenGLProjectedPolyDataRayBounder::vtkOpenGLProjectedPolyDataRayBounder() { this->DisplayList = 0; this->DepthRangeBuffer = NULL; } // Description: // Destruct the vtkOpenGLProjectedPolyDataRayBounder. Free the // DepthRangeBuffer if necessary vtkOpenGLProjectedPolyDataRayBounder::~vtkOpenGLProjectedPolyDataRayBounder() { if ( this->DepthRangeBuffer ) delete this->DepthRangeBuffer; } // Description: // Create a display list from the polygons contained in pdata. // Lines and vertices are ignored, polys and strips are used. void vtkOpenGLProjectedPolyDataRayBounder::Build( vtkPolyData *pdata ) { vtkCellArray *polys; vtkCellArray *strips; vtkPoints *points; int *pts, npts; int current_num_vertices = -1; int i; polys = pdata->GetPolys(); points = pdata->GetPoints(); strips = pdata->GetStrips(); if ( !glIsList( this->DisplayList ) ) this->DisplayList = glGenLists( 1 ); glNewList( this->DisplayList, GL_COMPILE ); for ( polys->InitTraversal(); polys->GetNextCell( npts, pts ); ) { // If we are doing a different number of vertices, or if this // is a polygon, then end what we were doing and begin again if ( current_num_vertices != npts || npts > 4 ) { // Unless of course this is our first time through - then we // don't want to end if ( current_num_vertices != -1 ) glEnd(); // How many vertices do we have? if ( npts == 3 ) glBegin( GL_TRIANGLES ); else if ( npts == 4 ) glBegin( GL_QUADS ); else glBegin( GL_POLYGON ); } // Draw the vertices for ( i = 0; i < npts; i++ ) glVertex3fv( points->GetPoint( pts[i] ) ); current_num_vertices = npts; } glEnd(); for ( strips->InitTraversal(); strips->GetNextCell( npts, pts ); ) { glBegin( GL_TRIANGLE_STRIP ); // Draw the vertices for ( i = 0; i < npts; i++ ) glVertex3fv( points->GetPoint( pts[i] ) ); glEnd(); } glEndList(); } // Description: // Draw the display list and create the depth range buffer. // // Known problem: // camera clipping planes (near/far) may clip the projected // geometry resulting in incorrect results. float *vtkOpenGLProjectedPolyDataRayBounder::Draw( vtkRenderer *ren, vtkMatrix4x4 *position_matrix ) { GLboolean lighting_on; int size[2]; float *near_buffer, *far_buffer; vtkTransform *transform; vtkMatrix4x4 *matrix; float ren_aspect[2], aspect, range[2]; float *ray_ptr; float *near_ptr, *far_ptr; float *range_ptr; vtkRayCaster *ray_caster; float z_numerator, z_denom_mult, z_denom_add; float zfactor; int i, j; GLint current_viewport[4]; ray_caster = ren->GetRayCaster(); // Create some objects that we will need later transform = vtkTransform::New(); matrix = vtkMatrix4x4::New(); // The size of the view rays is the size of the image we are creating ren->GetRayCaster()->GetViewRaysSize( size ); // This should be fixed - I should not be off in someone else's viewport // if there are more than one of them... glGetIntegerv( GL_VIEWPORT, current_viewport ); glPushAttrib(GL_VIEWPORT_BIT); glViewport( current_viewport[0], current_viewport[1], (GLsizei) size[0], (GLsizei) size[1] ); // Create the near buffer storage near_buffer = new float[ size[0] * size[1] ]; // Create the far buffer storage far_buffer = new float[ size[0] * size[1] ]; if ( this->DepthRangeBuffer ) delete this->DepthRangeBuffer; this->DepthRangeBuffer = new float[ size[0] * size[1] * 2 ]; // Save previous lighting state, and turn lighting off glGetBooleanv( GL_LIGHTING, &lighting_on ); glDisable( GL_LIGHTING ); // Put the volume's matrix on the stack position_matrix->Transpose(); glPushMatrix(); glMultMatrixf( (*position_matrix)[0] ); // Do the far buffer glDepthFunc( GL_GREATER ); glClearColor( (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0) ); glClearDepth( (GLclampd)(0.0) ); glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); glCallList( this->DisplayList ); glReadPixels( 0, 0, size[0], size[1], GL_DEPTH_COMPONENT, GL_FLOAT, far_buffer ); // Do the near buffer glDepthFunc( GL_LESS ); glClearColor( (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0) ); glClearDepth( (GLclampd)(1.0) ); glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); glCallList( this->DisplayList ); glReadPixels( (GLint) 0, (GLint) 0, (GLsizei) size[0], (GLsizei) size[1], GL_DEPTH_COMPONENT, GL_FLOAT, near_buffer ); // Clean up glPopMatrix(); glDepthFunc( GL_LEQUAL ); if ( lighting_on ) glEnable( GL_LIGHTING ); glPopAttrib(); near_ptr = near_buffer; far_ptr = far_buffer; range_ptr = this->DepthRangeBuffer; if( ren->GetActiveCamera()->GetParallelProjection() ) { // Get the aspect ratio of the renderer ren->GetAspect( ren_aspect ); aspect = ren_aspect[0]/ren_aspect[1]; // Get the clipping range of the active camera ren->GetActiveCamera()->GetClippingRange( range ); // Create the perspective matrix for the camera. This will be used // to decode z values, so we will need to inverted transform->SetMatrix( ren->GetActiveCamera()->GetPerspectiveTransform( aspect, 0, 1 ) ); transform->Inverse(); // To speed things up, we pull the matrix out of the transform. // This way, we can decode z values faster since we know which elements // of the matrix are important, and which are zero. transform->GetMatrix( *matrix ); // Just checking that our assumptions are correct. This code should // be removed after the debugging phase is complete if( this->Debug ) { if ( matrix->Element[3][0] || matrix->Element[3][1] || matrix->Element[3][2] || matrix->Element[2][3] || (matrix->Element[3][3] != 1.0) ) { vtkErrorMacro( << "Oh no! They aren't 0 like they're supposed to be!"); cout << *transform; } } // These are the important elements of the matrix. We will decode // z values by : ((zbuffer value)*znum3) zfactor = -(matrix->Element[2][2]); for ( j = 0; j < size[1]; j++ ) for ( i = 0; i < size[0]; i++ ) { if ( *near_ptr < 1.0 ) { *(range_ptr++) = ((*(near_ptr++))*2.0 -1.0) * zfactor; *(range_ptr++) = ((*( far_ptr++))*2.0 -1.0) * zfactor; } else { *(range_ptr++) = -1.0; *(range_ptr++) = -1.0; near_ptr++; far_ptr++; } } } else { // Get the aspect ratio of the renderer ren->GetAspect( ren_aspect ); aspect = ren_aspect[0]/ren_aspect[1]; // Get the clipping range of the active camera ren->GetActiveCamera()->GetClippingRange( range ); // Create the perspective matrix for the camera. This will be used // to decode z values, so we will need to invert it transform->SetMatrix( ren->GetActiveCamera()->GetPerspectiveTransform( aspect, 0, 1 ) ); transform->Inverse(); // To speed things up, we pull the matrix out of the transform. // This way, we can decode z values faster since we know which elements // of the matrix are important, and which are zero. transform->GetMatrix( *matrix ); // Just checking that our assumptions are correct. This code should // be removed after the debugging phase is complete if( this->Debug ) { if ( matrix->Element[2][0] || matrix->Element[2][1] || matrix->Element[3][0] || matrix->Element[3][1] || matrix->Element[2][2] ) vtkErrorMacro( << "Oh no! They aren't 0 like they're supposed to be!"); } // These are the important elements of the matrix. We will decode // z values by taking the znum1 and dividing by the zbuffer z value times // zdenom1 plus zdenom2. z_numerator = matrix->Element[2][3]; z_denom_mult = matrix->Element[3][2]; z_denom_add = matrix->Element[3][3]; ray_ptr = ray_caster->GetPerspectiveViewRays(); ray_ptr += 2; for ( j = 0; j < size[1]; j++ ) for ( i = 0; i < size[0]; i++ ) { if ( *near_ptr < 1.0 ) { *(range_ptr++) = (-z_numerator / ( ((*(near_ptr++))*2.0 -1.0) * z_denom_mult + z_denom_add )) / (-(*ray_ptr)); *(range_ptr++) = (-z_numerator / ( ((*(far_ptr++))*2.0 -1.0) * z_denom_mult + z_denom_add )) / (-(*ray_ptr)); ray_ptr += 3; } else { *(range_ptr++) = -1.0; *(range_ptr++) = -1.0; near_ptr++; far_ptr++; ray_ptr += 3; } } } delete near_buffer; delete far_buffer; // Delete the objects we created transform->Delete(); matrix->Delete(); return ( this->DepthRangeBuffer ); } // Description: // Print the vtkOpenGLProjectedPolyDataRayBounder void vtkOpenGLProjectedPolyDataRayBounder::PrintSelf(ostream& os, vtkIndent indent) { vtkProjectedPolyDataRayBounder::PrintSelf(os,indent); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: jscriptclasses.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:16:40 $ * * 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 __JSCRIPTCLASSES_HXX #define __JSCRIPTCLASSES_HXX #include <tools/presys.h> #include "stdafx.h" #include <tools/postsys.h> #include "comifaces.hxx" // Sequences are represented by prepending "[]", e.g. []char, [][]byte, [][][]object, etc. // To make a JScriptValue object to an out parameter, call // "InitOutParam" and to make it a in/out parameter call // "InitInOutParam" // If the object represents an out parameter then the value can after the call // be retrived by "Get". // From JavaScript the functions Get, Set, InitOutParam and InitInOutParam are // used, that is they are accessible through IDispatch. The functions are used // by the bridge. class JScriptValue: public CComObjectRootEx<CComMultiThreadModel>, public IJScriptValueObject, public IDispatch { public: JScriptValue(); virtual ~JScriptValue(); BEGIN_COM_MAP(JScriptValue) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IJScriptValueObject) END_COM_MAP() // IDispatch ------------------------------------------- STDMETHOD( GetTypeInfoCount)(UINT *pctinfo); STDMETHOD( GetTypeInfo)( UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo); STDMETHOD( GetIDsOfNames)( REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId); STDMETHOD( Invoke)( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); // IJScriptOutParam -------------------------------------- STDMETHOD( Set)( VARIANT type, VARIANT value); STDMETHOD( Get)( VARIANT *val); STDMETHOD( InitOutParam)(); STDMETHOD( InitInOutParam)( VARIANT type, VARIANT value); STDMETHOD( IsOutParam)( VARIANT_BOOL * flag); STDMETHOD( IsInOutParam)( VARIANT_BOOL * flag); STDMETHOD( GetValue)( BSTR* type, VARIANT *value); CComVariant m_varValue; CComBSTR m_bstrType; unsigned m_bOutParam: 1; unsigned m_bInOutParam: 1; }; // If a class is implemented in JScript, then its method class JScriptOutParam: public CComObjectRootEx<CComMultiThreadModel>, public IDispatch { public: JScriptOutParam(); virtual ~JScriptOutParam(); BEGIN_COM_MAP(JScriptOutParam) COM_INTERFACE_ENTRY(IDispatch) END_COM_MAP() // IDispatch ------------------------------------------- STDMETHOD( GetTypeInfoCount)(UINT *pctinfo); STDMETHOD( GetTypeInfo)( UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo); STDMETHOD( GetIDsOfNames)( REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId); STDMETHOD( Invoke)( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); private: CComVariant m_varValue; }; #endif <commit_msg>includes now directly atl headers instead of Stdafx.h, Stdafx.h and Stdafx.cpp has been removed<commit_after>/************************************************************************* * * $RCSfile: jscriptclasses.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: jl $ $Date: 2000-10-19 10:51:09 $ * * 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 __JSCRIPTCLASSES_HXX #define __JSCRIPTCLASSES_HXX #include <tools/presys.h> //#include "stdafx.h" #define STRICT #define _WIN32_WINNT 0x0400 #define _WIN32_DCOM #ifdef _DEBUG //#define _ATL_DEBUG_INTERFACES #endif #include <atlbase.h> extern CComModule _Module; #include <atlcom.h> #include <tools/postsys.h> #include "comifaces.hxx" // Sequences are represented by prepending "[]", e.g. []char, [][]byte, [][][]object, etc. // To make a JScriptValue object to an out parameter, call // "InitOutParam" and to make it a in/out parameter call // "InitInOutParam" // If the object represents an out parameter then the value can after the call // be retrived by "Get". // From JavaScript the functions Get, Set, InitOutParam and InitInOutParam are // used, that is they are accessible through IDispatch. The functions are used // by the bridge. class JScriptValue: public CComObjectRootEx<CComMultiThreadModel>, public IJScriptValueObject, public IDispatch { public: JScriptValue(); virtual ~JScriptValue(); BEGIN_COM_MAP(JScriptValue) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IJScriptValueObject) END_COM_MAP() // IDispatch ------------------------------------------- STDMETHOD( GetTypeInfoCount)(UINT *pctinfo); STDMETHOD( GetTypeInfo)( UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo); STDMETHOD( GetIDsOfNames)( REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId); STDMETHOD( Invoke)( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); // IJScriptOutParam -------------------------------------- STDMETHOD( Set)( VARIANT type, VARIANT value); STDMETHOD( Get)( VARIANT *val); STDMETHOD( InitOutParam)(); STDMETHOD( InitInOutParam)( VARIANT type, VARIANT value); STDMETHOD( IsOutParam)( VARIANT_BOOL * flag); STDMETHOD( IsInOutParam)( VARIANT_BOOL * flag); STDMETHOD( GetValue)( BSTR* type, VARIANT *value); CComVariant m_varValue; CComBSTR m_bstrType; unsigned m_bOutParam: 1; unsigned m_bInOutParam: 1; }; // If a class is implemented in JScript, then its method class JScriptOutParam: public CComObjectRootEx<CComMultiThreadModel>, public IDispatch { public: JScriptOutParam(); virtual ~JScriptOutParam(); BEGIN_COM_MAP(JScriptOutParam) COM_INTERFACE_ENTRY(IDispatch) END_COM_MAP() // IDispatch ------------------------------------------- STDMETHOD( GetTypeInfoCount)(UINT *pctinfo); STDMETHOD( GetTypeInfo)( UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo); STDMETHOD( GetIDsOfNames)( REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId); STDMETHOD( Invoke)( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); private: CComVariant m_varValue; }; #endif <|endoftext|>
<commit_before>// Author: Leticia Cunqueiro //Some explanations: //if fpythia==1, quenched pythia (qpythia) is configured. //if fpythia==2, pyquen afterburner applyed // The list of avaliable tunes can be checked in $ALICE_ROOT/PYTHIA6/pythiaX.f , inside subroutine PYTUNE // Note that if you are using QPYTHIA , it only works with Q2-ordered showers, that is tune<300. //More modern tunes are pt-ordered and use a different FSR shower. //In the implementation of qpythia in aliroot I set as default the following computation of the geometry: // -Glauber to determine the overlapping region of the nuclei and the impact parameter of the collision // -Random sampling of the initial coordinates of the hard scattering in the overlapping region // -Given the coordinates and direction of each parton in the shower, calculate the path length to the "end" // of the medium and the integrated qhat along this path length, alla PQM. //In the PQM approach, you integrate the qhat(dx,dy) along the path length and this is purely geometrical. See formula (13) in http://arxiv.org/pdf/hep-ph/0406201.pdf //There is a free parameter k (in fm), that sets the scale of the transport coefficient. In 0-10% PbPb collisions, //the average <qhat> and k are related via a number: // <qhat>/k =5.87 e^-5 fm^-4 //If you want a <qhat> of 10 GeV2/fm, // 10 /5.87e^-5 (GeV2 fm^3)=k //If you want k in fm then you have to divide by the squared of hbarc (hbar c=0.197 GeV fm) // This gives k=4.4e^6 fm, which is the quench value we set in SetQhat AliGenerator* AddMCGenQuench(Float_t e_cms = 2760., Double_t ptHardMin = 0., Double_t ptHardMax = 0., Int_t fpythia = 1, Double_t quench=4.4e6, ,Int_t ianglepyquen = 2) { //Add Pythia generator: pt-hard bin or min bias gSystem->Load("liblhapdf.so"); return CreatePythia6Gen(e_cms, ptHardMin, ptHardMax, fpythia, quench, ianglepyquen); } AliGenerator* CreatePythia6Gen(Float_t e_cms, Int_t ptHardMin, Int_t ptHardMax, Int_t fpythia, Double_t quench = 4.4e6, Int_t ianglepyquen=2) { gSystem->Load("libqpythia.so"); gSystem->Load("libEGPythia6.so"); gSystem->Load("libAliPythia6.so"); AliGenPythia* genP = new AliGenPythia(1); // vertex position and smearing genP->SetVertexSmear(kPerEvent); // charm, beauty, charm_unforced, beauty_unforced, jpsi, jpsi_chi, mb if (ptHardMin>0.) { genP->SetProcess(kPyJets); genP->SetPtHard((float)ptHardMin,(float)ptHardMax); } else genP->SetProcess(kPyMb); // Minimum Bias // Centre of mass energy genP->SetEnergyCMS(e_cms); // in GeV //for jet quenching with QPYTHIA if (fpythia == 1){ genP->SetTune(103); //tune DW, standard choice for Q2 showers genP->SetQuench(4); genP->SetQhat(quench); } //for pyquen afterburner if (fpythia == 2){ genP->SetTune(103); //tune DW, standard choice for Q2 showers genP->SetQuench(2); genP->SetPyquenPar(1,0.1,0,0,ianglepyquen); } return genP; } <commit_msg>fix typo<commit_after>// Author: Leticia Cunqueiro //Some explanations: //if fpythia==1, quenched pythia (qpythia) is configured. //if fpythia==2, pyquen afterburner applyed // The list of avaliable tunes can be checked in $ALICE_ROOT/PYTHIA6/pythiaX.f , inside subroutine PYTUNE // Note that if you are using QPYTHIA , it only works with Q2-ordered showers, that is tune<300. //More modern tunes are pt-ordered and use a different FSR shower. //In the implementation of qpythia in aliroot I set as default the following computation of the geometry: // -Glauber to determine the overlapping region of the nuclei and the impact parameter of the collision // -Random sampling of the initial coordinates of the hard scattering in the overlapping region // -Given the coordinates and direction of each parton in the shower, calculate the path length to the "end" // of the medium and the integrated qhat along this path length, alla PQM. //In the PQM approach, you integrate the qhat(dx,dy) along the path length and this is purely geometrical. See formula (13) in http://arxiv.org/pdf/hep-ph/0406201.pdf //There is a free parameter k (in fm), that sets the scale of the transport coefficient. In 0-10% PbPb collisions, //the average <qhat> and k are related via a number: // <qhat>/k =5.87 e^-5 fm^-4 //If you want a <qhat> of 10 GeV2/fm, // 10 /5.87e^-5 (GeV2 fm^3)=k //If you want k in fm then you have to divide by the squared of hbarc (hbar c=0.197 GeV fm) // This gives k=4.4e^6 fm, which is the quench value we set in SetQhat AliGenerator* AddMCGenQuench(Float_t e_cms = 2760., Double_t ptHardMin = 0., Double_t ptHardMax = 0., Int_t fpythia = 1, Double_t quench=4.4e6, Int_t ianglepyquen = 2) { //Add Pythia generator: pt-hard bin or min bias gSystem->Load("liblhapdf.so"); return CreatePythia6Gen(e_cms, ptHardMin, ptHardMax, fpythia, quench, ianglepyquen); } AliGenerator* CreatePythia6Gen(Float_t e_cms, Int_t ptHardMin, Int_t ptHardMax, Int_t fpythia, Double_t quench = 4.4e6, Int_t ianglepyquen=2) { gSystem->Load("libqpythia.so"); gSystem->Load("libEGPythia6.so"); gSystem->Load("libAliPythia6.so"); AliGenPythia* genP = new AliGenPythia(1); // vertex position and smearing genP->SetVertexSmear(kPerEvent); // charm, beauty, charm_unforced, beauty_unforced, jpsi, jpsi_chi, mb if (ptHardMin>0.) { genP->SetProcess(kPyJets); genP->SetPtHard((float)ptHardMin,(float)ptHardMax); } else genP->SetProcess(kPyMb); // Minimum Bias // Centre of mass energy genP->SetEnergyCMS(e_cms); // in GeV //for jet quenching with QPYTHIA if (fpythia == 1){ genP->SetTune(103); //tune DW, standard choice for Q2 showers genP->SetQuench(4); genP->SetQhat(quench); } //for pyquen afterburner if (fpythia == 2){ genP->SetTune(103); //tune DW, standard choice for Q2 showers genP->SetQuench(2); genP->SetPyquenPar(1,0.1,0,0,ianglepyquen); } return genP; } <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIScrollbar.cpp created: 13/4/2004 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team * * 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 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 "elements/CEGUIScrollbar.h" #include "elements/CEGUIThumb.h" #include "CEGUIWindowManager.h" #include "CEGUIExceptions.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const String Scrollbar::EventNamespace("Scrollbar"); const String Scrollbar::WidgetTypeName("CEGUI/Scrollbar"); //----------------------------------------------------------------------------// const String Scrollbar::EventScrollPositionChanged( "ScrollPositionChanged" ); const String Scrollbar::EventThumbTrackStarted("ThumbTrackStarted"); const String Scrollbar::EventThumbTrackEnded("ThumbTrackEnded"); const String Scrollbar::EventScrollConfigChanged("ScrollConfigChanged"); //----------------------------------------------------------------------------// const String Scrollbar::ThumbName("__auto_thumb__"); const String Scrollbar::IncreaseButtonName("__auto_incbtn__"); const String Scrollbar::DecreaseButtonName("__auto_decbtn__"); //----------------------------------------------------------------------------// ScrollbarWindowRenderer::ScrollbarWindowRenderer(const String& name) : WindowRenderer(name, Scrollbar::EventNamespace) { } //----------------------------------------------------------------------------// Scrollbar::Scrollbar(const String& type, const String& name) : Window(type, name), d_documentSize(1.0f), d_pageSize(0.0f), d_stepSize(1.0f), d_overlapSize(0.0f), d_position(0.0f), d_endLockPosition(false) { addScrollbarProperties(); } //----------------------------------------------------------------------------// Scrollbar::~Scrollbar(void) { } //----------------------------------------------------------------------------// void Scrollbar::initialiseComponents(void) { // Set up thumb Thumb* const t = getThumb(); t->subscribeEvent(Thumb::EventThumbPositionChanged, Event::Subscriber(&CEGUI::Scrollbar::handleThumbMoved, this)); t->subscribeEvent(Thumb::EventThumbTrackStarted, Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackStarted, this)); t->subscribeEvent(Thumb::EventThumbTrackEnded, Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackEnded, this)); // set up Increase button getIncreaseButton()-> subscribeEvent(PushButton::EventMouseButtonDown, Event::Subscriber(&CEGUI::Scrollbar::handleIncreaseClicked, this)); // set up Decrease button getDecreaseButton()-> subscribeEvent(PushButton::EventMouseButtonDown, Event::Subscriber(&CEGUI::Scrollbar::handleDecreaseClicked, this)); // do initial layout performChildWindowLayout(); } //----------------------------------------------------------------------------// void Scrollbar::setDocumentSize(float document_size) { if (d_documentSize != document_size) { const bool reset_max_position = d_endLockPosition && isAtEnd(); d_documentSize = document_size; if (reset_max_position) setScrollPosition(getMaxScrollPosition()); else updateThumb(); WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setPageSize(float page_size) { if (d_pageSize != page_size) { const bool reset_max_position = d_endLockPosition && isAtEnd(); d_pageSize = page_size; if (reset_max_position) setScrollPosition(getMaxScrollPosition()); else updateThumb(); WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setStepSize(float step_size) { if (d_stepSize != step_size) { d_stepSize = step_size; WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setOverlapSize(float overlap_size) { if (d_overlapSize != overlap_size) { d_overlapSize = overlap_size; WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setScrollPosition(float position) { const bool modified = setScrollPosition_impl(position); updateThumb(); // notification if required if (modified) { WindowEventArgs args(this); onScrollPositionChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::onScrollPositionChanged(WindowEventArgs& e) { fireEvent(EventScrollPositionChanged, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onThumbTrackStarted(WindowEventArgs& e) { fireEvent(EventThumbTrackStarted, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onThumbTrackEnded(WindowEventArgs& e) { fireEvent(EventThumbTrackEnded, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onScrollConfigChanged(WindowEventArgs& e) { performChildWindowLayout(); fireEvent(EventScrollConfigChanged, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onMouseButtonDown(MouseEventArgs& e) { // base class processing Window::onMouseButtonDown(e); if (e.button == LeftButton) { const float adj = getAdjustDirectionFromPoint(e.position); // adjust scroll bar position in whichever direction as required. if (adj != 0) setScrollPosition( d_position + ((d_pageSize - d_overlapSize) * adj)); ++e.handled; } } //----------------------------------------------------------------------------// void Scrollbar::onMouseWheel(MouseEventArgs& e) { // base class processing Window::onMouseWheel(e); // scroll by e.wheelChange * stepSize setScrollPosition(d_position + d_stepSize * -e.wheelChange); // ensure the message does not go to our parent. ++e.handled; } //----------------------------------------------------------------------------// bool Scrollbar::handleThumbMoved(const EventArgs&) { // adjust scroll bar position as required. setScrollPosition(getValueFromThumb()); return true; } //----------------------------------------------------------------------------// bool Scrollbar::handleIncreaseClicked(const EventArgs& e) { if (((const MouseEventArgs&)e).button == LeftButton) { // adjust scroll bar position as required. setScrollPosition(d_position + d_stepSize); return true; } return false; } //----------------------------------------------------------------------------// bool Scrollbar::handleDecreaseClicked(const EventArgs& e) { if (((const MouseEventArgs&)e).button == LeftButton) { // adjust scroll bar position as required. setScrollPosition(d_position - d_stepSize); return true; } return false; } //----------------------------------------------------------------------------// bool Scrollbar::handleThumbTrackStarted(const EventArgs&) { // simply trigger our own version of this event WindowEventArgs args(this); onThumbTrackStarted(args); return true; } //----------------------------------------------------------------------------// bool Scrollbar::handleThumbTrackEnded(const EventArgs&) { // simply trigger our own version of this event WindowEventArgs args(this); onThumbTrackEnded(args); return true; } //----------------------------------------------------------------------------// void Scrollbar::addScrollbarProperties(void) { const String propertyOrigin("Scrollbar"); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "DocumentSize", "Property to get/set the document size for the Scrollbar. Value is a float.", &Scrollbar::setDocumentSize, &Scrollbar::getDocumentSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "PageSize", "Property to get/set the page size for the Scrollbar. Value is a float.", &Scrollbar::setPageSize, &Scrollbar::getPageSize, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "StepSize", "Property to get/set the step size for the Scrollbar. Value is a float.", &Scrollbar::setStepSize, &Scrollbar::getStepSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "OverlapSize", "Property to get/set the overlap size for the Scrollbar. Value is a float.", &Scrollbar::setOverlapSize, &Scrollbar::getOverlapSize, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "ScrollPosition", "Property to get/set the scroll position of the Scrollbar. Value is a float.", &Scrollbar::setScrollPosition, &Scrollbar::getScrollPosition, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "EndLockEnabled", "Property to get/set the 'end lock' mode setting for the Scrollbar. " "Value is either \"True\" or \"False\".", &Scrollbar::setAlpha, &Scrollbar::getAlpha, false ); // we ban all these properties from xml for auto windows if (isAutoWindow()) { banPropertyFromXML("DocumentSize"); banPropertyFromXML("PageSize"); banPropertyFromXML("StepSize"); banPropertyFromXML("OverlapSize"); banPropertyFromXML("ScrollPosition"); // scrollbars tend to have their visibility toggled alot, so we ban // that as well banPropertyFromXML("Visible"); } } //----------------------------------------------------------------------------// PushButton* Scrollbar::getIncreaseButton() const { return static_cast<PushButton*>(getChild(IncreaseButtonName)); } //----------------------------------------------------------------------------// PushButton* Scrollbar::getDecreaseButton() const { return static_cast<PushButton*>(getChild(DecreaseButtonName)); } //----------------------------------------------------------------------------// Thumb* Scrollbar::getThumb() const { return static_cast<Thumb*>(getChild(ThumbName)); } //----------------------------------------------------------------------------// void Scrollbar::updateThumb(void) { if (!d_windowRenderer) CEGUI_THROW(InvalidRequestException("Scrollbar::updateThumb: This " "function must be implemented by the window renderer object (no " "window renderer is assigned.)")); static_cast<ScrollbarWindowRenderer*>(d_windowRenderer)->updateThumb(); } //----------------------------------------------------------------------------// float Scrollbar::getValueFromThumb(void) const { if (!d_windowRenderer) CEGUI_THROW(InvalidRequestException("Scrollbar::getValueFromThumb: This " "function must be implemented by the window renderer object (no " "window renderer is assigned.)")); return static_cast<ScrollbarWindowRenderer*>( d_windowRenderer)->getValueFromThumb(); } //----------------------------------------------------------------------------// float Scrollbar::getAdjustDirectionFromPoint(const Vector2f& pt) const { if (!d_windowRenderer) CEGUI_THROW(InvalidRequestException( "Scrollbar::getAdjustDirectionFromPoint: " "This function must be implemented by the window renderer object " "(no window renderer is assigned.)")); return static_cast<ScrollbarWindowRenderer*>( d_windowRenderer)->getAdjustDirectionFromPoint(pt); } //----------------------------------------------------------------------------// bool Scrollbar::setScrollPosition_impl(const float position) { const float old_pos = d_position; const float max_pos = getMaxScrollPosition(); // limit position to valid range: 0 <= position <= max_pos d_position = (position >= 0) ? ((position <= max_pos) ? position : max_pos) : 0.0f; return d_position != old_pos; } //----------------------------------------------------------------------------// void Scrollbar::setConfig(const float* const document_size, const float* const page_size, const float* const step_size, const float* const overlap_size, const float* const position) { const bool reset_max_position = d_endLockPosition && isAtEnd(); bool config_changed = false; bool position_changed = false; if (document_size && (d_documentSize != *document_size)) { d_documentSize = *document_size; config_changed = true; } if (page_size && (d_pageSize != *page_size)) { d_pageSize = *page_size; config_changed = true; } if (step_size && (d_stepSize != *step_size)) { d_stepSize = *step_size; config_changed = true; } if (overlap_size && (d_overlapSize != *overlap_size)) { d_overlapSize = *overlap_size; config_changed = true; } if (position) position_changed = setScrollPosition_impl(*position); else if (reset_max_position) position_changed = setScrollPosition_impl(getMaxScrollPosition()); // _always_ update the thumb to keep things in sync. (though this // can cause a double-trigger of EventScrollPositionChanged, which // also happens with setScrollPosition anyway). updateThumb(); // // Fire appropriate events based on actions we took. // if (config_changed) { WindowEventArgs args(this); onScrollConfigChanged(args); } if (position_changed) { WindowEventArgs args(this); onScrollPositionChanged(args); } } //----------------------------------------------------------------------------// float Scrollbar::getMaxScrollPosition() const { // max position is (docSize - pageSize) // but must be at least 0 (in case doc size is very small) return ceguimax((d_documentSize - d_pageSize), 0.0f); } //----------------------------------------------------------------------------// bool Scrollbar::isAtEnd() const { return d_position >= getMaxScrollPosition(); } //----------------------------------------------------------------------------// void Scrollbar::setEndLockEnabled(const bool enabled) { d_endLockPosition = enabled; } //----------------------------------------------------------------------------// bool Scrollbar::isEndLockEnabled() const { return d_endLockPosition; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>MOD: fix the dump copy and paste error in Scrollbar with EndLockEnabled<commit_after>/*********************************************************************** filename: CEGUIScrollbar.cpp created: 13/4/2004 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team * * 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 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 "elements/CEGUIScrollbar.h" #include "elements/CEGUIThumb.h" #include "CEGUIWindowManager.h" #include "CEGUIExceptions.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const String Scrollbar::EventNamespace("Scrollbar"); const String Scrollbar::WidgetTypeName("CEGUI/Scrollbar"); //----------------------------------------------------------------------------// const String Scrollbar::EventScrollPositionChanged( "ScrollPositionChanged" ); const String Scrollbar::EventThumbTrackStarted("ThumbTrackStarted"); const String Scrollbar::EventThumbTrackEnded("ThumbTrackEnded"); const String Scrollbar::EventScrollConfigChanged("ScrollConfigChanged"); //----------------------------------------------------------------------------// const String Scrollbar::ThumbName("__auto_thumb__"); const String Scrollbar::IncreaseButtonName("__auto_incbtn__"); const String Scrollbar::DecreaseButtonName("__auto_decbtn__"); //----------------------------------------------------------------------------// ScrollbarWindowRenderer::ScrollbarWindowRenderer(const String& name) : WindowRenderer(name, Scrollbar::EventNamespace) { } //----------------------------------------------------------------------------// Scrollbar::Scrollbar(const String& type, const String& name) : Window(type, name), d_documentSize(1.0f), d_pageSize(0.0f), d_stepSize(1.0f), d_overlapSize(0.0f), d_position(0.0f), d_endLockPosition(false) { addScrollbarProperties(); } //----------------------------------------------------------------------------// Scrollbar::~Scrollbar(void) { } //----------------------------------------------------------------------------// void Scrollbar::initialiseComponents(void) { // Set up thumb Thumb* const t = getThumb(); t->subscribeEvent(Thumb::EventThumbPositionChanged, Event::Subscriber(&CEGUI::Scrollbar::handleThumbMoved, this)); t->subscribeEvent(Thumb::EventThumbTrackStarted, Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackStarted, this)); t->subscribeEvent(Thumb::EventThumbTrackEnded, Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackEnded, this)); // set up Increase button getIncreaseButton()-> subscribeEvent(PushButton::EventMouseButtonDown, Event::Subscriber(&CEGUI::Scrollbar::handleIncreaseClicked, this)); // set up Decrease button getDecreaseButton()-> subscribeEvent(PushButton::EventMouseButtonDown, Event::Subscriber(&CEGUI::Scrollbar::handleDecreaseClicked, this)); // do initial layout performChildWindowLayout(); } //----------------------------------------------------------------------------// void Scrollbar::setDocumentSize(float document_size) { if (d_documentSize != document_size) { const bool reset_max_position = d_endLockPosition && isAtEnd(); d_documentSize = document_size; if (reset_max_position) setScrollPosition(getMaxScrollPosition()); else updateThumb(); WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setPageSize(float page_size) { if (d_pageSize != page_size) { const bool reset_max_position = d_endLockPosition && isAtEnd(); d_pageSize = page_size; if (reset_max_position) setScrollPosition(getMaxScrollPosition()); else updateThumb(); WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setStepSize(float step_size) { if (d_stepSize != step_size) { d_stepSize = step_size; WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setOverlapSize(float overlap_size) { if (d_overlapSize != overlap_size) { d_overlapSize = overlap_size; WindowEventArgs args(this); onScrollConfigChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::setScrollPosition(float position) { const bool modified = setScrollPosition_impl(position); updateThumb(); // notification if required if (modified) { WindowEventArgs args(this); onScrollPositionChanged(args); } } //----------------------------------------------------------------------------// void Scrollbar::onScrollPositionChanged(WindowEventArgs& e) { fireEvent(EventScrollPositionChanged, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onThumbTrackStarted(WindowEventArgs& e) { fireEvent(EventThumbTrackStarted, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onThumbTrackEnded(WindowEventArgs& e) { fireEvent(EventThumbTrackEnded, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onScrollConfigChanged(WindowEventArgs& e) { performChildWindowLayout(); fireEvent(EventScrollConfigChanged, e, EventNamespace); } //----------------------------------------------------------------------------// void Scrollbar::onMouseButtonDown(MouseEventArgs& e) { // base class processing Window::onMouseButtonDown(e); if (e.button == LeftButton) { const float adj = getAdjustDirectionFromPoint(e.position); // adjust scroll bar position in whichever direction as required. if (adj != 0) setScrollPosition( d_position + ((d_pageSize - d_overlapSize) * adj)); ++e.handled; } } //----------------------------------------------------------------------------// void Scrollbar::onMouseWheel(MouseEventArgs& e) { // base class processing Window::onMouseWheel(e); // scroll by e.wheelChange * stepSize setScrollPosition(d_position + d_stepSize * -e.wheelChange); // ensure the message does not go to our parent. ++e.handled; } //----------------------------------------------------------------------------// bool Scrollbar::handleThumbMoved(const EventArgs&) { // adjust scroll bar position as required. setScrollPosition(getValueFromThumb()); return true; } //----------------------------------------------------------------------------// bool Scrollbar::handleIncreaseClicked(const EventArgs& e) { if (((const MouseEventArgs&)e).button == LeftButton) { // adjust scroll bar position as required. setScrollPosition(d_position + d_stepSize); return true; } return false; } //----------------------------------------------------------------------------// bool Scrollbar::handleDecreaseClicked(const EventArgs& e) { if (((const MouseEventArgs&)e).button == LeftButton) { // adjust scroll bar position as required. setScrollPosition(d_position - d_stepSize); return true; } return false; } //----------------------------------------------------------------------------// bool Scrollbar::handleThumbTrackStarted(const EventArgs&) { // simply trigger our own version of this event WindowEventArgs args(this); onThumbTrackStarted(args); return true; } //----------------------------------------------------------------------------// bool Scrollbar::handleThumbTrackEnded(const EventArgs&) { // simply trigger our own version of this event WindowEventArgs args(this); onThumbTrackEnded(args); return true; } //----------------------------------------------------------------------------// void Scrollbar::addScrollbarProperties(void) { const String propertyOrigin("Scrollbar"); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "DocumentSize", "Property to get/set the document size for the Scrollbar. Value is a float.", &Scrollbar::setDocumentSize, &Scrollbar::getDocumentSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "PageSize", "Property to get/set the page size for the Scrollbar. Value is a float.", &Scrollbar::setPageSize, &Scrollbar::getPageSize, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "StepSize", "Property to get/set the step size for the Scrollbar. Value is a float.", &Scrollbar::setStepSize, &Scrollbar::getStepSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "OverlapSize", "Property to get/set the overlap size for the Scrollbar. Value is a float.", &Scrollbar::setOverlapSize, &Scrollbar::getOverlapSize, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "ScrollPosition", "Property to get/set the scroll position of the Scrollbar. Value is a float.", &Scrollbar::setScrollPosition, &Scrollbar::getScrollPosition, 0.0f ); CEGUI_DEFINE_PROPERTY(Scrollbar, float, "EndLockEnabled", "Property to get/set the 'end lock' mode setting for the Scrollbar. " "Value is either \"True\" or \"False\".", &Scrollbar::setEndLockEnabled, &Scrollbar::getEndLockEnabled, false ); // we ban all these properties from xml for auto windows if (isAutoWindow()) { banPropertyFromXML("DocumentSize"); banPropertyFromXML("PageSize"); banPropertyFromXML("StepSize"); banPropertyFromXML("OverlapSize"); banPropertyFromXML("ScrollPosition"); // scrollbars tend to have their visibility toggled alot, so we ban // that as well banPropertyFromXML("Visible"); } } //----------------------------------------------------------------------------// PushButton* Scrollbar::getIncreaseButton() const { return static_cast<PushButton*>(getChild(IncreaseButtonName)); } //----------------------------------------------------------------------------// PushButton* Scrollbar::getDecreaseButton() const { return static_cast<PushButton*>(getChild(DecreaseButtonName)); } //----------------------------------------------------------------------------// Thumb* Scrollbar::getThumb() const { return static_cast<Thumb*>(getChild(ThumbName)); } //----------------------------------------------------------------------------// void Scrollbar::updateThumb(void) { if (!d_windowRenderer) CEGUI_THROW(InvalidRequestException("Scrollbar::updateThumb: This " "function must be implemented by the window renderer object (no " "window renderer is assigned.)")); static_cast<ScrollbarWindowRenderer*>(d_windowRenderer)->updateThumb(); } //----------------------------------------------------------------------------// float Scrollbar::getValueFromThumb(void) const { if (!d_windowRenderer) CEGUI_THROW(InvalidRequestException("Scrollbar::getValueFromThumb: This " "function must be implemented by the window renderer object (no " "window renderer is assigned.)")); return static_cast<ScrollbarWindowRenderer*>( d_windowRenderer)->getValueFromThumb(); } //----------------------------------------------------------------------------// float Scrollbar::getAdjustDirectionFromPoint(const Vector2f& pt) const { if (!d_windowRenderer) CEGUI_THROW(InvalidRequestException( "Scrollbar::getAdjustDirectionFromPoint: " "This function must be implemented by the window renderer object " "(no window renderer is assigned.)")); return static_cast<ScrollbarWindowRenderer*>( d_windowRenderer)->getAdjustDirectionFromPoint(pt); } //----------------------------------------------------------------------------// bool Scrollbar::setScrollPosition_impl(const float position) { const float old_pos = d_position; const float max_pos = getMaxScrollPosition(); // limit position to valid range: 0 <= position <= max_pos d_position = (position >= 0) ? ((position <= max_pos) ? position : max_pos) : 0.0f; return d_position != old_pos; } //----------------------------------------------------------------------------// void Scrollbar::setConfig(const float* const document_size, const float* const page_size, const float* const step_size, const float* const overlap_size, const float* const position) { const bool reset_max_position = d_endLockPosition && isAtEnd(); bool config_changed = false; bool position_changed = false; if (document_size && (d_documentSize != *document_size)) { d_documentSize = *document_size; config_changed = true; } if (page_size && (d_pageSize != *page_size)) { d_pageSize = *page_size; config_changed = true; } if (step_size && (d_stepSize != *step_size)) { d_stepSize = *step_size; config_changed = true; } if (overlap_size && (d_overlapSize != *overlap_size)) { d_overlapSize = *overlap_size; config_changed = true; } if (position) position_changed = setScrollPosition_impl(*position); else if (reset_max_position) position_changed = setScrollPosition_impl(getMaxScrollPosition()); // _always_ update the thumb to keep things in sync. (though this // can cause a double-trigger of EventScrollPositionChanged, which // also happens with setScrollPosition anyway). updateThumb(); // // Fire appropriate events based on actions we took. // if (config_changed) { WindowEventArgs args(this); onScrollConfigChanged(args); } if (position_changed) { WindowEventArgs args(this); onScrollPositionChanged(args); } } //----------------------------------------------------------------------------// float Scrollbar::getMaxScrollPosition() const { // max position is (docSize - pageSize) // but must be at least 0 (in case doc size is very small) return ceguimax((d_documentSize - d_pageSize), 0.0f); } //----------------------------------------------------------------------------// bool Scrollbar::isAtEnd() const { return d_position >= getMaxScrollPosition(); } //----------------------------------------------------------------------------// void Scrollbar::setEndLockEnabled(const bool enabled) { d_endLockPosition = enabled; } //----------------------------------------------------------------------------// bool Scrollbar::isEndLockEnabled() const { return d_endLockPosition; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before><commit_msg>Do not wrap non-HTTP(s) requests.<commit_after><|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/cusolver_context.h" #include "tensorflow/compiler/xla/util.h" #if !defined(TENSORFLOW_USE_ROCM) using gpuStream_t = cudaStream_t; #else #include "rocm/include/hip/hip_complex.h" using gpuStream_t = hipStream_t; #define cusolverDnCreate rocblas_create_handle #define cusolverDnSetStream rocblas_set_stream #define cusolverDnDestroy rocblas_destroy_handle #endif namespace xla { namespace gpu { namespace { // Type traits to get CUDA complex types from std::complex<T>. template <typename T> struct CUDAComplexT { typedef T type; }; #if !defined(TENSORFLOW_USE_ROCM) template <> struct CUDAComplexT<std::complex<float>> { typedef cuComplex type; }; template <> struct CUDAComplexT<std::complex<double>> { typedef cuDoubleComplex type; }; #else // can't use gpuFloatComplex, gpuDoubleComplex, because e.g. // hipFloatComplex and rocblas_float_complex are two unrelated types template <> struct CUDAComplexT<std::complex<float>> { typedef rocblas_float_complex type; }; template <> struct CUDAComplexT<std::complex<double>> { typedef rocblas_double_complex type; }; #endif template <typename T> inline typename CUDAComplexT<T>::type* ToDevicePointer(se::DeviceMemory<T> p) { return static_cast<typename CUDAComplexT<T>::type*>(p.opaque()); } #if !defined(TENSORFLOW_USE_ROCM) cublasFillMode_t CUDABlasUpperLower(se::blas::UpperLower uplo) { switch (uplo) { case se::blas::UpperLower::kUpper: return CUBLAS_FILL_MODE_UPPER; case se::blas::UpperLower::kLower: return CUBLAS_FILL_MODE_LOWER; default: LOG(FATAL) << "Invalid value of blas::UpperLower."; } } // Converts a cuSolver status to a Status. Status CusolverStatusToStatus(cusolverStatus_t status) { switch (status) { case CUSOLVER_STATUS_SUCCESS: return Status::OK(); case CUSOLVER_STATUS_NOT_INITIALIZED: return FailedPrecondition("cuSolver has not been initialized"); case CUSOLVER_STATUS_ALLOC_FAILED: return ResourceExhausted("cuSolver allocation failed"); case CUSOLVER_STATUS_INVALID_VALUE: return InvalidArgument("cuSolver invalid value error"); case CUSOLVER_STATUS_ARCH_MISMATCH: return FailedPrecondition("cuSolver architecture mismatch error"); case CUSOLVER_STATUS_MAPPING_ERROR: return Unknown("cuSolver mapping error"); case CUSOLVER_STATUS_EXECUTION_FAILED: return Unknown("cuSolver execution failed"); case CUSOLVER_STATUS_INTERNAL_ERROR: return Internal("cuSolver internal error"); case CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED: return Unimplemented("cuSolver matrix type not supported error"); case CUSOLVER_STATUS_NOT_SUPPORTED: return Unimplemented("cuSolver not supported error"); case CUSOLVER_STATUS_ZERO_PIVOT: return InvalidArgument("cuSolver zero pivot error"); case CUSOLVER_STATUS_INVALID_LICENSE: return FailedPrecondition("cuSolver invalid license error"); default: return Unknown("Unknown cuSolver error"); } } #else rocblas_fill CUDABlasUpperLower(se::blas::UpperLower uplo) { switch (uplo) { case se::blas::UpperLower::kUpper: return rocblas_fill_upper; case se::blas::UpperLower::kLower: return rocblas_fill_lower; default: LOG(FATAL) << "Invalid value of blas::UpperLower."; } } // Converts a cuSolver status to a Status. Status CusolverStatusToStatus(rocblas_status status) { switch (status) { case rocblas_status_success: return Status::OK(); case rocblas_status_invalid_handle: return FailedPrecondition("handle not initialized, invalid or null"); case rocblas_status_not_implemented: return Internal("function is not implemented"); case rocblas_status_invalid_pointer: return InvalidArgument("invalid pointer argument"); case rocblas_status_invalid_size: return InvalidArgument("invalid size argument"); case rocblas_status_memory_error: return Internal("failed internal memory allocation, copy or dealloc"); case rocblas_status_internal_error: return Internal("other internal library failure"); case rocblas_status_perf_degraded: return Internal("performance degraded due to low device memory"); case rocblas_status_size_query_mismatch: return Unknown("unmatched start/stop size query"); case rocblas_status_size_increased: return Unknown("queried device memory size increased"); case rocblas_status_size_unchanged: return Unknown("queried device memory size unchanged"); case rocblas_status_invalid_value: return InvalidArgument("passed argument not valid"); case rocblas_status_continue: return Unknown("nothing preventing function to proceed"); default: return Unknown("Unknown rocsolver error"); } } #endif } // namespace StatusOr<CusolverContext> CusolverContext::Create(se::Stream* stream) { cusolverDnHandle_t handle; TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnCreate(&handle))); CusolverContext context(stream, handle); if (stream) { // StreamExecutor really should just expose the Cuda stream to clients... const gpuStream_t* cuda_stream = CHECK_NOTNULL(reinterpret_cast<const gpuStream_t*>( stream->implementation()->GpuStreamMemberHack())); TF_RETURN_IF_ERROR( CusolverStatusToStatus(cusolverDnSetStream(handle, *cuda_stream))); } return std::move(context); } CusolverContext::CusolverContext(se::Stream* stream, cusolverDnHandle_t handle) : stream_(stream), handle_(handle) {} CusolverContext::CusolverContext(CusolverContext&& other) { handle_ = other.handle_; stream_ = other.stream_; other.handle_ = nullptr; other.stream_ = nullptr; } CusolverContext& CusolverContext::operator=(CusolverContext&& other) { std::swap(handle_, other.handle_); std::swap(stream_, other.stream_); return *this; } CusolverContext::~CusolverContext() { if (handle_) { Status status = CusolverStatusToStatus(cusolverDnDestroy(handle_)); if (!status.ok()) { LOG(ERROR) << "cusolverDnDestroy failed: " << status; } } } #if !defined(TENSORFLOW_USE_ROCM) #define CALL_LAPACK_TYPES(m) \ m(float, S) m(double, D) m(std::complex<float>, C) m(std::complex<double>, Z) #define DN_SOLVER_FN(method, type_prefix) cusolverDn##type_prefix##method #else #define CALL_LAPACK_TYPES(m) \ m(float, s) m(double, d) m(std::complex<float>, c) m(std::complex<double>, z) #define DN_SOLVER_FN(method, type_prefix) \ tensorflow::wrap::rocsolver_##type_prefix##method #endif // Note: NVidia have promised that it is safe to pass 'nullptr' as the argument // buffers to cuSolver buffer size methods and this will be a documented // behavior in a future cuSolver release. StatusOr<int64> CusolverContext::PotrfBufferSize(PrimitiveType type, se::blas::UpperLower uplo, int n, int lda) { #if !defined(TENSORFLOW_USE_ROCM) int size = -1; switch (type) { case F32: { TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnSpotrf_bufferSize( handle(), CUDABlasUpperLower(uplo), n, /*A=*/nullptr, lda, &size))); break; } case F64: { TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnDpotrf_bufferSize( handle(), CUDABlasUpperLower(uplo), n, /*A=*/nullptr, lda, &size))); break; } case C64: { TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnCpotrf_bufferSize( handle(), CUDABlasUpperLower(uplo), n, /*A=*/nullptr, lda, &size))); break; } case C128: { TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnZpotrf_bufferSize( handle(), CUDABlasUpperLower(uplo), n, /*A=*/nullptr, lda, &size))); break; } default: return InvalidArgument("Invalid type for cholesky decomposition: %s", PrimitiveType_Name(type)); } return size; #else return 0; #endif } #if !defined(TENSORFLOW_USE_ROCM) #define POTRF_INSTANCE(T, type_prefix) \ template <> \ Status CusolverContext::Potrf<T>( \ se::blas::UpperLower uplo, int n, se::DeviceMemory<T> A, int lda, \ se::DeviceMemory<int> lapack_info, se::DeviceMemory<T> workspace) { \ return CusolverStatusToStatus(DN_SOLVER_FN(potrf, type_prefix)( \ handle(), CUDABlasUpperLower(uplo), n, ToDevicePointer(A), lda, \ ToDevicePointer(workspace), workspace.ElementCount(), \ ToDevicePointer(lapack_info))); \ } #else #define POTRF_INSTANCE(T, type_prefix) \ template <> \ Status CusolverContext::Potrf<T>( \ se::blas::UpperLower uplo, int n, se::DeviceMemory<T> A, int lda, \ se::DeviceMemory<int> lapack_info, se::DeviceMemory<T> workspace) { \ return CusolverStatusToStatus(DN_SOLVER_FN(potrf, type_prefix)( \ handle(), CUDABlasUpperLower(uplo), n, ToDevicePointer(A), lda, \ ToDevicePointer(lapack_info))); \ } #endif CALL_LAPACK_TYPES(POTRF_INSTANCE); } // namespace gpu } // namespace xla <commit_msg>updates to address review feedback<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/cusolver_context.h" #include "tensorflow/compiler/xla/util.h" #if defined(TENSORFLOW_USE_ROCM) #include "rocm/include/hip/hip_complex.h" #endif namespace xla { namespace gpu { namespace { // Type traits to get CUDA complex types from std::complex<T>. template <typename T> struct CUDAComplexT { typedef T type; }; #if !defined(TENSORFLOW_USE_ROCM) template <> struct CUDAComplexT<std::complex<float>> { typedef cuComplex type; }; template <> struct CUDAComplexT<std::complex<double>> { typedef cuDoubleComplex type; }; #else template <> struct CUDAComplexT<std::complex<float>> { typedef rocblas_float_complex type; }; template <> struct CUDAComplexT<std::complex<double>> { typedef rocblas_double_complex type; }; #endif template <typename T> inline typename CUDAComplexT<T>::type* ToDevicePointer(se::DeviceMemory<T> p) { return static_cast<typename CUDAComplexT<T>::type*>(p.opaque()); } #if !defined(TENSORFLOW_USE_ROCM) cublasFillMode_t CUDABlasUpperLower(se::blas::UpperLower uplo) { switch (uplo) { case se::blas::UpperLower::kUpper: return CUBLAS_FILL_MODE_UPPER; case se::blas::UpperLower::kLower: return CUBLAS_FILL_MODE_LOWER; default: LOG(FATAL) << "Invalid value of blas::UpperLower."; } } // Converts a cuSolver status to a Status. Status CusolverStatusToStatus(cusolverStatus_t status) { switch (status) { case CUSOLVER_STATUS_SUCCESS: return Status::OK(); case CUSOLVER_STATUS_NOT_INITIALIZED: return FailedPrecondition("cuSolver has not been initialized"); case CUSOLVER_STATUS_ALLOC_FAILED: return ResourceExhausted("cuSolver allocation failed"); case CUSOLVER_STATUS_INVALID_VALUE: return InvalidArgument("cuSolver invalid value error"); case CUSOLVER_STATUS_ARCH_MISMATCH: return FailedPrecondition("cuSolver architecture mismatch error"); case CUSOLVER_STATUS_MAPPING_ERROR: return Unknown("cuSolver mapping error"); case CUSOLVER_STATUS_EXECUTION_FAILED: return Unknown("cuSolver execution failed"); case CUSOLVER_STATUS_INTERNAL_ERROR: return Internal("cuSolver internal error"); case CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED: return Unimplemented("cuSolver matrix type not supported error"); case CUSOLVER_STATUS_NOT_SUPPORTED: return Unimplemented("cuSolver not supported error"); case CUSOLVER_STATUS_ZERO_PIVOT: return InvalidArgument("cuSolver zero pivot error"); case CUSOLVER_STATUS_INVALID_LICENSE: return FailedPrecondition("cuSolver invalid license error"); default: return Unknown("Unknown cuSolver error"); } } #else rocblas_fill CUDABlasUpperLower(se::blas::UpperLower uplo) { switch (uplo) { case se::blas::UpperLower::kUpper: return rocblas_fill_upper; case se::blas::UpperLower::kLower: return rocblas_fill_lower; default: LOG(FATAL) << "Invalid value of blas::UpperLower."; } } // Converts a cuSolver status to a Status. Status CusolverStatusToStatus(rocblas_status status) { switch (status) { case rocblas_status_success: return Status::OK(); case rocblas_status_invalid_handle: return FailedPrecondition("handle not initialized, invalid or null"); case rocblas_status_not_implemented: return Internal("function is not implemented"); case rocblas_status_invalid_pointer: return InvalidArgument("invalid pointer argument"); case rocblas_status_invalid_size: return InvalidArgument("invalid size argument"); case rocblas_status_memory_error: return Internal("failed internal memory allocation, copy or dealloc"); case rocblas_status_internal_error: return Internal("other internal library failure"); case rocblas_status_perf_degraded: return Internal("performance degraded due to low device memory"); case rocblas_status_size_query_mismatch: return Unknown("unmatched start/stop size query"); case rocblas_status_size_increased: return Unknown("queried device memory size increased"); case rocblas_status_size_unchanged: return Unknown("queried device memory size unchanged"); case rocblas_status_invalid_value: return InvalidArgument("passed argument not valid"); case rocblas_status_continue: return Unknown("nothing preventing function to proceed"); default: return Unknown("Unknown rocsolver error"); } } #endif } // namespace #if !defined(TENSORFLOW_USE_ROCM) StatusOr<CusolverContext> CusolverContext::Create(se::Stream* stream) { cusolverDnHandle_t handle; TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnCreate(&handle))); CusolverContext context(stream, handle); if (stream) { // StreamExecutor really should just expose the Cuda stream to clients... const cudaStream_t* cuda_stream = CHECK_NOTNULL(reinterpret_cast<const cudaStream_t*>( stream->implementation()->GpuStreamMemberHack())); TF_RETURN_IF_ERROR( CusolverStatusToStatus(cusolverDnSetStream(handle, *cuda_stream))); } return std::move(context); } #else StatusOr<CusolverContext> CusolverContext::Create(se::Stream* stream) { cusolverDnHandle_t handle; TF_RETURN_IF_ERROR(CusolverStatusToStatus(rocblas_create_handle(&handle))); CusolverContext context(stream, handle); if (stream) { // StreamExecutor really should just expose the Cuda stream to clients... const hipStream_t* hip_stream = CHECK_NOTNULL(reinterpret_cast<const hipStream_t*>( stream->implementation()->GpuStreamMemberHack())); TF_RETURN_IF_ERROR( CusolverStatusToStatus(rocblas_set_stream(handle, *hip_stream))); } return std::move(context); } #endif CusolverContext::CusolverContext(se::Stream* stream, cusolverDnHandle_t handle) : stream_(stream), handle_(handle) {} CusolverContext::CusolverContext(CusolverContext&& other) { handle_ = other.handle_; stream_ = other.stream_; other.handle_ = nullptr; other.stream_ = nullptr; } CusolverContext& CusolverContext::operator=(CusolverContext&& other) { std::swap(handle_, other.handle_); std::swap(stream_, other.stream_); return *this; } #if !defined(TENSORFLOW_USE_ROCM) CusolverContext::~CusolverContext() { if (handle_) { Status status = CusolverStatusToStatus(cusolverDnDestroy(handle_)); if (!status.ok()) { LOG(ERROR) << "cusolverDnDestroy failed: " << status; } } } #else CusolverContext::~CusolverContext() { if (handle_) { Status status = CusolverStatusToStatus(rocblas_destroy_handle(handle_)); if (!status.ok()) { LOG(ERROR) << "cusolverDnDestroy failed: " << status; } } } #endif #if !defined(TENSORFLOW_USE_ROCM) #define CALL_LAPACK_TYPES(m) \ m(float, S) m(double, D) m(std::complex<float>, C) m(std::complex<double>, Z) #define DN_SOLVER_FN(method, type_prefix) cusolverDn##type_prefix##method #else #define CALL_LAPACK_TYPES(m) \ m(float, s) m(double, d) m(std::complex<float>, c) m(std::complex<double>, z) #define DN_SOLVER_FN(method, type_prefix) \ tensorflow::wrap::rocsolver_##type_prefix##method #endif // Note: NVidia have promised that it is safe to pass 'nullptr' as the argument // buffers to cuSolver buffer size methods and this will be a documented // behavior in a future cuSolver release. StatusOr<int64> CusolverContext::PotrfBufferSize(PrimitiveType type, se::blas::UpperLower uplo, int n, int lda) { #if !defined(TENSORFLOW_USE_ROCM) int size = -1; switch (type) { case F32: { TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnSpotrf_bufferSize( handle(), CUDABlasUpperLower(uplo), n, /*A=*/nullptr, lda, &size))); break; } case F64: { TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnDpotrf_bufferSize( handle(), CUDABlasUpperLower(uplo), n, /*A=*/nullptr, lda, &size))); break; } case C64: { TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnCpotrf_bufferSize( handle(), CUDABlasUpperLower(uplo), n, /*A=*/nullptr, lda, &size))); break; } case C128: { TF_RETURN_IF_ERROR(CusolverStatusToStatus(cusolverDnZpotrf_bufferSize( handle(), CUDABlasUpperLower(uplo), n, /*A=*/nullptr, lda, &size))); break; } default: return InvalidArgument("Invalid type for cholesky decomposition: %s", PrimitiveType_Name(type)); } return size; #else return 0; #endif } #if !defined(TENSORFLOW_USE_ROCM) #define POTRF_INSTANCE(T, type_prefix) \ template <> \ Status CusolverContext::Potrf<T>( \ se::blas::UpperLower uplo, int n, se::DeviceMemory<T> A, int lda, \ se::DeviceMemory<int> lapack_info, se::DeviceMemory<T> workspace) { \ return CusolverStatusToStatus(DN_SOLVER_FN(potrf, type_prefix)( \ handle(), CUDABlasUpperLower(uplo), n, ToDevicePointer(A), lda, \ ToDevicePointer(workspace), workspace.ElementCount(), \ ToDevicePointer(lapack_info))); \ } #else #define POTRF_INSTANCE(T, type_prefix) \ template <> \ Status CusolverContext::Potrf<T>( \ se::blas::UpperLower uplo, int n, se::DeviceMemory<T> A, int lda, \ se::DeviceMemory<int> lapack_info, se::DeviceMemory<T> workspace) { \ return CusolverStatusToStatus(DN_SOLVER_FN(potrf, type_prefix)( \ handle(), CUDABlasUpperLower(uplo), n, ToDevicePointer(A), lda, \ ToDevicePointer(lapack_info))); \ } #endif CALL_LAPACK_TYPES(POTRF_INSTANCE); } // namespace gpu } // namespace xla <|endoftext|>
<commit_before>#include <Arduino.h> #include "TybluServo.h" /* * TybluServo constructor arguments: (int, int, int, int, int, float, float, int) * int pwmPin Pin used to control servo. * int minAngle, int maxAngle Allowed range of movement. * int safeAngle Nominal position for servo. * int sensorPin Angle sensor pin (A0, A1, ...). * float sensorSlope, float sensorOffset Initial angle sensor linear coefficients. * int pt_count Number of float measurements to use when * calibrating angle sensor. NOTE: Should * hard-code this and use other memory (PROGMEM, etc.) to get around this * memory constraint. */ TybluServo boom1Servo (10, 80, 100, 90, A1, 0.557, -49.64, 50); // TowerPro 946R, sensor needs verification TybluServo boom2Servo (11, 70, 115, 80, A0, 1.113, -147.1, 50); // Power HD 1501MG TybluServo turretServo ( 6, 30, 150, 90, A3, 1.000, -1.000, 50); // not measured TybluServo clawServo ( 9, 80, 130, 100, A2, 0.557, -61.38, 50); // TowerPro 946R, angles need verification TybluServo * servos[4] = { &boom1Servo, &boom2Servo, &turretServo, &clawServo }; long timestamp = millis(); void dots(int n, int t); void ellipsis(); void setup() { delay(2000); Serial.begin(9600); Serial.println(__FILE__ " compiled " __DATE__ " at " __TIME__); Serial.println(); Serial.print("Calibrating Sensors"); ellipsis(); for (int i=0; i<4; i++) { servos[i]->attach(); servos[i]->calibrateSensor(); servos[i]->smooth( servos[i]->getSafeAngle() ); } Serial.println(); Serial.print("y = "); Serial.print(boom2Servo.getSensorSlope()); Serial.print(" * x "); float offset = boom2Servo.getSensorOffset(); if (offset < 0) Serial.print("- "); else Serial.print("+ "); Serial.print(abs(offset)); Serial.println(); delay(2000); boom2Servo.detach(); } void loop() { Serial.println("Made it!"); delay(5000); // if (timestamp + 1000 > millis() ) // { // Serial.print( boomArmServo.read() ); // Serial.write(','); // long sampleTime = millis(); // int analogAngle = boomArmServo.getAnalogAngle(); // sampleTime = millis() - sampleTime; // Serial.print( analogAngle ); // Serial.write(','); // Serial.print( sampleTime ); // Serial.println(); // } // else // { // if (angle >= boomArmServo.getMaxAngle() || angle <= boomArmServo.getMinAngle() ) // angleAdjustment *= -1; // angle += angleAdjustment; // boomArmServo.write(angle); // delay(1000); // timestamp = millis(); // } } void dots(int num, int delayTime) { for (int i=0; i<num; i++) { Serial.write('.'); delay(delayTime); } } void ellipsis() { dots(3, 100); } <commit_msg>Moved servo pins to free up SPI pins (GPIO 10-13) for SD card.<commit_after>#include <Arduino.h> #include "TybluServo.h" #define BOOM1_PWM_PIN 6 #define BOOM2_PWM_PIN 9 #define CLAW_PWM_PIN 5 #define TURRET_PWM_PIN 3 /* * TybluServo constructor arguments: (int, int, int, int, int, float, float, int) * int pwmPin Pin used to control servo. * int minAngle, int maxAngle Allowed range of movement. * int safeAngle Nominal position for servo. * int sensorPin Angle sensor pin (A0, A1, ...). * float sensorSlope, float sensorOffset Initial angle sensor linear coefficients. * int pt_count Number of float measurements to use when * calibrating angle sensor. NOTE: Should * hard-code this and use other memory (PROGMEM, etc.) to get around this * memory constraint. */ TybluServo boom1Servo (BOOM1_PWM_PIN, 120, 150, 90, A1, 0.557, -49.64, 50); // TowerPro 946R, sensor needs verification TybluServo boom2Servo (BOOM2_PWM_PIN, 70, 115, 80, A0, 1.113, -147.1, 50); // Power HD 1501MG //TybluServo turretServo (TURRET_PWM_PIN, 30, 150, 90, A3, 1.000, -1.000, 50); // not measured //TybluServo clawServo (CLAW_PWM_PIN, 80, 130, 100, A2, 0.557, -61.38, 50); // TowerPro 946R, angles need verification #define NUM_ACTIVE_SERVOS 2 TybluServo * servos[NUM_ACTIVE_SERVOS] = { &boom1Servo, &boom2Servo }; void dots(int n, int t); void ellipsis(); void setup() { delay(2000); Serial.begin(9600); Serial.println(__FILE__ " compiled " __DATE__ " at " __TIME__); Serial.println(); Serial.print("Calibrating Sensors"); ellipsis(); for (int i=0; i<4; i++) { servos[i]->attach(); servos[i]->calibrateSensor(); servos[i]->smooth( servos[i]->getSafeAngle() ); } Serial.println(); Serial.print("y = "); Serial.print(boom2Servo.getSensorSlope()); Serial.print(" * x "); float offset = boom2Servo.getSensorOffset(); if (offset < 0) Serial.print("- "); else Serial.print("+ "); Serial.print(abs(offset)); Serial.println(); delay(2000); boom2Servo.detach(); } void loop() { Serial.println("Made it!"); delay(5000); // if (timestamp + 1000 > millis() ) // { // Serial.print( boomArmServo.read() ); // Serial.write(','); // long sampleTime = millis(); // int analogAngle = boomArmServo.getAnalogAngle(); // sampleTime = millis() - sampleTime; // Serial.print( analogAngle ); // Serial.write(','); // Serial.print( sampleTime ); // Serial.println(); // } // else // { // if (angle >= boomArmServo.getMaxAngle() || angle <= boomArmServo.getMinAngle() ) // angleAdjustment *= -1; // angle += angleAdjustment; // boomArmServo.write(angle); // delay(1000); // timestamp = millis(); // } } void dots(int num, int delayTime) { for (int i=0; i<num; i++) { Serial.write('.'); delay(delayTime); } } void ellipsis() { dots(3, 100); } <|endoftext|>
<commit_before>#include "drape_frontend/rule_drawer.hpp" #include "drape_frontend/stylist.hpp" #include "drape_frontend/engine_context.hpp" #include "drape_frontend/apply_feature_functors.hpp" #include "drape_frontend/visual_params.hpp" #include "indexer/feature.hpp" #include "indexer/feature_algo.hpp" #include "base/assert.hpp" #include "std/bind.hpp" namespace df { int const SIMPLIFY_BOTTOM = 9; int const SIMPLIFY_TOP = 13; RuleDrawer::RuleDrawer(TDrawerCallback const & fn, ref_ptr<EngineContext> context) : m_callback(fn) , m_context(context) { m_globalRect = m_context->GetTileKey().GetGlobalRect(); int32_t tileSize = df::VisualParams::Instance().GetTileSize(); m_geometryConvertor.OnSize(0, 0, tileSize, tileSize); m_geometryConvertor.SetFromRect(m2::AnyRectD(m_globalRect)); m_currentScaleGtoP = 1.0f / m_geometryConvertor.GetScale(); } void RuleDrawer::operator()(FeatureType const & f) { Stylist s; m_callback(f, s); if (s.IsEmpty()) return; if (s.IsCoastLine() && (!m_coastlines.insert(s.GetCaptionDescription().GetMainText()).second)) return; #ifdef DEBUG // Validate on feature styles if (s.AreaStyleExists() == false) { int checkFlag = s.PointStyleExists() ? 1 : 0; checkFlag += s.LineStyleExists() ? 1 : 0; ASSERT(checkFlag == 1, ()); } #endif int zoomLevel = m_context->GetTileKey().m_zoomLevel; if (s.AreaStyleExists()) { ApplyAreaFeature apply(m_context, f.GetID(), s.GetCaptionDescription()); f.ForEachTriangleRef(apply, zoomLevel); if (s.PointStyleExists()) apply(feature::GetCenter(f, zoomLevel)); s.ForEachRule(bind(&ApplyAreaFeature::ProcessRule, &apply, _1)); apply.Finish(); } else if (s.LineStyleExists()) { ApplyLineFeature apply(m_context, f.GetID(), s.GetCaptionDescription(), m_currentScaleGtoP, zoomLevel > SIMPLIFY_BOTTOM && zoomLevel < SIMPLIFY_TOP); f.ForEachPointRef(apply, zoomLevel); if (apply.HasGeometry()) s.ForEachRule(bind(&ApplyLineFeature::ProcessRule, &apply, _1)); apply.Finish(); } else { ASSERT(s.PointStyleExists(), ()); ApplyPointFeature apply(m_context, f.GetID(), s.GetCaptionDescription()); f.ForEachPointRef(apply, zoomLevel); s.ForEachRule(bind(&ApplyPointFeature::ProcessRule, &apply, _1)); apply.Finish(); } m_context->Flush(); } } // namespace df <commit_msg>review fix<commit_after>#include "drape_frontend/rule_drawer.hpp" #include "drape_frontend/stylist.hpp" #include "drape_frontend/engine_context.hpp" #include "drape_frontend/apply_feature_functors.hpp" #include "drape_frontend/visual_params.hpp" #include "indexer/feature.hpp" #include "indexer/feature_algo.hpp" #include "base/assert.hpp" #include "std/bind.hpp" namespace df { int const SIMPLIFY_BOTTOM = 10; int const SIMPLIFY_TOP = 12; RuleDrawer::RuleDrawer(TDrawerCallback const & fn, ref_ptr<EngineContext> context) : m_callback(fn) , m_context(context) { m_globalRect = m_context->GetTileKey().GetGlobalRect(); int32_t tileSize = df::VisualParams::Instance().GetTileSize(); m_geometryConvertor.OnSize(0, 0, tileSize, tileSize); m_geometryConvertor.SetFromRect(m2::AnyRectD(m_globalRect)); m_currentScaleGtoP = 1.0f / m_geometryConvertor.GetScale(); } void RuleDrawer::operator()(FeatureType const & f) { Stylist s; m_callback(f, s); if (s.IsEmpty()) return; if (s.IsCoastLine() && (!m_coastlines.insert(s.GetCaptionDescription().GetMainText()).second)) return; #ifdef DEBUG // Validate on feature styles if (s.AreaStyleExists() == false) { int checkFlag = s.PointStyleExists() ? 1 : 0; checkFlag += s.LineStyleExists() ? 1 : 0; ASSERT(checkFlag == 1, ()); } #endif int zoomLevel = m_context->GetTileKey().m_zoomLevel; if (s.AreaStyleExists()) { ApplyAreaFeature apply(m_context, f.GetID(), s.GetCaptionDescription()); f.ForEachTriangleRef(apply, zoomLevel); if (s.PointStyleExists()) apply(feature::GetCenter(f, zoomLevel)); s.ForEachRule(bind(&ApplyAreaFeature::ProcessRule, &apply, _1)); apply.Finish(); } else if (s.LineStyleExists()) { ApplyLineFeature apply(m_context, f.GetID(), s.GetCaptionDescription(), m_currentScaleGtoP, zoomLevel >= SIMPLIFY_BOTTOM && zoomLevel <= SIMPLIFY_TOP); f.ForEachPointRef(apply, zoomLevel); if (apply.HasGeometry()) s.ForEachRule(bind(&ApplyLineFeature::ProcessRule, &apply, _1)); apply.Finish(); } else { ASSERT(s.PointStyleExists(), ()); ApplyPointFeature apply(m_context, f.GetID(), s.GetCaptionDescription()); f.ForEachPointRef(apply, zoomLevel); s.ForEachRule(bind(&ApplyPointFeature::ProcessRule, &apply, _1)); apply.Finish(); } m_context->Flush(); } } // namespace df <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: BaseGFXHelper.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-03 13:43:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "BaseGFXHelper.hxx" #ifndef _COM_SUN_STAR_DRAWING_DOUBLESEQUENCE_HPP_ #include <com/sun/star/drawing/DoubleSequence.hpp> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::drawing; using namespace ::basegfx; namespace chart { namespace BaseGFXHelper { ::basegfx::B3DRange getBoundVolume( const drawing::PolyPolygonShape3D& rPolyPoly ) { ::basegfx::B3DRange aRet; bool bInited = false; sal_Int32 nPolyCount = rPolyPoly.SequenceX.getLength(); for(sal_Int32 nPoly = 0; nPoly < nPolyCount; nPoly++) { sal_Int32 nPointCount = rPolyPoly.SequenceX[nPoly].getLength(); for( sal_Int32 nPoint = 0; nPoint < nPointCount; nPoint++) { if(!bInited) { aRet = ::basegfx::B3DRange(::basegfx::B3DTuple( rPolyPoly.SequenceX[nPoly][nPoint] , rPolyPoly.SequenceY[nPoly][nPoint] , rPolyPoly.SequenceZ[nPoly][nPoint])); bInited = true; } else { aRet.expand( ::basegfx::B3DTuple( rPolyPoly.SequenceX[nPoly][nPoint] , rPolyPoly.SequenceY[nPoly][nPoint] , rPolyPoly.SequenceZ[nPoly][nPoint])); } } } return aRet; } B2IRectangle makeRectangle( const awt::Point& rPos, const awt::Size& rSize ) { return B2IRectangle(rPos.X,rPos.Y,rPos.X+rSize.Width,rPos.Y+rSize.Height); } awt::Point B2IRectangleToAWTPoint( const ::basegfx::B2IRectangle& rB2IRectangle ) { return awt::Point( rB2IRectangle.getMinX(), rB2IRectangle.getMinY() ); } awt::Size B2IRectangleToAWTSize( const ::basegfx::B2IRectangle& rB2IRectangle ) { return awt::Size( rB2IRectangle.getWidth(), rB2IRectangle.getHeight() ); } awt::Rectangle B2IRectangleToAWTRectangle( const ::basegfx::B2IRectangle& rB2IRectangle ) { return awt::Rectangle( rB2IRectangle.getMinX(), rB2IRectangle.getMinY() , rB2IRectangle.getWidth(), rB2IRectangle.getHeight() ); } B3DVector Direction3DToB3DVector( const Direction3D& rDirection ) { return B3DVector( rDirection.DirectionX , rDirection.DirectionY , rDirection.DirectionZ ); } Direction3D B3DVectorToDirection3D( const B3DVector& rB3DVector ) { return Direction3D( rB3DVector.getX() , rB3DVector.getY() , rB3DVector.getZ() ); } B3DVector Position3DToB3DVector( const Position3D& rPosition ) { return B3DVector( rPosition.PositionX , rPosition.PositionY , rPosition.PositionZ ); } Position3D B3DVectorToPosition3D( const B3DVector& rB3DVector ) { return Position3D( rB3DVector.getX() , rB3DVector.getY() , rB3DVector.getZ() ); } B3DHomMatrix HomogenMatrixToB3DHomMatrix( const HomogenMatrix & rHomogenMatrix ) { B3DHomMatrix aResult; aResult.set( 0, 0, rHomogenMatrix.Line1.Column1 ); aResult.set( 0, 1, rHomogenMatrix.Line1.Column2 ); aResult.set( 0, 2, rHomogenMatrix.Line1.Column3 ); aResult.set( 0, 3, rHomogenMatrix.Line1.Column4 ); aResult.set( 1, 0, rHomogenMatrix.Line2.Column1 ); aResult.set( 1, 1, rHomogenMatrix.Line2.Column2 ); aResult.set( 1, 2, rHomogenMatrix.Line2.Column3 ); aResult.set( 1, 3, rHomogenMatrix.Line2.Column4 ); aResult.set( 2, 0, rHomogenMatrix.Line3.Column1 ); aResult.set( 2, 1, rHomogenMatrix.Line3.Column2 ); aResult.set( 2, 2, rHomogenMatrix.Line3.Column3 ); aResult.set( 2, 3, rHomogenMatrix.Line3.Column4 ); aResult.set( 3, 0, rHomogenMatrix.Line4.Column1 ); aResult.set( 3, 1, rHomogenMatrix.Line4.Column2 ); aResult.set( 3, 2, rHomogenMatrix.Line4.Column3 ); aResult.set( 3, 3, rHomogenMatrix.Line4.Column4 ); return aResult; } HomogenMatrix B3DHomMatrixToHomogenMatrix( const B3DHomMatrix & rB3DMatrix ) { HomogenMatrix aResult; aResult.Line1.Column1 = rB3DMatrix.get( 0, 0 ); aResult.Line1.Column2 = rB3DMatrix.get( 0, 1 ); aResult.Line1.Column3 = rB3DMatrix.get( 0, 2 ); aResult.Line1.Column4 = rB3DMatrix.get( 0, 3 ); aResult.Line2.Column1 = rB3DMatrix.get( 1, 0 ); aResult.Line2.Column2 = rB3DMatrix.get( 1, 1 ); aResult.Line2.Column3 = rB3DMatrix.get( 1, 2 ); aResult.Line2.Column4 = rB3DMatrix.get( 1, 3 ); aResult.Line3.Column1 = rB3DMatrix.get( 2, 0 ); aResult.Line3.Column2 = rB3DMatrix.get( 2, 1 ); aResult.Line3.Column3 = rB3DMatrix.get( 2, 2 ); aResult.Line3.Column4 = rB3DMatrix.get( 2, 3 ); aResult.Line4.Column1 = rB3DMatrix.get( 3, 0 ); aResult.Line4.Column2 = rB3DMatrix.get( 3, 1 ); aResult.Line4.Column3 = rB3DMatrix.get( 3, 2 ); aResult.Line4.Column4 = rB3DMatrix.get( 3, 3 ); return aResult; } B3DTuple GetRotationFromMatrix( const B3DHomMatrix & rB3DMatrix ) { B3DTuple aScale, aTranslation, aRotation, aShearing; rB3DMatrix.decompose( aScale, aTranslation, aRotation, aShearing ); return aRotation; } B3DTuple GetScaleFromMatrix( const B3DHomMatrix & rB3DMatrix ) { B3DTuple aScale, aTranslation, aRotation, aShearing; rB3DMatrix.decompose( aScale, aTranslation, aRotation, aShearing ); return aScale; } void ReduceToRotationMatrix( ::basegfx::B3DHomMatrix & rB3DMatrix ) { B3DTuple aR( GetRotationFromMatrix( rB3DMatrix ) ); ::basegfx::B3DHomMatrix aRotationMatrix; aRotationMatrix.rotate(aR.getX(),aR.getY(),aR.getZ()); rB3DMatrix = aRotationMatrix; } double Deg2Rad( double fDegrees ) { return fDegrees * ( F_PI / 180.0 ); } double Rad2Deg( double fRadians ) { return fRadians * ( 180.0 / F_PI ); } } // namespace BaseGFXHelper } // namespace chart <commit_msg>INTEGRATION: CWS chart07 (1.3.4); FILE MERGED 2007/07/10 11:57:30 bm 1.3.4.1: #i69281# warnings removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: BaseGFXHelper.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2007-07-25 08:55:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "BaseGFXHelper.hxx" #ifndef _COM_SUN_STAR_DRAWING_DOUBLESEQUENCE_HPP_ #include <com/sun/star/drawing/DoubleSequence.hpp> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::drawing; using namespace ::basegfx; namespace chart { namespace BaseGFXHelper { ::basegfx::B3DRange getBoundVolume( const drawing::PolyPolygonShape3D& rPolyPoly ) { ::basegfx::B3DRange aRet; bool bInited = false; sal_Int32 nPolyCount = rPolyPoly.SequenceX.getLength(); for(sal_Int32 nPoly = 0; nPoly < nPolyCount; nPoly++) { sal_Int32 nPointCount = rPolyPoly.SequenceX[nPoly].getLength(); for( sal_Int32 nPoint = 0; nPoint < nPointCount; nPoint++) { if(!bInited) { aRet = ::basegfx::B3DRange(::basegfx::B3DTuple( rPolyPoly.SequenceX[nPoly][nPoint] , rPolyPoly.SequenceY[nPoly][nPoint] , rPolyPoly.SequenceZ[nPoly][nPoint])); bInited = true; } else { aRet.expand( ::basegfx::B3DTuple( rPolyPoly.SequenceX[nPoly][nPoint] , rPolyPoly.SequenceY[nPoly][nPoint] , rPolyPoly.SequenceZ[nPoly][nPoint])); } } } return aRet; } B2IRectangle makeRectangle( const awt::Point& rPos, const awt::Size& rSize ) { return B2IRectangle(rPos.X,rPos.Y,rPos.X+rSize.Width,rPos.Y+rSize.Height); } awt::Point B2IRectangleToAWTPoint( const ::basegfx::B2IRectangle& rB2IRectangle ) { return awt::Point( rB2IRectangle.getMinX(), rB2IRectangle.getMinY() ); } awt::Size B2IRectangleToAWTSize( const ::basegfx::B2IRectangle& rB2IRectangle ) { return awt::Size( static_cast< sal_Int32 >( rB2IRectangle.getWidth()), static_cast< sal_Int32 >( rB2IRectangle.getHeight())); } awt::Rectangle B2IRectangleToAWTRectangle( const ::basegfx::B2IRectangle& rB2IRectangle ) { return awt::Rectangle( rB2IRectangle.getMinX(), rB2IRectangle.getMinY(), static_cast< sal_Int32 >( rB2IRectangle.getWidth()), static_cast< sal_Int32 >( rB2IRectangle.getHeight())); } B3DVector Direction3DToB3DVector( const Direction3D& rDirection ) { return B3DVector( rDirection.DirectionX , rDirection.DirectionY , rDirection.DirectionZ ); } Direction3D B3DVectorToDirection3D( const B3DVector& rB3DVector ) { return Direction3D( rB3DVector.getX() , rB3DVector.getY() , rB3DVector.getZ() ); } B3DVector Position3DToB3DVector( const Position3D& rPosition ) { return B3DVector( rPosition.PositionX , rPosition.PositionY , rPosition.PositionZ ); } Position3D B3DVectorToPosition3D( const B3DVector& rB3DVector ) { return Position3D( rB3DVector.getX() , rB3DVector.getY() , rB3DVector.getZ() ); } B3DHomMatrix HomogenMatrixToB3DHomMatrix( const HomogenMatrix & rHomogenMatrix ) { B3DHomMatrix aResult; aResult.set( 0, 0, rHomogenMatrix.Line1.Column1 ); aResult.set( 0, 1, rHomogenMatrix.Line1.Column2 ); aResult.set( 0, 2, rHomogenMatrix.Line1.Column3 ); aResult.set( 0, 3, rHomogenMatrix.Line1.Column4 ); aResult.set( 1, 0, rHomogenMatrix.Line2.Column1 ); aResult.set( 1, 1, rHomogenMatrix.Line2.Column2 ); aResult.set( 1, 2, rHomogenMatrix.Line2.Column3 ); aResult.set( 1, 3, rHomogenMatrix.Line2.Column4 ); aResult.set( 2, 0, rHomogenMatrix.Line3.Column1 ); aResult.set( 2, 1, rHomogenMatrix.Line3.Column2 ); aResult.set( 2, 2, rHomogenMatrix.Line3.Column3 ); aResult.set( 2, 3, rHomogenMatrix.Line3.Column4 ); aResult.set( 3, 0, rHomogenMatrix.Line4.Column1 ); aResult.set( 3, 1, rHomogenMatrix.Line4.Column2 ); aResult.set( 3, 2, rHomogenMatrix.Line4.Column3 ); aResult.set( 3, 3, rHomogenMatrix.Line4.Column4 ); return aResult; } HomogenMatrix B3DHomMatrixToHomogenMatrix( const B3DHomMatrix & rB3DMatrix ) { HomogenMatrix aResult; aResult.Line1.Column1 = rB3DMatrix.get( 0, 0 ); aResult.Line1.Column2 = rB3DMatrix.get( 0, 1 ); aResult.Line1.Column3 = rB3DMatrix.get( 0, 2 ); aResult.Line1.Column4 = rB3DMatrix.get( 0, 3 ); aResult.Line2.Column1 = rB3DMatrix.get( 1, 0 ); aResult.Line2.Column2 = rB3DMatrix.get( 1, 1 ); aResult.Line2.Column3 = rB3DMatrix.get( 1, 2 ); aResult.Line2.Column4 = rB3DMatrix.get( 1, 3 ); aResult.Line3.Column1 = rB3DMatrix.get( 2, 0 ); aResult.Line3.Column2 = rB3DMatrix.get( 2, 1 ); aResult.Line3.Column3 = rB3DMatrix.get( 2, 2 ); aResult.Line3.Column4 = rB3DMatrix.get( 2, 3 ); aResult.Line4.Column1 = rB3DMatrix.get( 3, 0 ); aResult.Line4.Column2 = rB3DMatrix.get( 3, 1 ); aResult.Line4.Column3 = rB3DMatrix.get( 3, 2 ); aResult.Line4.Column4 = rB3DMatrix.get( 3, 3 ); return aResult; } B3DTuple GetRotationFromMatrix( const B3DHomMatrix & rB3DMatrix ) { B3DTuple aScale, aTranslation, aRotation, aShearing; rB3DMatrix.decompose( aScale, aTranslation, aRotation, aShearing ); return aRotation; } B3DTuple GetScaleFromMatrix( const B3DHomMatrix & rB3DMatrix ) { B3DTuple aScale, aTranslation, aRotation, aShearing; rB3DMatrix.decompose( aScale, aTranslation, aRotation, aShearing ); return aScale; } void ReduceToRotationMatrix( ::basegfx::B3DHomMatrix & rB3DMatrix ) { B3DTuple aR( GetRotationFromMatrix( rB3DMatrix ) ); ::basegfx::B3DHomMatrix aRotationMatrix; aRotationMatrix.rotate(aR.getX(),aR.getY(),aR.getZ()); rB3DMatrix = aRotationMatrix; } double Deg2Rad( double fDegrees ) { return fDegrees * ( F_PI / 180.0 ); } double Rad2Deg( double fRadians ) { return fRadians * ( 180.0 / F_PI ); } } // namespace BaseGFXHelper } // namespace chart <|endoftext|>
<commit_before>#include "ofApp.h" void ofApp::setup(){ ofDisableArbTex(); _video.initGrabber(1280, 720); _currentFilter = 0; _filters.push_back(new DoGFilter(_video.getWidth(), _video.getHeight(), 11, 1.7, 8.5, 0.983, 4, 4)); _filters.push_back(new KuwaharaFilter()); _filters.push_back(new SobelEdgeDetectionFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new BilateralFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new SketchFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new DilationFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new PerlinPixellationFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new XYDerivativeFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new ZoomBlurFilter()); _filters.push_back(new EmbossFilter(_video.getWidth(), _video.getHeight(), 2.f)); _filters.push_back(new SmoothToonFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new TiltShiftFilter(_video.getTextureReference())); _filters.push_back(new VoronoiFilter(_video.getTextureReference())); _filters.push_back(new DoGFilter(_video.getWidth(), _video.getHeight(), 56, 1.36, 0.01, 0.987, 4, 0, ofVec2f(3.3, 0.0))); _filters.push_back(new CGAColorspaceFilter()); _filters.push_back(new ErosionFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new LookupFilter(_video.getWidth(), _video.getHeight(), "img/lookup_amatorka.png")); _filters.push_back(new LookupFilter(_video.getWidth(), _video.getHeight(), "img/lookup_miss_etikate.png")); _filters.push_back(new LookupFilter(_video.getWidth(), _video.getHeight(), "img/lookup_soft_elegance_1.png")); _filters.push_back(new VignetteFilter()); _filters.push_back(new PosterizeFilter(8)); _filters.push_back(new LaplacianFilter(_video.getWidth(), _video.getHeight(), ofVec2f(1, 1))); _filters.push_back(new PixelateFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new HarrisCornerDetectionFilter(_video.getTextureReference())); _filters.push_back(new MotionDetectionFilter(_video.getTextureReference())); _filters.push_back(new LowPassFilter(_video.getWidth(), _video.getHeight(), 0.9)); _filters.push_back(new DisplacementFilter("img/mandel.jpg", _video.getWidth(), _video.getHeight(), 25.f)); _filters.push_back(new PoissonBlendFilter("img/wes.jpg", _video.getWidth(), _video.getHeight(), 2.0)); // and here's how you might daisy-chain a bunch of filters FilterChain * foggyTexturedGlassChain = new FilterChain(_video.getWidth(), _video.getHeight(), "Weird Glass"); foggyTexturedGlassChain->addFilter(new PerlinPixellationFilter(_video.getWidth(), _video.getHeight(), 13.f)); foggyTexturedGlassChain->addFilter(new EmbossFilter(_video.getWidth(), _video.getHeight(), 0.5)); foggyTexturedGlassChain->addFilter(new GaussianBlurFilter(_video.getWidth(), _video.getHeight(), 3.f)); _filters.push_back(foggyTexturedGlassChain); // here's another unimaginative filter chain FilterChain * watercolorChain = new FilterChain(_video.getWidth(), _video.getHeight(), "Monet"); watercolorChain->addFilter(new KuwaharaFilter(9)); watercolorChain->addFilter(new LookupFilter(_video.getWidth(), _video.getHeight(), "img/lookup_miss_etikate.png")); watercolorChain->addFilter(new BilateralFilter(_video.getWidth(), _video.getHeight())); watercolorChain->addFilter(new PoissonBlendFilter("img/canvas_texture.jpg", _video.getWidth(), _video.getHeight(), 2.0)); watercolorChain->addFilter(new VignetteFilter()); _filters.push_back(watercolorChain); // and here's a random gradient map for posterity vector<GradientMapColorPoint> colors; for (float percent=0.0; percent<=1.0; percent+= 0.1) colors.push_back( GradientMapColorPoint(ofRandomuf(),ofRandomuf(),ofRandomuf(),percent) ); _filters.push_back(new GradientMapFilter(colors)); } void ofApp::update(){ _video.update(); } void ofApp::draw(){ ofBackground(0, 0, 0); ofSetColor(255); ofPushMatrix(); ofScale(-1, 1); ofTranslate(-_video.getWidth(), 0); _filters[_currentFilter]->begin(); _video.draw(0,0); _filters[_currentFilter]->end(); ofPopMatrix(); ofSetColor(255); ofDrawBitmapString( _filters[_currentFilter]->getName() + " Filter\n(press SPACE to change filters)", ofPoint(40, 20)); } void ofApp::keyPressed(int key){ if (key==' ') { _currentFilter ++; if (_currentFilter>=_filters.size()) _currentFilter = 0; } else if (key=='f') ofToggleFullscreen(); } <commit_msg>added examples of DoG and blending<commit_after>#include "ofApp.h" void ofApp::setup(){ ofDisableArbTex(); _video.initGrabber(1280, 720); _currentFilter = 0; _filters.push_back(new KuwaharaFilter()); _filters.push_back(new SobelEdgeDetectionFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new BilateralFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new SketchFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new DilationFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new PerlinPixellationFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new XYDerivativeFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new ZoomBlurFilter()); _filters.push_back(new EmbossFilter(_video.getWidth(), _video.getHeight(), 2.f)); _filters.push_back(new SmoothToonFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new TiltShiftFilter(_video.getTextureReference())); _filters.push_back(new VoronoiFilter(_video.getTextureReference())); _filters.push_back(new DoGFilter(_video.getWidth(), _video.getHeight(), 56, 1.36, 0.01, 0.987, 4, 0, ofVec2f(3.3, 0.0))); _filters.push_back(new CGAColorspaceFilter()); _filters.push_back(new ErosionFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new LookupFilter(_video.getWidth(), _video.getHeight(), "img/lookup_amatorka.png")); _filters.push_back(new LookupFilter(_video.getWidth(), _video.getHeight(), "img/lookup_miss_etikate.png")); _filters.push_back(new LookupFilter(_video.getWidth(), _video.getHeight(), "img/lookup_soft_elegance_1.png")); _filters.push_back(new VignetteFilter()); _filters.push_back(new PosterizeFilter(8)); _filters.push_back(new LaplacianFilter(_video.getWidth(), _video.getHeight(), ofVec2f(1, 1))); _filters.push_back(new PixelateFilter(_video.getWidth(), _video.getHeight())); _filters.push_back(new HarrisCornerDetectionFilter(_video.getTextureReference())); _filters.push_back(new MotionDetectionFilter(_video.getTextureReference())); _filters.push_back(new LowPassFilter(_video.getWidth(), _video.getHeight(), 0.9)); _filters.push_back(new DisplacementFilter("img/mandel.jpg", _video.getWidth(), _video.getHeight(), 25.f)); _filters.push_back(new PoissonBlendFilter("img/wes.jpg", _video.getWidth(), _video.getHeight(), 2.0)); _filters.push_back(new DisplacementFilter("img/glass/3.jpg", _video.getWidth(), _video.getHeight(), 40.0)); // and here's how you might daisy-chain a bunch of filters FilterChain * foggyTexturedGlassChain = new FilterChain(_video.getWidth(), _video.getHeight(), "Weird Glass"); foggyTexturedGlassChain->addFilter(new PerlinPixellationFilter(_video.getWidth(), _video.getHeight(), 13.f)); foggyTexturedGlassChain->addFilter(new EmbossFilter(_video.getWidth(), _video.getHeight(), 0.5)); foggyTexturedGlassChain->addFilter(new GaussianBlurFilter(_video.getWidth(), _video.getHeight(), 3.f)); _filters.push_back(foggyTexturedGlassChain); // here's another unimaginative filter chain FilterChain * watercolorChain = new FilterChain(_video.getWidth(), _video.getHeight(), "Monet"); watercolorChain->addFilter(new KuwaharaFilter(9)); watercolorChain->addFilter(new LookupFilter(_video.getWidth(), _video.getHeight(), "img/lookup_miss_etikate.png")); watercolorChain->addFilter(new BilateralFilter(_video.getWidth(), _video.getHeight())); watercolorChain->addFilter(new PoissonBlendFilter("img/canvas_texture.jpg", _video.getWidth(), _video.getHeight(), 2.0)); watercolorChain->addFilter(new VignetteFilter()); _filters.push_back(watercolorChain); // and here's a random gradient map for posterity vector<GradientMapColorPoint> colors; for (float percent=0.0; percent<=1.0; percent+= 0.1) colors.push_back( GradientMapColorPoint(ofRandomuf(),ofRandomuf(),ofRandomuf(),percent) ); _filters.push_back(new GradientMapFilter(colors)); } void ofApp::update(){ _video.update(); } void ofApp::draw(){ ofBackground(0, 0, 0); ofSetColor(255); ofPushMatrix(); ofScale(-1, 1); ofTranslate(-_video.getWidth(), 0); _filters[_currentFilter]->begin(); _video.draw(0,0); _filters[_currentFilter]->end(); ofPopMatrix(); ofSetColor(255); ofDrawBitmapString( _filters[_currentFilter]->getName() + " Filter\n(press SPACE to change filters)", ofPoint(40, 20)); } void ofApp::keyPressed(int key){ if (key==' ') { _currentFilter ++; if (_currentFilter>=_filters.size()) _currentFilter = 0; } else if (key=='f') ofToggleFullscreen(); } <|endoftext|>
<commit_before>/* * Copyright 2008-2010 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 <stdio.h> #include "esnpapi.h" namespace { NPObject* stubAllocate(NPP npp, NPClass* aClass) { return new StubObject(npp); } void stubDeallocate(NPObject* object) { delete static_cast<StubObject*>(object); } void stubInvalidate(NPObject* object) { return static_cast<StubObject*>(object)->invalidate(); } bool stubHasMethod(NPObject* object, NPIdentifier name) { return static_cast<StubObject*>(object)->hasMethod(name); } bool stubInvoke(NPObject* object, NPIdentifier name, const NPVariant* args, uint32_t argCount, NPVariant* result) { return static_cast<StubObject*>(object)->invoke(name, args, argCount, result); } bool stubInvokeDefault(NPObject* object, const NPVariant* args, uint32_t argCount, NPVariant* result) { return static_cast<StubObject*>(object)->invokeDefault(args, argCount, result); } bool stubHasProperty(NPObject* object, NPIdentifier name) { return static_cast<StubObject*>(object)->hasProperty(name); } bool stubGetProperty(NPObject* object, NPIdentifier name, NPVariant* result) { return static_cast<StubObject*>(object)->getProperty(name, result); } bool stubSetProperty(NPObject* object, NPIdentifier name, const NPVariant* value) { return static_cast<StubObject*>(object)->setProperty(name, value); } bool stubRemoveProperty(NPObject* object, NPIdentifier name) { return static_cast<StubObject*>(object)->removeProperty(name); } bool stubEnumeration(NPObject* object, NPIdentifier** value, uint32_t* count) { return static_cast<StubObject*>(object)->enumeration(value, count); } bool stubConstruct(NPObject* object, const NPVariant* args, uint32_t argCount, NPVariant* result) { return static_cast<StubObject*>(object)->construct(args, argCount, result); } unsigned lookupSymbolTalbe(Object* object, const char* identifier, unsigned& interfaceNumber, unsigned& symbolNumber) { const Reflect::SymbolData* symbolTable; while (symbolTable = object->getSymbolTable(interfaceNumber)) { unsigned offset = 0; for (symbolTable += symbolNumber; symbolTable->symbol; ++symbolNumber, ++symbolTable) { if (!std::strcmp(symbolTable->symbol, identifier)) { return symbolTable->offset; } } ++interfaceNumber; } return 0; } } // namespace void StubObject::invalidate() { } bool StubObject::hasMethod(NPIdentifier name) { NPUTF8* identifier = NPN_UTF8FromIdentifier(name); if (!identifier) { return false; } printf("%s(%s)\n", __func__, identifier); bool found = false; unsigned interfaceNumber = 0; unsigned symbolNumber = 0; for (;; ++symbolNumber) { unsigned offset = lookupSymbolTalbe(object, identifier, interfaceNumber, symbolNumber); if (!offset) { break; } const char* metaData = object->getMetaData(interfaceNumber); metaData += offset; if (*metaData == Reflect::kOperation) { found = true; break; } } NPN_MemFree(identifier); return found; } bool StubObject::invoke(NPIdentifier name, const NPVariant* args, uint32_t arg_count, NPVariant* result) { NPUTF8* identifier = NPN_UTF8FromIdentifier(name); if (!identifier) { return false; } printf("%s(%s)\n", __func__, identifier); bool found = false; unsigned interfaceNumber = 0; unsigned symbolNumber = 0; for (;; ++symbolNumber) { unsigned offset = lookupSymbolTalbe(object, identifier, interfaceNumber, symbolNumber); if (!offset) { break; } const char* metaData = object->getMetaData(interfaceNumber); metaData += offset; if (*metaData == Reflect::kOperation) { Reflect::Method method(metaData); unsigned argumentCount = method.getParameterCount(); // TODO: Support variadic operation if (argumentCount != arg_count) { continue; } Any arguments[argumentCount]; for (unsigned i = 0; i < argumentCount; ++i) { arguments[i] = convertToAny(npp, &args[i]); // TODO: Use , type) } Any value = object->call(interfaceNumber, symbolNumber, argumentCount, arguments); convertToVariant(npp,value, result); found = true; break; } } NPN_MemFree(identifier); return found; } bool StubObject::invokeDefault(const NPVariant* args, uint32_t arg_count, NPVariant* result) { printf("%s()\n", __func__); return false; } bool StubObject::hasProperty(NPIdentifier name) { NPUTF8* identifier = NPN_UTF8FromIdentifier(name); if (!identifier) { return false; } printf("%s(%s)\n", __func__, identifier); bool found = false; unsigned interfaceNumber = 0; unsigned symbolNumber = 0; for (;; ++symbolNumber) { unsigned offset = lookupSymbolTalbe(object, identifier, interfaceNumber, symbolNumber); if (!offset) { break; } const char* metaData = object->getMetaData(interfaceNumber); metaData += offset; if (*metaData == Reflect::kConstant || *metaData == Reflect::kGetter || *metaData == Reflect::kSetter) { found = true; break; } } NPN_MemFree(identifier); return found; } bool StubObject::getProperty(NPIdentifier name, NPVariant* result) { NPUTF8* identifier = NPN_UTF8FromIdentifier(name); if (!identifier) { return false; } printf("%s(%s)\n", __func__, identifier); bool found = false; unsigned interfaceNumber = 0; unsigned symbolNumber = 0; for (;; ++symbolNumber) { unsigned offset = lookupSymbolTalbe(object, identifier, interfaceNumber, symbolNumber); if (!offset) { break; } const char* metaData = object->getMetaData(interfaceNumber); metaData += offset; if (*metaData == Reflect::kConstant) { // TODO: eval the constant value found = true; break; } if (*metaData == Reflect::kGetter) { Any property = object->call(interfaceNumber, symbolNumber, 0, 0); convertToVariant(npp, property, result); found = true; break; } } NPN_MemFree(identifier); return found; } bool StubObject::setProperty(NPIdentifier name, const NPVariant* value) { return false; } bool StubObject::removeProperty(NPIdentifier name) { return false; } bool StubObject::enumeration(NPIdentifier** value, uint32_t* count) { return false; } bool StubObject::construct(const NPVariant* args, uint32_t argCount, NPVariant* result) { return false; } NPClass StubObject::npclass = { NP_CLASS_STRUCT_VERSION_CTOR, stubAllocate, stubDeallocate, stubInvalidate, stubHasMethod, stubInvoke, stubInvokeDefault, stubHasProperty, stubGetProperty, stubSetProperty, stubRemoveProperty, stubEnumeration, stubConstruct }; <commit_msg>(StubObject) : Implement setProperty.<commit_after>/* * Copyright 2008-2010 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 <stdio.h> #include "esnpapi.h" namespace { NPObject* stubAllocate(NPP npp, NPClass* aClass) { return new StubObject(npp); } void stubDeallocate(NPObject* object) { delete static_cast<StubObject*>(object); } void stubInvalidate(NPObject* object) { return static_cast<StubObject*>(object)->invalidate(); } bool stubHasMethod(NPObject* object, NPIdentifier name) { return static_cast<StubObject*>(object)->hasMethod(name); } bool stubInvoke(NPObject* object, NPIdentifier name, const NPVariant* args, uint32_t argCount, NPVariant* result) { return static_cast<StubObject*>(object)->invoke(name, args, argCount, result); } bool stubInvokeDefault(NPObject* object, const NPVariant* args, uint32_t argCount, NPVariant* result) { return static_cast<StubObject*>(object)->invokeDefault(args, argCount, result); } bool stubHasProperty(NPObject* object, NPIdentifier name) { return static_cast<StubObject*>(object)->hasProperty(name); } bool stubGetProperty(NPObject* object, NPIdentifier name, NPVariant* result) { return static_cast<StubObject*>(object)->getProperty(name, result); } bool stubSetProperty(NPObject* object, NPIdentifier name, const NPVariant* value) { return static_cast<StubObject*>(object)->setProperty(name, value); } bool stubRemoveProperty(NPObject* object, NPIdentifier name) { return static_cast<StubObject*>(object)->removeProperty(name); } bool stubEnumeration(NPObject* object, NPIdentifier** value, uint32_t* count) { return static_cast<StubObject*>(object)->enumeration(value, count); } bool stubConstruct(NPObject* object, const NPVariant* args, uint32_t argCount, NPVariant* result) { return static_cast<StubObject*>(object)->construct(args, argCount, result); } unsigned lookupSymbolTalbe(Object* object, const char* identifier, unsigned& interfaceNumber, unsigned& symbolNumber) { const Reflect::SymbolData* symbolTable; while (symbolTable = object->getSymbolTable(interfaceNumber)) { unsigned offset = 0; for (symbolTable += symbolNumber; symbolTable->symbol; ++symbolNumber, ++symbolTable) { if (!std::strcmp(symbolTable->symbol, identifier)) { return symbolTable->offset; } } ++interfaceNumber; } return 0; } } // namespace void StubObject::invalidate() { } bool StubObject::hasMethod(NPIdentifier name) { NPUTF8* identifier = NPN_UTF8FromIdentifier(name); if (!identifier) { return false; } printf("%s(%s)\n", __func__, identifier); bool found = false; unsigned interfaceNumber = 0; unsigned symbolNumber = 0; for (;; ++symbolNumber) { unsigned offset = lookupSymbolTalbe(object, identifier, interfaceNumber, symbolNumber); if (!offset) { break; } const char* metaData = object->getMetaData(interfaceNumber); metaData += offset; if (*metaData == Reflect::kOperation) { found = true; break; } } NPN_MemFree(identifier); return found; } bool StubObject::invoke(NPIdentifier name, const NPVariant* args, uint32_t arg_count, NPVariant* result) { NPUTF8* identifier = NPN_UTF8FromIdentifier(name); if (!identifier) { return false; } printf("%s(%s)\n", __func__, identifier); bool found = false; unsigned interfaceNumber = 0; unsigned symbolNumber = 0; for (;; ++symbolNumber) { unsigned offset = lookupSymbolTalbe(object, identifier, interfaceNumber, symbolNumber); if (!offset) { break; } const char* metaData = object->getMetaData(interfaceNumber); metaData += offset; if (*metaData == Reflect::kOperation) { Reflect::Method method(metaData); unsigned argumentCount = method.getParameterCount(); // TODO: Support variadic operation if (argumentCount != arg_count) { continue; } Any arguments[argumentCount]; for (unsigned i = 0; i < argumentCount; ++i) { arguments[i] = convertToAny(npp, &args[i]); // TODO: Use , type) } Any value = object->call(interfaceNumber, symbolNumber, argumentCount, arguments); convertToVariant(npp,value, result); found = true; break; } } NPN_MemFree(identifier); return found; } bool StubObject::invokeDefault(const NPVariant* args, uint32_t arg_count, NPVariant* result) { printf("%s()\n", __func__); return false; } bool StubObject::hasProperty(NPIdentifier name) { NPUTF8* identifier = NPN_UTF8FromIdentifier(name); if (!identifier) { return false; } printf("%s(%s)\n", __func__, identifier); bool found = false; unsigned interfaceNumber = 0; unsigned symbolNumber = 0; for (;; ++symbolNumber) { unsigned offset = lookupSymbolTalbe(object, identifier, interfaceNumber, symbolNumber); if (!offset) { break; } const char* metaData = object->getMetaData(interfaceNumber); metaData += offset; if (*metaData == Reflect::kConstant || *metaData == Reflect::kGetter || *metaData == Reflect::kSetter) { found = true; break; } } NPN_MemFree(identifier); return found; } bool StubObject::getProperty(NPIdentifier name, NPVariant* result) { NPUTF8* identifier = NPN_UTF8FromIdentifier(name); if (!identifier) { return false; } printf("%s(%s)\n", __func__, identifier); bool found = false; unsigned interfaceNumber = 0; unsigned symbolNumber = 0; for (;; ++symbolNumber) { unsigned offset = lookupSymbolTalbe(object, identifier, interfaceNumber, symbolNumber); if (!offset) { break; } const char* metaData = object->getMetaData(interfaceNumber); metaData += offset; if (*metaData == Reflect::kConstant) { // TODO: eval the constant value found = true; break; } if (*metaData == Reflect::kGetter) { Any property = object->call(interfaceNumber, symbolNumber, 0, 0); convertToVariant(npp, property, result); found = true; break; } } NPN_MemFree(identifier); return found; } bool StubObject::setProperty(NPIdentifier name, const NPVariant* value) { NPUTF8* identifier = NPN_UTF8FromIdentifier(name); if (!identifier) { return false; } printf("%s(%s)\n", __func__, identifier); bool found = false; unsigned interfaceNumber = 0; unsigned symbolNumber = 0; for (;; ++symbolNumber) { unsigned offset = lookupSymbolTalbe(object, identifier, interfaceNumber, symbolNumber); if (!offset) { break; } const char* metaData = object->getMetaData(interfaceNumber); metaData += offset; if (*metaData == Reflect::kSetter) { Any argument = convertToAny(npp, value); // TODO: Use , type) object->call(interfaceNumber, symbolNumber, 1, &argument); found = true; break; } } NPN_MemFree(identifier); return found; } bool StubObject::removeProperty(NPIdentifier name) { return false; } bool StubObject::enumeration(NPIdentifier** value, uint32_t* count) { return false; } bool StubObject::construct(const NPVariant* args, uint32_t argCount, NPVariant* result) { return false; } NPClass StubObject::npclass = { NP_CLASS_STRUCT_VERSION_CTOR, stubAllocate, stubDeallocate, stubInvalidate, stubHasMethod, stubInvoke, stubInvokeDefault, stubHasProperty, stubGetProperty, stubSetProperty, stubRemoveProperty, stubEnumeration, stubConstruct }; <|endoftext|>
<commit_before>/* example1.cpp ============ Basic usage of the Horse Whisperer Compile with: c++ -std=c++11 example1.cpp -o example Run with ./example Try to run: ./example ./example --help ./example gallop ./example gallop --ponies 5 ./example gallop --ponies 6 ./example gallop --ponies 5 --tired */ #include "../include/horsewhisperer/horsewhisperer.h" #include <string> using namespace HorseWhisperer; bool validation(int x) { // Max value we accept is 5 if (x > 5) { std::cout << "You have assigned too many ponies!" << std::endl; return false; } return true; } // help callback void gallop_help(std::string command_name) { std::cout << "The horses, they be a galloping" << std::endl; } // action callback int gallop(std::string command_name, std::vector<std::string> arguments) { for (int i = 0; i < GetFlag<int>("ponies"); i++) { if (!GetFlag<int>("tired")) { std::cout << "Galloping into the night!" << std::endl; } else { std::cout << "The pony is too tired to gallop." << std::endl; } } return 0; } int main(int argc, char* argv[]) { // Configuring the global context SetHelpBanner("Usage: myprog [global options] <action> [options]"); SetVersion("MyProg version - 0.1.0\n"); SetDelimiters(std::vector<std::string>{"+", ";", "_then"}); // Define global flags DefineGlobalFlag<int>("ponies", "all the ponies", 1, validation); DefineAction("gallop", 0, false, "make the ponies gallop", gallop_help, gallop); DefineActionFlag<bool>("gallop", "tired", "are the horses tired?", false, nullptr); Parse(argc, argv); return Start(); } <commit_msg>Updating help message to string and ActionCallback.<commit_after>/* example1.cpp ============ Basic usage of the Horse Whisperer Compile with: c++ -std=c++11 example1.cpp -o example Run with ./example Try to run: ./example ./example --help ./example gallop ./example gallop --ponies 5 ./example gallop --ponies 6 ./example gallop --ponies 5 --tired */ #include "../include/horsewhisperer/horsewhisperer.h" #include <string> using namespace HorseWhisperer; bool validation(int x) { // Max value we accept is 5 if (x > 5) { std::cout << "You have assigned too many ponies!" << std::endl; return false; } return true; } // help message std::string gallop_help = "The horses, they be galloping\n"; // action callback int gallop(std::vector<std::string> arguments) { for (int i = 0; i < GetFlag<int>("ponies"); i++) { if (!GetFlag<int>("tired")) { std::cout << "Galloping into the night!" << std::endl; } else { std::cout << "The pony is too tired to gallop." << std::endl; } } return 0; } int main(int argc, char* argv[]) { // Configuring the global context SetHelpBanner("Usage: myprog [global options] <action> [options]"); SetVersion("MyProg version - 0.1.0\n"); SetDelimiters(std::vector<std::string>{"+", ";", "_then"}); // Define global flags DefineGlobalFlag<int>("ponies", "all the ponies", 1, validation); DefineAction("gallop", 0, false, "make the ponies gallop", gallop_help, gallop); DefineActionFlag<bool>("gallop", "tired", "are the horses tired?", false, nullptr); Parse(argc, argv); return Start(); } <|endoftext|>
<commit_before> #include <iostream> #include <vector> #include <stdlib.h> #include <assert.h> #include "viennamath/expression.hpp" #include "viennamath/eval.hpp" #include "viennamath/substitute.hpp" #include "viennamath/diff.hpp" #include "viennamath/equation.hpp" #include "viennamath/integral.hpp" #include "viennamath/weak_form.hpp" #include "viennamath/apply_coordinate_system.hpp" using namespace viennamath; int main() { std::cout << "************************************************" << std::endl; std::cout << "***** Demo for ViennaMath with FEM *****" << std::endl; std::cout << "************************************************" << std::endl; function_symbol<unknown_tag<0> > u; //an unknown function /*typedef function_symbol<unknown_tag<0> > U0; typedef function_symbol<unknown_tag<1> > U1; typedef function_symbol<unknown_tag<2> > U2; ct_vector_3<U0, U1, U2> u = make_vector(U0(), U1(), U2()); */ function_symbol<test_tag<0> > v; //a test function (typical for FEM and FVM) /*typedef function_symbol<test_tag<0> > V0; typedef function_symbol<test_tag<1> > V1; typedef function_symbol<test_tag<2> > V2; ct_vector_3<V0, V1, V2> v = make_vector(V0(), V1(), V2());*/ std::cout << "-- Printing div(u): --" << std::endl; std::cout << div(u) << std::endl; std::cout << "-- Printing div(u) with coordinate system applied in 1d, 2d and 3d: --" << std::endl; std::cout << apply_coordinate_system(cartesian<1>(), div(u)) << std::endl; std::cout << apply_coordinate_system(cartesian<2>(), div(u)) << std::endl; std::cout << apply_coordinate_system(cartesian<3>(), div(u)) << std::endl; std::cout << "-- Printing div(v): --" << std::endl; std::cout << div(v) << std::endl; std::cout << "-- Printing div(u) * div(v): --" << std::endl; std::cout << div(u)*div(v) << std::endl; std::cout << "-- Printing div(u) * div(v) with coordinate system applied in 1d, 2d and 3d: --" << std::endl; std::cout << apply_coordinate_system(cartesian<1>(), div(u)*div(v)) << std::endl; std::cout << apply_coordinate_system(cartesian<2>(), div(u)*div(v)) << std::endl; std::cout << apply_coordinate_system(cartesian<3>(), div(u)*div(v)) << std::endl; // // Step 1: Define the classical Lame equation // (lambda + mu) div(u) div(v) + mu grad(u):grad(v) = F // with force F set to 0. // viennamath::constant<double> lambda(1.0); viennamath::constant<double> mu(1.0); /* equation<> strong_form = make_equation( (lambda + mu) * grad(div(u)) + mu * laplace(u), 0); std::cout << "Strong (classical) form of equation:" << std::endl; std::cout << " " << strong_form << std::endl; // // Step 2: Specify weak form: // equation<> weak_form_general = make_equation( (lambda + mu) * integral(Omega(), div(u) * div(v), symbolic_tag()) + mu * integral(Omega(), tensor_add(grad(u), grad(v)), symbolic_tag()), // = 0 ); std::cout << "General weak form: " << std::endl; std::cout << " " << weak_form_general << std::endl; // Step 3: The final form of the gradient still depends on the underlying coordinate system. // We thus transform the general weak form to cartesian coordinate systems. // // Example in 2d: grad(u) * grad(v) is transformed to u_x * v_x + u_y * v_y // equation<> weak_form_1d = apply_coordinate_system(cartesian<1>(), weak_form_general); std::cout << "Weak form in 1d:" << std::endl; std::cout << " " << weak_form_1d << std::endl; equation<> weak_form_2d = apply_coordinate_system(cartesian<2>(), weak_form_general); std::cout << "Weak form in 2d:" << std::endl; std::cout << " " << weak_form_2d << std::endl; equation<> weak_form_3d = apply_coordinate_system(cartesian<3>(), weak_form_general); std::cout << "Weak form in 3d:" << std::endl; std::cout << " " << weak_form_3d << std::endl; */ // // That's it! Everything else is left to ViennaFEM // std::cout << "************************************************" << std::endl; std::cout << "***** TEST COMPLETED SUCCESSFULLY! *****" << std::endl; std::cout << "************************************************" << std::endl; return EXIT_SUCCESS; }<commit_msg>Continued playing with Lame example...<commit_after> #include <iostream> #include <vector> #include <stdlib.h> #include <assert.h> #include "viennamath/expression.hpp" #include "viennamath/eval.hpp" #include "viennamath/substitute.hpp" #include "viennamath/diff.hpp" #include "viennamath/equation.hpp" #include "viennamath/integral.hpp" #include "viennamath/weak_form.hpp" #include "viennamath/apply_coordinate_system.hpp" using namespace viennamath; int main() { std::cout << "************************************************" << std::endl; std::cout << "***** Demo for ViennaMath with FEM *****" << std::endl; std::cout << "************************************************" << std::endl; function_symbol<unknown_tag<0> > u1; //an unknown function function_symbol<unknown_tag<1> > u2; //an unknown function function_symbol<unknown_tag<2> > u3; //an unknown function /*typedef function_symbol<unknown_tag<0> > U0; typedef function_symbol<unknown_tag<1> > U1; typedef function_symbol<unknown_tag<2> > U2; ct_vector_3<U0, U1, U2> u = make_vector(U0(), U1(), U2()); */ function_symbol<test_tag<0> > v1; //a test function (typical for FEM and FVM) function_symbol<test_tag<1> > v2; //a test function (typical for FEM and FVM) function_symbol<test_tag<2> > v3; //a test function (typical for FEM and FVM) /*typedef function_symbol<test_tag<0> > V0; typedef function_symbol<test_tag<1> > V1; typedef function_symbol<test_tag<2> > V2; ct_vector_3<V0, V1, V2> v = make_vector(V0(), V1(), V2());*/ variable<0> x; variable<1> y; variable<2> z; std::cout << "-- Printing div(u): --" << std::endl; std::cout << div(u1) << std::endl; std::cout << "-- Printing div(u) with coordinate system applied in 1d, 2d and 3d: --" << std::endl; std::cout << apply_coordinate_system(cartesian<1>(), div(u1)) << std::endl; std::cout << apply_coordinate_system(cartesian<2>(), div(u1)) << std::endl; std::cout << apply_coordinate_system(cartesian<3>(), div(u1)) << std::endl; std::cout << "-- Printing div(v): --" << std::endl; std::cout << div(v2) << std::endl; std::cout << "-- Printing div(u) * div(v): --" << std::endl; std::cout << div(u1)*div(v2) << std::endl; std::cout << "-- Printing div(u) * div(v) with coordinate system applied in 1d, 2d and 3d: --" << std::endl; std::cout << apply_coordinate_system(cartesian<1>(), div(u1)*div(v1)) << std::endl; std::cout << apply_coordinate_system(cartesian<2>(), div(u2)*div(v2)) << std::endl; std::cout << apply_coordinate_system(cartesian<3>(), div(u3)*div(v3)) << std::endl; // // Step 1: Define the classical Lame equation // (lambda + mu) div(u) div(v) + mu grad(u):grad(v) = F // with force F set to 0. // viennamath::constant<double> lambda(1.0); viennamath::constant<double> mu(1.0); viennamath::constant<double> one_half(0.5); /* equation<> strong_form = make_equation( (lambda + mu) * grad(div(u)) + mu * laplace(u), 0); std::cout << "Strong (classical) form of equation:" << std::endl; std::cout << " " << strong_form << std::endl; // // Step 2: Specify weak form: // equation<> weak_form_general = make_equation( (lambda + mu) * integral(Omega(), div(u) * div(v), symbolic_tag()) + mu * integral(Omega(), tensor_add(grad(u), grad(v)), symbolic_tag()), // = 0 ); */ std::vector<equation<> > lame_equations(3*3); //first row: tested with (phi, 0, 0): lame_equations.push_back( make_equation( mu * integral(Omega(), diff(u1, x) * diff(v1, x) + one_half * (diff(u1, y) * diff(v1, y)) + one_half * (diff(u1, z) * diff(v1, z)), symbolic_tag()) + lambda / 0.5 * integral(Omega(), diff(u1, x) * diff(v1, x), symbolic_tag()), // = lambda * (mu * 0.5) * integral(Omega(), diff(v1, x), symbolic_tag()) ) ); lame_equations.push_back( make_equation( mu * integral(Omega(), diff(u2, x) * diff(v1, y), symbolic_tag()) + lambda / 0.5 * integral(Omega(), diff(u2, y) * diff(v1, x), symbolic_tag()), // = 0 ) ); lame_equations.push_back( make_equation( mu * integral(Omega(), diff(u3, x) * diff(v1, z), symbolic_tag()) + lambda / 0.5 * integral(Omega(), diff(u3, z) * diff(v1, x), symbolic_tag()), // = 0 ) ); //second row: tested with (0, phi, 0): //TODO: Check formulas!! lame_equations.push_back( make_equation( mu * integral(Omega(), diff(u1, x) * diff(v2, x), symbolic_tag()) + lambda / 0.5 * integral(Omega(), diff(u1, x) * diff(v2, x), symbolic_tag()), // = lambda * (mu * 0.5) * integral(Omega(), diff(v1, x), symbolic_tag()) ) ); lame_equations.push_back( make_equation( mu * integral(Omega(), diff(u2, x) * diff(v2, y) + one_half * (diff(u1, y) * diff(v2, y)) + one_half * (diff(u1, z) * diff(v2, z)), symbolic_tag()) + lambda / 0.5 * integral(Omega(), diff(u2, y) * diff(v2, x), symbolic_tag()), // = 0 ) ); lame_equations.push_back( make_equation( mu * integral(Omega(), diff(u3, x) * diff(v2, z), symbolic_tag()) + lambda / 0.5 * integral(Omega(), diff(u3, z) * diff(v2, x), symbolic_tag()), // = 0 ) ); //third row: tested with (0, 0, phi): //TODO: Check formulas!! lame_equations.push_back( make_equation( mu * integral(Omega(), diff(u1, x) * diff(v3, x), symbolic_tag()) + lambda / 0.5 * integral(Omega(), diff(u1, x) * diff(v3, x), symbolic_tag()), // = lambda * (mu * 0.5) * integral(Omega(), diff(v1, x), symbolic_tag()) ) ); lame_equations.push_back( make_equation( mu * integral(Omega(), diff(u2, x) * diff(v3, y), symbolic_tag()) + lambda / 0.5 * integral(Omega(), diff(u2, y) * diff(v3, x), symbolic_tag()), // = 0 ) ); lame_equations.push_back( make_equation( mu * integral(Omega(), diff(u3, x) * diff(v3, z) + one_half * (diff(u1, y) * diff(v3, y)) + one_half * (diff(u1, z) * diff(v3, z)), symbolic_tag()) + lambda / 0.5 * integral(Omega(), diff(u3, z) * diff(v3, x), symbolic_tag()), // = 0 ) ); /* std::cout << "General weak form: " << std::endl; std::cout << " " << weak_form_general << std::endl; // Step 3: The final form of the gradient still depends on the underlying coordinate system. // We thus transform the general weak form to cartesian coordinate systems. // // Example in 2d: grad(u) * grad(v) is transformed to u_x * v_x + u_y * v_y // equation<> weak_form_1d = apply_coordinate_system(cartesian<1>(), weak_form_general); std::cout << "Weak form in 1d:" << std::endl; std::cout << " " << weak_form_1d << std::endl; equation<> weak_form_2d = apply_coordinate_system(cartesian<2>(), weak_form_general); std::cout << "Weak form in 2d:" << std::endl; std::cout << " " << weak_form_2d << std::endl; equation<> weak_form_3d = apply_coordinate_system(cartesian<3>(), weak_form_general); std::cout << "Weak form in 3d:" << std::endl; std::cout << " " << weak_form_3d << std::endl; */ // // That's it! Everything else is left to ViennaFEM // std::cout << "************************************************" << std::endl; std::cout << "***** TEST COMPLETED SUCCESSFULLY! *****" << std::endl; std::cout << "************************************************" << std::endl; return EXIT_SUCCESS; }<|endoftext|>
<commit_before>/* * Copyright (C) 2018 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 "resource_manager.hh" #include "manager.hh" #include "log.hh" #include <boost/range/algorithm/for_each.hpp> #include <boost/range/adaptor/map.hpp> #include "lister.hh" #include "disk-error-handler.hh" #include "seastarx.hh" #include <seastar/core/sleep.hh> namespace db { namespace hints { static logging::logger resource_manager_logger("hints_resource_manager"); future<dev_t> get_device_id(boost::filesystem::path path) { return open_directory(path.native()).then([](file f) { return f.stat().then([f = std::move(f)](struct stat st) { return st.st_dev; }); }); } future<bool> is_mountpoint(boost::filesystem::path path) { // Special case for '/', which is always a mount point if (path == path.parent_path()) { return make_ready_future<bool>(true); } return when_all(get_device_id(path.native()), get_device_id(path.parent_path().native())).then([](std::tuple<future<dev_t>, future<dev_t>> ids) { return std::get<0>(ids).get0() != std::get<1>(ids).get0(); }); } future<semaphore_units<semaphore_default_exception_factory>> resource_manager::get_send_units_for(size_t buf_size) { // Let's approximate the memory size the mutation is going to consume by the size of its serialized form size_t hint_memory_budget = std::max(_min_send_hint_budget, buf_size); // Allow a very big mutation to be sent out by consuming the whole shard budget hint_memory_budget = std::min(hint_memory_budget, _max_send_in_flight_memory); resource_manager_logger.trace("memory budget: need {} have {}", hint_memory_budget, _send_limiter.available_units()); return get_units(_send_limiter, hint_memory_budget); } const std::chrono::seconds space_watchdog::_watchdog_period = std::chrono::seconds(1); space_watchdog::space_watchdog(shard_managers_set& managers, per_device_limits_map& per_device_limits_map) : _shard_managers(managers) , _per_device_limits_map(per_device_limits_map) {} void space_watchdog::start() { _started = seastar::async([this] { while (!_as.abort_requested()) { on_timer(); seastar::sleep_abortable(_watchdog_period, _as).get(); } }).handle_exception_type([] (const seastar::sleep_aborted& ignored) { }); } future<> space_watchdog::stop() noexcept { _as.request_abort(); return std::move(_started); } future<> space_watchdog::scan_one_ep_dir(boost::filesystem::path path, manager& shard_manager, ep_key_type ep_key) { return lister::scan_dir(path, { directory_entry_type::regular }, [this, ep_key, &shard_manager] (lister::path dir, directory_entry de) { // Put the current end point ID to state.eps_with_pending_hints when we see the second hints file in its directory if (_files_count == 1) { shard_manager.add_ep_with_pending_hints(ep_key); } ++_files_count; return io_check(file_size, (dir / de.name.c_str()).c_str()).then([this] (uint64_t fsize) { _total_size += fsize; }); }); } void space_watchdog::on_timer() { futurize_apply([this] { _total_size = 0; return do_for_each(_shard_managers, [this] (manager& shard_manager) { shard_manager.clear_eps_with_pending_hints(); // The hints directories are organized as follows: // <hints root> // |- <shard1 ID> // | |- <EP1 address> // | |- <hints file1> // | |- <hints file2> // | |- ... // | |- <EP2 address> // | |- ... // | |-... // |- <shard2 ID> // | |- ... // ... // |- <shardN ID> // | |- ... // return lister::scan_dir(shard_manager.hints_dir(), {directory_entry_type::directory}, [this, &shard_manager] (lister::path dir, directory_entry de) { _files_count = 0; // Let's scan per-end-point directories and enumerate hints files... // // Let's check if there is a corresponding end point manager (may not exist if the corresponding DC is // not hintable). // If exists - let's take a file update lock so that files are not changed under our feet. Otherwise, simply // continue to enumeration - there is no one to change them. auto it = shard_manager.find_ep_manager(de.name); if (it != shard_manager.ep_managers_end()) { return with_lock(it->second.file_update_mutex(), [this, &shard_manager, dir = std::move(dir), ep_name = std::move(de.name)]() mutable { return scan_one_ep_dir(dir / ep_name.c_str(), shard_manager, ep_key_type(ep_name)); }); } else { return scan_one_ep_dir(dir / de.name.c_str(), shard_manager, ep_key_type(de.name)); } }); }).then([this] { return do_for_each(_per_device_limits_map, [this](per_device_limits_map::value_type& per_device_limits_entry) { space_watchdog::per_device_limits& per_device_limits = per_device_limits_entry.second; size_t adjusted_quota = 0; size_t delta = boost::accumulate(per_device_limits.managers, 0, [] (size_t sum, manager& shard_manager) { return sum + shard_manager.ep_managers_size() * resource_manager::hint_segment_size_in_mb * 1024 * 1024; }); if (per_device_limits.max_shard_disk_space_size > delta) { adjusted_quota = per_device_limits.max_shard_disk_space_size - delta; } bool can_hint = _total_size < adjusted_quota; resource_manager_logger.trace("space_watchdog: total_size ({}) {} max_shard_disk_space_size ({})", _total_size, can_hint ? "<" : ">=", adjusted_quota); if (!can_hint) { for (manager& shard_manager : per_device_limits.managers) { shard_manager.forbid_hints_for_eps_with_pending_hints(); } } else { for (manager& shard_manager : per_device_limits.managers) { shard_manager.allow_hints(); } } }); }); }).handle_exception([this] (auto eptr) { resource_manager_logger.trace("space_watchdog: unexpected exception - stop all hints generators"); // Stop all hint generators if space_watchdog callback failed for (manager& shard_manager : _shard_managers) { shard_manager.forbid_hints(); } }).get(); } future<> resource_manager::start(shared_ptr<service::storage_proxy> proxy_ptr, shared_ptr<gms::gossiper> gossiper_ptr, shared_ptr<service::storage_service> ss_ptr) { return parallel_for_each(_shard_managers, [proxy_ptr, gossiper_ptr, ss_ptr](manager& m) { return m.start(proxy_ptr, gossiper_ptr, ss_ptr); }).then([this]() { return prepare_per_device_limits(); }).then([this]() { return _space_watchdog.start(); }); } future<> resource_manager::stop() noexcept { return parallel_for_each(_shard_managers, [](manager& m) { return m.stop(); }).finally([this]() { return _space_watchdog.stop(); }); } void resource_manager::register_manager(manager& m) { _shard_managers.insert(m); } future<> resource_manager::prepare_per_device_limits() { return do_for_each(_shard_managers, [this] (manager& shard_manager) mutable { dev_t device_id = shard_manager.hints_dir_device_id(); auto it = _per_device_limits_map.find(device_id); if (it == _per_device_limits_map.end()) { return is_mountpoint(shard_manager.hints_dir().parent_path()).then([this, device_id, &shard_manager](bool is_mountpoint) { auto [it, inserted] = _per_device_limits_map.emplace(device_id, space_watchdog::per_device_limits{}); // Since we possibly deferred, we need to recheck the _per_device_limits_map. if (inserted) { // By default, give each group of managers 10% of the available disk space. Give each shard an equal share of the available space. it->second.max_shard_disk_space_size = boost::filesystem::space(shard_manager.hints_dir().c_str()).capacity / (10 * smp::count); // If hints directory is a mountpoint, we assume it's on dedicated (i.e. not shared with data/commitlog/etc) storage. // Then, reserve 90% of all space instead of 10% above. if (is_mountpoint) { it->second.max_shard_disk_space_size *= 9; } } it->second.managers.emplace_back(std::ref(shard_manager)); }); } else { it->second.managers.emplace_back(std::ref(shard_manager)); return make_ready_future<>(); } }); } } } <commit_msg>db/hints/resource_manager: Correctly account resources in space_watchdog<commit_after>/* * Copyright (C) 2018 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 "resource_manager.hh" #include "manager.hh" #include "log.hh" #include <boost/range/algorithm/for_each.hpp> #include <boost/range/adaptor/map.hpp> #include "lister.hh" #include "disk-error-handler.hh" #include "seastarx.hh" #include <seastar/core/sleep.hh> namespace db { namespace hints { static logging::logger resource_manager_logger("hints_resource_manager"); future<dev_t> get_device_id(boost::filesystem::path path) { return open_directory(path.native()).then([](file f) { return f.stat().then([f = std::move(f)](struct stat st) { return st.st_dev; }); }); } future<bool> is_mountpoint(boost::filesystem::path path) { // Special case for '/', which is always a mount point if (path == path.parent_path()) { return make_ready_future<bool>(true); } return when_all(get_device_id(path.native()), get_device_id(path.parent_path().native())).then([](std::tuple<future<dev_t>, future<dev_t>> ids) { return std::get<0>(ids).get0() != std::get<1>(ids).get0(); }); } future<semaphore_units<semaphore_default_exception_factory>> resource_manager::get_send_units_for(size_t buf_size) { // Let's approximate the memory size the mutation is going to consume by the size of its serialized form size_t hint_memory_budget = std::max(_min_send_hint_budget, buf_size); // Allow a very big mutation to be sent out by consuming the whole shard budget hint_memory_budget = std::min(hint_memory_budget, _max_send_in_flight_memory); resource_manager_logger.trace("memory budget: need {} have {}", hint_memory_budget, _send_limiter.available_units()); return get_units(_send_limiter, hint_memory_budget); } const std::chrono::seconds space_watchdog::_watchdog_period = std::chrono::seconds(1); space_watchdog::space_watchdog(shard_managers_set& managers, per_device_limits_map& per_device_limits_map) : _shard_managers(managers) , _per_device_limits_map(per_device_limits_map) {} void space_watchdog::start() { _started = seastar::async([this] { while (!_as.abort_requested()) { try { on_timer(); } catch (...) { resource_manager_logger.trace("space_watchdog: unexpected exception - stop all hints generators"); // Stop all hint generators if space_watchdog callback failed for (manager& shard_manager : _shard_managers) { shard_manager.forbid_hints(); } } seastar::sleep_abortable(_watchdog_period, _as).get(); } }).handle_exception_type([] (const seastar::sleep_aborted& ignored) { }); } future<> space_watchdog::stop() noexcept { _as.request_abort(); return std::move(_started); } future<> space_watchdog::scan_one_ep_dir(boost::filesystem::path path, manager& shard_manager, ep_key_type ep_key) { return lister::scan_dir(path, { directory_entry_type::regular }, [this, ep_key, &shard_manager] (lister::path dir, directory_entry de) { // Put the current end point ID to state.eps_with_pending_hints when we see the second hints file in its directory if (_files_count == 1) { shard_manager.add_ep_with_pending_hints(ep_key); } ++_files_count; return io_check(file_size, (dir / de.name.c_str()).c_str()).then([this] (uint64_t fsize) { _total_size += fsize; }); }); } // Called from the context of a seastar::thread. void space_watchdog::on_timer() { // The hints directories are organized as follows: // <hints root> // |- <shard1 ID> // | |- <EP1 address> // | |- <hints file1> // | |- <hints file2> // | |- ... // | |- <EP2 address> // | |- ... // | |-... // |- <shard2 ID> // | |- ... // ... // |- <shardN ID> // | |- ... // for (auto& per_device_limits : _per_device_limits_map | boost::adaptors::map_values) { _total_size = 0; for (manager& shard_manager : per_device_limits.managers) { shard_manager.clear_eps_with_pending_hints(); lister::scan_dir(shard_manager.hints_dir(), {directory_entry_type::directory}, [this, &shard_manager] (lister::path dir, directory_entry de) { _files_count = 0; // Let's scan per-end-point directories and enumerate hints files... // // Let's check if there is a corresponding end point manager (may not exist if the corresponding DC is // not hintable). // If exists - let's take a file update lock so that files are not changed under our feet. Otherwise, simply // continue to enumeration - there is no one to change them. auto it = shard_manager.find_ep_manager(de.name); if (it != shard_manager.ep_managers_end()) { return with_lock(it->second.file_update_mutex(), [this, &shard_manager, dir = std::move(dir), ep_name = std::move(de.name)]() mutable { return scan_one_ep_dir(dir / ep_name.c_str(), shard_manager, ep_key_type(ep_name)); }); } else { return scan_one_ep_dir(dir / de.name.c_str(), shard_manager, ep_key_type(de.name)); } }).get(); } // Adjust the quota to take into account the space we guarantee to every end point manager size_t adjusted_quota = 0; size_t delta = boost::accumulate(per_device_limits.managers, 0, [] (size_t sum, manager& shard_manager) { return sum + shard_manager.ep_managers_size() * resource_manager::hint_segment_size_in_mb * 1024 * 1024; }); if (per_device_limits.max_shard_disk_space_size > delta) { adjusted_quota = per_device_limits.max_shard_disk_space_size - delta; } bool can_hint = _total_size < adjusted_quota; resource_manager_logger.trace("space_watchdog: total_size ({}) {} max_shard_disk_space_size ({})", _total_size, can_hint ? "<" : ">=", adjusted_quota); if (!can_hint) { for (manager& shard_manager : per_device_limits.managers) { shard_manager.forbid_hints_for_eps_with_pending_hints(); } } else { for (manager& shard_manager : per_device_limits.managers) { shard_manager.allow_hints(); } } } } future<> resource_manager::start(shared_ptr<service::storage_proxy> proxy_ptr, shared_ptr<gms::gossiper> gossiper_ptr, shared_ptr<service::storage_service> ss_ptr) { return parallel_for_each(_shard_managers, [proxy_ptr, gossiper_ptr, ss_ptr](manager& m) { return m.start(proxy_ptr, gossiper_ptr, ss_ptr); }).then([this]() { return prepare_per_device_limits(); }).then([this]() { return _space_watchdog.start(); }); } future<> resource_manager::stop() noexcept { return parallel_for_each(_shard_managers, [](manager& m) { return m.stop(); }).finally([this]() { return _space_watchdog.stop(); }); } void resource_manager::register_manager(manager& m) { _shard_managers.insert(m); } future<> resource_manager::prepare_per_device_limits() { return do_for_each(_shard_managers, [this] (manager& shard_manager) mutable { dev_t device_id = shard_manager.hints_dir_device_id(); auto it = _per_device_limits_map.find(device_id); if (it == _per_device_limits_map.end()) { return is_mountpoint(shard_manager.hints_dir().parent_path()).then([this, device_id, &shard_manager](bool is_mountpoint) { auto [it, inserted] = _per_device_limits_map.emplace(device_id, space_watchdog::per_device_limits{}); // Since we possibly deferred, we need to recheck the _per_device_limits_map. if (inserted) { // By default, give each group of managers 10% of the available disk space. Give each shard an equal share of the available space. it->second.max_shard_disk_space_size = boost::filesystem::space(shard_manager.hints_dir().c_str()).capacity / (10 * smp::count); // If hints directory is a mountpoint, we assume it's on dedicated (i.e. not shared with data/commitlog/etc) storage. // Then, reserve 90% of all space instead of 10% above. if (is_mountpoint) { it->second.max_shard_disk_space_size *= 9; } } it->second.managers.emplace_back(std::ref(shard_manager)); }); } else { it->second.managers.emplace_back(std::ref(shard_manager)); return make_ready_future<>(); } }); } } } <|endoftext|>
<commit_before><commit_msg>Unit Tests - arguments.t<commit_after><|endoftext|>
<commit_before>/* Dorm LED Project: led_window_anim_cmds.cpp This file contains the window LED animation commands. These are meant to be executed using the multithreaded system. Created by: Michael Fischler 10/22/2016 @ WPI */ /* Template for a Command std::vector<int> (*cmd)(std::vector<int>) std::vector<int> cmd(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); int t = var_stack.at(1); // run command code ... // update variables var_stack.at(0) = i; var_stack.at(1) = t; return var_stack; } */ /* ~~~~~~ Off Commands ~~~~~~ */ // &&& Functions for Off Commands &&& // &&& Command Ready Functions for Off Commands &&& /* ~~~~~~ Static Commands ~~~~~~ */ // &&& Functions for Static Commands &&& // &&& Command Ready Functions for Animated Commands &&& /* ~~~~~~ Animated Commands ~~~~~~ */ // &&& Functions for Animated Commands &&& void _win_all_wpp_fade(int i){ for(int x = 0; x < WINDOW_LENGTH; x++){ setAllWindowPixelColor(x, window_generic.Color((int)(((float)i / 150.0) * 100), 0, i)); } showAllWindowStrips(); } void _win_all_WPI_spirit(int i, short int mode){ //uint8_t red = window_generic.Color(172, 43, 55); //uint8_t white = window_generic.Color(169, 176, 183); if(mode == 0){ window1.setPixelColor(i, window_generic.Color(255, 21, 27)); if(i%2 == 0){ window2.setPixelColor(i, window_generic.Color(169, 176, 183)); }else{ window2.setPixelColor(i, window_generic.Color(255, 21, 27)); } int modified = WINDOW_LENGTH + 9 - 1 - i; if(modified >= WINDOW_LENGTH){ modified -= WINDOW_LENGTH; } window3.setPixelColor(modified, window_generic.Color(255, 21, 27)); }else if(mode == 1){ window1.setPixelColor(i, window_generic.Color(169, 176, 183)); for(int j = 0; j < WINDOW_LENGTH; j++){ if(i%2 != 0){ window2.setPixelColor(i, window_generic.Color(169, 176, 183)); }else{ window2.setPixelColor(i, window_generic.Color(255, 21, 27)); } } int modified = WINDOW_LENGTH + 9 - 1 - i; if(modified >= WINDOW_LENGTH){ modified -= WINDOW_LENGTH; } window3.setPixelColor(modified, window_generic.Color(169, 176, 183)); } window1.show(); window3.show(); } // &&& Command Ready Functions for Animated Commands &&& // Every LED fades in and out a with calm purple // Initial input var_stack : std::vector<int> stack{0,1} std::vector<int> win_all_wpp_fade(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); short int increasing = var_stack.at(1); // run command code _win_all_wpp_fade(i); if(increasing == 1){ if(i == 150){ i--; increasing = 0; }else{ i++; } }else{ if(i == 0){ i++; increasing = 1; }else{ i--; } } // update variables var_stack.at(0) = i; var_stack.at(1) = increasing; return var_stack; } // A spirited display for my college, WPI // Initial input var_stack : std::vector<int> stack{0,0} std::vector<int> win_all_WPI_spirit(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); short int mode = var_stack.at(1); // run command code _win_all_WPI_spirit(i, mode); if(mode == 0){ if(i + 1 == WINDOW_LENGTH){ i = 0; mode = 1; window2.show(); }else{ i++; } }else if(mode == 1){ if(i + 1 == WINDOW_LENGTH){ i = 0; mode = 0; window2.show(); }else{ i++; } } // update variables var_stack.at(0) = i; var_stack.at(1) = mode; return var_stack; } // Rainbow Color Wipe for first window // Initial input var_stack : std::vector<int> stack {0,0} std::vector<int> win_1_rainbow_wipe(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); int color_mode = var_stack.at(1); // run command code if(color_mode % 2 != 0){ window1.setPixelColor(i, window_generic.Color(0, 0, 0)); // Off }else if(color_mode == 0){ window1.setPixelColor(i, window_generic.Color(255, 0, 0)); // Red }else if(color_mode == 2){ window1.setPixelColor(i, window_generic.Color(255, 50, 0)); // Orange }else if(color_mode == 4){ window1.setPixelColor(i, window_generic.Color(255, 150, 0)); // Yellow }else if(color_mode == 6){ window1.setPixelColor(i, window_generic.Color(0, 255, 0)); // Green }else if(color_mode == 8){ window1.setPixelColor(i, window_generic.Color(0, 255, 200)); // Sea Green }else if(color_mode == 10){ window1.setPixelColor(i, window_generic.Color(0, 0, 255)); // Blue }else if(color_mode == 12){ window1.setPixelColor(i, window_generic.Color(100, 0, 255)); // Indigo }else if(color_mode == 14){ window1.setPixelColor(i, window_generic.Color(255, 0, 255)); // Violet } window1.show(); i++; if(i == WINDOW_LENGTH){ color_mode++; i = 0; } // update variables var_stack.at(0) = i; var_stack.at(1) = color_mode; return var_stack; } // Rainbow Color Wipe for second window // Initial input var_stack : std::vector<int> stack {0,0} std::vector<int> win_2_rainbow_wipe(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); int color_mode = var_stack.at(1); // run command code if(color_mode % 2 != 0){ window2.setPixelColor(i, window_generic.Color(0, 0, 0)); // Off }else if(color_mode == 0){ window2.setPixelColor(i, window_generic.Color(255, 0, 0)); // Red }else if(color_mode == 2){ window2.setPixelColor(i, window_generic.Color(255, 50, 0)); // Orange }else if(color_mode == 4){ window2.setPixelColor(i, window_generic.Color(255, 150, 0)); // Yellow }else if(color_mode == 6){ window2.setPixelColor(i, window_generic.Color(0, 255, 0)); // Green }else if(color_mode == 8){ window2.setPixelColor(i, window_generic.Color(0, 255, 200)); // Sea Green }else if(color_mode == 10){ window2.setPixelColor(i, window_generic.Color(0, 0, 255)); // Blue }else if(color_mode == 12){ window2.setPixelColor(i, window_generic.Color(100, 0, 255)); // Indigo }else if(color_mode == 14){ window2.setPixelColor(i, window_generic.Color(255, 0, 255)); // Violet } window2.show(); i++; if(i == WINDOW_LENGTH){ color_mode++; i = 0; } // update variables var_stack.at(0) = i; var_stack.at(1) = color_mode; return var_stack; } // Rainbow Color Wipe for third window // Initial input var_stack : std::vector<int> stack {0,0} std::vector<int> win_3_rainbow_wipe(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); int color_mode = var_stack.at(1); // run command code if(color_mode % 2 != 0){ window3.setPixelColor(i, window_generic.Color(0, 0, 0)); // Off }else if(color_mode == 0){ window3.setPixelColor(i, window_generic.Color(255, 0, 0)); // Red }else if(color_mode == 2){ window3.setPixelColor(i, window_generic.Color(255, 50, 0)); // Orange }else if(color_mode == 4){ window3.setPixelColor(i, window_generic.Color(255, 150, 0)); // Yellow }else if(color_mode == 6){ window3.setPixelColor(i, window_generic.Color(0, 255, 0)); // Green }else if(color_mode == 8){ window3.setPixelColor(i, window_generic.Color(0, 255, 200)); // Sea Green }else if(color_mode == 10){ window3.setPixelColor(i, window_generic.Color(0, 0, 255)); // Blue }else if(color_mode == 12){ window3.setPixelColor(i, window_generic.Color(100, 0, 255)); // Indigo }else if(color_mode == 14){ window3.setPixelColor(i, window_generic.Color(255, 0, 255)); // Violet } window3.show(); i++; if(i == WINDOW_LENGTH){ color_mode++; i = 0; } // update variables var_stack.at(0) = i; var_stack.at(1) = color_mode; return var_stack; } <commit_msg>color wipe now loops<commit_after>/* Dorm LED Project: led_window_anim_cmds.cpp This file contains the window LED animation commands. These are meant to be executed using the multithreaded system. Created by: Michael Fischler 10/22/2016 @ WPI */ /* Template for a Command std::vector<int> (*cmd)(std::vector<int>) std::vector<int> cmd(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); int t = var_stack.at(1); // run command code ... // update variables var_stack.at(0) = i; var_stack.at(1) = t; return var_stack; } */ /* ~~~~~~ Off Commands ~~~~~~ */ // &&& Functions for Off Commands &&& // &&& Command Ready Functions for Off Commands &&& /* ~~~~~~ Static Commands ~~~~~~ */ // &&& Functions for Static Commands &&& // &&& Command Ready Functions for Animated Commands &&& /* ~~~~~~ Animated Commands ~~~~~~ */ // &&& Functions for Animated Commands &&& void _win_all_wpp_fade(int i){ for(int x = 0; x < WINDOW_LENGTH; x++){ setAllWindowPixelColor(x, window_generic.Color((int)(((float)i / 150.0) * 100), 0, i)); } showAllWindowStrips(); } void _win_all_WPI_spirit(int i, short int mode){ //uint8_t red = window_generic.Color(172, 43, 55); //uint8_t white = window_generic.Color(169, 176, 183); if(mode == 0){ window1.setPixelColor(i, window_generic.Color(255, 21, 27)); if(i%2 == 0){ window2.setPixelColor(i, window_generic.Color(169, 176, 183)); }else{ window2.setPixelColor(i, window_generic.Color(255, 21, 27)); } int modified = WINDOW_LENGTH + 9 - 1 - i; if(modified >= WINDOW_LENGTH){ modified -= WINDOW_LENGTH; } window3.setPixelColor(modified, window_generic.Color(255, 21, 27)); }else if(mode == 1){ window1.setPixelColor(i, window_generic.Color(169, 176, 183)); for(int j = 0; j < WINDOW_LENGTH; j++){ if(i%2 != 0){ window2.setPixelColor(i, window_generic.Color(169, 176, 183)); }else{ window2.setPixelColor(i, window_generic.Color(255, 21, 27)); } } int modified = WINDOW_LENGTH + 9 - 1 - i; if(modified >= WINDOW_LENGTH){ modified -= WINDOW_LENGTH; } window3.setPixelColor(modified, window_generic.Color(169, 176, 183)); } window1.show(); window3.show(); } // &&& Command Ready Functions for Animated Commands &&& // Every LED fades in and out a with calm purple // Initial input var_stack : std::vector<int> stack{0,1} std::vector<int> win_all_wpp_fade(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); short int increasing = var_stack.at(1); // run command code _win_all_wpp_fade(i); if(increasing == 1){ if(i == 150){ i--; increasing = 0; }else{ i++; } }else{ if(i == 0){ i++; increasing = 1; }else{ i--; } } // update variables var_stack.at(0) = i; var_stack.at(1) = increasing; return var_stack; } // A spirited display for my college, WPI // Initial input var_stack : std::vector<int> stack{0,0} std::vector<int> win_all_WPI_spirit(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); short int mode = var_stack.at(1); // run command code _win_all_WPI_spirit(i, mode); if(mode == 0){ if(i + 1 == WINDOW_LENGTH){ i = 0; mode = 1; window2.show(); }else{ i++; } }else if(mode == 1){ if(i + 1 == WINDOW_LENGTH){ i = 0; mode = 0; window2.show(); }else{ i++; } } // update variables var_stack.at(0) = i; var_stack.at(1) = mode; return var_stack; } // Rainbow Color Wipe for first window // Initial input var_stack : std::vector<int> stack {0,0} std::vector<int> win_1_rainbow_wipe(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); int color_mode = var_stack.at(1); // run command code if(color_mode % 2 != 0){ window1.setPixelColor(i, window_generic.Color(0, 0, 0)); // Off }else if(color_mode == 0){ window1.setPixelColor(i, window_generic.Color(255, 0, 0)); // Red }else if(color_mode == 2){ window1.setPixelColor(i, window_generic.Color(255, 50, 0)); // Orange }else if(color_mode == 4){ window1.setPixelColor(i, window_generic.Color(255, 150, 0)); // Yellow }else if(color_mode == 6){ window1.setPixelColor(i, window_generic.Color(0, 255, 0)); // Green }else if(color_mode == 8){ window1.setPixelColor(i, window_generic.Color(0, 255, 200)); // Sea Green }else if(color_mode == 10){ window1.setPixelColor(i, window_generic.Color(0, 0, 255)); // Blue }else if(color_mode == 12){ window1.setPixelColor(i, window_generic.Color(100, 0, 255)); // Indigo }else if(color_mode == 14){ window1.setPixelColor(i, window_generic.Color(255, 0, 255)); // Violet } window1.show(); i++; if(i == WINDOW_LENGTH){ color_mode++; i = 0; if(color_mode == 16){ color_mode = 0; } } // update variables var_stack.at(0) = i; var_stack.at(1) = color_mode; return var_stack; } // Rainbow Color Wipe for second window // Initial input var_stack : std::vector<int> stack {0,0} std::vector<int> win_2_rainbow_wipe(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); int color_mode = var_stack.at(1); // run command code if(color_mode % 2 != 0){ window2.setPixelColor(i, window_generic.Color(0, 0, 0)); // Off }else if(color_mode == 0){ window2.setPixelColor(i, window_generic.Color(255, 0, 0)); // Red }else if(color_mode == 2){ window2.setPixelColor(i, window_generic.Color(255, 50, 0)); // Orange }else if(color_mode == 4){ window2.setPixelColor(i, window_generic.Color(255, 150, 0)); // Yellow }else if(color_mode == 6){ window2.setPixelColor(i, window_generic.Color(0, 255, 0)); // Green }else if(color_mode == 8){ window2.setPixelColor(i, window_generic.Color(0, 255, 200)); // Sea Green }else if(color_mode == 10){ window2.setPixelColor(i, window_generic.Color(0, 0, 255)); // Blue }else if(color_mode == 12){ window2.setPixelColor(i, window_generic.Color(100, 0, 255)); // Indigo }else if(color_mode == 14){ window2.setPixelColor(i, window_generic.Color(255, 0, 255)); // Violet } window2.show(); i++; if(i == WINDOW_LENGTH){ color_mode++; i = 0; if(color_mode == 16){ color_mode = 0; } } // update variables var_stack.at(0) = i; var_stack.at(1) = color_mode; return var_stack; } // Rainbow Color Wipe for third window // Initial input var_stack : std::vector<int> stack {0,0} std::vector<int> win_3_rainbow_wipe(std::vector<int> var_stack){ // set variables int i = var_stack.at(0); int color_mode = var_stack.at(1); // run command code if(color_mode % 2 != 0){ window3.setPixelColor(i, window_generic.Color(0, 0, 0)); // Off }else if(color_mode == 0){ window3.setPixelColor(i, window_generic.Color(255, 0, 0)); // Red }else if(color_mode == 2){ window3.setPixelColor(i, window_generic.Color(255, 50, 0)); // Orange }else if(color_mode == 4){ window3.setPixelColor(i, window_generic.Color(255, 150, 0)); // Yellow }else if(color_mode == 6){ window3.setPixelColor(i, window_generic.Color(0, 255, 0)); // Green }else if(color_mode == 8){ window3.setPixelColor(i, window_generic.Color(0, 255, 200)); // Sea Green }else if(color_mode == 10){ window3.setPixelColor(i, window_generic.Color(0, 0, 255)); // Blue }else if(color_mode == 12){ window3.setPixelColor(i, window_generic.Color(100, 0, 255)); // Indigo }else if(color_mode == 14){ window3.setPixelColor(i, window_generic.Color(255, 0, 255)); // Violet } window3.show(); i++; if(i == WINDOW_LENGTH){ color_mode++; i = 0; if(color_mode == 16){ color_mode = 0; } } // update variables var_stack.at(0) = i; var_stack.at(1) = color_mode; return var_stack; } <|endoftext|>
<commit_before>#include "common/quic/client_connection_factory_impl.h" #include "common/quic/quic_transport_socket_factory.h" #include "test/common/upstream/utility.h" #include "test/mocks/common.h" #include "test/mocks/event/mocks.h" #include "test/mocks/server/transport_socket_factory_context.h" #include "test/mocks/ssl/mocks.h" #include "test/mocks/upstream/cluster_info.h" #include "test/mocks/upstream/host.h" #include "test/test_common/simulated_time_system.h" namespace Envoy { namespace Quic { class QuicNetworkConnectionTest : public Event::TestUsingSimulatedTime, public testing::Test { protected: NiceMock<Event::MockDispatcher> dispatcher_; std::shared_ptr<Upstream::MockClusterInfo> cluster_{new NiceMock<Upstream::MockClusterInfo>()}; Upstream::HostSharedPtr host_{new NiceMock<Upstream::MockHost>}; NiceMock<Random::MockRandomGenerator> random_; Upstream::ClusterConnectivityState state_; Network::Address::InstanceConstSharedPtr test_address_ = Network::Utility::resolveUrl("tcp://127.0.0.1:3000"); NiceMock<Server::Configuration::MockTransportSocketFactoryContext> context_; Quic::QuicClientTransportSocketFactory factory_{ std::unique_ptr<Envoy::Ssl::ClientContextConfig>(new NiceMock<Ssl::MockClientContextConfig>), context_}; }; TEST_F(QuicNetworkConnectionTest, BufferLimits) { PersistentQuicInfoImpl info{dispatcher_, factory_, simTime(), test_address_}; std::unique_ptr<Network::ClientConnection> client_connection = createQuicNetworkConnection(info, dispatcher_, test_address_, test_address_); EnvoyQuicClientSession* session = static_cast<EnvoyQuicClientSession*>(client_connection.get()); session->Initialize(); client_connection->connect(); EXPECT_TRUE(client_connection->connecting()); ASSERT(session != nullptr); EXPECT_EQ(absl::nullopt, session->unixSocketPeerCredentials()); EXPECT_EQ(absl::nullopt, session->lastRoundTripTime()); client_connection->close(Network::ConnectionCloseType::NoFlush); } } // namespace Quic } // namespace Envoy <commit_msg>test: fix merge brekage (#16597)<commit_after>#include "common/quic/client_connection_factory_impl.h" #include "common/quic/quic_transport_socket_factory.h" #include "test/common/upstream/utility.h" #include "test/mocks/common.h" #include "test/mocks/event/mocks.h" #include "test/mocks/server/transport_socket_factory_context.h" #include "test/mocks/ssl/mocks.h" #include "test/mocks/upstream/cluster_info.h" #include "test/mocks/upstream/host.h" #include "test/test_common/simulated_time_system.h" using testing::Return; namespace Envoy { namespace Quic { class QuicNetworkConnectionTest : public Event::TestUsingSimulatedTime, public testing::Test { protected: void initialize() { Ssl::ClientContextSharedPtr context{new Ssl::MockClientContext()}; EXPECT_CALL(context_.context_manager_, createSslClientContext(_, _, _)) .WillOnce(Return(context)); factory_ = std::make_unique<Quic::QuicClientTransportSocketFactory>( std::unique_ptr<Envoy::Ssl::ClientContextConfig>( new NiceMock<Ssl::MockClientContextConfig>), context_); } NiceMock<Event::MockDispatcher> dispatcher_; std::shared_ptr<Upstream::MockClusterInfo> cluster_{new NiceMock<Upstream::MockClusterInfo>()}; Upstream::HostSharedPtr host_{new NiceMock<Upstream::MockHost>}; NiceMock<Random::MockRandomGenerator> random_; Upstream::ClusterConnectivityState state_; Network::Address::InstanceConstSharedPtr test_address_ = Network::Utility::resolveUrl("tcp://127.0.0.1:3000"); NiceMock<Server::Configuration::MockTransportSocketFactoryContext> context_; std::unique_ptr<Quic::QuicClientTransportSocketFactory> factory_; }; TEST_F(QuicNetworkConnectionTest, BufferLimits) { initialize(); PersistentQuicInfoImpl info{dispatcher_, *factory_, simTime(), test_address_}; std::unique_ptr<Network::ClientConnection> client_connection = createQuicNetworkConnection(info, dispatcher_, test_address_, test_address_); EnvoyQuicClientSession* session = static_cast<EnvoyQuicClientSession*>(client_connection.get()); session->Initialize(); client_connection->connect(); EXPECT_TRUE(client_connection->connecting()); ASSERT(session != nullptr); EXPECT_EQ(absl::nullopt, session->unixSocketPeerCredentials()); EXPECT_EQ(absl::nullopt, session->lastRoundTripTime()); client_connection->close(Network::ConnectionCloseType::NoFlush); } } // namespace Quic } // namespace Envoy <|endoftext|>
<commit_before>#include "xchainer/testing/array.h" #include <cassert> #include <cstdint> #include <functional> #include <string> #include <vector> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/device.h" #include "xchainer/dtype.h" #include "xchainer/native/native_backend.h" #include "xchainer/shape.h" #include "xchainer/testing/device_session.h" #include "xchainer/testing/routines.h" namespace xchainer { namespace testing { namespace { TEST(CheckForward, IncorrectOutputNumber) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( { CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{xs[0] * 2, xs[0] + 2}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}); }, testing::RoutinesCheckError); } TEST(CheckForward, IncorrectOutputShape) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( { CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{(xs[0] * 2).Reshape({1, 2})}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}); }, testing::RoutinesCheckError); } TEST(CheckForward, IncorrectOutputDtype) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( { CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{(xs[0] * 2).AsType(Dtype::kFloat64)}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}); }, testing::RoutinesCheckError); } TEST(CheckForward, IncorrectOutputDevice) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Device& dst_device = device_session.device().backend().GetDevice(1); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( { CheckForward( [&dst_device](const std::vector<Array>& xs) { return std::vector<Array>{(xs[0] * 2).ToDevice(dst_device)}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}); }, testing::RoutinesCheckError); } TEST(CheckForward, IncorrectOutputValue) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( { CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{xs[0] * 3}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}); }, testing::RoutinesCheckError); } } // namespace } // namespace testing } // namespace xchainer <commit_msg>Avoid braces in EXPECT_THROW<commit_after>#include "xchainer/testing/array.h" #include <cassert> #include <cstdint> #include <functional> #include <string> #include <vector> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/device.h" #include "xchainer/dtype.h" #include "xchainer/native/native_backend.h" #include "xchainer/shape.h" #include "xchainer/testing/device_session.h" #include "xchainer/testing/routines.h" namespace xchainer { namespace testing { namespace { TEST(CheckForward, IncorrectOutputNumber) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{xs[0] * 2, xs[0] + 2}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}), testing::RoutinesCheckError); } TEST(CheckForward, IncorrectOutputShape) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{(xs[0] * 2).Reshape({1, 2})}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}), testing::RoutinesCheckError); } TEST(CheckForward, IncorrectOutputDtype) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{(xs[0] * 2).AsType(Dtype::kFloat64)}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}), testing::RoutinesCheckError); } TEST(CheckForward, IncorrectOutputDevice) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Device& dst_device = device_session.device().backend().GetDevice(1); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( CheckForward( [&dst_device](const std::vector<Array>& xs) { return std::vector<Array>{(xs[0] * 2).ToDevice(dst_device)}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}), testing::RoutinesCheckError); } TEST(CheckForward, IncorrectOutputValue) { testing::DeviceSession device_session({native::NativeBackend::kDefaultName, 0}); Array x = Ones({2}, Dtype::kFloat32); EXPECT_THROW( CheckForward( [](const std::vector<Array>& xs) { return std::vector<Array>{xs[0] * 3}; }, std::vector<Array>{x}, std::vector<Array>{x * 2}), testing::RoutinesCheckError); } } // namespace } // namespace testing } // namespace xchainer <|endoftext|>
<commit_before>/* * caosVM_flow.cpp * openc2e * * Created by Alyssa Milburn on Sun May 30 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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. * */ #include "caosVM.h" #include <iostream> #include "openc2e.h" #include "World.h" // enum #include <cmath> // sqrt void caosVM::jumpToAfterEquivalentNext() { // todo: add non-ENUM things cmdinfo *next = getCmdInfo("NEXT", true); assert(next != 0); cmdinfo *enu = getCmdInfo("ENUM", true); assert(enu != 0); cmdinfo *esee = getCmdInfo("ESEE", true); assert(esee != 0); int stack = 0; for (unsigned int i = currentline + 1; i < currentscript->lines.size(); i++) { token front = currentscript->lines[i].front(); if (front.func == enu) { stack++; } else if (front.func == esee) { stack++; } else if (front.func == next) { if (stack) stack--; else { currentline = i + 1; return; } } } currentline = currentscript->lines.size(); std::cerr << "caosVM: couldn't find matching NEXT, stopping script\n"; } void caosVM::jumpToNextIfBlock() { cmdinfo *doif = getCmdInfo("DOIF", true); assert(doif != 0); cmdinfo *elif = getCmdInfo("ELIF", true); assert(elif != 0); cmdinfo *els = getCmdInfo("ELSE", true); assert(els != 0); cmdinfo *endi = getCmdInfo("ENDI", true); assert(endi != 0); int stack = 0; for (unsigned int i = currentline + 1; i < currentscript->lines.size(); i++) { token front = currentscript->lines[i].front(); if (front.func == doif) { stack++; } else if (front.func == endi) { if (stack) { stack--; continue; } currentline = i; return; } else if (stack) { continue; } else if ((front.func == elif) && !truthstack.back()) { currentline = i; return; } else if ((front.func == els) && !truthstack.back()) { currentline = i + 1; return; // we don't NEED to actually run 'else' } } currentline = currentscript->lines.size(); std::cerr << "caosVM: couldn't find matching block for IF blocks, stopping script\n"; } /** DOIF (command) condition (condition) Part of a DOIF/ELIF/ELSE/ENDI block. Jump to the next part of the block if condition is false, otherwise continue executing. */ void caosVM::c_DOIF() { VM_VERIFY_SIZE(0) truthstack.push_back(truth); if (!truth) jumpToNextIfBlock(); } /** ELIF (command) condition (condition) Part of a DOIF/ELIF/ELSE/ENDI block. If none of the previous DOIF/ELIF conditions have been true, and condition evaluates to true, then the code in the ELIF block is executed. */ void caosVM::c_ELIF() { VM_VERIFY_SIZE(0) assert(!truthstack.empty()); if (!truth || truthstack.back()) jumpToNextIfBlock(); else { truthstack.pop_back(); truthstack.push_back(true); } } /** ELSE (command) Part of a DOIF/ELIF/ELSE/ENDI block. If ELSE is present, it is jumped to when none of the previous DOIF/ELIF conditions are true. */ void caosVM::c_ELSE() { VM_VERIFY_SIZE(0) assert(!truthstack.empty()); assert(truthstack.back()); jumpToNextIfBlock(); } /** ENDI (command) The end of a DOIF/ELIF/ELSE/ENDI block. */ void caosVM::c_ENDI() { VM_VERIFY_SIZE(0) assert(!truthstack.empty()); truthstack.pop_back(); } /** REPS (command) reps (integer) */ void caosVM::c_REPS() { VM_VERIFY_SIZE(1) VM_PARAM_INTEGER(reps) assert(reps > 0); repstack.push_back(reps); linestack.push_back(currentline + 1); } /** REPE (command) */ void caosVM::c_REPE() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); assert(!repstack.empty()); int i = repstack.back() - 1; repstack.pop_back(); if (i) { repstack.push_back(i); currentline = linestack.back(); } else linestack.pop_back(); } /** LOOP (command) The start of a LOOP..EVER or LOOP..UNTL loop. */ void caosVM::c_LOOP() { VM_VERIFY_SIZE(0) linestack.push_back(currentline + 1); } /** EVER (command) Jump back to the matching LOOP, no matter what. */ void caosVM::c_EVER() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); currentline = linestack.back(); } /** UNTL (command) condition (condition) Jump back to the matching LOOP unless the condition evaluates to true. */ void caosVM::c_UNTL() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); if (!truth) currentline = linestack.back(); else linestack.pop_back(); } /** GSUB (command) label (label) Jump to a subroutine defined by SUBR with label 'label'. */ void caosVM::c_GSUB() { VM_VERIFY_SIZE(1) VM_PARAM_STRING(label) cmdinfo *subr = getCmdInfo("SUBR", true); assert(subr != 0); for (unsigned int i = currentline + 1; i < currentscript->lines.size(); i++) { std::list<token>::iterator j = currentscript->lines[i].begin(); // we're assuming that ++j is a label here, but the parser should force that issue if (((*j).func == subr) && ((*++j).data == label)) { linestack.push_back(currentline + 1); currentline = i + 1; return; } } std::cerr << "warning: GSUB didn't find matching SUBR for " << label << ", ignoring\n"; } /** SUBR (command) label (label) Define the start of a subroute to be called with GSUB, with label 'label'. If the command is encountered during execution, it acts like a STOP. */ void caosVM::c_SUBR() { VM_VERIFY_SIZE(1) VM_PARAM_STRING(label) c_STOP(); } /** RETN (command) Return from a subroutine called with GSUB. */ void caosVM::c_RETN() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); currentline = linestack.back(); linestack.pop_back(); } /** NEXT (command) */ void caosVM::c_NEXT() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); currentline = linestack.back(); linestack.pop_back(); } /** ENUM (command) family (integer) genus (integer) species (integer) */ void caosVM::c_ENUM() { VM_VERIFY_SIZE(3) VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535); VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255); VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255); // TODO: fix mess of 'r' initialisation unsigned int r = (enumdata.count(currentline) == 0 ? 1 : enumdata[currentline]), x = 0; for (std::multiset<Agent *, agentzorder>::iterator i = world.agents.begin(); i != world.agents.end(); i++) { if ((*i)->family == family) if ((*i)->genus == genus) if ((*i)->species == species) x++; if (x == r) { enumdata[currentline] = x + 1; setTarg(*i); linestack.push_back(currentline); return; } } enumdata[currentline] = 1; // TODO: erase it instead? setTarg(owner); jumpToAfterEquivalentNext(); } /** ESEE (command) family (integer) genus (integer) species (integer) like ENUM, but iterate through agents OWNR can see (todo: document exact rules) */ void caosVM::c_ESEE() { VM_VERIFY_SIZE(3) VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535); VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255); VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255); caos_assert(owner); // Copied from ENUM. // TODO: fix mess of 'r' initialisation unsigned int r = (enumdata.count(currentline) == 0 ? 1 : enumdata[currentline]), x = 0; for (std::multiset<Agent *, agentzorder>::iterator i = world.agents.begin(); i != world.agents.end(); i++) { double deltax = (*i)->x - owner->x; double deltay = (*i)->y - owner->y; deltax *= deltax; deltay *= deltay; double distance = sqrt(deltax + deltay); if (distance <= owner->range) if ((*i)->family == family) if ((*i)->genus == genus) if ((*i)->species == species) x++; if (x == r) { enumdata[currentline] = x + 1; setTarg(*i); linestack.push_back(currentline); return; } } enumdata[currentline] = 1; // TODO: erase it instead? setTarg(owner); jumpToAfterEquivalentNext(); } /** ETCH (command) family (integer) genus (integer) species (integer) like ENUM, but iterate through agents OWNR is touching */ void caosVM::c_ETCH() { VM_VERIFY_SIZE(3) VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535); VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255); VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255); // TODO: should probably implement this (ESEE) setTarg(owner); jumpToAfterEquivalentNext(); } /** EPAS (command) family (integer) genus (integer) species (integer) like ENUM, but iterate through OWNR vehicle's passengers */ void caosVM::c_EPAS() { VM_VERIFY_SIZE(3) VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535); VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255); VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255); // TODO: should probably implement this (ESEE) setTarg(owner); jumpToAfterEquivalentNext(); } <commit_msg>stupid GSUB fix<commit_after>/* * caosVM_flow.cpp * openc2e * * Created by Alyssa Milburn on Sun May 30 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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. * */ #include "caosVM.h" #include <iostream> #include "openc2e.h" #include "World.h" // enum #include <cmath> // sqrt void caosVM::jumpToAfterEquivalentNext() { // todo: add non-ENUM things cmdinfo *next = getCmdInfo("NEXT", true); assert(next != 0); cmdinfo *enu = getCmdInfo("ENUM", true); assert(enu != 0); cmdinfo *esee = getCmdInfo("ESEE", true); assert(esee != 0); int stack = 0; for (unsigned int i = currentline + 1; i < currentscript->lines.size(); i++) { token front = currentscript->lines[i].front(); if (front.func == enu) { stack++; } else if (front.func == esee) { stack++; } else if (front.func == next) { if (stack) stack--; else { currentline = i + 1; return; } } } currentline = currentscript->lines.size(); std::cerr << "caosVM: couldn't find matching NEXT, stopping script\n"; } void caosVM::jumpToNextIfBlock() { cmdinfo *doif = getCmdInfo("DOIF", true); assert(doif != 0); cmdinfo *elif = getCmdInfo("ELIF", true); assert(elif != 0); cmdinfo *els = getCmdInfo("ELSE", true); assert(els != 0); cmdinfo *endi = getCmdInfo("ENDI", true); assert(endi != 0); int stack = 0; for (unsigned int i = currentline + 1; i < currentscript->lines.size(); i++) { token front = currentscript->lines[i].front(); if (front.func == doif) { stack++; } else if (front.func == endi) { if (stack) { stack--; continue; } currentline = i; return; } else if (stack) { continue; } else if ((front.func == elif) && !truthstack.back()) { currentline = i; return; } else if ((front.func == els) && !truthstack.back()) { currentline = i + 1; return; // we don't NEED to actually run 'else' } } currentline = currentscript->lines.size(); std::cerr << "caosVM: couldn't find matching block for IF blocks, stopping script\n"; } /** DOIF (command) condition (condition) Part of a DOIF/ELIF/ELSE/ENDI block. Jump to the next part of the block if condition is false, otherwise continue executing. */ void caosVM::c_DOIF() { VM_VERIFY_SIZE(0) truthstack.push_back(truth); if (!truth) jumpToNextIfBlock(); } /** ELIF (command) condition (condition) Part of a DOIF/ELIF/ELSE/ENDI block. If none of the previous DOIF/ELIF conditions have been true, and condition evaluates to true, then the code in the ELIF block is executed. */ void caosVM::c_ELIF() { VM_VERIFY_SIZE(0) assert(!truthstack.empty()); if (!truth || truthstack.back()) jumpToNextIfBlock(); else { truthstack.pop_back(); truthstack.push_back(true); } } /** ELSE (command) Part of a DOIF/ELIF/ELSE/ENDI block. If ELSE is present, it is jumped to when none of the previous DOIF/ELIF conditions are true. */ void caosVM::c_ELSE() { VM_VERIFY_SIZE(0) assert(!truthstack.empty()); assert(truthstack.back()); jumpToNextIfBlock(); } /** ENDI (command) The end of a DOIF/ELIF/ELSE/ENDI block. */ void caosVM::c_ENDI() { VM_VERIFY_SIZE(0) assert(!truthstack.empty()); truthstack.pop_back(); } /** REPS (command) reps (integer) */ void caosVM::c_REPS() { VM_VERIFY_SIZE(1) VM_PARAM_INTEGER(reps) assert(reps > 0); repstack.push_back(reps); linestack.push_back(currentline + 1); } /** REPE (command) */ void caosVM::c_REPE() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); assert(!repstack.empty()); int i = repstack.back() - 1; repstack.pop_back(); if (i) { repstack.push_back(i); currentline = linestack.back(); } else linestack.pop_back(); } /** LOOP (command) The start of a LOOP..EVER or LOOP..UNTL loop. */ void caosVM::c_LOOP() { VM_VERIFY_SIZE(0) linestack.push_back(currentline + 1); } /** EVER (command) Jump back to the matching LOOP, no matter what. */ void caosVM::c_EVER() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); currentline = linestack.back(); } /** UNTL (command) condition (condition) Jump back to the matching LOOP unless the condition evaluates to true. */ void caosVM::c_UNTL() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); if (!truth) currentline = linestack.back(); else linestack.pop_back(); } /** GSUB (command) label (label) Jump to a subroutine defined by SUBR with label 'label'. */ void caosVM::c_GSUB() { VM_VERIFY_SIZE(1) VM_PARAM_STRING(label) cmdinfo *subr = getCmdInfo("SUBR", true); assert(subr != 0); for (unsigned int i = 0; i < currentscript->lines.size(); i++) { std::list<token>::iterator j = currentscript->lines[i].begin(); // we're assuming that ++j is a label here, but the parser should force that issue if (((*j).func == subr) && ((*++j).data == label)) { linestack.push_back(currentline + 1); currentline = i + 1; return; } } std::cerr << "warning: GSUB didn't find matching SUBR for " << label << ", ignoring\n"; } /** SUBR (command) label (label) Define the start of a subroute to be called with GSUB, with label 'label'. If the command is encountered during execution, it acts like a STOP. */ void caosVM::c_SUBR() { VM_VERIFY_SIZE(1) VM_PARAM_STRING(label) c_STOP(); } /** RETN (command) Return from a subroutine called with GSUB. */ void caosVM::c_RETN() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); currentline = linestack.back(); linestack.pop_back(); } /** NEXT (command) */ void caosVM::c_NEXT() { VM_VERIFY_SIZE(0) assert(!linestack.empty()); currentline = linestack.back(); linestack.pop_back(); } /** ENUM (command) family (integer) genus (integer) species (integer) */ void caosVM::c_ENUM() { VM_VERIFY_SIZE(3) VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535); VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255); VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255); // TODO: fix mess of 'r' initialisation unsigned int r = (enumdata.count(currentline) == 0 ? 1 : enumdata[currentline]), x = 0; for (std::multiset<Agent *, agentzorder>::iterator i = world.agents.begin(); i != world.agents.end(); i++) { if ((*i)->family == family) if ((*i)->genus == genus) if ((*i)->species == species) x++; if (x == r) { enumdata[currentline] = x + 1; setTarg(*i); linestack.push_back(currentline); return; } } enumdata[currentline] = 1; // TODO: erase it instead? setTarg(owner); jumpToAfterEquivalentNext(); } /** ESEE (command) family (integer) genus (integer) species (integer) like ENUM, but iterate through agents OWNR can see (todo: document exact rules) */ void caosVM::c_ESEE() { VM_VERIFY_SIZE(3) VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535); VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255); VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255); caos_assert(owner); // Copied from ENUM. // TODO: fix mess of 'r' initialisation unsigned int r = (enumdata.count(currentline) == 0 ? 1 : enumdata[currentline]), x = 0; for (std::multiset<Agent *, agentzorder>::iterator i = world.agents.begin(); i != world.agents.end(); i++) { double deltax = (*i)->x - owner->x; double deltay = (*i)->y - owner->y; deltax *= deltax; deltay *= deltay; double distance = sqrt(deltax + deltay); if (distance <= owner->range) if ((*i)->family == family) if ((*i)->genus == genus) if ((*i)->species == species) x++; if (x == r) { enumdata[currentline] = x + 1; setTarg(*i); linestack.push_back(currentline); return; } } enumdata[currentline] = 1; // TODO: erase it instead? setTarg(owner); jumpToAfterEquivalentNext(); } /** ETCH (command) family (integer) genus (integer) species (integer) like ENUM, but iterate through agents OWNR is touching */ void caosVM::c_ETCH() { VM_VERIFY_SIZE(3) VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535); VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255); VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255); // TODO: should probably implement this (ESEE) setTarg(owner); jumpToAfterEquivalentNext(); } /** EPAS (command) family (integer) genus (integer) species (integer) like ENUM, but iterate through OWNR vehicle's passengers */ void caosVM::c_EPAS() { VM_VERIFY_SIZE(3) VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535); VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255); VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255); // TODO: should probably implement this (ESEE) setTarg(owner); jumpToAfterEquivalentNext(); } <|endoftext|>
<commit_before>#include <stdio.h> #include <unistd.h> #include <string.h> #include <systemlib/err.h> #include <drivers/drv_hrt.h> #include <rc/sumd.h> #include "../../src/systemcmds/tests/tests.h" #include "gtest/gtest.h" TEST(SUMDTest, SUMD) { const char *filepath = "testdata/sumd_data.txt"; warnx("loading data from: %s", filepath); FILE *fp; fp = fopen(filepath, "rt"); //ASSERT_TRUE(fp); float f; unsigned x; int ret; // Trash the first 20 lines for (unsigned i = 0; i < 20; i++) { char buf[200]; (void)fgets(buf, sizeof(buf), fp); } float last_time = 0; while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) { if (((f - last_time) * 1000 * 1000) > 3000) { // warnx("FRAME RESET\n\n"); } uint8_t b = static_cast<uint8_t>(x); last_time = f; // Pipe the data into the parser //hrt_abstime now = hrt_absolute_time(); uint8_t rssi; uint8_t rx_count; uint16_t channel_count; uint16_t channels[32]; if (!sumd_decode(b, &rssi, &rx_count, &channel_count, channels, 32)) { //warnx("decoded: %u channels (converted to PPM range)", (unsigned)channel_count); for (unsigned i = 0; i < channel_count; i++) { //int16_t val = channels[i]; //warnx("channel %u: %d 0x%03X", i, static_cast<int>(val), static_cast<int>(val)); } } } ASSERT_EQ(EOF, ret); } <commit_msg>sumd test: Be less verbose<commit_after>#include <stdio.h> #include <unistd.h> #include <string.h> #include <systemlib/err.h> #include <drivers/drv_hrt.h> #include <rc/sumd.h> #include "../../src/systemcmds/tests/tests.h" #include "gtest/gtest.h" TEST(SUMDTest, SUMD) { const char *filepath = "testdata/sumd_data.txt"; //warnx("loading data from: %s", filepath); FILE *fp; fp = fopen(filepath, "rt"); //ASSERT_TRUE(fp); float f; unsigned x; int ret; // Trash the first 20 lines for (unsigned i = 0; i < 20; i++) { char buf[200]; (void)fgets(buf, sizeof(buf), fp); } float last_time = 0; while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) { if (((f - last_time) * 1000 * 1000) > 3000) { // warnx("FRAME RESET\n\n"); } uint8_t b = static_cast<uint8_t>(x); last_time = f; // Pipe the data into the parser //hrt_abstime now = hrt_absolute_time(); uint8_t rssi; uint8_t rx_count; uint16_t channel_count; uint16_t channels[32]; if (!sumd_decode(b, &rssi, &rx_count, &channel_count, channels, 32)) { //warnx("decoded: %u channels (converted to PPM range)", (unsigned)channel_count); for (unsigned i = 0; i < channel_count; i++) { //int16_t val = channels[i]; //warnx("channel %u: %d 0x%03X", i, static_cast<int>(val), static_cast<int>(val)); } } } ASSERT_EQ(EOF, ret); } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE "test_read_3spn2_base_stacking_interaction" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/input/read_local_interaction.hpp> BOOST_AUTO_TEST_CASE(read_3spn2_base_stacking_interaction) { mjolnir::LoggerManager::set_default_logger("test_read_3spn2_base_stacking_interaction.log"); using base_stack_kind = mjolnir::parameter_3SPN2::base_stack_kind; using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; { using namespace toml::literals; const toml::value v = u8R"( interaction = "3SPN2BaseStacking" potential = "3SPN2" topology = "nucleotide" parameters = [ {strand = 0, nucleotide = 0, S = 0, B = 1, Base = "A"}, # AA {strand = 0, nucleotide = 1, P = 2, S = 3, B = 4, Base = "A"}, # AT {strand = 0, nucleotide = 2, P = 5, S = 6, B = 7, Base = "T"}, # TG {strand = 0, nucleotide = 3, P = 8, S = 9, B = 10, Base = "G"}, # GC {strand = 0, nucleotide = 4, P = 11, S = 12, B = 13, Base = "C"}, # CA {strand = 0, nucleotide = 5, P = 14, S = 15, B = 16, Base = "A"}, # AT {strand = 0, nucleotide = 6, P = 17, S = 18, B = 19, Base = "T"}, # TG {strand = 0, nucleotide = 7, P = 20, S = 21, B = 22, Base = "G"}, # GC {strand = 0, nucleotide = 8, P = 23, S = 24, B = 25, Base = "C"}, # CA {strand = 0, nucleotide = 9, P = 26, S = 27, B = 28, Base = "A"}, # AT {strand = 0, nucleotide = 10, P = 29, S = 30, B = 31, Base = "T"}, # TG {strand = 0, nucleotide = 11, P = 32, S = 33, B = 34, Base = "G"}, # GC {strand = 0, nucleotide = 12, P = 35, S = 36, B = 37, Base = "C"}, # CA {strand = 0, nucleotide = 13, P = 38, S = 39, B = 40, Base = "A"}, # AT {strand = 0, nucleotide = 14, P = 41, S = 42, B = 43, Base = "T"}, # TG {strand = 0, nucleotide = 15, P = 44, S = 45, B = 46, Base = "G"}, # GC {strand = 0, nucleotide = 16, P = 47, S = 48, B = 49, Base = "C"}, # x ] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast< mjolnir::ThreeSPN2BaseStackingInteraction<traits_type>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); BOOST_TEST(derv->connection_kind() == "nucleotide"); BOOST_TEST_REQUIRE(derv->parameters().size() == 16u); for(std::size_t i=0; i<16; ++i) { BOOST_TEST(derv->parameters().at(i).first.at(0) == 0 + i*3); BOOST_TEST(derv->parameters().at(i).first.at(1) == 1 + i*3); BOOST_TEST(derv->parameters().at(i).first.at(2) == 4 + i*3); } BOOST_TEST(derv->parameters().at( 0).second == base_stack_kind::AA); BOOST_TEST(derv->parameters().at( 1).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at( 2).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at( 3).second == base_stack_kind::GC); BOOST_TEST(derv->parameters().at( 4).second == base_stack_kind::CA); BOOST_TEST(derv->parameters().at( 5).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at( 6).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at( 7).second == base_stack_kind::GC); BOOST_TEST(derv->parameters().at( 8).second == base_stack_kind::CA); BOOST_TEST(derv->parameters().at( 9).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at(10).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at(11).second == base_stack_kind::GC); BOOST_TEST(derv->parameters().at(12).second == base_stack_kind::CA); BOOST_TEST(derv->parameters().at(13).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at(14).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at(15).second == base_stack_kind::GC); } } <commit_msg>test: improve test case for base stacking<commit_after>#define BOOST_TEST_MODULE "test_read_3spn2_base_stacking_interaction" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/input/read_local_interaction.hpp> BOOST_AUTO_TEST_CASE(read_3spn2_base_stacking_interaction) { mjolnir::LoggerManager::set_default_logger("test_read_3spn2_base_stacking_interaction.log"); using base_stack_kind = mjolnir::parameter_3SPN2::base_stack_kind; using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; { using namespace toml::literals; const toml::value v = u8R"( interaction = "3SPN2BaseStacking" potential = "3SPN2" topology = "nucleotide" parameters = [ {strand = 0, nucleotide = 0, S = 0, B = 1, Base = "A"}, # AA {strand = 0, nucleotide = 1, P = 2, S = 3, B = 4, Base = "A"}, # AT {strand = 0, nucleotide = 2, P = 5, S = 6, B = 7, Base = "T"}, # TG {strand = 0, nucleotide = 3, P = 8, S = 9, B = 10, Base = "G"}, # GC {strand = 0, nucleotide = 4, P = 11, S = 12, B = 13, Base = "C"}, # CA {strand = 0, nucleotide = 5, P = 14, S = 15, B = 16, Base = "A"}, # AT {strand = 0, nucleotide = 6, P = 17, S = 18, B = 19, Base = "T"}, # TG {strand = 0, nucleotide = 7, P = 20, S = 21, B = 22, Base = "G"}, # GC {strand = 0, nucleotide = 8, P = 23, S = 24, B = 25, Base = "C"}, # CA {strand = 0, nucleotide = 9, P = 26, S = 27, B = 28, Base = "A"}, # AT {strand = 0, nucleotide = 10, P = 29, S = 30, B = 31, Base = "T"}, # TG {strand = 0, nucleotide = 11, P = 32, S = 33, B = 34, Base = "G"}, # GC {strand = 0, nucleotide = 12, P = 35, S = 36, B = 37, Base = "C"}, # CA {strand = 0, nucleotide = 13, P = 38, S = 39, B = 40, Base = "A"}, # AT {strand = 0, nucleotide = 14, P = 41, S = 42, B = 43, Base = "T"}, # TG {strand = 0, nucleotide = 15, P = 44, S = 45, B = 46, Base = "G"}, # X {strand = 1, nucleotide = 16, S = 47, B = 48, Base = "A"}, # AA {strand = 1, nucleotide = 17, P = 49, S = 50, B = 51, Base = "A"}, # AT {strand = 1, nucleotide = 18, P = 52, S = 53, B = 54, Base = "T"}, # TG {strand = 1, nucleotide = 19, P = 55, S = 56, B = 57, Base = "G"}, # GC {strand = 1, nucleotide = 20, P = 58, S = 59, B = 60, Base = "C"}, # CA {strand = 1, nucleotide = 21, P = 61, S = 62, B = 63, Base = "A"}, # AT {strand = 1, nucleotide = 22, P = 64, S = 65, B = 66, Base = "T"}, # TG {strand = 1, nucleotide = 23, P = 67, S = 68, B = 69, Base = "G"}, # GC {strand = 1, nucleotide = 24, P = 70, S = 71, B = 72, Base = "C"}, # CA {strand = 1, nucleotide = 25, P = 73, S = 74, B = 75, Base = "A"}, # AT {strand = 1, nucleotide = 26, P = 76, S = 77, B = 78, Base = "T"}, # TG {strand = 1, nucleotide = 27, P = 79, S = 80, B = 81, Base = "G"}, # GC {strand = 1, nucleotide = 28, P = 82, S = 83, B = 84, Base = "C"}, # CA {strand = 1, nucleotide = 29, P = 85, S = 86, B = 87, Base = "A"}, # AT {strand = 1, nucleotide = 30, P = 88, S = 89, B = 90, Base = "T"}, # TG {strand = 1, nucleotide = 31, P = 91, S = 92, B = 93, Base = "G"}, # X ] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast< mjolnir::ThreeSPN2BaseStackingInteraction<traits_type>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); BOOST_TEST(derv->connection_kind() == "nucleotide"); BOOST_TEST_REQUIRE(derv->parameters().size() == 30u); for(std::size_t i=0; i<15; ++i) { BOOST_TEST(derv->parameters().at(i).first.at(0) == 0 + i*3); BOOST_TEST(derv->parameters().at(i).first.at(1) == 1 + i*3); BOOST_TEST(derv->parameters().at(i).first.at(2) == 4 + i*3); } for(std::size_t i=15; i<30; ++i) { BOOST_TEST(derv->parameters().at(i).first.at(0) == 47 + (i-15)*3); BOOST_TEST(derv->parameters().at(i).first.at(1) == 48 + (i-15)*3); BOOST_TEST(derv->parameters().at(i).first.at(2) == 51 + (i-15)*3); } BOOST_TEST(derv->parameters().at( 0).second == base_stack_kind::AA); BOOST_TEST(derv->parameters().at( 1).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at( 2).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at( 3).second == base_stack_kind::GC); BOOST_TEST(derv->parameters().at( 4).second == base_stack_kind::CA); BOOST_TEST(derv->parameters().at( 5).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at( 6).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at( 7).second == base_stack_kind::GC); BOOST_TEST(derv->parameters().at( 8).second == base_stack_kind::CA); BOOST_TEST(derv->parameters().at( 9).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at(10).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at(11).second == base_stack_kind::GC); BOOST_TEST(derv->parameters().at(12).second == base_stack_kind::CA); BOOST_TEST(derv->parameters().at(13).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at(14).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at(15).second == base_stack_kind::AA); BOOST_TEST(derv->parameters().at(16).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at(17).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at(18).second == base_stack_kind::GC); BOOST_TEST(derv->parameters().at(19).second == base_stack_kind::CA); BOOST_TEST(derv->parameters().at(20).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at(21).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at(22).second == base_stack_kind::GC); BOOST_TEST(derv->parameters().at(23).second == base_stack_kind::CA); BOOST_TEST(derv->parameters().at(24).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at(25).second == base_stack_kind::TG); BOOST_TEST(derv->parameters().at(26).second == base_stack_kind::GC); BOOST_TEST(derv->parameters().at(27).second == base_stack_kind::CA); BOOST_TEST(derv->parameters().at(28).second == base_stack_kind::AT); BOOST_TEST(derv->parameters().at(29).second == base_stack_kind::TG); } } <|endoftext|>
<commit_before>#pragma once #include <algorithm> #include <cctype> #include "acmacs-base/named-type.hh" // ---------------------------------------------------------------------- namespace acmacs { template <typename Tag> class uppercased : public named_string_t<Tag> { public: uppercased() = default; template <typename S> explicit uppercased(S&& source) : named_string_t<Tag>(std::forward<S>(source)) { std::transform(this->get().begin(), this->get().end(), this->get().begin(), ::toupper); } template <typename S> uppercased& operator=(S&& source) { const std::string_view src{source}; this->get().resize(src.size(), ' '); std::transform(src.begin(), src.end(), this->get().begin(), ::toupper); return *this; } template <typename S> bool operator==(const S& rhs) const { return this->get() == std::string_view{rhs}; } template <typename S> bool operator!=(const S& rhs) const { return !operator==(rhs); } }; template <typename Tag> class lowercased : public named_string_t<Tag> { public: lowercased() = default; template <typename S> explicit lowercased(S&& source) : named_string_t<Tag>(std::forward<S>(source)) { std::transform(this->get().begin(), this->get().end(), this->get().begin(), ::tolower); } template <typename S> lowercased& operator=(S&& source) { const std::string_view src{source}; this->get().resize(src.size(), ' '); std::transform(src.begin(), src.end(), this->get().begin(), ::tolower); return *this; } template <typename S> bool operator==(const S& rhs) const { return this->get() == std::string_view{rhs}; } template <typename S> bool operator!=(const S& rhs) const { return !operator==(rhs); } }; // ---------------------------------------------------------------------- class uppercase : public uppercased<struct uppercase_tag> { public: uppercase() = default; template <typename S> uppercase(S&& source) : uppercased<struct uppercase_tag>(std::forward<S>(source)) {} operator std::string_view() const noexcept { return this->get(); } }; class lowercase : public lowercased<struct lowercase_tag> { public: lowercase() = default; template <typename S> lowercase(S&& source) : lowercased<struct lowercase_tag>(std::forward<S>(source)) {} operator std::string_view() const noexcept { return this->get(); } }; } // namespace acmacs // ---------------------------------------------------------------------- template <typename Tag> struct fmt::formatter<acmacs::uppercased<Tag>> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::uppercased<Tag>& uc, FormatCtx& ctx) { return fmt::formatter<std::string>::format(uc.get(), ctx); } }; template <typename Tag> struct fmt::formatter<acmacs::lowercased<Tag>> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::lowercased<Tag>& uc, FormatCtx& ctx) { return fmt::formatter<std::string>::format(uc.get(), ctx); } }; template <> struct fmt::formatter<acmacs::uppercase> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::uppercase& uc, FormatCtx& ctx) { return fmt::formatter<std::string>::format(uc.get(), ctx); } }; template <> struct fmt::formatter<acmacs::lowercase> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::lowercase& uc, FormatCtx& ctx) { return fmt::formatter<std::string>::format(uc.get(), ctx); } }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>minor improvement<commit_after>#pragma once #include <algorithm> #include <cctype> #include "acmacs-base/named-type.hh" // ---------------------------------------------------------------------- namespace acmacs { template <typename Tag> class uppercased : public named_string_t<Tag> { public: uppercased() = default; template <typename S> explicit uppercased(S&& source) : named_string_t<Tag>(std::forward<S>(source)) { std::transform(this->get().begin(), this->get().end(), this->get().begin(), ::toupper); } template <typename S> uppercased& operator=(S&& source) { const std::string_view src{source}; this->get().resize(src.size(), ' '); std::transform(src.begin(), src.end(), this->get().begin(), ::toupper); return *this; } template <typename S> bool operator==(const S& rhs) const { return this->get() == std::string_view{rhs}; } template <typename S> bool operator!=(const S& rhs) const { return !operator==(rhs); } }; template <typename Tag> class lowercased : public named_string_t<Tag> { public: lowercased() = default; template <typename S> explicit lowercased(S&& source) : named_string_t<Tag>(std::forward<S>(source)) { std::transform(this->get().begin(), this->get().end(), this->get().begin(), ::tolower); } template <typename S> lowercased& operator=(S&& source) { const std::string_view src{source}; this->get().resize(src.size(), ' '); std::transform(src.begin(), src.end(), this->get().begin(), ::tolower); return *this; } template <typename S> bool operator==(const S& rhs) const { return this->get() == std::string_view{rhs}; } template <typename S> bool operator!=(const S& rhs) const { return !operator==(rhs); } }; // ---------------------------------------------------------------------- class uppercase : public uppercased<struct uppercase_tag> { public: uppercase() = default; template <typename S> uppercase(S&& source) : uppercased<struct uppercase_tag>(std::forward<S>(source)) {} operator std::string_view() const noexcept { return this->get(); } char operator[](size_t pos) const { return this->get()[pos]; } }; class lowercase : public lowercased<struct lowercase_tag> { public: lowercase() = default; template <typename S> lowercase(S&& source) : lowercased<struct lowercase_tag>(std::forward<S>(source)) {} operator std::string_view() const noexcept { return this->get(); } char operator[](size_t pos) const { return this->get()[pos]; } }; } // namespace acmacs // ---------------------------------------------------------------------- template <typename Tag> struct fmt::formatter<acmacs::uppercased<Tag>> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::uppercased<Tag>& uc, FormatCtx& ctx) { return fmt::formatter<std::string>::format(uc.get(), ctx); } }; template <typename Tag> struct fmt::formatter<acmacs::lowercased<Tag>> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::lowercased<Tag>& uc, FormatCtx& ctx) { return fmt::formatter<std::string>::format(uc.get(), ctx); } }; template <> struct fmt::formatter<acmacs::uppercase> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::uppercase& uc, FormatCtx& ctx) { return fmt::formatter<std::string>::format(uc.get(), ctx); } }; template <> struct fmt::formatter<acmacs::lowercase> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::lowercase& uc, FormatCtx& ctx) { return fmt::formatter<std::string>::format(uc.get(), ctx); } }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include <iostream> using std::cout; using std::endl; using std::begin; using std::end; void print(const int* pi) { if (pi) cout << *pi << endl; } void print(const char* p) { if (p) while (*p) cout << *p++; cout << endl; } void print(const int* beg, const int* end) { while (beg != end) cout << *beg++ << endl; } void print(const int ia[], size_t size) { for (size_t i = 0; i != size; ++i) { cout << ia[i] << endl; } } void print(int(&arr)[2]) { for (auto i : arr) cout << i << endl; } int main() { int i = 0, j[2] = {0, 1}; char ch[5] = "pezy"; print(ch); print(begin(j), end(j)); print(&i); print(j, end(j) - begin(j)); print(j); return 0; } <commit_msg>Update ex6_23.cpp<commit_after>#include <iostream> #include <iterator> using std::cout; using std::endl; using std::begin; using std::end; void print(const int* pi) { if (pi) cout << *pi << endl; } void print(const char* p) { if (p) while (*p) cout << *p++; cout << endl; } void print(const int* beg, const int* end) { while (beg != end) cout << *beg++ << endl; } void print(const int ia[], size_t size) { for (size_t i = 0; i != size; ++i) { cout << ia[i] << endl; } } void print(int(&arr)[2]) { for (auto i : arr) cout << i << endl; } int main() { int i = 0, j[2] = {0, 1}; char ch[5] = "pezy"; print(ch); print(begin(j), end(j)); print(&i); print(j, end(j) - begin(j)); print(j); return 0; } <|endoftext|>
<commit_before>// @Yue Wang // // Exercise 9.50: // Write a program to process a vector<string>s whose elements represent integral values. // Produce the sum of all the elements in that vector. // Change the program so that it sums of strings that represent floating-point values. // #include <iostream> #include <string> #include <vector> int sum_for_int(std::vector<std::string> const& v) { int sum = 0; for (auto const& s : v) sum += std::stoi(s); return sum; } float sum_for_float(std::vector<std::string> const& v) { float sum = 0.0; for (auto const& s : v) sum += std::stof(s); return sum; } int main() { std::vector<std::string> v = { "1", "2", "3", "4.5" }; std::cout << sum_for_int(v) << std::endl; std::cout << sum_for_float(v) << std::endl; return 0; } <commit_msg>Update ex9_50.cpp<commit_after>// @Yue Wang // // Exercise 9.50: // Write a program to process a vector<string>s whose elements represent integral values. // Produce the sum of all the elements in that vector. // Change the program so that it sums of strings that represent floating-point values. // #include <iostream> #include <string> #include <vector> auto sum_for_int(std::vector<std::string> const& v) { int sum = 0; for (auto const& s : v) sum += std::stoi(s); return sum; } auto sum_for_float(std::vector<std::string> const& v) { float sum = 0.0; for (auto const& s : v) sum += std::stof(s); return sum; } int main() { std::vector<std::string> v = { "1", "2", "3", "4.5" }; std::cout << sum_for_int(v) << std::endl; std::cout << sum_for_float(v) << std::endl; return 0; } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #define LOG_THIS BX_CPU_THIS_PTR void BX_CPU_C::DAS(BxInstruction_t *) { Bit8u tmpCF, tmpAL; /* ??? */ /* the algorithm for DAS is fashioned after the pseudo code in the * Pentium Processor Family Developer's Manual, volume 3. It seems * to have changed from earlier processor's manuals. I'm not sure * if this is a correction in the algorithm printed, or Intel has * changed the handling of instruction. It might not even be * correct yet... */ tmpCF = 0; tmpAL = AL; /* DAS effect the following flags: A,C,S,Z,P */ if (((tmpAL & 0x0F) > 0x09) || get_AF()) { set_AF(1); tmpCF = (AL < 0x06) || get_CF(); AL = AL - 0x06; /*tmpCF = (AL < 0) || CF;*/ } if ( (tmpAL > 0x99) || get_CF() ) { AL = AL - 0x60; tmpCF = 1; } set_CF(tmpCF); set_SF(AL >> 7); set_ZF(AL==0); set_PF_base(AL); } void BX_CPU_C::AAA(BxInstruction_t *) { Bit8u ALcarry; ALcarry = AL > 0xf9; /* AAA effects the following flags: A,C */ if ( ((AL & 0x0f) > 9) || get_AF() ) { AL = (AL + 6) & 0x0f; AH = AH + 1 + ALcarry; set_AF(1); set_CF(1); } else { set_AF(0); set_CF(0); AL = AL & 0x0f; } } void BX_CPU_C::AAS(BxInstruction_t *) { Bit8u ALborrow; /* AAS affects the following flags: A,C */ ALborrow = AL < 6; if ( ((AL & 0x0F) > 0x09) || get_AF() ) { AL = (AL - 6) & 0x0f; AH = AH - 1 - ALborrow; set_AF(1); set_CF(1); } else { set_CF(0); set_AF(0); AL = AL & 0x0f; } } void BX_CPU_C::AAM(BxInstruction_t *i) { Bit8u al, imm8; imm8 = i->Ib; al = AL; AH = al / imm8; AL = al % imm8; /* AAM affects the following flags: S,Z,P */ set_SF((AH & 0x80) > 0); set_ZF(AX==0); set_PF_base(AL); /* ??? */ } void BX_CPU_C::AAD(BxInstruction_t *i) { Bit8u imm8; imm8 = i->Ib; AL = AH * imm8 + AL; AH = 0; /* AAD effects the following flags: S,Z,P */ set_SF(AL >= 0x80); set_ZF(AL == 0); set_PF_base(AL); } void BX_CPU_C::DAA(BxInstruction_t *) { Bit8u al; al = AL; // DAA affects the following flags: S,Z,A,P,C // ??? if (((al & 0x0F) > 0x09) || get_AF()) { al = al + 0x06; set_AF(1); } else set_AF(0); if ((al > 0x9F) || get_CF()) { al = al + 0x60; set_CF(1); } AL = al; set_SF(al >> 7); set_ZF(al==0); set_PF_base(al); } <commit_msg>- AAM can generate an exception (divide by 0) - AAM: modification of flags depends on AL, not AX - AAM always clears CF and AF - AAD can also modify AF, CF and OF - DAA can also clear the CF<commit_after>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #define LOG_THIS BX_CPU_THIS_PTR void BX_CPU_C::DAS(BxInstruction_t *) { Bit8u tmpCF, tmpAL; /* ??? */ /* the algorithm for DAS is fashioned after the pseudo code in the * Pentium Processor Family Developer's Manual, volume 3. It seems * to have changed from earlier processor's manuals. I'm not sure * if this is a correction in the algorithm printed, or Intel has * changed the handling of instruction. It might not even be * correct yet... */ tmpCF = 0; tmpAL = AL; /* DAS effect the following flags: A,C,S,Z,P */ if (((tmpAL & 0x0F) > 0x09) || get_AF()) { set_AF(1); tmpCF = (AL < 0x06) || get_CF(); AL = AL - 0x06; /*tmpCF = (AL < 0) || CF;*/ } if ( (tmpAL > 0x99) || get_CF() ) { AL = AL - 0x60; tmpCF = 1; } set_CF(tmpCF); set_SF(AL >> 7); set_ZF(AL==0); set_PF_base(AL); } void BX_CPU_C::AAA(BxInstruction_t *) { Bit8u ALcarry; ALcarry = AL > 0xf9; /* AAA effects the following flags: A,C */ if ( ((AL & 0x0f) > 9) || get_AF() ) { AL = (AL + 6) & 0x0f; AH = AH + 1 + ALcarry; set_AF(1); set_CF(1); } else { set_AF(0); set_CF(0); AL = AL & 0x0f; } } void BX_CPU_C::AAS(BxInstruction_t *) { Bit8u ALborrow; /* AAS affects the following flags: A,C */ ALborrow = AL < 6; if ( ((AL & 0x0F) > 0x09) || get_AF() ) { AL = (AL - 6) & 0x0f; AH = AH - 1 - ALborrow; set_AF(1); set_CF(1); } else { set_CF(0); set_AF(0); AL = AL & 0x0f; } } void BX_CPU_C::AAM(BxInstruction_t *i) { Bit8u al, imm8; imm8 = i->Ib; if (imm8 == 0) { exception(BX_DE_EXCEPTION, 0, 0); } al = AL; AH = al / imm8; AL = al % imm8; /* AAM always clears the flags A and C */ set_AF(0); set_CF(0); /* AAM affects the following flags: S,Z,P */ set_SF((AL & 0x80) > 0); set_ZF(AL == 0); set_PF_base(AL); } void BX_CPU_C::AAD(BxInstruction_t *i) { Bit8u al, imm8; Bit16u ax1, ax2; imm8 = i->Ib; ax1 = AH * imm8; ax2 = ax1 + AL; al = AL; AL = (Bit8u)ax2; AH = 0; /* AAD effects the following flags: A,C,O,S,Z,P */ /* modification of flags A,C,O is undocumented */ set_AF((ax1 & 0x08) != (ax2 & 0x08)); set_CF(ax2 > 0xff); set_OF((AL & 0x80) != (al & 0x80)); set_SF(AL >= 0x80); set_ZF(AL == 0); set_PF_base(AL); } void BX_CPU_C::DAA(BxInstruction_t *) { Bit8u al; al = AL; // DAA affects the following flags: S,Z,A,P,C // ??? if (((al & 0x0F) > 0x09) || get_AF()) { al = al + 0x06; set_AF(1); } else set_AF(0); if ((al > 0x9F) || get_CF()) { al = al + 0x60; set_CF(1); } else set_CF(0); AL = al; set_SF(al >> 7); set_ZF(al==0); set_PF_base(al); } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <fstream> #include <ostream> #include <thread> // NOLINT #include <vector> #include "paddle/fluid/operators/listen_and_serv_op.h" namespace paddle { namespace operators { void RunServer(std::shared_ptr<detail::AsyncGRPCServer> service) { service->RunSyncUpdate(); VLOG(4) << "RunServer thread end"; } static void split(const std::string &str, char sep, std::vector<std::string> *pieces) { pieces->clear(); if (str.empty()) { return; } size_t pos = 0; size_t next = str.find(sep, pos); while (next != std::string::npos) { pieces->push_back(str.substr(pos, next - pos)); pos = next + 1; next = str.find(sep, pos); } if (!str.substr(pos).empty()) { pieces->push_back(str.substr(pos)); } } static void AsyncExecuteBlock(framework::Executor *executor, framework::ExecutorPrepareContext *prepared, framework::Scope *scope) { std::future<void> future = framework::Async([&executor, &prepared, &scope]() { try { executor->RunPreparedContext(prepared, scope, false, false); } catch (std::exception &e) { LOG(ERROR) << "run sub program error " << e.what(); } }); // TODO(qiao) maybe we can remove this future.wait(); } static void ParallelExecuteBlocks( const std::vector<size_t> &parallel_blkids, framework::Executor *executor, const std::vector<std::shared_ptr<framework::ExecutorPrepareContext>> &prepared, framework::ProgramDesc *program, framework::Scope *scope) { std::vector<std::future<void>> fs; for (size_t idx : parallel_blkids) { fs.push_back( framework::Async([&executor, &prepared, &program, &scope, idx]() { int run_block = idx; // thread local try { executor->RunPreparedContext(prepared[run_block].get(), scope, false, false); } catch (std::exception &e) { LOG(ERROR) << "run sub program error " << e.what(); } })); } for (size_t i = 0; i < fs.size(); ++i) fs[i].wait(); } static void SavePort(std::shared_ptr<detail::AsyncGRPCServer> rpc_service) { std::ofstream port_file; port_file.open("/tmp/paddle.selected_port"); port_file << rpc_service->GetSelectedPort(); port_file.close(); } ListenAndServOp::ListenAndServOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorBase(type, inputs, outputs, attrs) {} int ListenAndServOp::GetSelectedPort() const { return rpc_service_->GetSelectedPort(); } void ListenAndServOp::Stop() { rpc_service_->Push(LISTEN_TERMINATE_MESSAGE); server_thread_->join(); } void ListenAndServOp::RunSyncLoop(framework::Executor *executor, framework::ProgramDesc *program, framework::Scope *recv_scope, framework::BlockDesc *prefetch_block) const { auto fan_in = Attr<int>("Fanin"); size_t num_blocks = program->Size(); PADDLE_ENFORCE_GE(num_blocks, 2, "server program should have at least 2 blocks"); std::vector<int> block_list; for (size_t blkid = 1; blkid < num_blocks; ++blkid) { block_list.push_back(blkid); } auto optimize_prepared = executor->Prepare(*program, block_list); // Insert placeholder for block0 which holds current op itself. optimize_prepared.insert( optimize_prepared.begin(), std::shared_ptr<framework::ExecutorPrepareContext>(nullptr)); bool exit_flag = false; // Record received sparse variables, so that // we could reset those after execute optimize program std::vector<framework::Variable *> sparse_vars; while (!exit_flag) { // Get from multiple trainers, we don't care about the order in which // the gradients arrives, just add suffix 0~n and merge the gradient. rpc_service_->SetCond(0); size_t recv_var_cnt = 0; int batch_barrier = 0; while (batch_barrier != fan_in) { const detail::ReceivedMessage v = rpc_service_->Get(); auto recv_var_name = v.first; if (recv_var_name == LISTEN_TERMINATE_MESSAGE) { LOG(INFO) << "received terminate message and exit"; exit_flag = true; break; } else if (recv_var_name == BATCH_BARRIER_MESSAGE) { VLOG(3) << "recv batch barrier message"; batch_barrier++; continue; } else { VLOG(3) << "received grad: " << recv_var_name; recv_var_cnt++; auto var = v.second->GetVar(); if (var == nullptr) { LOG(ERROR) << "Can not find server side var: " << recv_var_name; PADDLE_THROW("Can not find server side var"); } if (var->IsType<framework::SelectedRows>()) { sparse_vars.push_back(var); } } } if (exit_flag) { rpc_service_->SetCond(1); rpc_service_->ShutDown(); break; } // NOTE: if is_gpu_place, CUDA kernels are launched by multiple threads // and this will still work. // The optimize blocks which have the same parent ID would run parallel // TODO(Yancey1989): need to use ParallelExecutor for future int32_t last_parent_blkid = program->Block(1).Parent(); std::vector<size_t> parallel_blkids; parallel_blkids.push_back(1); double ts = detail::GetTimestamp(); for (size_t blkid = 2; blkid < num_blocks; ++blkid) { if (blkid != static_cast<size_t>(prefetch_block->ID())) { if (program->Block(blkid).Parent() != last_parent_blkid) { ParallelExecuteBlocks(parallel_blkids, executor, optimize_prepared, program, recv_scope); parallel_blkids.clear(); last_parent_blkid = program->Block(blkid).Parent(); } parallel_blkids.push_back(blkid); } } ParallelExecuteBlocks(parallel_blkids, executor, optimize_prepared, program, recv_scope); VLOG(2) << "run all blocks spent " << detail::GetTimestamp() - ts << "(ms)"; // Reset the received sparse variables, the sum operator would not // sum the input sparse variables which rows is empty at the next // mini-batch. // TODO(Yancey1989): move the reset action into an operator, we couldn't // have any hide logic in the operator. for (auto &var : sparse_vars) { var->GetMutable<framework::SelectedRows>()->mutable_rows()->clear(); } rpc_service_->SetCond(1); // FIXME(typhoonzero): use another condition to sync wait clients get. rpc_service_->WaitClientGet(fan_in); sparse_vars.clear(); } // while(true) } void ListenAndServOp::RunAsyncLoop(framework::Executor *executor, framework::ProgramDesc *program, framework::Scope *recv_scope, framework::BlockDesc *prefetch_block) const { VLOG(3) << "RunAsyncLoop in"; // grad name to block id std::unordered_map<std::string, int32_t> grad_to_id; std::unordered_map<int32_t, std::string> id_to_grad; auto grad_to_id_str = Attr<std::vector<std::string>>("grad_to_id"); for (auto &grad_and_id : grad_to_id_str) { std::vector<std::string> pieces; split(grad_and_id, ':', &pieces); VLOG(3) << "after split, grad = " << pieces[0] << ", id=" << pieces[1]; PADDLE_ENFORCE_EQ(pieces.size(), 2); PADDLE_ENFORCE_EQ(grad_to_id.count(pieces[0]), 0); int block_id = std::stoi(pieces[1]); grad_to_id[pieces[0]] = block_id; id_to_grad[block_id] = pieces[0]; } size_t num_blocks = program->Size(); PADDLE_ENFORCE_GE(num_blocks, 2, "server program should have at least 2 blocks"); std::vector<int> block_list; for (size_t blkid = 1; blkid < num_blocks; ++blkid) { block_list.push_back(blkid); } auto optimize_prepared = executor->Prepare(*program, block_list); std::unordered_map<std::string, std::shared_ptr<framework::ExecutorPrepareContext>> grad_to_prepared; for (size_t i = 0; i < block_list.size(); ++i) { grad_to_prepared[id_to_grad[block_list[i]]] = optimize_prepared[i]; } VLOG(3) << "RunAsyncLoop into while"; bool exit_flag = false; while (!exit_flag) { const detail::ReceivedMessage v = rpc_service_->Get(); auto recv_var_name = v.first; if (recv_var_name == LISTEN_TERMINATE_MESSAGE) { LOG(INFO) << "received terminate message and exit"; exit_flag = true; break; } else { VLOG(3) << "received grad: " << recv_var_name; auto var = v.second->GetVar(); if (var == nullptr) { LOG(ERROR) << "Can not find server side var: " << recv_var_name; PADDLE_THROW("Can not find server side var"); } AsyncExecuteBlock(executor, grad_to_prepared[recv_var_name].get(), &(v.second->GetLocalScope())); // TODO(qiao): explain why if (var->IsType<framework::SelectedRows>()) { var->GetMutable<framework::SelectedRows>()->mutable_rows()->clear(); } } if (exit_flag) { rpc_service_->ShutDown(); break; } } // while(true) } void ListenAndServOp::RunImpl(const framework::Scope &scope, const platform::Place &dev_place) const { platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(dev_place); framework::Scope &recv_scope = scope.NewScope(); bool sync_mode = Attr<bool>("sync_mode"); PADDLE_ENFORCE(!rpc_service_); std::string endpoint = Attr<std::string>("endpoint"); rpc_service_.reset(new detail::AsyncGRPCServer(endpoint, sync_mode)); auto *optimize_block = Attr<framework::BlockDesc *>(kOptimizeBlock); auto *prefetch_block = Attr<framework::BlockDesc *>(kPrefetchBlock); auto *program = optimize_block->Program(); framework::Executor executor(dev_place); // prepare rpc_service rpc_service_->SetScope(&recv_scope); rpc_service_->SetDevCtx(&dev_ctx); rpc_service_->SetProgram(program); rpc_service_->SetExecutor(&executor); // prepare for prefetch VLOG(3) << "prefetch block id is " << prefetch_block->ID(); auto prefetch_prepared = executor.Prepare(*program, prefetch_block->ID()); rpc_service_->SetPrefetchPreparedCtx(prefetch_prepared.get()); prefetch_prepared.release(); // start the server listening after all member initialized. server_thread_.reset(new std::thread(RunServer, rpc_service_)); VLOG(3) << "wait server thread to become ready..."; sleep(5); // Write to a file of server selected port for python use. SavePort(rpc_service_); if (sync_mode) { RunSyncLoop(&executor, program, &recv_scope, prefetch_block); } else { RunAsyncLoop(&executor, program, &recv_scope, prefetch_block); } } class ListenAndServOpMaker : public framework::OpProtoAndCheckerMaker { public: ListenAndServOpMaker(OpProto *proto, OpAttrChecker *op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("X", "(Tensor) Variables that server recv.").AsDuplicable(); AddComment(R"DOC( ListenAndServ operator This operator will start a RPC server which can receive variables from send_op and send back variables to recv_op. )DOC"); AddAttr<std::string>("endpoint", "(string, default 127.0.0.1:6164)" "IP address to listen on.") .SetDefault("127.0.0.1:6164") .AddCustomChecker([](const std::string &ip) { return !ip.empty(); }); AddAttr<std::vector<std::string>>( "grad_to_id", "['param1@GRAD.block0:1', 'param2@GRAD.blockn:2'] " "a map from grad name to it's optimize block id") .SetDefault({}); AddAttr<bool>("sync_mode", "if works at sync_mode or not") .SetDefault(false); AddAttr<framework::BlockDesc *>(kOptimizeBlock, "BlockID to run on server side."); AddAttr<framework::BlockDesc *>(kPrefetchBlock, "prefetch block to run on server side."); AddAttr<int>("Fanin", "How many clients send to this server.") .SetDefault(1); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(listen_and_serv, ops::ListenAndServOp, ops::ListenAndServOpMaker); <commit_msg>listen and serv default sync mode<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <fstream> #include <ostream> #include <thread> // NOLINT #include <vector> #include "paddle/fluid/operators/listen_and_serv_op.h" namespace paddle { namespace operators { void RunServer(std::shared_ptr<detail::AsyncGRPCServer> service) { service->RunSyncUpdate(); VLOG(4) << "RunServer thread end"; } static void split(const std::string &str, char sep, std::vector<std::string> *pieces) { pieces->clear(); if (str.empty()) { return; } size_t pos = 0; size_t next = str.find(sep, pos); while (next != std::string::npos) { pieces->push_back(str.substr(pos, next - pos)); pos = next + 1; next = str.find(sep, pos); } if (!str.substr(pos).empty()) { pieces->push_back(str.substr(pos)); } } static void AsyncExecuteBlock(framework::Executor *executor, framework::ExecutorPrepareContext *prepared, framework::Scope *scope) { std::future<void> future = framework::Async([&executor, &prepared, &scope]() { try { executor->RunPreparedContext(prepared, scope, false, false); } catch (std::exception &e) { LOG(ERROR) << "run sub program error " << e.what(); } }); // TODO(qiao) maybe we can remove this future.wait(); } static void ParallelExecuteBlocks( const std::vector<size_t> &parallel_blkids, framework::Executor *executor, const std::vector<std::shared_ptr<framework::ExecutorPrepareContext>> &prepared, framework::ProgramDesc *program, framework::Scope *scope) { std::vector<std::future<void>> fs; for (size_t idx : parallel_blkids) { fs.push_back( framework::Async([&executor, &prepared, &program, &scope, idx]() { int run_block = idx; // thread local try { executor->RunPreparedContext(prepared[run_block].get(), scope, false, false); } catch (std::exception &e) { LOG(ERROR) << "run sub program error " << e.what(); } })); } for (size_t i = 0; i < fs.size(); ++i) fs[i].wait(); } static void SavePort(std::shared_ptr<detail::AsyncGRPCServer> rpc_service) { std::ofstream port_file; port_file.open("/tmp/paddle.selected_port"); port_file << rpc_service->GetSelectedPort(); port_file.close(); } ListenAndServOp::ListenAndServOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorBase(type, inputs, outputs, attrs) {} int ListenAndServOp::GetSelectedPort() const { return rpc_service_->GetSelectedPort(); } void ListenAndServOp::Stop() { rpc_service_->Push(LISTEN_TERMINATE_MESSAGE); server_thread_->join(); } void ListenAndServOp::RunSyncLoop(framework::Executor *executor, framework::ProgramDesc *program, framework::Scope *recv_scope, framework::BlockDesc *prefetch_block) const { auto fan_in = Attr<int>("Fanin"); size_t num_blocks = program->Size(); PADDLE_ENFORCE_GE(num_blocks, 2, "server program should have at least 2 blocks"); std::vector<int> block_list; for (size_t blkid = 1; blkid < num_blocks; ++blkid) { block_list.push_back(blkid); } auto optimize_prepared = executor->Prepare(*program, block_list); // Insert placeholder for block0 which holds current op itself. optimize_prepared.insert( optimize_prepared.begin(), std::shared_ptr<framework::ExecutorPrepareContext>(nullptr)); bool exit_flag = false; // Record received sparse variables, so that // we could reset those after execute optimize program std::vector<framework::Variable *> sparse_vars; while (!exit_flag) { // Get from multiple trainers, we don't care about the order in which // the gradients arrives, just add suffix 0~n and merge the gradient. rpc_service_->SetCond(0); size_t recv_var_cnt = 0; int batch_barrier = 0; while (batch_barrier != fan_in) { const detail::ReceivedMessage v = rpc_service_->Get(); auto recv_var_name = v.first; if (recv_var_name == LISTEN_TERMINATE_MESSAGE) { LOG(INFO) << "received terminate message and exit"; exit_flag = true; break; } else if (recv_var_name == BATCH_BARRIER_MESSAGE) { VLOG(3) << "recv batch barrier message"; batch_barrier++; continue; } else { VLOG(3) << "received grad: " << recv_var_name; recv_var_cnt++; auto var = v.second->GetVar(); if (var == nullptr) { LOG(ERROR) << "Can not find server side var: " << recv_var_name; PADDLE_THROW("Can not find server side var"); } if (var->IsType<framework::SelectedRows>()) { sparse_vars.push_back(var); } } } if (exit_flag) { rpc_service_->SetCond(1); rpc_service_->ShutDown(); break; } // NOTE: if is_gpu_place, CUDA kernels are launched by multiple threads // and this will still work. // The optimize blocks which have the same parent ID would run parallel // TODO(Yancey1989): need to use ParallelExecutor for future int32_t last_parent_blkid = program->Block(1).Parent(); std::vector<size_t> parallel_blkids; parallel_blkids.push_back(1); double ts = detail::GetTimestamp(); for (size_t blkid = 2; blkid < num_blocks; ++blkid) { if (blkid != static_cast<size_t>(prefetch_block->ID())) { if (program->Block(blkid).Parent() != last_parent_blkid) { ParallelExecuteBlocks(parallel_blkids, executor, optimize_prepared, program, recv_scope); parallel_blkids.clear(); last_parent_blkid = program->Block(blkid).Parent(); } parallel_blkids.push_back(blkid); } } ParallelExecuteBlocks(parallel_blkids, executor, optimize_prepared, program, recv_scope); VLOG(2) << "run all blocks spent " << detail::GetTimestamp() - ts << "(ms)"; // Reset the received sparse variables, the sum operator would not // sum the input sparse variables which rows is empty at the next // mini-batch. // TODO(Yancey1989): move the reset action into an operator, we couldn't // have any hide logic in the operator. for (auto &var : sparse_vars) { var->GetMutable<framework::SelectedRows>()->mutable_rows()->clear(); } rpc_service_->SetCond(1); // FIXME(typhoonzero): use another condition to sync wait clients get. rpc_service_->WaitClientGet(fan_in); sparse_vars.clear(); } // while(true) } void ListenAndServOp::RunAsyncLoop(framework::Executor *executor, framework::ProgramDesc *program, framework::Scope *recv_scope, framework::BlockDesc *prefetch_block) const { VLOG(3) << "RunAsyncLoop in"; // grad name to block id std::unordered_map<std::string, int32_t> grad_to_id; std::unordered_map<int32_t, std::string> id_to_grad; auto grad_to_id_str = Attr<std::vector<std::string>>("grad_to_id"); for (auto &grad_and_id : grad_to_id_str) { std::vector<std::string> pieces; split(grad_and_id, ':', &pieces); VLOG(3) << "after split, grad = " << pieces[0] << ", id=" << pieces[1]; PADDLE_ENFORCE_EQ(pieces.size(), 2); PADDLE_ENFORCE_EQ(grad_to_id.count(pieces[0]), 0); int block_id = std::stoi(pieces[1]); grad_to_id[pieces[0]] = block_id; id_to_grad[block_id] = pieces[0]; } size_t num_blocks = program->Size(); PADDLE_ENFORCE_GE(num_blocks, 2, "server program should have at least 2 blocks"); std::vector<int> block_list; for (size_t blkid = 1; blkid < num_blocks; ++blkid) { block_list.push_back(blkid); } auto optimize_prepared = executor->Prepare(*program, block_list); std::unordered_map<std::string, std::shared_ptr<framework::ExecutorPrepareContext>> grad_to_prepared; for (size_t i = 0; i < block_list.size(); ++i) { grad_to_prepared[id_to_grad[block_list[i]]] = optimize_prepared[i]; } VLOG(3) << "RunAsyncLoop into while"; bool exit_flag = false; while (!exit_flag) { const detail::ReceivedMessage v = rpc_service_->Get(); auto recv_var_name = v.first; if (recv_var_name == LISTEN_TERMINATE_MESSAGE) { LOG(INFO) << "received terminate message and exit"; exit_flag = true; break; } else { VLOG(3) << "received grad: " << recv_var_name; auto var = v.second->GetVar(); if (var == nullptr) { LOG(ERROR) << "Can not find server side var: " << recv_var_name; PADDLE_THROW("Can not find server side var"); } AsyncExecuteBlock(executor, grad_to_prepared[recv_var_name].get(), &(v.second->GetLocalScope())); // TODO(qiao): explain why if (var->IsType<framework::SelectedRows>()) { var->GetMutable<framework::SelectedRows>()->mutable_rows()->clear(); } } if (exit_flag) { rpc_service_->ShutDown(); break; } } // while(true) } void ListenAndServOp::RunImpl(const framework::Scope &scope, const platform::Place &dev_place) const { platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(dev_place); framework::Scope &recv_scope = scope.NewScope(); bool sync_mode = Attr<bool>("sync_mode"); PADDLE_ENFORCE(!rpc_service_); std::string endpoint = Attr<std::string>("endpoint"); rpc_service_.reset(new detail::AsyncGRPCServer(endpoint, sync_mode)); auto *optimize_block = Attr<framework::BlockDesc *>(kOptimizeBlock); auto *prefetch_block = Attr<framework::BlockDesc *>(kPrefetchBlock); auto *program = optimize_block->Program(); framework::Executor executor(dev_place); // prepare rpc_service rpc_service_->SetScope(&recv_scope); rpc_service_->SetDevCtx(&dev_ctx); rpc_service_->SetProgram(program); rpc_service_->SetExecutor(&executor); // prepare for prefetch VLOG(3) << "prefetch block id is " << prefetch_block->ID(); auto prefetch_prepared = executor.Prepare(*program, prefetch_block->ID()); rpc_service_->SetPrefetchPreparedCtx(prefetch_prepared.get()); prefetch_prepared.release(); // start the server listening after all member initialized. server_thread_.reset(new std::thread(RunServer, rpc_service_)); VLOG(3) << "wait server thread to become ready..."; sleep(5); // Write to a file of server selected port for python use. SavePort(rpc_service_); if (sync_mode) { RunSyncLoop(&executor, program, &recv_scope, prefetch_block); } else { RunAsyncLoop(&executor, program, &recv_scope, prefetch_block); } } class ListenAndServOpMaker : public framework::OpProtoAndCheckerMaker { public: ListenAndServOpMaker(OpProto *proto, OpAttrChecker *op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("X", "(Tensor) Variables that server recv.").AsDuplicable(); AddComment(R"DOC( ListenAndServ operator This operator will start a RPC server which can receive variables from send_op and send back variables to recv_op. )DOC"); AddAttr<std::string>("endpoint", "(string, default 127.0.0.1:6164)" "IP address to listen on.") .SetDefault("127.0.0.1:6164") .AddCustomChecker([](const std::string &ip) { return !ip.empty(); }); AddAttr<std::vector<std::string>>( "grad_to_id", "['param1@GRAD.block0:1', 'param2@GRAD.blockn:2'] " "a map from grad name to it's optimize block id") .SetDefault({}); AddAttr<bool>("sync_mode", "if works at sync_mode or not").SetDefault(true); AddAttr<framework::BlockDesc *>(kOptimizeBlock, "BlockID to run on server side."); AddAttr<framework::BlockDesc *>(kPrefetchBlock, "prefetch block to run on server side."); AddAttr<int>("Fanin", "How many clients send to this server.") .SetDefault(1); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(listen_and_serv, ops::ListenAndServOp, ops::ListenAndServOpMaker); <|endoftext|>
<commit_before>extern "C" { #include <lua/lualib.h> } #include <luabind/luabind.hpp> #include "lua_state_raii.h" #include "augs/window_framework/platform_utils.h" #include "augs/log.h" #include "augs/ensure.h" #include "augs/filesystem/file.h" namespace augs { lua_state_raii::lua_state_raii(lua_State* state) : raw(state) { owns = false; } lua_state_raii::lua_state_raii() : raw(luaL_newstate()) { luaopen_base(raw); luaL_openlibs(raw); } lua_state_raii::~lua_state_raii() { if(owns) lua_close(raw); } lua_state_raii::operator lua_State*() { return raw; } std::string lua_state_raii::get_error() { lua_State* L = raw; std::string str; { const auto* p = lua_tostring(L, -1); if (p != nullptr) { str = p; } } lua_pop(L, 1); return str.empty() ? "\nFailed to retrieve the lua error!" : ("\n" + str); } std::string lua_state_raii::get_stack() { call_debug_traceback(); lua_State* L = raw; std::string str; { const auto* p = lua_tostring(L, -1); if (p != nullptr) { str = p; } } lua_pop(L, 1); return str.empty() ? "\nFailed to retrieve the lua call stack!" : ("\n" + str); } void lua_state_raii::call_debug_traceback(const std::string& method) { lua_State* L = raw; lua_getglobal(L, "debug"); lua_getfield(L, -1, method.c_str()); lua_pushvalue(L, 1); lua_pushinteger(L, 2); lua_call(L, 2, 1); } std::string lua_execution_result::open_editor() const { if (error_message.empty()) { return ""; } std::stringstream ss(error_message); std::string to; std::string full_command = std::string("\"") + getenv("AUG_SCRIPTEDITOR") + "\" "; std::string lines; int lines_found = 0; while (std::getline(ss, to, '\n')) { std::stringstream line(to); std::string to2; line >> to2; if (to2.empty()) continue; to2.erase(to2.end() - 1); if (to2.find(".lua") != std::string::npos) { auto ws = window::get_executable_path(); std::string exe_path(ws.begin(), ws.end()); std::string full_file_path = (exe_path + "\\" + to2); lines += full_file_path + "\n"; full_command += full_file_path + " "; ++lines_found; } } if (lines_found > 0) { CALL_SHELL(full_command); } return lines; } int lua_writer(lua_State *L, const void* p, size_t sz, void* ud) { auto* ptr = static_cast<const char*>(p); auto& char_vec = *static_cast<std::vector<char>*>(ud); char_vec.resize(char_vec.size() + sz); memcpy(char_vec.data() + char_vec.size() - sz, ptr, sz); return 0; } const char* lua_reader(lua_State *L, void *data, size_t *sz) { const auto& bytecode = *static_cast<const std::vector<char>*>(data); *sz = bytecode.size(); return bytecode.data(); } void lua_state_raii::dofile_and_report_errors(const std::string& filename) { LOG("Calling script %x", filename); ensure(augs::file_exists(filename)); const auto compiled = compile_file(filename); const bool compilation_failed = compiled.error_message.size() > 0; if (compilation_failed) { LOG("Lua compilation error (%x): %x", filename, compiled.error_message); ensure(!compilation_failed); return; } else { const auto executed = execute(compiled.bytecode); const bool execution_failed = executed.error_message.size() > 0 || executed.exception_message.size() > 0; if (execution_failed) { LOG("Lua execution error (%x): %x\n%x", filename, executed.error_message, executed.exception_message); executed.open_editor(); ensure(!execution_failed); } } } lua_compilation_result lua_state_raii::compile_file(const std::string& filename) { return compile_script(augs::get_file_contents(filename)); } lua_compilation_result lua_state_raii::compile_script(const std::string& script) { lua_compilation_result output; const auto result = luaL_loadstring(raw, script.c_str()); if (result != 0) { output.error_message = get_error(); } else { lua_dump(raw, lua_writer, &output.bytecode, 0); lua_pop(raw, 1); } return std::move(output); } lua_execution_result lua_state_raii::execute(std::vector<char> bytecode) { lua_execution_result output; try { if (lua_load(raw, lua_reader, reinterpret_cast<void*>(&bytecode), "scriptname", "b") != 0) { output.error_message = get_error() + get_stack(); } luabind::call_function<void>(luabind::object(luabind::from_stack(raw, -1))); lua_pop(raw, 1); } catch (char* e) { output.exception_message = typesafe_sprintf("Exception thrown! %x", e); output.error_message = get_error() + get_stack(); } catch (...) { output.exception_message = typesafe_sprintf("Exception (unknown) thrown!"); output.error_message = get_error() + get_stack(); } return std::move(output); } }<commit_msg>some refactor<commit_after>extern "C" { #include <lua/lualib.h> } #include <luabind/luabind.hpp> #include "lua_state_raii.h" #include "augs/window_framework/platform_utils.h" #include "augs/log.h" #include "augs/ensure.h" #include "augs/filesystem/file.h" namespace augs { lua_state_raii::lua_state_raii(lua_State* state) : raw(state) { owns = false; } lua_state_raii::lua_state_raii() : raw(luaL_newstate()) { luaopen_base(raw); luaL_openlibs(raw); } lua_state_raii::~lua_state_raii() { if(owns) lua_close(raw); } lua_state_raii::operator lua_State*() { return raw; } std::string lua_state_raii::get_error() { lua_State* L = raw; std::string str; { const auto* p = lua_tostring(L, -1); if (p != nullptr) { str = p; } } return str.empty() ? "\nFailed to retrieve the lua error!" : ("\n" + str); } std::string lua_state_raii::get_stack() { call_debug_traceback(); lua_State* L = raw; std::string str; { const auto* p = lua_tostring(L, -1); if (p != nullptr) { str = p; } } return str.empty() ? "\nFailed to retrieve the lua call stack!" : ("\n" + str); } void lua_state_raii::call_debug_traceback(const std::string& method) { lua_State* L = raw; luaL_traceback(L, L, nullptr, 0); } std::string lua_execution_result::open_editor() const { if (error_message.empty()) { return ""; } std::stringstream ss(error_message); std::string to; std::string full_command = std::string("\"") + getenv("AUG_SCRIPTEDITOR") + "\" "; std::string lines; int lines_found = 0; while (std::getline(ss, to, '\n')) { std::stringstream line(to); std::string to2; line >> to2; if (to2.empty()) continue; to2.erase(to2.end() - 1); if (to2.find(".lua") != std::string::npos) { auto ws = window::get_executable_path(); std::string exe_path(ws.begin(), ws.end()); std::string full_file_path = (exe_path + "\\" + to2); lines += full_file_path + "\n"; full_command += full_file_path + " "; ++lines_found; } } if (lines_found > 0) { CALL_SHELL(full_command); } return lines; } int lua_writer(lua_State *L, const void* p, size_t sz, void* ud) { auto* ptr = static_cast<const char*>(p); auto& char_vec = *static_cast<std::vector<char>*>(ud); char_vec.resize(char_vec.size() + sz); memcpy(char_vec.data() + char_vec.size() - sz, ptr, sz); return 0; } const char* lua_reader(lua_State *L, void *data, size_t *sz) { const auto& bytecode = *static_cast<const std::vector<char>*>(data); *sz = bytecode.size(); return bytecode.data(); } void lua_state_raii::dofile_and_report_errors(const std::string& filename) { LOG("Calling script %x", filename); ensure(augs::file_exists(filename)); const auto compiled = compile_file(filename); const bool compilation_failed = compiled.error_message.size() > 0; if (compilation_failed) { LOG("Lua compilation error (%x): %x", filename, compiled.error_message); ensure(!compilation_failed); return; } else { const auto executed = execute(compiled.bytecode); const bool execution_failed = executed.error_message.size() > 0 || executed.exception_message.size() > 0; if (execution_failed) { LOG("Lua execution error (%x): %x\n%x", filename, executed.error_message, executed.exception_message); executed.open_editor(); ensure(!execution_failed); } } } lua_compilation_result lua_state_raii::compile_file(const std::string& filename) { return compile_script(augs::get_file_contents(filename)); } lua_compilation_result lua_state_raii::compile_script(const std::string& script) { lua_compilation_result output; const auto result = luaL_loadstring(raw, script.c_str()); if (result != 0) { output.error_message = get_error(); } else { lua_dump(raw, lua_writer, &output.bytecode, 0); lua_pop(raw, 1); } return std::move(output); } lua_execution_result lua_state_raii::execute(std::vector<char> bytecode) { lua_execution_result output; try { if (lua_load(raw, lua_reader, reinterpret_cast<void*>(&bytecode), "scriptname", "b") != 0) { output.error_message = get_stack() + get_error(); } luabind::call_function<void>(luabind::object(luabind::from_stack(raw, -1))); lua_pop(raw, 1); } catch (char* e) { output.exception_message = typesafe_sprintf("Exception thrown! %x", e); output.error_message = get_stack() + get_error(); } catch (std::runtime_error e) { output.exception_message = typesafe_sprintf("std::runtime_error thrown: %x", e.what()); output.error_message = get_stack() + get_error(); } catch (luabind::cast_failed e) { output.exception_message = typesafe_sprintf("cast_failed thrown: %x (%x)", e.what(), e.info().name()); output.error_message = get_stack() + get_error(); } catch (luabind::error e) { output.exception_message = typesafe_sprintf("luabind::error thrown: %x", e.what()); output.error_message = get_stack() + get_error(); } return std::move(output); } }<|endoftext|>
<commit_before>#include <Arduino.h> #include "SoftwareSerial.h" #include "A6lib.h" #ifdef DEBUG #define log(msg) Serial.print(msg) #define logln(msg) Serial.println(msg) #else #define log(msg) #define logln(msg) #endif #define countof(a) (sizeof(a) / sizeof(a[0])) #define OK 0 #define NOTOK 1 #define TIMEOUT 2 #define A6_CMD_TIMEOUT 2000 ///////////////////////////////////////////// // Public methods. // A6::A6(int transmitPin, int receivePin) { A6conn = new SoftwareSerial(receivePin, transmitPin, false, 1024); A6conn->setTimeout(100); } A6::~A6() { delete A6conn; } // Block until the module is ready. void A6::blockUntilReady(long baudRate) { while(0 != begin(baudRate)) { delay(1000); logln("Waiting for module to be ready..."); } } // Initialize the software serial connection and change the baud rate from the // default (autodetected) to the desired speed. char A6::begin(long baudRate) { A6conn->flush(); if (OK != setRate(baudRate)) return NOTOK; // Factory reset. A6command("AT&F", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Echo off. A6command("ATE0", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Switch audio to headset. enableSpeaker(0); // Set caller ID on. A6command("AT+CLIP=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Set SMS to text mode. A6command("AT+CMGF=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Set SMS indicators to on. A6command("AT+CNMI=2,1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Set SMS storage to the GSM modem. A6command("AT+CPMS=ME,ME,ME", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Set SMS character set. setSMScharset("UCS2"); } // Reboot the module by setting the specified pin HIGH, then LOW. The pin should // be connected to a P-MOSFET, not the A6's POWER pin. void A6::powerCycle(int pin) { logln("Power-cycling module..."); powerOff(pin); delay(1000); powerOn(pin); // Give the module some time to settle. logln("Done, waiting for the module to initialize..."); delay(20000); logln("Done."); A6conn->flush(); } // Turn the modem power completely off. void A6::powerOff(int pin) { pinMode(pin, OUTPUT); digitalWrite(pin, LOW); } // Turn the modem power on. void A6::powerOn(int pin) { pinMode(pin, OUTPUT); digitalWrite(pin, HIGH); } // Dial a number. void A6::dial(String number) { char buffer[50]; logln("Dialing number..."); sprintf(buffer, "ATD%s;", number.c_str()); A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Redial the last number. void A6::redial() { logln("Redialing last number..."); A6command("AT+DLST", "OK", "CONNECT", A6_CMD_TIMEOUT, 2, NULL); } // Answer a call. void A6::answer() { A6command("ATA", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Hang up the phone. void A6::hangUp() { A6command("ATH", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Check whether there is an active call. callInfo A6::checkCallStatus() { char number[50]; String response = ""; int respStart = 0, matched = 0; callInfo cinfo = (const struct callInfo){ 0 }; // Issue the command and wait for the response. A6command("AT+CLCC", "OK", "+CLCC", A6_CMD_TIMEOUT, 2, &response); // Parse the response if it contains a valid +CLCC. respStart = response.indexOf("+CLCC"); if (respStart >= 0) { matched = sscanf(response.substring(respStart).c_str(), "+CLCC: %d,%d,%d,%d,%d,\"%s\",%d", &cinfo.index, &cinfo.direction, &cinfo.state, &cinfo.mode, &cinfo.multiparty, number, &cinfo.type); cinfo.number = String(number); } return cinfo; } // Send an SMS. byte A6::sendSMS(String number, String text) { char ctrlZ[2] = { 0x1a, 0x00 }; char buffer[100]; if (text.length() > 159) { // We can't send messages longer than 160 characters. return NOTOK; } log("Sending SMS to "); log(number); logln("..."); sprintf(buffer, "AT+CMGS=\"%s\"", number.c_str()); A6command(buffer, ">", "yy", A6_CMD_TIMEOUT, 2, NULL); delay(100); A6conn->println(text.c_str()); A6conn->println(ctrlZ); A6conn->println(); return OK; } // Delete the SMS at index. byte A6::deleteSMS(int index) { char buffer[100]; sprintf(buffer, "AT+CMGD=%d", index); return A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Set the SMS charset. byte A6::setSMScharset(String charset) { char buffer[100]; sprintf(buffer, "AT+CSCS=\"%s\"", charset.c_str()); return A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Set the volume for the speaker. level should be a number between 5 and // 8 inclusive. void A6::setVol(byte level) { char buffer[30]; // level should be between 5 and 8. level = min(max(level, 5), 8); sprintf(buffer, "AT+CLVL=%d", level); A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Enable the speaker, rather than the headphones. Pass 0 to route audio through // headphones, 1 through speaker. void A6::enableSpeaker(byte enable) { char buffer[30]; // enable should be between 0 and 1. enable = min(max(enable, 0), 1); sprintf(buffer, "AT+SNFS=%d", enable); A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } ///////////////////////////////////////////// // Private methods. // // Autodetect the connection rate. long A6::detectRate() { int rate = 0; int rates[] = {9600, 115200}; // Try to autodetect the rate. logln("Autodetecting connection rate..."); for (int i = 0; i < countof(rates); i++) { rate = rates[i]; A6conn->begin(rate); log("Trying rate "); log(rate); logln("..."); delay(100); if (A6command("\rAT", "OK", "+CME", 2000, 2, NULL) == OK) { return rate; } } logln("Couldn't detect the rate."); return NOTOK; } // Set the A6 baud rate. char A6::setRate(long baudRate) { int rate = 0; rate = detectRate(); if (rate == NOTOK) return NOTOK; // The rate is already the desired rate, return. //if (rate == baudRate) return OK; logln("Setting baud rate on the module..."); // Change the rate to the requested. char buffer[30]; sprintf(buffer, "AT+IPR=%d", baudRate); A6command(buffer, "OK", "+IPR=", A6_CMD_TIMEOUT, 3, NULL); logln("Switching to the new rate..."); // Begin the connection again at the requested rate. A6conn->begin(baudRate); logln("Rate set."); return OK; } // Read some data from the A6 in a non-blocking manner. String A6::read() { String reply = ""; if (A6conn->available()) reply = A6conn->readString(); return reply; } // Issue a command. byte A6::A6command(const char *command, const char *resp1, const char *resp2, int timeout, int repetitions, String *response) { byte returnValue = NOTOK; byte count = 0; // Get rid of any buffered output. A6conn->flush(); while (count < repetitions && returnValue != OK) { log("Issuing command: "); logln(command); A6conn->write(command); A6conn->write('\r'); if (A6waitFor(resp1, resp2, timeout, response) == OK) { returnValue = OK; } else { returnValue = NOTOK; } count++; } return returnValue; } // Wait for responses. byte A6::A6waitFor(const char *resp1, const char *resp2, int timeout, String *response) { unsigned long entry = millis(); int count = 0; String reply = ""; byte retVal = 99; do { reply += read(); yield(); } while (((reply.indexOf(resp1) + reply.indexOf(resp2)) == -2) && ((millis() - entry) < timeout)); if (reply != "") { log("Reply in "); log((millis() - entry)); log(" ms: "); logln(reply); } if (response != NULL) *response = reply; if ((millis() - entry) >= timeout) { retVal = TIMEOUT; logln("Timed out."); } else { if (reply.indexOf(resp1) + reply.indexOf(resp2) > -2) { logln("Reply OK."); retVal = OK; } else { logln("Reply NOT OK."); retVal = NOTOK; } } return retVal; } <commit_msg>Turn SMS indicators off.<commit_after>#include <Arduino.h> #include "SoftwareSerial.h" #include "A6lib.h" #ifdef DEBUG #define log(msg) Serial.print(msg) #define logln(msg) Serial.println(msg) #else #define log(msg) #define logln(msg) #endif #define countof(a) (sizeof(a) / sizeof(a[0])) #define OK 0 #define NOTOK 1 #define TIMEOUT 2 #define A6_CMD_TIMEOUT 2000 ///////////////////////////////////////////// // Public methods. // A6::A6(int transmitPin, int receivePin) { A6conn = new SoftwareSerial(receivePin, transmitPin, false, 1024); A6conn->setTimeout(100); } A6::~A6() { delete A6conn; } // Block until the module is ready. void A6::blockUntilReady(long baudRate) { while(0 != begin(baudRate)) { delay(1000); logln("Waiting for module to be ready..."); } } // Initialize the software serial connection and change the baud rate from the // default (autodetected) to the desired speed. char A6::begin(long baudRate) { A6conn->flush(); if (OK != setRate(baudRate)) return NOTOK; // Factory reset. A6command("AT&F", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Echo off. A6command("ATE0", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Switch audio to headset. enableSpeaker(0); // Set caller ID on. A6command("AT+CLIP=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Set SMS to text mode. A6command("AT+CMGF=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Turn SMS indicators off. A6command("AT+CNMI=1,0", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Set SMS storage to the GSM modem. A6command("AT+CPMS=ME,ME,ME", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); // Set SMS character set. setSMScharset("UCS2"); } // Reboot the module by setting the specified pin HIGH, then LOW. The pin should // be connected to a P-MOSFET, not the A6's POWER pin. void A6::powerCycle(int pin) { logln("Power-cycling module..."); powerOff(pin); delay(1000); powerOn(pin); // Give the module some time to settle. logln("Done, waiting for the module to initialize..."); delay(20000); logln("Done."); A6conn->flush(); } // Turn the modem power completely off. void A6::powerOff(int pin) { pinMode(pin, OUTPUT); digitalWrite(pin, LOW); } // Turn the modem power on. void A6::powerOn(int pin) { pinMode(pin, OUTPUT); digitalWrite(pin, HIGH); } // Dial a number. void A6::dial(String number) { char buffer[50]; logln("Dialing number..."); sprintf(buffer, "ATD%s;", number.c_str()); A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Redial the last number. void A6::redial() { logln("Redialing last number..."); A6command("AT+DLST", "OK", "CONNECT", A6_CMD_TIMEOUT, 2, NULL); } // Answer a call. void A6::answer() { A6command("ATA", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Hang up the phone. void A6::hangUp() { A6command("ATH", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Check whether there is an active call. callInfo A6::checkCallStatus() { char number[50]; String response = ""; int respStart = 0, matched = 0; callInfo cinfo = (const struct callInfo){ 0 }; // Issue the command and wait for the response. A6command("AT+CLCC", "OK", "+CLCC", A6_CMD_TIMEOUT, 2, &response); // Parse the response if it contains a valid +CLCC. respStart = response.indexOf("+CLCC"); if (respStart >= 0) { matched = sscanf(response.substring(respStart).c_str(), "+CLCC: %d,%d,%d,%d,%d,\"%s\",%d", &cinfo.index, &cinfo.direction, &cinfo.state, &cinfo.mode, &cinfo.multiparty, number, &cinfo.type); cinfo.number = String(number); } return cinfo; } // Send an SMS. byte A6::sendSMS(String number, String text) { char ctrlZ[2] = { 0x1a, 0x00 }; char buffer[100]; if (text.length() > 159) { // We can't send messages longer than 160 characters. return NOTOK; } log("Sending SMS to "); log(number); logln("..."); sprintf(buffer, "AT+CMGS=\"%s\"", number.c_str()); A6command(buffer, ">", "yy", A6_CMD_TIMEOUT, 2, NULL); delay(100); A6conn->println(text.c_str()); A6conn->println(ctrlZ); A6conn->println(); return OK; } // Delete the SMS at index. byte A6::deleteSMS(int index) { char buffer[100]; sprintf(buffer, "AT+CMGD=%d", index); return A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Set the SMS charset. byte A6::setSMScharset(String charset) { char buffer[100]; sprintf(buffer, "AT+CSCS=\"%s\"", charset.c_str()); return A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Set the volume for the speaker. level should be a number between 5 and // 8 inclusive. void A6::setVol(byte level) { char buffer[30]; // level should be between 5 and 8. level = min(max(level, 5), 8); sprintf(buffer, "AT+CLVL=%d", level); A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } // Enable the speaker, rather than the headphones. Pass 0 to route audio through // headphones, 1 through speaker. void A6::enableSpeaker(byte enable) { char buffer[30]; // enable should be between 0 and 1. enable = min(max(enable, 0), 1); sprintf(buffer, "AT+SNFS=%d", enable); A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); } ///////////////////////////////////////////// // Private methods. // // Autodetect the connection rate. long A6::detectRate() { int rate = 0; int rates[] = {9600, 115200}; // Try to autodetect the rate. logln("Autodetecting connection rate..."); for (int i = 0; i < countof(rates); i++) { rate = rates[i]; A6conn->begin(rate); log("Trying rate "); log(rate); logln("..."); delay(100); if (A6command("\rAT", "OK", "+CME", 2000, 2, NULL) == OK) { return rate; } } logln("Couldn't detect the rate."); return NOTOK; } // Set the A6 baud rate. char A6::setRate(long baudRate) { int rate = 0; rate = detectRate(); if (rate == NOTOK) return NOTOK; // The rate is already the desired rate, return. //if (rate == baudRate) return OK; logln("Setting baud rate on the module..."); // Change the rate to the requested. char buffer[30]; sprintf(buffer, "AT+IPR=%d", baudRate); A6command(buffer, "OK", "+IPR=", A6_CMD_TIMEOUT, 3, NULL); logln("Switching to the new rate..."); // Begin the connection again at the requested rate. A6conn->begin(baudRate); logln("Rate set."); return OK; } // Read some data from the A6 in a non-blocking manner. String A6::read() { String reply = ""; if (A6conn->available()) reply = A6conn->readString(); return reply; } // Issue a command. byte A6::A6command(const char *command, const char *resp1, const char *resp2, int timeout, int repetitions, String *response) { byte returnValue = NOTOK; byte count = 0; // Get rid of any buffered output. A6conn->flush(); while (count < repetitions && returnValue != OK) { log("Issuing command: "); logln(command); A6conn->write(command); A6conn->write('\r'); if (A6waitFor(resp1, resp2, timeout, response) == OK) { returnValue = OK; } else { returnValue = NOTOK; } count++; } return returnValue; } // Wait for responses. byte A6::A6waitFor(const char *resp1, const char *resp2, int timeout, String *response) { unsigned long entry = millis(); int count = 0; String reply = ""; byte retVal = 99; do { reply += read(); yield(); } while (((reply.indexOf(resp1) + reply.indexOf(resp2)) == -2) && ((millis() - entry) < timeout)); if (reply != "") { log("Reply in "); log((millis() - entry)); log(" ms: "); logln(reply); } if (response != NULL) *response = reply; if ((millis() - entry) >= timeout) { retVal = TIMEOUT; logln("Timed out."); } else { if (reply.indexOf(resp1) + reply.indexOf(resp2) > -2) { logln("Reply OK."); retVal = OK; } else { logln("Reply NOT OK."); retVal = NOTOK; } } return retVal; } <|endoftext|>
<commit_before>#include <avalon/physics/loadercallbacks.h> #include <Box2D/Box2D.h> #include <boost/any.hpp> #include <avalon/physics/Box2dContainer.h> namespace { std::shared_ptr<b2PolygonShape> initRectangleShape(float width, float height, float pixelsInMeter) { auto shape = make_shared<b2PolygonShape>(); shape->SetAsBox((width / pixelsInMeter) * 0.5f, (height / pixelsInMeter) * 0.5f); return shape; } std::shared_ptr<b2ChainShape> initChainShape(std::list<cocos2d::Point> points, float pixelsInMeter, bool loop = false) { std::vector<b2Vec2> vecs; vecs.reserve(points.size()); for (auto& p : points) { p = p / pixelsInMeter; vecs.push_back({p.x, -p.y}); } auto shape = make_shared<b2ChainShape>(); if (loop) { shape->CreateLoop(&vecs[0], points.size()); } else { shape->CreateChain(&vecs[0], points.size()); } return shape; } std::shared_ptr<b2EdgeShape> initEdgeShape(cocos2d::Point p1, cocos2d::Point p2, float pixelsInMeter) { p1 = p1 / pixelsInMeter; p2 = p2 / pixelsInMeter; auto shape = make_shared<b2EdgeShape>(); shape->Set({p1.x, p1.y}, {p2.x, p2.y}); return shape; } std::shared_ptr<b2Shape> initShapeFromPoints(const std::list<cocos2d::Point>& points, float pixelsInMeter, bool loop = false) { if (points.size() == 2) { return initEdgeShape(points.front(), points.back(), pixelsInMeter); } else { return initChainShape(points, pixelsInMeter, loop); } } } // namespace namespace avalon { namespace physics { namespace loadercallbacks { avalon::io::TiledMapLoader::Callback createShapes(int filterCategory, bool isSensor) { return [filterCategory, isSensor](const avalon::io::TiledMapLoader::Configuration& config) { float x = boost::any_cast<float>(config.settings.at("x")); float y = boost::any_cast<float>(config.settings.at("y")); float width = boost::any_cast<float>(config.settings.at("width")); float height = boost::any_cast<float>(config.settings.at("height")); float pixelsInMeter = config.box2dContainer->pixelsInMeter; float density = 0.0; float friction = 1.0; float restitution = 0.0; std::string bodytype = "static"; if (config.settings.count("friction")) friction = boost::any_cast<float>(config.settings.at("friction")); if (config.settings.count("density")) density = boost::any_cast<float>(config.settings.at("density")); if (config.settings.count("restitution")) restitution = boost::any_cast<float>(config.settings.at("restitution")); if (config.settings.count("bodytype")) bodytype = boost::any_cast<std::string>(config.settings.at("bodytype")); // create the body b2BodyDef bodyDef; if (bodytype == "static") bodyDef.type = b2_staticBody; else if (bodytype == "dynamic") bodyDef.type = b2_dynamicBody; else if (bodytype == "kinematic") bodyDef.type = b2_kinematicBody; else throw new std::invalid_argument("Unknown box2d type"); bodyDef.position.Set((x + (width / 2.0f)) / pixelsInMeter, (y + (height / 2.0f)) / pixelsInMeter); b2Body* body = config.box2dContainer->world->CreateBody(&bodyDef); std::shared_ptr<b2Shape> shape; if (config.settings.count("polylinePoints")) { auto points = boost::any_cast<std::list<cocos2d::Point>>(config.settings.at("polylinePoints")); shape = initShapeFromPoints(points, pixelsInMeter); } else if (config.settings.count("points") > 0) { auto points = boost::any_cast<std::list<cocos2d::Point>>(config.settings.at("points")); shape = initShapeFromPoints(points, pixelsInMeter, true); } else { shape = initRectangleShape(width, height, pixelsInMeter); } b2FixtureDef fixtureDef; fixtureDef.shape = shape.get(); fixtureDef.isSensor = isSensor; fixtureDef.friction = friction; fixtureDef.restitution = restitution; fixtureDef.density = density; fixtureDef.filter.categoryBits = filterCategory; fixtureDef.filter.maskBits = 0xFFFF; fixtureDef.filter.groupIndex = 0; body->CreateFixture(&fixtureDef); }; } } // namespace loadercallbacks } // namespace physics } // namespace avalon <commit_msg>small re-ordering<commit_after>#include <avalon/physics/loadercallbacks.h> #include <Box2D/Box2D.h> #include <boost/any.hpp> #include <avalon/physics/Box2dContainer.h> namespace { std::shared_ptr<b2PolygonShape> initRectangleShape(float width, float height, float pixelsInMeter) { auto shape = make_shared<b2PolygonShape>(); shape->SetAsBox((width / pixelsInMeter) * 0.5f, (height / pixelsInMeter) * 0.5f); return shape; } std::shared_ptr<b2ChainShape> initChainShape(std::list<cocos2d::Point> points, float pixelsInMeter, bool loop = false) { std::vector<b2Vec2> vecs; vecs.reserve(points.size()); for (auto& p : points) { p = p / pixelsInMeter; vecs.push_back({p.x, -p.y}); } auto shape = make_shared<b2ChainShape>(); if (loop) { shape->CreateLoop(&vecs[0], points.size()); } else { shape->CreateChain(&vecs[0], points.size()); } return shape; } std::shared_ptr<b2EdgeShape> initEdgeShape(cocos2d::Point p1, cocos2d::Point p2, float pixelsInMeter) { p1 = p1 / pixelsInMeter; p2 = p2 / pixelsInMeter; auto shape = make_shared<b2EdgeShape>(); shape->Set({p1.x, p1.y}, {p2.x, p2.y}); return shape; } std::shared_ptr<b2Shape> initShapeFromPoints(const std::list<cocos2d::Point>& points, float pixelsInMeter, bool loop = false) { if (points.size() == 2) { return initEdgeShape(points.front(), points.back(), pixelsInMeter); } else { return initChainShape(points, pixelsInMeter, loop); } } } // namespace namespace avalon { namespace physics { namespace loadercallbacks { avalon::io::TiledMapLoader::Callback createShapes(int filterCategory, bool isSensor) { return [filterCategory, isSensor](const avalon::io::TiledMapLoader::Configuration& config) { float x = boost::any_cast<float>(config.settings.at("x")); float y = boost::any_cast<float>(config.settings.at("y")); float width = boost::any_cast<float>(config.settings.at("width")); float height = boost::any_cast<float>(config.settings.at("height")); float pixelsInMeter = config.box2dContainer->pixelsInMeter; float density = 0.0; float friction = 1.0; float restitution = 0.0; std::string bodytype = "static"; if (config.settings.count("friction")) friction = boost::any_cast<float>(config.settings.at("friction")); if (config.settings.count("density")) density = boost::any_cast<float>(config.settings.at("density")); if (config.settings.count("restitution")) restitution = boost::any_cast<float>(config.settings.at("restitution")); if (config.settings.count("bodytype")) bodytype = boost::any_cast<std::string>(config.settings.at("bodytype")); std::shared_ptr<b2Shape> shape; if (config.settings.count("polylinePoints")) { auto points = boost::any_cast<std::list<cocos2d::Point>>(config.settings.at("polylinePoints")); shape = initShapeFromPoints(points, pixelsInMeter); } else if (config.settings.count("points") > 0) { auto points = boost::any_cast<std::list<cocos2d::Point>>(config.settings.at("points")); shape = initShapeFromPoints(points, pixelsInMeter, true); } else { shape = initRectangleShape(width, height, pixelsInMeter); } b2FixtureDef fixtureDef; fixtureDef.shape = shape.get(); fixtureDef.isSensor = isSensor; fixtureDef.friction = friction; fixtureDef.restitution = restitution; fixtureDef.density = density; fixtureDef.filter.categoryBits = filterCategory; fixtureDef.filter.maskBits = 0xFFFF; fixtureDef.filter.groupIndex = 0; b2BodyDef bodyDef; bodyDef.position.Set((x + (width / 2.0f)) / pixelsInMeter, (y + (height / 2.0f)) / pixelsInMeter); if (bodytype == "static") bodyDef.type = b2_staticBody; else if (bodytype == "dynamic") bodyDef.type = b2_dynamicBody; else if (bodytype == "kinematic") bodyDef.type = b2_kinematicBody; else throw new std::invalid_argument("Unknown box2d type"); auto body = config.box2dContainer->world->CreateBody(&bodyDef); body->CreateFixture(&fixtureDef); }; } } // namespace loadercallbacks } // namespace physics } // namespace avalon <|endoftext|>
<commit_before>/* * This file is part of Handset UX Share user interface * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * Contact: Jukka Tiihonen <jukka.tiihonen@nokia.com> * * 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 "service.h" #include <QDebug> #include <ShareUI/ItemContainer> #include <ShareUI/PluginLoader> #include <QApplication> #include <QTimer> #include <ShareWidgets/UiLoader> Service::Service(QObject *parent) : QObject(parent), m_uiLoader (new ShareWidgets::UiLoader (this)) { } Service::~Service() { qDebug() << "Deleting the service"; } QApplication * Service::loadPluginAndGetApp (int argc, char **argv) { if (!m_uiLoader->loadPlugin (pLoader)) { return 0; } QApplication * app = m_uiLoader->getApplicationPointer (argc, argv); if (pLoader->pluginCount() == 0) { pLoader->setPluginLoadingDelay(100); connect (m_uiLoader, SIGNAL(startLoadingPlugins()), pLoader, SLOT(loadPlugins())); } return app; } void Service::share (const QStringList &fileList) { ShareUI::PluginLoader *pLoader = new ShareUI::PluginLoader (this); ShareUI::ItemContainer * container = new ShareUI::ItemContainer (0, this); if (fileList.count() > 0) { container->appendItems (fileList); } if (!m_uiLoader->showUI (pLoader, container)) { qCritical() << "Share failed: failed to load UI"; QTimer::singleShot (500, this, SLOT (forceShutdownApp())); } } void Service::forceShutdownApp () { QCoreApplication * app = QCoreApplication::instance (); if (app != 0) { qCritical() << "Force shutdown application"; app->quit (); } else { qCritical() << "Failed to force shutdown application!"; } } <commit_msg>Fixed compilation errors<commit_after>/* * This file is part of Handset UX Share user interface * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * Contact: Jukka Tiihonen <jukka.tiihonen@nokia.com> * * 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 "service.h" #include <QDebug> #include <ShareUI/ItemContainer> #include <ShareUI/PluginLoader> #include <QApplication> #include <QTimer> #include <ShareWidgets/UiLoader> Service::Service(QObject *parent) : QObject(parent), m_uiLoader (new ShareWidgets::UiLoader (this)) { } Service::~Service() { qDebug() << "Deleting the service"; } QApplication * Service::loadPluginAndGetApp (int argc, char **argv) { if (!m_uiLoader->loadPlugin ()) { return 0; } QApplication * app = m_uiLoader->getApplicationPointer (argc, argv); return app; } void Service::share (const QStringList &fileList) { ShareUI::PluginLoader *pLoader = new ShareUI::PluginLoader (this); if (pLoader->pluginCount() == 0) { pLoader->setPluginLoadingDelay(100); connect (m_uiLoader, SIGNAL(startLoadingPlugins()), pLoader, SLOT(loadPlugins())); } ShareUI::ItemContainer * container = new ShareUI::ItemContainer (0, this); if (fileList.count() > 0) { container->appendItems (fileList); } if (!m_uiLoader->showUI (pLoader, container)) { qCritical() << "Share failed: failed to load UI"; QTimer::singleShot (500, this, SLOT (forceShutdownApp())); } } void Service::forceShutdownApp () { QCoreApplication * app = QCoreApplication::instance (); if (app != 0) { qCritical() << "Force shutdown application"; app->quit (); } else { qCritical() << "Failed to force shutdown application!"; } } <|endoftext|>
<commit_before> /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "test_precomp.hpp" using namespace cv; using namespace std; void loadImage(string path, Mat &img) { img = imread(path, -1); ASSERT_FALSE(img.empty()) << "Could not load input image " << path; } void checkEqual(Mat img0, Mat img1, double threshold, const string& name) { double max = 1.0; minMaxLoc(abs(img0 - img1), NULL, &max); ASSERT_FALSE(max > threshold) << "max=" << max << " threshold=" << threshold << " method=" << name; } static vector<float> DEFAULT_VECTOR; void loadExposureSeq(String path, vector<Mat>& images, vector<float>& times = DEFAULT_VECTOR) { ifstream list_file((path + "list.txt").c_str()); ASSERT_TRUE(list_file.is_open()); string name; float val; while(list_file >> name >> val) { Mat img = imread(path + name); ASSERT_FALSE(img.empty()) << "Could not load input image " << path + name; images.push_back(img); times.push_back(1 / val); } list_file.close(); } void loadResponseCSV(String path, Mat& response) { response = Mat(256, 1, CV_32FC3); ifstream resp_file(path.c_str()); for(int i = 0; i < 256; i++) { for(int c = 0; c < 3; c++) { resp_file >> response.at<Vec3f>(i)[c]; resp_file.ignore(1); } } resp_file.close(); } TEST(Photo_Tonemap, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/tonemap/"; Mat img, expected, result; loadImage(test_path + "image.hdr", img); float gamma = 2.2f; Ptr<Tonemap> linear = createTonemap(gamma); linear->process(img, result); loadImage(test_path + "linear.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Simple"); Ptr<TonemapDrago> drago = createTonemapDrago(gamma); drago->process(img, result); loadImage(test_path + "drago.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Drago"); Ptr<TonemapDurand> durand = createTonemapDurand(gamma); durand->process(img, result); loadImage(test_path + "durand.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Durand"); Ptr<TonemapReinhard> reinhard = createTonemapReinhard(gamma); reinhard->process(img, result); loadImage(test_path + "reinhard.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Reinhard"); Ptr<TonemapMantiuk> mantiuk = createTonemapMantiuk(gamma); mantiuk->process(img, result); loadImage(test_path + "mantiuk.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Mantiuk"); } TEST(Photo_AlignMTB, regression) { const int TESTS_COUNT = 100; string folder = string(cvtest::TS::ptr()->get_data_path()) + "shared/"; string file_name = folder + "lena.png"; Mat img; loadImage(file_name, img); cvtColor(img, img, COLOR_RGB2GRAY); int max_bits = 5; int max_shift = 32; srand(static_cast<unsigned>(time(0))); int errors = 0; Ptr<AlignMTB> align = createAlignMTB(max_bits); for(int i = 0; i < TESTS_COUNT; i++) { Point shift(rand() % max_shift, rand() % max_shift); Mat res; align->shiftMat(img, res, shift); Point calc = align->calculateShift(img, res); errors += (calc != -shift); } ASSERT_TRUE(errors < 5) << errors << " errors"; } TEST(Photo_MergeMertens, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; loadExposureSeq((test_path + "exposures/").c_str() , images); Ptr<MergeMertens> merge = createMergeMertens(); Mat result, expected; loadImage(test_path + "merge/mertens.png", expected); merge->process(images, result); result.convertTo(result, CV_8UC3, 255); checkEqual(expected, result, 3, "Mertens"); Mat uniform(100, 100, CV_8UC3); uniform = Scalar(0, 255, 0); images.clear(); images.push_back(uniform); merge->process(images, result); result.convertTo(result, CV_8UC3, 255); checkEqual(uniform, result, 1e-2f, "Mertens"); } TEST(Photo_MergeDebevec, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; vector<float> times; Mat response; loadExposureSeq(test_path + "exposures/", images, times); loadResponseCSV(test_path + "exposures/response.csv", response); Ptr<MergeDebevec> merge = createMergeDebevec(); Mat result, expected; loadImage(test_path + "merge/debevec.hdr", expected); merge->process(images, result, times, response); Ptr<Tonemap> map = createTonemap(); map->process(result, result); map->process(expected, expected); checkEqual(expected, result, 1e-2f, "Debevec"); } TEST(Photo_MergeRobertson, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; vector<float> times; loadExposureSeq(test_path + "exposures/", images, times); Ptr<MergeRobertson> merge = createMergeRobertson(); Mat result, expected; loadImage(test_path + "merge/robertson.hdr", expected); merge->process(images, result, times); checkEqual(expected, result, 5.f, "MergeRobertson"); } TEST(Photo_CalibrateDebevec, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; vector<float> times; Mat response, expected; loadExposureSeq(test_path + "exposures/", images, times); loadResponseCSV(test_path + "calibrate/debevec.csv", expected); Ptr<CalibrateDebevec> calibrate = createCalibrateDebevec(); calibrate->process(images, response, times); Mat diff = abs(response - expected); diff = diff.mul(1.0f / response); double max; minMaxLoc(diff, NULL, &max); ASSERT_FALSE(max > 0.1); } TEST(Photo_CalibrateRobertson, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; vector<float> times; Mat response, expected; loadExposureSeq(test_path + "exposures/", images, times); loadResponseCSV(test_path + "calibrate/robertson.csv", expected); Ptr<CalibrateRobertson> calibrate = createCalibrateRobertson(); calibrate->process(images, response, times); checkEqual(expected, response, 1e-1f, "CalibrateRobertson"); } <commit_msg>photo(test): fix MergeRobertson test for AARCH64 build<commit_after> /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "test_precomp.hpp" using namespace cv; using namespace std; void loadImage(string path, Mat &img) { img = imread(path, -1); ASSERT_FALSE(img.empty()) << "Could not load input image " << path; } void checkEqual(Mat img0, Mat img1, double threshold, const string& name) { double max = 1.0; minMaxLoc(abs(img0 - img1), NULL, &max); ASSERT_FALSE(max > threshold) << "max=" << max << " threshold=" << threshold << " method=" << name; } static vector<float> DEFAULT_VECTOR; void loadExposureSeq(String path, vector<Mat>& images, vector<float>& times = DEFAULT_VECTOR) { ifstream list_file((path + "list.txt").c_str()); ASSERT_TRUE(list_file.is_open()); string name; float val; while(list_file >> name >> val) { Mat img = imread(path + name); ASSERT_FALSE(img.empty()) << "Could not load input image " << path + name; images.push_back(img); times.push_back(1 / val); } list_file.close(); } void loadResponseCSV(String path, Mat& response) { response = Mat(256, 1, CV_32FC3); ifstream resp_file(path.c_str()); for(int i = 0; i < 256; i++) { for(int c = 0; c < 3; c++) { resp_file >> response.at<Vec3f>(i)[c]; resp_file.ignore(1); } } resp_file.close(); } TEST(Photo_Tonemap, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/tonemap/"; Mat img, expected, result; loadImage(test_path + "image.hdr", img); float gamma = 2.2f; Ptr<Tonemap> linear = createTonemap(gamma); linear->process(img, result); loadImage(test_path + "linear.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Simple"); Ptr<TonemapDrago> drago = createTonemapDrago(gamma); drago->process(img, result); loadImage(test_path + "drago.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Drago"); Ptr<TonemapDurand> durand = createTonemapDurand(gamma); durand->process(img, result); loadImage(test_path + "durand.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Durand"); Ptr<TonemapReinhard> reinhard = createTonemapReinhard(gamma); reinhard->process(img, result); loadImage(test_path + "reinhard.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Reinhard"); Ptr<TonemapMantiuk> mantiuk = createTonemapMantiuk(gamma); mantiuk->process(img, result); loadImage(test_path + "mantiuk.png", expected); result.convertTo(result, CV_8UC3, 255); checkEqual(result, expected, 3, "Mantiuk"); } TEST(Photo_AlignMTB, regression) { const int TESTS_COUNT = 100; string folder = string(cvtest::TS::ptr()->get_data_path()) + "shared/"; string file_name = folder + "lena.png"; Mat img; loadImage(file_name, img); cvtColor(img, img, COLOR_RGB2GRAY); int max_bits = 5; int max_shift = 32; srand(static_cast<unsigned>(time(0))); int errors = 0; Ptr<AlignMTB> align = createAlignMTB(max_bits); for(int i = 0; i < TESTS_COUNT; i++) { Point shift(rand() % max_shift, rand() % max_shift); Mat res; align->shiftMat(img, res, shift); Point calc = align->calculateShift(img, res); errors += (calc != -shift); } ASSERT_TRUE(errors < 5) << errors << " errors"; } TEST(Photo_MergeMertens, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; loadExposureSeq((test_path + "exposures/").c_str() , images); Ptr<MergeMertens> merge = createMergeMertens(); Mat result, expected; loadImage(test_path + "merge/mertens.png", expected); merge->process(images, result); result.convertTo(result, CV_8UC3, 255); checkEqual(expected, result, 3, "Mertens"); Mat uniform(100, 100, CV_8UC3); uniform = Scalar(0, 255, 0); images.clear(); images.push_back(uniform); merge->process(images, result); result.convertTo(result, CV_8UC3, 255); checkEqual(uniform, result, 1e-2f, "Mertens"); } TEST(Photo_MergeDebevec, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; vector<float> times; Mat response; loadExposureSeq(test_path + "exposures/", images, times); loadResponseCSV(test_path + "exposures/response.csv", response); Ptr<MergeDebevec> merge = createMergeDebevec(); Mat result, expected; loadImage(test_path + "merge/debevec.hdr", expected); merge->process(images, result, times, response); Ptr<Tonemap> map = createTonemap(); map->process(result, result); map->process(expected, expected); checkEqual(expected, result, 1e-2f, "Debevec"); } TEST(Photo_MergeRobertson, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; vector<float> times; loadExposureSeq(test_path + "exposures/", images, times); Ptr<MergeRobertson> merge = createMergeRobertson(); Mat result, expected; loadImage(test_path + "merge/robertson.hdr", expected); merge->process(images, result, times); #ifdef __aarch64__ const float eps = 6.f; #else const float eps = 5.f; #endif checkEqual(expected, result, eps, "MergeRobertson"); } TEST(Photo_CalibrateDebevec, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; vector<float> times; Mat response, expected; loadExposureSeq(test_path + "exposures/", images, times); loadResponseCSV(test_path + "calibrate/debevec.csv", expected); Ptr<CalibrateDebevec> calibrate = createCalibrateDebevec(); calibrate->process(images, response, times); Mat diff = abs(response - expected); diff = diff.mul(1.0f / response); double max; minMaxLoc(diff, NULL, &max); ASSERT_FALSE(max > 0.1); } TEST(Photo_CalibrateRobertson, regression) { string test_path = string(cvtest::TS::ptr()->get_data_path()) + "hdr/"; vector<Mat> images; vector<float> times; Mat response, expected; loadExposureSeq(test_path + "exposures/", images, times); loadResponseCSV(test_path + "calibrate/robertson.csv", expected); Ptr<CalibrateRobertson> calibrate = createCalibrateRobertson(); calibrate->process(images, response, times); checkEqual(expected, response, 1e-1f, "CalibrateRobertson"); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "rpcserver.h" #include "init.h" #include "main.h" #include "sync.h" #include "wallet.h" #include <fstream> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string &str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"bitcoinprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"bitcoinprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional) an optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a json rpc call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false") ); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"") ); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"bitcoinaddress\"\n" "\nReveals the private key corresponding to 'bitcoinaddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"bitcoinaddress\" (string, required) The bitcoin address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"") ); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"") ); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Bitcoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <commit_msg>Fix importwallet nTimeFirstKey<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "rpcserver.h" #include "init.h" #include "main.h" #include "sync.h" #include "wallet.h" #include <fstream> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string &str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"bitcoinprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"bitcoinprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional) an optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a json rpc call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false") ); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"") ); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"bitcoinaddress\"\n" "\nReveals the private key corresponding to 'bitcoinaddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"bitcoinaddress\" (string, required) The bitcoin address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"") ); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"") ); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Bitcoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/test/ui/ui_layout_test.h" namespace { const char* kResources[] = { "content", "media-file.js", "video-test.js", }; } // anonymous namespace class AudioUILayoutTest : public UILayoutTest { protected: virtual ~AudioUILayoutTest() { } void RunMediaLayoutTest(const std::string& test_case_file_name) { 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])); } printf("Test: %s\n", test_case_file_name.c_str()); RunLayoutTest(test_case_file_name, kNoHttpPort); } }; TEST_F(AudioUILayoutTest, AudioConstructorPreload) { RunMediaLayoutTest("audio-constructor-preload.html"); } TEST_F(AudioUILayoutTest, AudioConstructor) { RunMediaLayoutTest("audio-constructor.html"); } TEST_F(AudioUILayoutTest, AudioConstructorSrc) { RunMediaLayoutTest("audio-constructor-src.html"); } TEST_F(AudioUILayoutTest, AudioDataUrl) { RunMediaLayoutTest("audio-data-url.html"); } // The test fails since there is no real audio device on the build bots to get // the ended event fired. Should pass once we run it on bots with audio devices. TEST_F(AudioUILayoutTest, DISABLED_AudioGarbageCollect) { RunMediaLayoutTest("audio-garbage-collect.html"); } TEST_F(AudioUILayoutTest, AudioNoInstalledEngines) { RunMediaLayoutTest("audio-no-installed-engines.html"); } TEST_F(AudioUILayoutTest, AudioOnlyVideoIntrinsicSize) { RunMediaLayoutTest("audio-only-video-intrinsic-size.html"); } TEST_F(AudioUILayoutTest, AudioPlayEvent) { RunMediaLayoutTest("audio-play-event.html"); } TEST_F(AudioUILayoutTest, MediaCanPlayWavAudio) { RunMediaLayoutTest("media-can-play-wav-audio.html"); } TEST_F(AudioUILayoutTest, MediaDocumentAudioSize) { RunMediaLayoutTest("media-document-audio-size.html"); } <commit_msg>Mark AudioUILayoutTest.AudioOnlyVideoIntrinsicSize test flaky.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/test/ui/ui_layout_test.h" namespace { const char* kResources[] = { "content", "media-file.js", "video-test.js", }; } // anonymous namespace class AudioUILayoutTest : public UILayoutTest { protected: virtual ~AudioUILayoutTest() { } void RunMediaLayoutTest(const std::string& test_case_file_name) { 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])); } printf("Test: %s\n", test_case_file_name.c_str()); RunLayoutTest(test_case_file_name, kNoHttpPort); } }; TEST_F(AudioUILayoutTest, AudioConstructorPreload) { RunMediaLayoutTest("audio-constructor-preload.html"); } TEST_F(AudioUILayoutTest, AudioConstructor) { RunMediaLayoutTest("audio-constructor.html"); } TEST_F(AudioUILayoutTest, AudioConstructorSrc) { RunMediaLayoutTest("audio-constructor-src.html"); } TEST_F(AudioUILayoutTest, AudioDataUrl) { RunMediaLayoutTest("audio-data-url.html"); } // The test fails since there is no real audio device on the build bots to get // the ended event fired. Should pass once we run it on bots with audio devices. TEST_F(AudioUILayoutTest, DISABLED_AudioGarbageCollect) { RunMediaLayoutTest("audio-garbage-collect.html"); } TEST_F(AudioUILayoutTest, AudioNoInstalledEngines) { RunMediaLayoutTest("audio-no-installed-engines.html"); } #if defined(OS_CHROMEOS) && defined(USE_AURA) // http://crbug.com/115530 #define MAYBE_AudioOnlyVideoIntrinsicSize FLAKY_AudioOnlyVideoIntrinsicSize #else #define MAYBE_AudioOnlyVideoIntrinsicSize AudioOnlyVideoIntrinsicSize #endif TEST_F(AudioUILayoutTest, MAYBE_AudioOnlyVideoIntrinsicSize) { RunMediaLayoutTest("audio-only-video-intrinsic-size.html"); } TEST_F(AudioUILayoutTest, AudioPlayEvent) { RunMediaLayoutTest("audio-play-event.html"); } TEST_F(AudioUILayoutTest, MediaCanPlayWavAudio) { RunMediaLayoutTest("media-can-play-wav-audio.html"); } TEST_F(AudioUILayoutTest, MediaDocumentAudioSize) { RunMediaLayoutTest("media-document-audio-size.html"); } <|endoftext|>
<commit_before>#ifndef GE_ACTOR_TICKER_SUBSYSTEM_HPP #define GE_ACTOR_TICKER_SUBSYSTEM_HPP #pragma once #include "ge/subsystem.hpp" #include "ge/tickable.hpp" namespace ge { struct actor_ticker_subsystem : subsystem { struct config { }; bool initialize(config){}; virtual bool update(std::chrono::duration<float> delta) override { m_runtime->get_root_actor()->propagate_to_children([delta](actor& act) { if (act.implements_interface<tickable>()) { act.get_interface_storage<tickable>()->tickfunc(delta); } }); } }; } #endif // GE_ACTOR_TICKER_SUBSYSTEM_HPP <commit_msg>Fix build error<commit_after>#ifndef GE_ACTOR_TICKER_SUBSYSTEM_HPP #define GE_ACTOR_TICKER_SUBSYSTEM_HPP #pragma once #include "ge/subsystem.hpp" #include "ge/tickable.hpp" #include "ge/runtime.hpp" namespace ge { struct actor_ticker_subsystem : subsystem { struct config { }; bool initialize(config){}; virtual bool update(std::chrono::duration<float> delta) override { m_runtime->get_root_actor()->propagate_to_children([delta](actor& act) { if (act.implements_interface<tickable>()) { act.get_interface_storage<tickable>()->tickfunc(delta); } }); } }; } #endif // GE_ACTOR_TICKER_SUBSYSTEM_HPP <|endoftext|>
<commit_before> #include <test.hpp> TEST_CASE("basic") { SECTION("default constructed pbf message is okay") { mapbox::util::pbf item; REQUIRE(!item.next()); } SECTION("empty buffer is okay") { std::string buffer; mapbox::util::pbf item(buffer.data(), 0); REQUIRE(!item.next()); } SECTION("check every possible value for single byte in buffer") { char buffer[1]; for (int i = 0; i <= 255; ++i) { *buffer = static_cast<char>(i); mapbox::util::pbf item(buffer, 1); REQUIRE_THROWS({ item.next(); item.skip(); }); } } } <commit_msg>Add tests for operator bool().<commit_after> #include <test.hpp> TEST_CASE("basic") { SECTION("default constructed pbf message is okay") { mapbox::util::pbf item; REQUIRE(!item.next()); } SECTION("empty buffer is okay") { std::string buffer; mapbox::util::pbf item(buffer.data(), 0); REQUIRE(!item); // test operator bool() REQUIRE(!item.next()); } SECTION("check every possible value for single byte in buffer") { char buffer[1]; for (int i = 0; i <= 255; ++i) { *buffer = static_cast<char>(i); mapbox::util::pbf item(buffer, 1); REQUIRE(!!item); // test operator bool() REQUIRE_THROWS({ item.next(); item.skip(); }); } } } <|endoftext|>
<commit_before><commit_msg>Drop useless const<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TransformerTokenMap.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:59:34 $ * * 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 _XMLOFF_TRANSFORMERTOKENMAPS_HXX #define _XMLOFF_TRANSFORMERTOKENMAPS_HXX #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #include <hash_map> #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_TRANSFORMERTOKENMAP_HXX #include "TransformerTokenMap.hxx" #endif class XMLTransformerTokenMap : public ::std::hash_map< ::rtl::OUString, ::xmloff::token::XMLTokenEnum, ::rtl::OUStringHash, ::comphelper::UStringEqual > { public: XMLTransformerTokenMap( ::xmloff::token::XMLTokenEnum *pInit ); ~XMLTransformerTokenMap(); }; #endif // _XMLOFF_TRANSFORMERTOKENMAPS_HXX <commit_msg>INTEGRATION: CWS vgbugs07 (1.3.276); FILE MERGED 2007/06/04 13:23:46 vg 1.3.276.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TransformerTokenMap.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2007-06-27 16:26:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_TRANSFORMERTOKENMAPS_HXX #define _XMLOFF_TRANSFORMERTOKENMAPS_HXX #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #include <hash_map> #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_TRANSFORMERTOKENMAP_HXX #include "TransformerTokenMap.hxx" #endif class XMLTransformerTokenMap : public ::std::hash_map< ::rtl::OUString, ::xmloff::token::XMLTokenEnum, ::rtl::OUStringHash, ::comphelper::UStringEqual > { public: XMLTransformerTokenMap( ::xmloff::token::XMLTokenEnum *pInit ); ~XMLTransformerTokenMap(); }; #endif // _XMLOFF_TRANSFORMERTOKENMAPS_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmllib_export.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: ab $ $Date: 2001-10-23 15:25:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <xmlscript/xmllib_imexp.hxx> #include <xmlscript/xml_helper.hxx> using namespace com::sun::star::uno; using namespace com::sun::star; using namespace rtl; namespace xmlscript { //################################################################################################## //================================================================================================== SAL_DLLEXPORT void SAL_CALL exportLibraryContainer( Reference< xml::sax::XExtendedDocumentHandler > const & xOut, const LibDescriptorArray* pLibArray ) SAL_THROW( (Exception) ) { xOut->startDocument(); OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM( "<!DOCTYPE library:libraries PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\"" " \"libraries.dtd\">" ) ); xOut->unknown( aDocTypeStr ); xOut->ignorableWhitespace( OUString() ); OUString aLibrariesName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":libraries") ); XMLElement* pLibsElement = new XMLElement( aLibrariesName ); Reference< xml::sax::XAttributeList > xAttributes( pLibsElement ); pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ), OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) ); pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_XLINK_PREFIX) ), OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_URI) ) ); xOut->ignorableWhitespace( OUString() ); xOut->startElement( aLibrariesName, xAttributes ); OUString aTrueStr ( RTL_CONSTASCII_USTRINGPARAM("true") ); OUString aFalseStr( RTL_CONSTASCII_USTRINGPARAM("false") ); int nLibCount = pLibArray->mnLibCount; for( sal_Int32 i = 0 ; i < nLibCount ; i++ ) { LibDescriptor& rLib = pLibArray->mpLibs[i]; OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") ); XMLElement* pLibElement = new XMLElement( aLibraryName ); Reference< xml::sax::XAttributeList > xLibElementAttribs; xLibElementAttribs = static_cast< xml::sax::XAttributeList* >( pLibElement ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ), rLib.aName ); if( rLib.bLink && rLib.aStorageURL.getLength() ) { pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":href") ), rLib.aStorageURL ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":type") ), OUString( RTL_CONSTASCII_USTRINGPARAM("simple") ) ); } pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":link") ), rLib.bLink ? aTrueStr : aFalseStr ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":readonly") ), rLib.bReadOnly ? aTrueStr : aFalseStr ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":passwordprotected") ), rLib.bPasswordProtected ? aTrueStr : aFalseStr ); sal_Int32 nElementCount = rLib.aElementNames.getLength(); if( nElementCount ) { const OUString* pElementNames = rLib.aElementNames.getConstArray(); for( sal_Int32 i = 0 ; i < nElementCount ; i++ ) { XMLElement* pElement = new XMLElement( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":element" ) ) ); Reference< xml::sax::XAttributeList > xElementAttribs; xElementAttribs = static_cast< xml::sax::XAttributeList* >( pElement ); pElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ), pElementNames[i] ); pLibElement->addSubElement( pElement ); } } pLibElement->dump( xOut ); } xOut->ignorableWhitespace( OUString() ); xOut->endElement( aLibrariesName ); xOut->endDocument(); } }; <commit_msg>#86383# Export for new library index files<commit_after>/************************************************************************* * * $RCSfile: xmllib_export.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ab $ $Date: 2001-11-07 18:21:04 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <xmlscript/xmllib_imexp.hxx> #include <xmlscript/xml_helper.hxx> using namespace com::sun::star::uno; using namespace com::sun::star; using namespace rtl; namespace xmlscript { static OUString aTrueStr ( RTL_CONSTASCII_USTRINGPARAM("true") ); static OUString aFalseStr( RTL_CONSTASCII_USTRINGPARAM("false") ); //################################################################################################## //================================================================================================== SAL_DLLEXPORT void SAL_CALL exportLibraryContainer( Reference< xml::sax::XExtendedDocumentHandler > const & xOut, const LibDescriptorArray* pLibArray ) SAL_THROW( (Exception) ) { xOut->startDocument(); OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM( "<!DOCTYPE library:libraries PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\"" " \"libraries.dtd\">" ) ); xOut->unknown( aDocTypeStr ); xOut->ignorableWhitespace( OUString() ); OUString aLibrariesName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":libraries") ); XMLElement* pLibsElement = new XMLElement( aLibrariesName ); Reference< xml::sax::XAttributeList > xAttributes( pLibsElement ); pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ), OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) ); pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_XLINK_PREFIX) ), OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_URI) ) ); xOut->ignorableWhitespace( OUString() ); xOut->startElement( aLibrariesName, xAttributes ); int nLibCount = pLibArray->mnLibCount; for( sal_Int32 i = 0 ; i < nLibCount ; i++ ) { LibDescriptor& rLib = pLibArray->mpLibs[i]; OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") ); XMLElement* pLibElement = new XMLElement( aLibraryName ); Reference< xml::sax::XAttributeList > xLibElementAttribs; xLibElementAttribs = static_cast< xml::sax::XAttributeList* >( pLibElement ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ), rLib.aName ); if( rLib.aStorageURL.getLength() ) { pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":href") ), rLib.aStorageURL ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":type") ), OUString( RTL_CONSTASCII_USTRINGPARAM("simple") ) ); } pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":link") ), rLib.bLink ? aTrueStr : aFalseStr ); pLibElement->dump( xOut ); } xOut->ignorableWhitespace( OUString() ); xOut->endElement( aLibrariesName ); xOut->endDocument(); } //================================================================================================== SAL_DLLEXPORT void SAL_CALL exportLibrary( ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XExtendedDocumentHandler > const & xOut, const LibDescriptor& rLib ) SAL_THROW( (::com::sun::star::uno::Exception) ) { xOut->startDocument(); OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM( "<!DOCTYPE library:library PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\"" " \"library.dtd\">" ) ); xOut->unknown( aDocTypeStr ); xOut->ignorableWhitespace( OUString() ); OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") ); XMLElement* pLibElement = new XMLElement( aLibraryName ); Reference< xml::sax::XAttributeList > xAttributes( pLibElement ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ), OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ), rLib.aName ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":readonly") ), rLib.bReadOnly ? aTrueStr : aFalseStr ); pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":passwordprotected") ), rLib.bPasswordProtected ? aTrueStr : aFalseStr ); sal_Int32 nElementCount = rLib.aElementNames.getLength(); if( nElementCount ) { const OUString* pElementNames = rLib.aElementNames.getConstArray(); for( sal_Int32 i = 0 ; i < nElementCount ; i++ ) { XMLElement* pElement = new XMLElement( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":element" ) ) ); Reference< xml::sax::XAttributeList > xElementAttribs; xElementAttribs = static_cast< xml::sax::XAttributeList* >( pElement ); pElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ), pElementNames[i] ); pLibElement->addSubElement( pElement ); } } pLibElement->dump( xOut ); xOut->endDocument(); } }; <|endoftext|>
<commit_before>#pragma once #include "Runtime/IOStreams.hpp" #include "Runtime/Character/CPASAnimParm.hpp" namespace urde { class CPASParmInfo { public: enum class EWeightFunction { ExactMatch, PercentError, AngularPercent, NoWeight }; CPASAnimParm::EParmType x0_type; EWeightFunction x4_weightFunction; float x8_weight; CPASAnimParm::UParmValue xc_min; CPASAnimParm::UParmValue x10_max; public: explicit CPASParmInfo(CInputStream& in); CPASAnimParm::EParmType GetParameterType() const { return x0_type; } EWeightFunction GetWeightFunction() const { return x4_weightFunction; } float GetParameterWeight() const { return x8_weight; } CPASAnimParm::UParmValue GetWeightMinValue() const { return xc_min; } CPASAnimParm::UParmValue GetWeightMaxValue() const { return x10_max; } }; } // namespace urde <commit_msg>CPASParmInfo: Make data members private<commit_after>#pragma once #include "Runtime/IOStreams.hpp" #include "Runtime/Character/CPASAnimParm.hpp" namespace urde { class CPASParmInfo { public: enum class EWeightFunction { ExactMatch, PercentError, AngularPercent, NoWeight }; private: CPASAnimParm::EParmType x0_type; EWeightFunction x4_weightFunction; float x8_weight; CPASAnimParm::UParmValue xc_min; CPASAnimParm::UParmValue x10_max; public: explicit CPASParmInfo(CInputStream& in); CPASAnimParm::EParmType GetParameterType() const { return x0_type; } EWeightFunction GetWeightFunction() const { return x4_weightFunction; } float GetParameterWeight() const { return x8_weight; } CPASAnimParm::UParmValue GetWeightMinValue() const { return xc_min; } CPASAnimParm::UParmValue GetWeightMaxValue() const { return x10_max; } }; } // namespace urde <|endoftext|>
<commit_before>#include <iostream> #include "tinysplinecpp.h" int main( int argc, char** argv ) { try { // t variable float t = 0.0f; // Create a clamped spline of degree 3 in 2D consisting of 7 control points. ts::BSpline spline(3, 2, 7, TS_CLAMPED); // Setup the control points. std::vector<float> ctrlp = spline.ctrlp(); ctrlp[0] = -1.75f; // x0 ctrlp[1] = -1.0f; // y0 ctrlp[2] = -1.5f; // x1 ctrlp[3] = -0.5f; // y1 ctrlp[4] = -1.5f; // x2 ctrlp[5] = 0.0f; // y2 ctrlp[6] = -1.25f; // x3 ctrlp[7] = 0.5f; // y3 ctrlp[8] = -0.75f; // x4 ctrlp[9] = 0.75f; // y4 ctrlp[10] = 0.0f; // x5 ctrlp[11] = 0.5f; // y5 ctrlp[12] = 0.5f; // x6 ctrlp[13] = 0.0f; // y6 spline.setCtrlp(ctrlp); // Evaluate `spline` at t = 0.4 t = 0.4f; std::vector<float> result = spline.evaluate(t).result(); std::cout << "evaluate spline at t=" << t << ": (" << result[0] << ", " << result[1] << ")" << std::endl; // Derive `spline` and subdivide it into a sequence of Bezier curves. ts::BSpline beziers = spline.derive().toBeziers(); // Evaluate `beziers` at t = 0.3 t = 0.3f; result = beziers(t).result(); // you can use '()' instead of 'evaluate' std::cout << "evaluate beziers at t=" << t << ": (" << result[0] << ", " << result[1] << ")" << std::endl; } catch(std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; } } <commit_msg>use ts::rational in C++ example<commit_after>#include <iostream> #include "tinysplinecpp.h" int main( int argc, char** argv ) { try { // t variable ts::rational t = 0.0f; // Create a clamped spline of degree 3 in 2D consisting of 7 control points. ts::BSpline spline(3, 2, 7, TS_CLAMPED); // Setup the control points. std::vector<ts::rational> ctrlp = spline.ctrlp(); ctrlp[0] = -1.75f; // x0 ctrlp[1] = -1.0f; // y0 ctrlp[2] = -1.5f; // x1 ctrlp[3] = -0.5f; // y1 ctrlp[4] = -1.5f; // x2 ctrlp[5] = 0.0f; // y2 ctrlp[6] = -1.25f; // x3 ctrlp[7] = 0.5f; // y3 ctrlp[8] = -0.75f; // x4 ctrlp[9] = 0.75f; // y4 ctrlp[10] = 0.0f; // x5 ctrlp[11] = 0.5f; // y5 ctrlp[12] = 0.5f; // x6 ctrlp[13] = 0.0f; // y6 spline.setCtrlp(ctrlp); // Evaluate `spline` at t = 0.4 t = 0.4f; std::vector<ts::rational> result = spline.evaluate(t).result(); std::cout << "evaluate spline at t=" << t << ": (" << result[0] << ", " << result[1] << ")" << std::endl; // Derive `spline` and subdivide it into a sequence of Bezier curves. ts::BSpline beziers = spline.derive().toBeziers(); // Evaluate `beziers` at t = 0.3 t = 0.3f; result = beziers(t).result(); // you can use '()' instead of 'evaluate' std::cout << "evaluate beziers at t=" << t << ": (" << result[0] << ", " << result[1] << ")" << std::endl; } catch(std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; } } <|endoftext|>
<commit_before>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2006 Refractions Research Inc. * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: noding/SegmentNodeList.java rev. 1.8 (JTS-1.10) * **********************************************************************/ #include <cassert> #include <set> #include <algorithm> #include <geos/profiler.h> #include <geos/util.h> #include <geos/util/GEOSException.h> #include <geos/noding/SegmentNodeList.h> #include <geos/noding/NodedSegmentString.h> #include <geos/noding/SegmentString.h> // for use #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/CoordinateArraySequence.h> // FIXME: should we really be using this ? #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif #ifdef GEOS_DEBUG #include <iostream> #endif // using namespace geos::geom; namespace geos { namespace noding { // geos.noding #if PROFILE static Profiler* profiler = Profiler::instance(); #endif void SegmentNodeList::add(const Coordinate& intPt, std::size_t segmentIndex) { SegmentNode sn(edge, intPt, segmentIndex, edge.getSegmentOctant(segmentIndex)); nodeMap.push_back(sn); ready = false; } void SegmentNodeList::prepare() const { if (!ready) { std::sort(nodeMap.begin(), nodeMap.end(), [](const SegmentNode& s1, const SegmentNode& s2) { return s1.compareTo(s2) < 0; }); nodeMap.erase(std::unique(nodeMap.begin(), nodeMap.end(), [](const SegmentNode& s1, const SegmentNode& s2) { return s1.compareTo(s2) == 0; }), nodeMap.end()); ready = true; } } void SegmentNodeList::addEndpoints() { std::size_t maxSegIndex = edge.size() - 1; add(&(edge.getCoordinate(0)), 0); add(&(edge.getCoordinate(maxSegIndex)), maxSegIndex); } /* private */ void SegmentNodeList::addCollapsedNodes() { std::vector<size_t> collapsedVertexIndexes; findCollapsesFromInsertedNodes(collapsedVertexIndexes); findCollapsesFromExistingVertices(collapsedVertexIndexes); // node the collapses for(std::size_t vertexIndex : collapsedVertexIndexes) { add(edge.getCoordinate(vertexIndex), vertexIndex); } } /* private */ void SegmentNodeList::findCollapsesFromExistingVertices( std::vector<size_t>& collapsedVertexIndexes) const { if(edge.size() < 2) { return; // or we'll never exit the loop below } for(std::size_t i = 0, n = edge.size() - 2; i < n; ++i) { const Coordinate& p0 = edge.getCoordinate(i); const Coordinate& p2 = edge.getCoordinate(i + 2); if(p0.equals2D(p2)) { // add base of collapse as node collapsedVertexIndexes.push_back(i + 1); } } } /* private */ void SegmentNodeList::findCollapsesFromInsertedNodes( std::vector<size_t>& collapsedVertexIndexes) const { std::size_t collapsedVertexIndex; // there should always be at least two entries in the list, // since the endpoints are nodes auto it = begin(); const SegmentNode* eiPrev = &(*it); ++it; for(auto itEnd = end(); it != itEnd; ++it) { const SegmentNode* ei = &(*it); bool isCollapsed = findCollapseIndex(*eiPrev, *ei, collapsedVertexIndex); if(isCollapsed) { collapsedVertexIndexes.push_back(collapsedVertexIndex); } eiPrev = ei; } } /* private */ bool SegmentNodeList::findCollapseIndex(const SegmentNode& ei0, const SegmentNode& ei1, size_t& collapsedVertexIndex) { assert(ei1.segmentIndex >= ei0.segmentIndex); // only looking for equal nodes if(! ei0.coord.equals2D(ei1.coord)) { return false; } auto numVerticesBetween = ei1.segmentIndex - ei0.segmentIndex; if(! ei1.isInterior()) { numVerticesBetween--; } // if there is a single vertex between the two equal nodes, // this is a collapse if(numVerticesBetween == 1) { collapsedVertexIndex = ei0.segmentIndex + 1; return true; } return false; } /* public */ void SegmentNodeList::addSplitEdges(std::vector<SegmentString*>& edgeList) { // testingOnly #if GEOS_DEBUG std::cerr << __FUNCTION__ << " entered" << std::endl; std::vector<SegmentString*> testingSplitEdges; #endif // ensure that the list has entries for the first and last // point of the edge addEndpoints(); addCollapsedNodes(); // there should always be at least two entries in the list // since the endpoints are nodes auto it = begin(); const SegmentNode* eiPrev = &(*it); assert(eiPrev); ++it; for(auto itEnd = end(); it != itEnd; ++it) { const SegmentNode* ei = &(*it); assert(ei); if(! ei->compareTo(*eiPrev)) { continue; } std::unique_ptr<SegmentString> newEdge = createSplitEdge(eiPrev, ei); edgeList.push_back(newEdge.release()); #if GEOS_DEBUG testingSplitEdges.push_back(newEdge); #endif eiPrev = ei; } #if GEOS_DEBUG std::cerr << __FUNCTION__ << " finished, now checking correctness" << std::endl; checkSplitEdgesCorrectness(testingSplitEdges); #endif } /*private*/ void SegmentNodeList::checkSplitEdgesCorrectness(const std::vector<SegmentString*>& splitEdges) const { const CoordinateSequence* edgePts = edge.getCoordinates(); assert(edgePts); // check that first and last points of split edges // are same as endpoints of edge SegmentString* split0 = splitEdges[0]; assert(split0); const Coordinate& pt0 = split0->getCoordinate(0); if(!(pt0 == edgePts->getAt(0))) { throw util::GEOSException("bad split edge start point at " + pt0.toString()); } SegmentString* splitn = splitEdges[splitEdges.size() - 1]; assert(splitn); const CoordinateSequence* splitnPts = splitn->getCoordinates(); assert(splitnPts); const Coordinate& ptn = splitnPts->getAt(splitnPts->getSize() - 1); if(!(ptn == edgePts->getAt(edgePts->getSize() - 1))) { throw util::GEOSException("bad split edge end point at " + ptn.toString()); } } /*private*/ std::unique_ptr<SegmentString> SegmentNodeList::createSplitEdge(const SegmentNode* ei0, const SegmentNode* ei1) const { std::vector<Coordinate> pts; createSplitEdgePts(ei0, ei1, pts); return detail::make_unique<NodedSegmentString>(new CoordinateArraySequence(std::move(pts)), edge.getData()); } /*private*/ void SegmentNodeList::createSplitEdgePts(const SegmentNode* ei0, const SegmentNode* ei1, std::vector<Coordinate>& pts) const { //int npts = ei1->segmentIndex - (ei0->segmentIndex + 2); bool twoPoints = (ei1->segmentIndex == ei0->segmentIndex); // if only two points in split edge they must be the node points if (twoPoints) { pts.emplace_back(ei0->coord); pts.emplace_back(ei1->coord); return; } const Coordinate& lastSegStartPt = edge.getCoordinate(ei1->segmentIndex); /** * If the last intersection point is not equal to the its segment start pt, * add it to the points list as well. * This check is needed because the distance metric is not totally reliable! * Also ensure that the created edge always has at least 2 points. * The check for point equality is 2D only - Z values are ignored */ bool useIntPt1 = ei1->isInterior() || ! ei1->coord.equals2D(lastSegStartPt); //if (!useIntPt1) { // npts--; //} pts.emplace_back(ei0->coord); for (std::size_t i = ei0->segmentIndex + 1; i <= ei1->segmentIndex; i++) { pts.emplace_back(edge.getCoordinate(i)); } if (useIntPt1) { pts.emplace_back(ei1->coord); } } /*public*/ std::vector<Coordinate> SegmentNodeList::getSplitCoordinates() { // ensure that the list has entries for the first and last point of the edge addEndpoints(); std::vector<Coordinate> coordList; // there should always be at least two entries in the list, since the endpoints are nodes auto it = begin(); const SegmentNode* eiPrev = &(*it); for(auto itEnd = end(); it != itEnd; ++it) { const SegmentNode* ei = &(*it); addEdgeCoordinates(eiPrev, ei, coordList); eiPrev = ei; } return coordList; } /*private*/ void SegmentNodeList::addEdgeCoordinates(const SegmentNode* ei0, const SegmentNode* ei1, std::vector<Coordinate>& coordList) const { std::vector<Coordinate> pts; createSplitEdgePts(ei0, ei1, pts); // Append pts to coordList coordList.insert(coordList.end(), pts.begin(), pts.end()); // Remove duplicate Coordinates from coordList coordList.erase(std::unique(coordList.begin(), coordList.end()), coordList.end()); } std::ostream& operator<< (std::ostream& os, const SegmentNodeList& nlist) { os << "Intersections: (" << nlist.nodeMap.size() << "):" << std::endl; for(const SegmentNode& ei: nlist.nodeMap) { os << " " << ei; } return os; } } // namespace geos.noding } // namespace geos <commit_msg>Avoid one copy by emplacing insteading of pushing back new SegmentNodes<commit_after>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2006 Refractions Research Inc. * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: noding/SegmentNodeList.java rev. 1.8 (JTS-1.10) * **********************************************************************/ #include <cassert> #include <set> #include <algorithm> #include <geos/profiler.h> #include <geos/util.h> #include <geos/util/GEOSException.h> #include <geos/noding/SegmentNodeList.h> #include <geos/noding/NodedSegmentString.h> #include <geos/noding/SegmentString.h> // for use #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/CoordinateArraySequence.h> // FIXME: should we really be using this ? #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif #ifdef GEOS_DEBUG #include <iostream> #endif // using namespace geos::geom; namespace geos { namespace noding { // geos.noding #if PROFILE static Profiler* profiler = Profiler::instance(); #endif void SegmentNodeList::add(const Coordinate& intPt, std::size_t segmentIndex) { // SegmentNode sn(edge, intPt, segmentIndex, edge.getSegmentOctant(segmentIndex)); nodeMap.emplace_back(edge, intPt, segmentIndex, edge.getSegmentOctant(segmentIndex)); ready = false; } void SegmentNodeList::prepare() const { if (!ready) { std::sort(nodeMap.begin(), nodeMap.end(), [](const SegmentNode& s1, const SegmentNode& s2) { return s1.compareTo(s2) < 0; }); nodeMap.erase(std::unique(nodeMap.begin(), nodeMap.end(), [](const SegmentNode& s1, const SegmentNode& s2) { return s1.compareTo(s2) == 0; }), nodeMap.end()); ready = true; } } void SegmentNodeList::addEndpoints() { std::size_t maxSegIndex = edge.size() - 1; add(&(edge.getCoordinate(0)), 0); add(&(edge.getCoordinate(maxSegIndex)), maxSegIndex); } /* private */ void SegmentNodeList::addCollapsedNodes() { std::vector<size_t> collapsedVertexIndexes; findCollapsesFromInsertedNodes(collapsedVertexIndexes); findCollapsesFromExistingVertices(collapsedVertexIndexes); // node the collapses for(std::size_t vertexIndex : collapsedVertexIndexes) { add(edge.getCoordinate(vertexIndex), vertexIndex); } } /* private */ void SegmentNodeList::findCollapsesFromExistingVertices( std::vector<size_t>& collapsedVertexIndexes) const { if(edge.size() < 2) { return; // or we'll never exit the loop below } for(std::size_t i = 0, n = edge.size() - 2; i < n; ++i) { const Coordinate& p0 = edge.getCoordinate(i); const Coordinate& p2 = edge.getCoordinate(i + 2); if(p0.equals2D(p2)) { // add base of collapse as node collapsedVertexIndexes.push_back(i + 1); } } } /* private */ void SegmentNodeList::findCollapsesFromInsertedNodes( std::vector<size_t>& collapsedVertexIndexes) const { std::size_t collapsedVertexIndex; // there should always be at least two entries in the list, // since the endpoints are nodes auto it = begin(); const SegmentNode* eiPrev = &(*it); ++it; for(auto itEnd = end(); it != itEnd; ++it) { const SegmentNode* ei = &(*it); bool isCollapsed = findCollapseIndex(*eiPrev, *ei, collapsedVertexIndex); if(isCollapsed) { collapsedVertexIndexes.push_back(collapsedVertexIndex); } eiPrev = ei; } } /* private */ bool SegmentNodeList::findCollapseIndex(const SegmentNode& ei0, const SegmentNode& ei1, size_t& collapsedVertexIndex) { assert(ei1.segmentIndex >= ei0.segmentIndex); // only looking for equal nodes if(! ei0.coord.equals2D(ei1.coord)) { return false; } auto numVerticesBetween = ei1.segmentIndex - ei0.segmentIndex; if(! ei1.isInterior()) { numVerticesBetween--; } // if there is a single vertex between the two equal nodes, // this is a collapse if(numVerticesBetween == 1) { collapsedVertexIndex = ei0.segmentIndex + 1; return true; } return false; } /* public */ void SegmentNodeList::addSplitEdges(std::vector<SegmentString*>& edgeList) { // testingOnly #if GEOS_DEBUG std::cerr << __FUNCTION__ << " entered" << std::endl; std::vector<SegmentString*> testingSplitEdges; #endif // ensure that the list has entries for the first and last // point of the edge addEndpoints(); addCollapsedNodes(); // there should always be at least two entries in the list // since the endpoints are nodes auto it = begin(); const SegmentNode* eiPrev = &(*it); assert(eiPrev); ++it; for(auto itEnd = end(); it != itEnd; ++it) { const SegmentNode* ei = &(*it); assert(ei); if(! ei->compareTo(*eiPrev)) { continue; } std::unique_ptr<SegmentString> newEdge = createSplitEdge(eiPrev, ei); edgeList.push_back(newEdge.release()); #if GEOS_DEBUG testingSplitEdges.push_back(newEdge); #endif eiPrev = ei; } #if GEOS_DEBUG std::cerr << __FUNCTION__ << " finished, now checking correctness" << std::endl; checkSplitEdgesCorrectness(testingSplitEdges); #endif } /*private*/ void SegmentNodeList::checkSplitEdgesCorrectness(const std::vector<SegmentString*>& splitEdges) const { const CoordinateSequence* edgePts = edge.getCoordinates(); assert(edgePts); // check that first and last points of split edges // are same as endpoints of edge SegmentString* split0 = splitEdges[0]; assert(split0); const Coordinate& pt0 = split0->getCoordinate(0); if(!(pt0 == edgePts->getAt(0))) { throw util::GEOSException("bad split edge start point at " + pt0.toString()); } SegmentString* splitn = splitEdges[splitEdges.size() - 1]; assert(splitn); const CoordinateSequence* splitnPts = splitn->getCoordinates(); assert(splitnPts); const Coordinate& ptn = splitnPts->getAt(splitnPts->getSize() - 1); if(!(ptn == edgePts->getAt(edgePts->getSize() - 1))) { throw util::GEOSException("bad split edge end point at " + ptn.toString()); } } /*private*/ std::unique_ptr<SegmentString> SegmentNodeList::createSplitEdge(const SegmentNode* ei0, const SegmentNode* ei1) const { std::vector<Coordinate> pts; createSplitEdgePts(ei0, ei1, pts); return detail::make_unique<NodedSegmentString>(new CoordinateArraySequence(std::move(pts)), edge.getData()); } /*private*/ void SegmentNodeList::createSplitEdgePts(const SegmentNode* ei0, const SegmentNode* ei1, std::vector<Coordinate>& pts) const { //int npts = ei1->segmentIndex - (ei0->segmentIndex + 2); bool twoPoints = (ei1->segmentIndex == ei0->segmentIndex); // if only two points in split edge they must be the node points if (twoPoints) { pts.emplace_back(ei0->coord); pts.emplace_back(ei1->coord); return; } const Coordinate& lastSegStartPt = edge.getCoordinate(ei1->segmentIndex); /** * If the last intersection point is not equal to the its segment start pt, * add it to the points list as well. * This check is needed because the distance metric is not totally reliable! * Also ensure that the created edge always has at least 2 points. * The check for point equality is 2D only - Z values are ignored */ bool useIntPt1 = ei1->isInterior() || ! ei1->coord.equals2D(lastSegStartPt); //if (!useIntPt1) { // npts--; //} pts.emplace_back(ei0->coord); for (std::size_t i = ei0->segmentIndex + 1; i <= ei1->segmentIndex; i++) { pts.emplace_back(edge.getCoordinate(i)); } if (useIntPt1) { pts.emplace_back(ei1->coord); } } /*public*/ std::vector<Coordinate> SegmentNodeList::getSplitCoordinates() { // ensure that the list has entries for the first and last point of the edge addEndpoints(); std::vector<Coordinate> coordList; // there should always be at least two entries in the list, since the endpoints are nodes auto it = begin(); const SegmentNode* eiPrev = &(*it); for(auto itEnd = end(); it != itEnd; ++it) { const SegmentNode* ei = &(*it); addEdgeCoordinates(eiPrev, ei, coordList); eiPrev = ei; } return coordList; } /*private*/ void SegmentNodeList::addEdgeCoordinates(const SegmentNode* ei0, const SegmentNode* ei1, std::vector<Coordinate>& coordList) const { std::vector<Coordinate> pts; createSplitEdgePts(ei0, ei1, pts); // Append pts to coordList coordList.insert(coordList.end(), pts.begin(), pts.end()); // Remove duplicate Coordinates from coordList coordList.erase(std::unique(coordList.begin(), coordList.end()), coordList.end()); } std::ostream& operator<< (std::ostream& os, const SegmentNodeList& nlist) { os << "Intersections: (" << nlist.nodeMap.size() << "):" << std::endl; for(const SegmentNode& ei: nlist.nodeMap) { os << " " << ei; } return os; } } // namespace geos.noding } // namespace geos <|endoftext|>
<commit_before>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2006 Refractions Research Inc. * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: noding/SegmentNodeList.java rev. 1.8 (JTS-1.10) * **********************************************************************/ #include <cassert> #include <set> #include <algorithm> #include <geos/profiler.h> #include <geos/util.h> #include <geos/util/GEOSException.h> #include <geos/noding/SegmentNodeList.h> #include <geos/noding/NodedSegmentString.h> #include <geos/noding/SegmentString.h> // for use #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/CoordinateArraySequence.h> // FIXME: should we really be using this ? #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif #ifdef GEOS_DEBUG #include <iostream> #endif //using namespace std; using namespace geos::geom; namespace geos { namespace noding { // geos.noding #if PROFILE static Profiler* profiler = Profiler::instance(); #endif SegmentNode* SegmentNodeList::add(const Coordinate& intPt, size_t segmentIndex) { nodeQue.emplace_back(edge, intPt, segmentIndex, edge.getSegmentOctant(segmentIndex)); SegmentNode* eiNew = &(nodeQue.back()); std::pair<SegmentNodeList::iterator, bool> p = nodeMap.insert(eiNew); if(p.second) { // new SegmentNode inserted return eiNew; } else { // sanity check assert(eiNew->coord.equals2D(intPt)); nodeQue.pop_back(); return *(p.first); } } SegmentNodeList::~SegmentNodeList() { } void SegmentNodeList::addEndpoints() { size_t maxSegIndex = edge.size() - 1; add(&(edge.getCoordinate(0)), 0); add(&(edge.getCoordinate(maxSegIndex)), maxSegIndex); } /* private */ void SegmentNodeList::addCollapsedNodes() { std::vector<size_t> collapsedVertexIndexes; findCollapsesFromInsertedNodes(collapsedVertexIndexes); findCollapsesFromExistingVertices(collapsedVertexIndexes); // node the collapses for(std::vector<size_t>::iterator i = collapsedVertexIndexes.begin(), e = collapsedVertexIndexes.end(); i != e; ++i) { auto vertexIndex = *i; add(edge.getCoordinate(vertexIndex), vertexIndex); } } /* private */ void SegmentNodeList::findCollapsesFromExistingVertices( std::vector<size_t>& collapsedVertexIndexes) const { if(edge.size() < 2) { return; // or we'll never exit the loop below } for(size_t i = 0, n = edge.size() - 2; i < n; ++i) { const Coordinate& p0 = edge.getCoordinate(i); const Coordinate& p2 = edge.getCoordinate(i + 2); if(p0.equals2D(p2)) { // add base of collapse as node collapsedVertexIndexes.push_back(i + 1); } } } /* private */ void SegmentNodeList::findCollapsesFromInsertedNodes( std::vector<size_t>& collapsedVertexIndexes) const { size_t collapsedVertexIndex; // there should always be at least two entries in the list, // since the endpoints are nodes iterator it = begin(); SegmentNode* eiPrev = *it; ++it; for(iterator itEnd = end(); it != itEnd; ++it) { SegmentNode* ei = *it; bool isCollapsed = findCollapseIndex(*eiPrev, *ei, collapsedVertexIndex); if(isCollapsed) { collapsedVertexIndexes.push_back(collapsedVertexIndex); } eiPrev = ei; } } /* private */ bool SegmentNodeList::findCollapseIndex(const SegmentNode& ei0, const SegmentNode& ei1, size_t& collapsedVertexIndex) const { assert(ei1.segmentIndex >= ei0.segmentIndex); // only looking for equal nodes if(! ei0.coord.equals2D(ei1.coord)) { return false; } auto numVerticesBetween = ei1.segmentIndex - ei0.segmentIndex; if(! ei1.isInterior()) { numVerticesBetween--; } // if there is a single vertex between the two equal nodes, // this is a collapse if(numVerticesBetween == 1) { collapsedVertexIndex = ei0.segmentIndex + 1; return true; } return false; } /* public */ void SegmentNodeList::addSplitEdges(std::vector<SegmentString*>& edgeList) { // testingOnly #if GEOS_DEBUG std::cerr << __FUNCTION__ << " entered" << std::endl; std::vector<SegmentString*> testingSplitEdges; #endif // ensure that the list has entries for the first and last // point of the edge addEndpoints(); addCollapsedNodes(); // there should always be at least two entries in the list // since the endpoints are nodes iterator it = begin(); SegmentNode* eiPrev = *it; assert(eiPrev); ++it; for(iterator itEnd = end(); it != itEnd; ++it) { SegmentNode* ei = *it; assert(ei); if(! ei->compareTo(*eiPrev)) { continue; } std::unique_ptr<SegmentString> newEdge = createSplitEdge(eiPrev, ei); edgeList.push_back(newEdge.release()); #if GEOS_DEBUG testingSplitEdges.push_back(newEdge); #endif eiPrev = ei; } #if GEOS_DEBUG std::cerr << __FUNCTION__ << " finished, now checking correctness" << std::endl; checkSplitEdgesCorrectness(testingSplitEdges); #endif } /*private*/ void SegmentNodeList::checkSplitEdgesCorrectness(const std::vector<SegmentString*>& splitEdges) const { const CoordinateSequence* edgePts = edge.getCoordinates(); assert(edgePts); // check that first and last points of split edges // are same as endpoints of edge SegmentString* split0 = splitEdges[0]; assert(split0); const Coordinate& pt0 = split0->getCoordinate(0); if(!(pt0 == edgePts->getAt(0))) { throw util::GEOSException("bad split edge start point at " + pt0.toString()); } SegmentString* splitn = splitEdges[splitEdges.size() - 1]; assert(splitn); const CoordinateSequence* splitnPts = splitn->getCoordinates(); assert(splitnPts); const Coordinate& ptn = splitnPts->getAt(splitnPts->getSize() - 1); if(!(ptn == edgePts->getAt(edgePts->getSize() - 1))) { throw util::GEOSException("bad split edge end point at " + ptn.toString()); } } /*private*/ std::unique_ptr<SegmentString> SegmentNodeList::createSplitEdge(const SegmentNode* ei0, const SegmentNode* ei1) const { std::vector<Coordinate> pts; createSplitEdgePts(ei0, ei1, pts); return detail::make_unique<NodedSegmentString>(new CoordinateArraySequence(std::move(pts)), edge.getData()); } /*private*/ void SegmentNodeList::createSplitEdgePts(const SegmentNode* ei0, const SegmentNode* ei1, std::vector<Coordinate>& pts) const { //int npts = ei1->segmentIndex - (ei0->segmentIndex + 2); bool twoPoints = (ei1->segmentIndex == ei0->segmentIndex); // if only two points in split edge they must be the node points if (twoPoints) { pts.emplace_back(ei0->coord); pts.emplace_back(ei1->coord); return; } const Coordinate& lastSegStartPt = edge.getCoordinate(ei1->segmentIndex); /** * If the last intersection point is not equal to the its segment start pt, * add it to the points list as well. * This check is needed because the distance metric is not totally reliable! * Also ensure that the created edge always has at least 2 points. * The check for point equality is 2D only - Z values are ignored */ bool useIntPt1 = ei1->isInterior() || ! ei1->coord.equals2D(lastSegStartPt); //if (!useIntPt1) { // npts--; //} pts.emplace_back(ei0->coord); for (size_t i = ei0->segmentIndex + 1; i <= ei1->segmentIndex; i++) { pts.emplace_back(edge.getCoordinate(i)); } if (useIntPt1) { pts.emplace_back(ei1->coord); } return; } /*public*/ std::unique_ptr<std::vector<Coordinate>> SegmentNodeList::getSplitCoordinates() { // ensure that the list has entries for the first and last point of the edge addEndpoints(); std::unique_ptr<std::vector<Coordinate>> coordList(new std::vector<Coordinate>); // there should always be at least two entries in the list, since the endpoints are nodes iterator it = begin(); SegmentNode* eiPrev = *it; for(iterator itEnd = end(); it != itEnd; ++it) { SegmentNode* ei = *it; addEdgeCoordinates(eiPrev, ei, *coordList); eiPrev = ei; } return coordList; } /*private*/ void SegmentNodeList::addEdgeCoordinates(const SegmentNode* ei0, const SegmentNode* ei1, std::vector<Coordinate>& coordList) const { std::vector<Coordinate> pts; createSplitEdgePts(ei0, ei1, pts); // Append pts to coordList coordList.insert(coordList.end(), pts.begin(), pts.end()); // Remove duplicate Coordinates from coordList coordList.erase(std::unique(coordList.begin(), coordList.end()), coordList.end()); } std::ostream& operator<< (std::ostream& os, const SegmentNodeList& nlist) { os << "Intersections: (" << nlist.nodeMap.size() << "):" << std::endl; for(const SegmentNode* ei: nlist.nodeMap) { os << " " << *ei; } return os; } } // namespace geos.noding } // namespace geos <commit_msg>Change to automatic iterator syntax<commit_after>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2006 Refractions Research Inc. * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: noding/SegmentNodeList.java rev. 1.8 (JTS-1.10) * **********************************************************************/ #include <cassert> #include <set> #include <algorithm> #include <geos/profiler.h> #include <geos/util.h> #include <geos/util/GEOSException.h> #include <geos/noding/SegmentNodeList.h> #include <geos/noding/NodedSegmentString.h> #include <geos/noding/SegmentString.h> // for use #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/CoordinateArraySequence.h> // FIXME: should we really be using this ? #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif #ifdef GEOS_DEBUG #include <iostream> #endif //using namespace std; using namespace geos::geom; namespace geos { namespace noding { // geos.noding #if PROFILE static Profiler* profiler = Profiler::instance(); #endif SegmentNode* SegmentNodeList::add(const Coordinate& intPt, size_t segmentIndex) { nodeQue.emplace_back(edge, intPt, segmentIndex, edge.getSegmentOctant(segmentIndex)); SegmentNode* eiNew = &(nodeQue.back()); std::pair<SegmentNodeList::iterator, bool> p = nodeMap.insert(eiNew); if(p.second) { // new SegmentNode inserted return eiNew; } else { // sanity check assert(eiNew->coord.equals2D(intPt)); nodeQue.pop_back(); return *(p.first); } } SegmentNodeList::~SegmentNodeList() { } void SegmentNodeList::addEndpoints() { size_t maxSegIndex = edge.size() - 1; add(&(edge.getCoordinate(0)), 0); add(&(edge.getCoordinate(maxSegIndex)), maxSegIndex); } /* private */ void SegmentNodeList::addCollapsedNodes() { std::vector<size_t> collapsedVertexIndexes; findCollapsesFromInsertedNodes(collapsedVertexIndexes); findCollapsesFromExistingVertices(collapsedVertexIndexes); // node the collapses for(std::size_t vertexIndex : collapsedVertexIndexes) { add(edge.getCoordinate(vertexIndex), vertexIndex); } } /* private */ void SegmentNodeList::findCollapsesFromExistingVertices( std::vector<size_t>& collapsedVertexIndexes) const { if(edge.size() < 2) { return; // or we'll never exit the loop below } for(size_t i = 0, n = edge.size() - 2; i < n; ++i) { const Coordinate& p0 = edge.getCoordinate(i); const Coordinate& p2 = edge.getCoordinate(i + 2); if(p0.equals2D(p2)) { // add base of collapse as node collapsedVertexIndexes.push_back(i + 1); } } } /* private */ void SegmentNodeList::findCollapsesFromInsertedNodes( std::vector<size_t>& collapsedVertexIndexes) const { size_t collapsedVertexIndex; // there should always be at least two entries in the list, // since the endpoints are nodes iterator it = begin(); SegmentNode* eiPrev = *it; ++it; for(iterator itEnd = end(); it != itEnd; ++it) { SegmentNode* ei = *it; bool isCollapsed = findCollapseIndex(*eiPrev, *ei, collapsedVertexIndex); if(isCollapsed) { collapsedVertexIndexes.push_back(collapsedVertexIndex); } eiPrev = ei; } } /* private */ bool SegmentNodeList::findCollapseIndex(const SegmentNode& ei0, const SegmentNode& ei1, size_t& collapsedVertexIndex) const { assert(ei1.segmentIndex >= ei0.segmentIndex); // only looking for equal nodes if(! ei0.coord.equals2D(ei1.coord)) { return false; } auto numVerticesBetween = ei1.segmentIndex - ei0.segmentIndex; if(! ei1.isInterior()) { numVerticesBetween--; } // if there is a single vertex between the two equal nodes, // this is a collapse if(numVerticesBetween == 1) { collapsedVertexIndex = ei0.segmentIndex + 1; return true; } return false; } /* public */ void SegmentNodeList::addSplitEdges(std::vector<SegmentString*>& edgeList) { // testingOnly #if GEOS_DEBUG std::cerr << __FUNCTION__ << " entered" << std::endl; std::vector<SegmentString*> testingSplitEdges; #endif // ensure that the list has entries for the first and last // point of the edge addEndpoints(); addCollapsedNodes(); // there should always be at least two entries in the list // since the endpoints are nodes iterator it = begin(); SegmentNode* eiPrev = *it; assert(eiPrev); ++it; for(iterator itEnd = end(); it != itEnd; ++it) { SegmentNode* ei = *it; assert(ei); if(! ei->compareTo(*eiPrev)) { continue; } std::unique_ptr<SegmentString> newEdge = createSplitEdge(eiPrev, ei); edgeList.push_back(newEdge.release()); #if GEOS_DEBUG testingSplitEdges.push_back(newEdge); #endif eiPrev = ei; } #if GEOS_DEBUG std::cerr << __FUNCTION__ << " finished, now checking correctness" << std::endl; checkSplitEdgesCorrectness(testingSplitEdges); #endif } /*private*/ void SegmentNodeList::checkSplitEdgesCorrectness(const std::vector<SegmentString*>& splitEdges) const { const CoordinateSequence* edgePts = edge.getCoordinates(); assert(edgePts); // check that first and last points of split edges // are same as endpoints of edge SegmentString* split0 = splitEdges[0]; assert(split0); const Coordinate& pt0 = split0->getCoordinate(0); if(!(pt0 == edgePts->getAt(0))) { throw util::GEOSException("bad split edge start point at " + pt0.toString()); } SegmentString* splitn = splitEdges[splitEdges.size() - 1]; assert(splitn); const CoordinateSequence* splitnPts = splitn->getCoordinates(); assert(splitnPts); const Coordinate& ptn = splitnPts->getAt(splitnPts->getSize() - 1); if(!(ptn == edgePts->getAt(edgePts->getSize() - 1))) { throw util::GEOSException("bad split edge end point at " + ptn.toString()); } } /*private*/ std::unique_ptr<SegmentString> SegmentNodeList::createSplitEdge(const SegmentNode* ei0, const SegmentNode* ei1) const { std::vector<Coordinate> pts; createSplitEdgePts(ei0, ei1, pts); return detail::make_unique<NodedSegmentString>(new CoordinateArraySequence(std::move(pts)), edge.getData()); } /*private*/ void SegmentNodeList::createSplitEdgePts(const SegmentNode* ei0, const SegmentNode* ei1, std::vector<Coordinate>& pts) const { //int npts = ei1->segmentIndex - (ei0->segmentIndex + 2); bool twoPoints = (ei1->segmentIndex == ei0->segmentIndex); // if only two points in split edge they must be the node points if (twoPoints) { pts.emplace_back(ei0->coord); pts.emplace_back(ei1->coord); return; } const Coordinate& lastSegStartPt = edge.getCoordinate(ei1->segmentIndex); /** * If the last intersection point is not equal to the its segment start pt, * add it to the points list as well. * This check is needed because the distance metric is not totally reliable! * Also ensure that the created edge always has at least 2 points. * The check for point equality is 2D only - Z values are ignored */ bool useIntPt1 = ei1->isInterior() || ! ei1->coord.equals2D(lastSegStartPt); //if (!useIntPt1) { // npts--; //} pts.emplace_back(ei0->coord); for (size_t i = ei0->segmentIndex + 1; i <= ei1->segmentIndex; i++) { pts.emplace_back(edge.getCoordinate(i)); } if (useIntPt1) { pts.emplace_back(ei1->coord); } return; } /*public*/ std::unique_ptr<std::vector<Coordinate>> SegmentNodeList::getSplitCoordinates() { // ensure that the list has entries for the first and last point of the edge addEndpoints(); std::unique_ptr<std::vector<Coordinate>> coordList(new std::vector<Coordinate>); // there should always be at least two entries in the list, since the endpoints are nodes iterator it = begin(); SegmentNode* eiPrev = *it; for(iterator itEnd = end(); it != itEnd; ++it) { SegmentNode* ei = *it; addEdgeCoordinates(eiPrev, ei, *coordList); eiPrev = ei; } return coordList; } /*private*/ void SegmentNodeList::addEdgeCoordinates(const SegmentNode* ei0, const SegmentNode* ei1, std::vector<Coordinate>& coordList) const { std::vector<Coordinate> pts; createSplitEdgePts(ei0, ei1, pts); // Append pts to coordList coordList.insert(coordList.end(), pts.begin(), pts.end()); // Remove duplicate Coordinates from coordList coordList.erase(std::unique(coordList.begin(), coordList.end()), coordList.end()); } std::ostream& operator<< (std::ostream& os, const SegmentNodeList& nlist) { os << "Intersections: (" << nlist.nodeMap.size() << "):" << std::endl; for(const SegmentNode* ei: nlist.nodeMap) { os << " " << *ei; } return os; } } // namespace geos.noding } // namespace geos <|endoftext|>
<commit_before>/* * Adapted from code copyright 2009-2011 Intel Corporation * Modifications Copyright 2012, Blender 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. */ //#define __KERNEL_SSE__ #include <stdlib.h> #include "bvh_binning.h" #include "util_algorithm.h" #include "util_boundbox.h" #include "util_types.h" CCL_NAMESPACE_BEGIN /* SSE replacements */ __forceinline void prefetch_L1 (const void* ptr) { } __forceinline void prefetch_L2 (const void* ptr) { } __forceinline void prefetch_L3 (const void* ptr) { } __forceinline void prefetch_NTA(const void* ptr) { } template<size_t src> __forceinline float extract(const int4& b) { return b[src]; } template<size_t dst> __forceinline const float4 insert(const float4& a, const float b) { float4 r = a; r[dst] = b; return r; } __forceinline int get_best_dimension(const float4& bestSAH) { // return (int)__bsf(movemask(reduce_min(bestSAH) == bestSAH)); float minSAH = min(bestSAH.x, min(bestSAH.y, bestSAH.z)); if(bestSAH.x == minSAH) return 0; else if(bestSAH.y == minSAH) return 1; else return 2; } /* BVH Object Binning */ BVHObjectBinning::BVHObjectBinning(const BVHRange& job, BVHReference *prims) : BVHRange(job), splitSAH(FLT_MAX), dim(0), pos(0) { /* compute number of bins to use and precompute scaling factor for binning */ num_bins = min(size_t(MAX_BINS), size_t(4.0f + 0.05f*size())); scale = rcp(cent_bounds().size()) * make_float3((float)num_bins); /* initialize binning counter and bounds */ BoundBox bin_bounds[MAX_BINS][4]; /* bounds for every bin in every dimension */ int4 bin_count[MAX_BINS]; /* number of primitives mapped to bin */ for(size_t i = 0; i < num_bins; i++) { bin_count[i] = make_int4(0); bin_bounds[i][0] = bin_bounds[i][1] = bin_bounds[i][2] = BoundBox::empty; } /* map geometry to bins, unrolled once */ { ssize_t i; for(i = 0; i < ssize_t(size()) - 1; i += 2) { prefetch_L2(&prims[start() + i + 8]); /* map even and odd primitive to bin */ BVHReference prim0 = prims[start() + i + 0]; BVHReference prim1 = prims[start() + i + 1]; int4 bin0 = get_bin(prim0.bounds()); int4 bin1 = get_bin(prim1.bounds()); /* increase bounds for bins for even primitive */ int b00 = extract<0>(bin0); bin_count[b00][0]++; bin_bounds[b00][0].grow(prim0.bounds()); int b01 = extract<1>(bin0); bin_count[b01][1]++; bin_bounds[b01][1].grow(prim0.bounds()); int b02 = extract<2>(bin0); bin_count[b02][2]++; bin_bounds[b02][2].grow(prim0.bounds()); /* increase bounds of bins for odd primitive */ int b10 = extract<0>(bin1); bin_count[b10][0]++; bin_bounds[b10][0].grow(prim1.bounds()); int b11 = extract<1>(bin1); bin_count[b11][1]++; bin_bounds[b11][1].grow(prim1.bounds()); int b12 = extract<2>(bin1); bin_count[b12][2]++; bin_bounds[b12][2].grow(prim1.bounds()); } /* for uneven number of primitives */ if(i < ssize_t(size())) { /* map primitive to bin */ BVHReference prim0 = prims[start() + i]; int4 bin0 = get_bin(prim0.bounds()); /* increase bounds of bins */ int b00 = extract<0>(bin0); bin_count[b00][0]++; bin_bounds[b00][0].grow(prim0.bounds()); int b01 = extract<1>(bin0); bin_count[b01][1]++; bin_bounds[b01][1].grow(prim0.bounds()); int b02 = extract<2>(bin0); bin_count[b02][2]++; bin_bounds[b02][2].grow(prim0.bounds()); } } /* sweep from right to left and compute parallel prefix of merged bounds */ float4 r_area[MAX_BINS]; /* area of bounds of primitives on the right */ float4 r_count[MAX_BINS]; /* number of primitives on the right */ int4 count = make_int4(0); BoundBox bx = BoundBox::empty; BoundBox by = BoundBox::empty; BoundBox bz = BoundBox::empty; for(size_t i = num_bins - 1; i > 0; i--) { count = count + bin_count[i]; r_count[i] = blocks(count); bx = merge(bx,bin_bounds[i][0]); r_area[i][0] = bx.half_area(); by = merge(by,bin_bounds[i][1]); r_area[i][1] = by.half_area(); bz = merge(bz,bin_bounds[i][2]); r_area[i][2] = bz.half_area(); } /* sweep from left to right and compute SAH */ int4 ii = make_int4(1); float4 bestSAH = make_float4(FLT_MAX); int4 bestSplit = make_int4(-1); count = make_int4(0); bx = BoundBox::empty; by = BoundBox::empty; bz = BoundBox::empty; for(size_t i = 1; i < num_bins; i++, ii += make_int4(1)) { count = count + bin_count[i-1]; bx = merge(bx,bin_bounds[i-1][0]); float Ax = bx.half_area(); by = merge(by,bin_bounds[i-1][1]); float Ay = by.half_area(); bz = merge(bz,bin_bounds[i-1][2]); float Az = bz.half_area(); float4 lCount = blocks(count); float4 lArea = make_float4(Ax,Ay,Az,Az); float4 sah = lArea*lCount + r_area[i]*r_count[i]; bestSplit = select(sah < bestSAH,ii,bestSplit); bestSAH = min(sah,bestSAH); } int4 mask = float3_to_float4(cent_bounds().size()) <= make_float4(0.0f); bestSAH = insert<3>(select(mask, make_float4(FLT_MAX), bestSAH), FLT_MAX); /* find best dimension */ dim = get_best_dimension(bestSAH); splitSAH = bestSAH[dim]; pos = bestSplit[dim]; leafSAH = bounds().half_area() * blocks(size()); } void BVHObjectBinning::split(BVHReference* prims, BVHObjectBinning& left_o, BVHObjectBinning& right_o) const { size_t N = size(); BoundBox lgeom_bounds = BoundBox::empty; BoundBox rgeom_bounds = BoundBox::empty; BoundBox lcent_bounds = BoundBox::empty; BoundBox rcent_bounds = BoundBox::empty; ssize_t l = 0, r = N-1; while(l <= r) { prefetch_L2(&prims[start() + l + 8]); prefetch_L2(&prims[start() + r - 8]); BVHReference prim = prims[start() + l]; float3 center = prim.bounds().center2(); if(get_bin(center)[dim] < pos) { lgeom_bounds.grow(prim.bounds()); lcent_bounds.grow(center); l++; } else { rgeom_bounds.grow(prim.bounds()); rcent_bounds.grow(center); swap(prims[start()+l],prims[start()+r]); r--; } } /* finish */ if(l != 0 && N-1-r != 0) { right_o = BVHObjectBinning(BVHRange(rgeom_bounds, rcent_bounds, start() + l, N-1-r), prims); left_o = BVHObjectBinning(BVHRange(lgeom_bounds, lcent_bounds, start(), l), prims); return; } /* object medium split if we did not make progress, can happen when all primitives have same centroid */ lgeom_bounds = BoundBox::empty; rgeom_bounds = BoundBox::empty; lcent_bounds = BoundBox::empty; rcent_bounds = BoundBox::empty; for(size_t i = 0; i < N/2; i++) { lgeom_bounds.grow(prims[start()+i].bounds()); lcent_bounds.grow(prims[start()+i].bounds().center2()); } for(size_t i = N/2; i < N; i++) { rgeom_bounds.grow(prims[start()+i].bounds()); rcent_bounds.grow(prims[start()+i].bounds().center2()); } right_o = BVHObjectBinning(BVHRange(rgeom_bounds, rcent_bounds, start() + N/2, N/2 + N%2), prims); left_o = BVHObjectBinning(BVHRange(lgeom_bounds, lcent_bounds, start(), N/2), prims); } CCL_NAMESPACE_END <commit_msg>Fix (harmless) uninitialized memory usage in BVH binning. Fix unneeded warnings with c++ guardedalloc, delete NULL is valid.<commit_after>/* * Adapted from code copyright 2009-2011 Intel Corporation * Modifications Copyright 2012, Blender 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. */ //#define __KERNEL_SSE__ #include <stdlib.h> #include "bvh_binning.h" #include "util_algorithm.h" #include "util_boundbox.h" #include "util_types.h" CCL_NAMESPACE_BEGIN /* SSE replacements */ __forceinline void prefetch_L1 (const void* ptr) { } __forceinline void prefetch_L2 (const void* ptr) { } __forceinline void prefetch_L3 (const void* ptr) { } __forceinline void prefetch_NTA(const void* ptr) { } template<size_t src> __forceinline float extract(const int4& b) { return b[src]; } template<size_t dst> __forceinline const float4 insert(const float4& a, const float b) { float4 r = a; r[dst] = b; return r; } __forceinline int get_best_dimension(const float4& bestSAH) { // return (int)__bsf(movemask(reduce_min(bestSAH) == bestSAH)); float minSAH = min(bestSAH.x, min(bestSAH.y, bestSAH.z)); if(bestSAH.x == minSAH) return 0; else if(bestSAH.y == minSAH) return 1; else return 2; } /* BVH Object Binning */ BVHObjectBinning::BVHObjectBinning(const BVHRange& job, BVHReference *prims) : BVHRange(job), splitSAH(FLT_MAX), dim(0), pos(0) { /* compute number of bins to use and precompute scaling factor for binning */ num_bins = min(size_t(MAX_BINS), size_t(4.0f + 0.05f*size())); scale = rcp(cent_bounds().size()) * make_float3((float)num_bins); /* initialize binning counter and bounds */ BoundBox bin_bounds[MAX_BINS][4]; /* bounds for every bin in every dimension */ int4 bin_count[MAX_BINS]; /* number of primitives mapped to bin */ for(size_t i = 0; i < num_bins; i++) { bin_count[i] = make_int4(0); bin_bounds[i][0] = bin_bounds[i][1] = bin_bounds[i][2] = BoundBox::empty; } /* map geometry to bins, unrolled once */ { ssize_t i; for(i = 0; i < ssize_t(size()) - 1; i += 2) { prefetch_L2(&prims[start() + i + 8]); /* map even and odd primitive to bin */ BVHReference prim0 = prims[start() + i + 0]; BVHReference prim1 = prims[start() + i + 1]; int4 bin0 = get_bin(prim0.bounds()); int4 bin1 = get_bin(prim1.bounds()); /* increase bounds for bins for even primitive */ int b00 = extract<0>(bin0); bin_count[b00][0]++; bin_bounds[b00][0].grow(prim0.bounds()); int b01 = extract<1>(bin0); bin_count[b01][1]++; bin_bounds[b01][1].grow(prim0.bounds()); int b02 = extract<2>(bin0); bin_count[b02][2]++; bin_bounds[b02][2].grow(prim0.bounds()); /* increase bounds of bins for odd primitive */ int b10 = extract<0>(bin1); bin_count[b10][0]++; bin_bounds[b10][0].grow(prim1.bounds()); int b11 = extract<1>(bin1); bin_count[b11][1]++; bin_bounds[b11][1].grow(prim1.bounds()); int b12 = extract<2>(bin1); bin_count[b12][2]++; bin_bounds[b12][2].grow(prim1.bounds()); } /* for uneven number of primitives */ if(i < ssize_t(size())) { /* map primitive to bin */ BVHReference prim0 = prims[start() + i]; int4 bin0 = get_bin(prim0.bounds()); /* increase bounds of bins */ int b00 = extract<0>(bin0); bin_count[b00][0]++; bin_bounds[b00][0].grow(prim0.bounds()); int b01 = extract<1>(bin0); bin_count[b01][1]++; bin_bounds[b01][1].grow(prim0.bounds()); int b02 = extract<2>(bin0); bin_count[b02][2]++; bin_bounds[b02][2].grow(prim0.bounds()); } } /* sweep from right to left and compute parallel prefix of merged bounds */ float4 r_area[MAX_BINS]; /* area of bounds of primitives on the right */ float4 r_count[MAX_BINS]; /* number of primitives on the right */ int4 count = make_int4(0); BoundBox bx = BoundBox::empty; BoundBox by = BoundBox::empty; BoundBox bz = BoundBox::empty; for(size_t i = num_bins - 1; i > 0; i--) { count = count + bin_count[i]; r_count[i] = blocks(count); bx = merge(bx,bin_bounds[i][0]); r_area[i][0] = bx.half_area(); by = merge(by,bin_bounds[i][1]); r_area[i][1] = by.half_area(); bz = merge(bz,bin_bounds[i][2]); r_area[i][2] = bz.half_area(); r_area[i][3] = r_area[i][2]; } /* sweep from left to right and compute SAH */ int4 ii = make_int4(1); float4 bestSAH = make_float4(FLT_MAX); int4 bestSplit = make_int4(-1); count = make_int4(0); bx = BoundBox::empty; by = BoundBox::empty; bz = BoundBox::empty; for(size_t i = 1; i < num_bins; i++, ii += make_int4(1)) { count = count + bin_count[i-1]; bx = merge(bx,bin_bounds[i-1][0]); float Ax = bx.half_area(); by = merge(by,bin_bounds[i-1][1]); float Ay = by.half_area(); bz = merge(bz,bin_bounds[i-1][2]); float Az = bz.half_area(); float4 lCount = blocks(count); float4 lArea = make_float4(Ax,Ay,Az,Az); float4 sah = lArea*lCount + r_area[i]*r_count[i]; bestSplit = select(sah < bestSAH,ii,bestSplit); bestSAH = min(sah,bestSAH); } int4 mask = float3_to_float4(cent_bounds().size()) <= make_float4(0.0f); bestSAH = insert<3>(select(mask, make_float4(FLT_MAX), bestSAH), FLT_MAX); /* find best dimension */ dim = get_best_dimension(bestSAH); splitSAH = bestSAH[dim]; pos = bestSplit[dim]; leafSAH = bounds().half_area() * blocks(size()); } void BVHObjectBinning::split(BVHReference* prims, BVHObjectBinning& left_o, BVHObjectBinning& right_o) const { size_t N = size(); BoundBox lgeom_bounds = BoundBox::empty; BoundBox rgeom_bounds = BoundBox::empty; BoundBox lcent_bounds = BoundBox::empty; BoundBox rcent_bounds = BoundBox::empty; ssize_t l = 0, r = N-1; while(l <= r) { prefetch_L2(&prims[start() + l + 8]); prefetch_L2(&prims[start() + r - 8]); BVHReference prim = prims[start() + l]; float3 center = prim.bounds().center2(); if(get_bin(center)[dim] < pos) { lgeom_bounds.grow(prim.bounds()); lcent_bounds.grow(center); l++; } else { rgeom_bounds.grow(prim.bounds()); rcent_bounds.grow(center); swap(prims[start()+l],prims[start()+r]); r--; } } /* finish */ if(l != 0 && N-1-r != 0) { right_o = BVHObjectBinning(BVHRange(rgeom_bounds, rcent_bounds, start() + l, N-1-r), prims); left_o = BVHObjectBinning(BVHRange(lgeom_bounds, lcent_bounds, start(), l), prims); return; } /* object medium split if we did not make progress, can happen when all primitives have same centroid */ lgeom_bounds = BoundBox::empty; rgeom_bounds = BoundBox::empty; lcent_bounds = BoundBox::empty; rcent_bounds = BoundBox::empty; for(size_t i = 0; i < N/2; i++) { lgeom_bounds.grow(prims[start()+i].bounds()); lcent_bounds.grow(prims[start()+i].bounds().center2()); } for(size_t i = N/2; i < N; i++) { rgeom_bounds.grow(prims[start()+i].bounds()); rcent_bounds.grow(prims[start()+i].bounds().center2()); } right_o = BVHObjectBinning(BVHRange(rgeom_bounds, rcent_bounds, start() + N/2, N/2 + N%2), prims); left_o = BVHObjectBinning(BVHRange(lgeom_bounds, lcent_bounds, start(), N/2), prims); } CCL_NAMESPACE_END <|endoftext|>
<commit_before>/*################################################### ##################Cic-Cac-Coe###################### ######## All rights reserved to SAFAD(C) ########## ###########Please read the LICENSE file############ ###################################################*/ #include <iostream> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; //This is our board, 0 => empty, 1 => X, 2 => O vector<int> originalBoard; //the game is running or not ? 1 yes , 0 no int status = 0; //turns 1 = player1, -1 = player2 OR CPU char turn = -1; //to define the character we put in the column char block; //the user input int selection; //AI vs Human int opponent; int checkGame(vector<int> board); void run(); //show the board char ReplaceBlocks(int blockId){ switch(blockId) { case -1: return 'X'; //it is the first player.. case 0: return ' '; //an empty block case 1: return 'O'; //second player here.. } return ' '; } void DrawBoard() { for(int i=0; i<7; i+=3) { cout << " " << ReplaceBlocks(originalBoard[i]) <<" | "<< ReplaceBlocks(originalBoard[i+1]) << " | " << ReplaceBlocks(originalBoard[i+2]) << endl; if (i != 6) { cout << "---+---+---" <<endl; } } } //tell them spike, tell them its a draw !! void show_draw(){ cout << "Nothing to see here Peeps, its a Draw" << endl; } //show winner ! void show_winner(){ cout << "Winner is Player " << turn << " congratulations !!" << endl; } //check who won ! int check_winner(vector<int> board){ for(int i=0; i<7; i+=3) { if((board[i] == -1 && board[i+1] == -1 && board[i+2] == -1) || (board[i] == 1 && board[i+1] == 1 && board[i+2] == 1)){ return board[i]; } } for(int i=0; i<3; i++) { if((board[i] == -1 && board[i+3] == -1 && board[i+6] == -1) || (board[i] == 1 && board[i+3] == 1 && board[i+6] == 1)){ return board[i]; } } for(int i=0; i<3; i+=2) { if((board[i] == -1 && board[4] == -1 && board[8-i] == -1) || (board[i] == 1 && board[4] == 1 && board[8-i] == 1)){ return board[i]; } } return 0; } bool check_draw(vector<int> board){ if (std::count(board.begin(), board.end(), 0) < 0) { //there still are no more moves //now lets see if someone one if (!check_winner(board)) { return true; } } return false; } //validates the user input bool validate_selection(int selection){ //first we check if it is out of range if (selection > 8 || selection < 0) { return false; } if(originalBoard[selection] == 1 || originalBoard[selection] == -1){ return false; } else { return true; } } //function to switch from player one to two and vice versa void switch_turns(){ turn = (turn == 1) ? -1 : 1; run(); } void check_status(vector<int> board){ int gameStatus = checkGame(board); //before we switch turns, we check if the user won or not if(gameStatus == 0){ switch_turns(); } //what if the game is a Draw ? else if(gameStatus == 2){ show_draw(); status = 0; } else if(gameStatus == 1){ //winnnnnn show_winner(); status = 0; } } vector<int> getAllPossibleMoves(vector<int> board){ vector<int> spaces; for (int i = 0; i < 9; ++i) { if (board[i] == 0) { //this is the chosen one spaces.push_back(i); } } return spaces; } //we use this function to check the game status, is it won, or draw //int unfinished = 0, won = 1, draw = 2; int checkGame(vector<int> board){ if(check_winner(board)){ return 1; } //what if the game is a Draw ? else if(check_draw(board)){ return 2; } return 0; } int minmax(vector<int> board, int player){ //player == 1 => X, == -1 => O int win = check_winner(board), bestScore = -2, bestMove = -1; if (win > 0) return player*win; for(std::vector<int>::size_type i = 0; i != originalBoard.size(); i++) { if (board[i] == 0) { board[i] = player; int score = -minmax(board, -player); cout << score << endl; if (score > bestScore) { bestScore = score; bestMove = i; } board[i] = 0; } } if(bestMove == -1) return 0; return bestScore; } void AI(){ //cout << "Calculating..." << endl; int bestScore = -2, bestMove = -1; for(std::vector<int>::size_type i = 0; i != originalBoard.size(); i++) { if (originalBoard[i] == 0) { originalBoard[i] = 1; int score = -minmax(originalBoard, -1); originalBoard[i] = 0; if (score > bestScore) { bestScore = score; bestMove = i; } } } //now we use it on screen originalBoard[bestMove] = 1; check_status(originalBoard); } void player(){ cout << "Player " << turn << " Please enter a valid number (0-8) :" <<endl; cin >> selection; if(validate_selection(selection)){ originalBoard[selection] = turn; check_status(originalBoard); }else{ //his choice is invalid cout << "invalid move" << endl; player(); } } //function to show the board void run(){ if (opponent == 2) { if (turn == -1) { DrawBoard(); } }else{ DrawBoard(); } //Artificial Inteligence :) if(opponent == 2 && turn == 1){ AI(); } else{ player(); } } int main(){ //we first populate the board with dummy strings int dummy[9] = {0,0,0,0,0,0,0,0,0}; for(int index=0;index<9; ++index) { originalBoard.push_back(dummy[index]); } if(status == 0){ cout << "Play VS :" << endl; cout << "1. Human" << endl; cout << "2. AI (CPU)" << endl; cin >> opponent; status = 1; } run(); } <commit_msg>fixed error on cic-cac-coe.cpp<commit_after>/*################################################### ##################Cic-Cac-Coe###################### ######## All rights reserved to SAFAD(C) ########## ###########Please read the LICENSE file############ ###################################################*/ #include <iostream> #include <cstdlib> #include <vector> #include <algorithm> #include <time.h> using namespace std; //PROTOTYPING vector<int> originalBoard; int status = 0; char turn = -1; char block; int selection; int opponent; int checkGame(vector<int> board); void run(); void show_winner(); void show_draw(); char convertToPlayer(int); bool validate_selection(int); void DrawBoard(); /*********************************** ************** MAIN **************** ***********************************/ int main(){ //we first populate the board with dummy strings int dummy[9] = {0,0,0,0,0,0,0,0,0}; for(int index=0;index<9; ++index) { originalBoard.push_back(dummy[index]); } if(status == 0){ cout << "Play VS :" << endl; cout << "1. Human" << endl; cout << "2. AI (CPU)" << endl; cin >> opponent; status = 1; } run(); } /*************************************************** * This is a function that takes the character in the * slot and returns what value is there. * X = -1 | O = 1 | _ = 0 ***************************************************/ char ReplaceBlocks(int blockId){ switch(blockId) { case -1: return 'X'; //it is the first player.. case 0: return ' '; //an empty block case 1: return 'O'; //second player here.. } return ' '; } /*************************************************** * This is a function that checks the board for * combinations that would be considered a winner * Standard rules apply. ***************************************************/ int check_winner(vector<int> board){ for(int i=0; i<7; i+=3) { if((board[i] == -1 && board[i+1] == -1 && board[i+2] == -1) || (board[i] == 1 && board[i+1] == 1 && board[i+2] == 1)){ return board[i]; } } for(int i=0; i<3; i++) { if((board[i] == -1 && board[i+3] == -1 && board[i+6] == -1) || (board[i] == 1 && board[i+3] == 1 && board[i+6] == 1)){ return board[i]; } } for(int i=0; i<3; i+=2) { if((board[i] == -1 && board[4] == -1 && board[8-i] == -1) || (board[i] == 1 && board[4] == 1 && board[8-i] == 1)){ return board[i]; } } return 0; } /*************************************************** * This is a function that notes that if all 9 spaces * have been taken up and that it should check for draw ***************************************************/ bool check_draw(vector<int> board){ if (std::count(board.begin(), board.end(), 0) < 0) { if (!check_winner(board)) { return true; } } return false; } /*************************************************** * This is a function to switch from player one to * two and vice versa. ***************************************************/ void switch_turns(){ turn = (turn == 1) ? -1 : 1; run(); } /*************************************************** * This is a function to set the status of if the * player has won the game so that it can be checked * in the next function. * No winner = 0 | winner = 1 | Draw = 2 ***************************************************/ int checkGame(vector<int> board){ if(check_winner(board)){ return 1; } //what if the game is a Draw ? else if(check_draw(board)){ return 2; } return 0; } /*************************************************** * This is a function to dictate if the person wins, * loses, draw, or if it continues and switches turns. * No winner = 0 | winner = 1 | Draw = 2 ***************************************************/ void check_status(vector<int> board){ int gameStatus = checkGame(board); if(gameStatus == 0){ // switch_turns(); // NO WINNER } // else if(gameStatus == 1){ // show_winner(); // THERE IS A WINNER status = 0; // } else if(gameStatus == 2){ // show_draw(); // THERE IS A DRAW status = 0; // } } /********************************************************* * This function takes the AI settings and who's turn it is * then proceeds through the menus. **********************************************************/ void player(){ if(opponent == 2 && turn != 1) { char whosTurn = convertToPlayer(turn); cout << "\n-------------------------------------------------------------" << endl; cout << "* Player " << whosTurn << " Please enter a valid number (0-8) : *" << endl; cout << "-------------------------------------------------------------" << endl; cin >> selection; } else if(opponent == 2 && turn == 1) { srand(time(NULL)); selection = rand() % 8; } //If current selection is empty, //then mark if(validate_selection(selection)) { originalBoard[selection] = turn; check_status(originalBoard); } else{ //his choice is invalid cout << "invalid move, lose a turn!" << endl << "switching turns\n"<< endl; switch_turns(); } } /***************************************** * This function is in place so that the * board is only drawn humans, not when * AI plays. ******************************************/ void run(){ if (opponent == 2) { if (turn == -1) { DrawBoard(); } } else { DrawBoard(); } if(opponent == 2 && turn == 1){ player(); } else{ player(); } } /********************************************************* * This is a function that will check the board to see * if there is already something in the place and report * true or false back so the other functions can * process accordingly. *********************************************************/ bool validate_selection(int selection){ //first we check if it is out of range if (selection > 8 || selection < 0) { return false; } if(originalBoard[selection] == 1 || originalBoard[selection] == -1){ return false; } else { return true; } } /*********************************************** * Game end - text out functions..... shows the * message of what the result was. ***********************************************/ void show_draw(){ DrawBoard(); cout << "Nothing to see here Peeps, its a Draw" << endl; } void show_winner(){ char winner = convertToPlayer(turn); DrawBoard(); cout << "***Winner is " << winner << ", congratulations !!***" << endl; } /*********************************************** * This functions converts the raw player * value (-1 or 1)into the actual letter (x or o) ***********************************************/ char convertToPlayer(int x) { char outputOf; if(x == -1) {outputOf = 'X';} else if (x == 1) {outputOf = 'O';} return outputOf; } /****************************** * Displays the board ******************************/ void DrawBoard() { for(int i=0; i<7; i+=3) { cout << " " << ReplaceBlocks(originalBoard[i]) <<" | "<< ReplaceBlocks(originalBoard[i+1]) << " | " << ReplaceBlocks(originalBoard[i+2]) << endl; if (i != 6) { cout << "---+---+---" <<endl; } } } <|endoftext|>
<commit_before>/// \file ROOT/TStringAttr.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2018-02-08 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TStringEnumAttr #define ROOT7_TStringEnumAttr #include <algorithm> #include <initializer_list> #include <string> #include <vector> namespace ROOT { namespace Experimental { /** \class ROOT::Experimental::TStringAttrSet Graphics attribute that consists of a string, selected from a set of options. This is the set of options. It's expected to be of static storage duration. */ class TStringEnumAttrSet { std::vector<std::string> fOptSet; ///< The set of options. public: TStringEnumAttrSet(std::initializer_list<const char*> il) { fOptSet.insert(fOptSet.end(), il.begin(), il.end()); } const std::vector<std::string>& GetSet() const { return fOptSet; } std::size_t Find(const std::string &opt) const { auto iter = std::find(fOptSet.begin(), fOptSet.end(), opt); if (iter != fOptSet.end()) return (std::size_t)(iter - fOptSet.begin()); return (std::size_t) -1; } const std::string &operator[](std::size_t idx) const { return fOptSet[idx]; } }; /** \class ROOT::Experimental::TStringEnumAttr Graphics attribute that consists of a string, selected from a set of options. */ class TStringEnumAttr { std::size_t fIdx; ///< Selected option from fStringSet. const TStringEnumAttrSet &fStringSet; ///< Reference to the set of options. public: /// Construct the option from the set of strings and the selected option index. TStringEnumAttr(std::size_t idx, const TStringEnumAttrSet &strSet): fIdx(idx), fStringSet(strSet) {} /// Set the index of the selected option. void SetIndex(int idx) { fIdx = idx; } /// Get the string representing the selected option. const std::string& GetAsString() const { return fStringSet[fIdx]; } /// Get the index of the selected option. std::size_t GetIndex() const { return fIdx; } }; /// Initialize an attribute `val` from a string value. /// ///\param[in] name - the attribute name, for diagnostic purposes. ///\param[in] strval - the attribute value as a string. ///\param[out] val - the value to be initialized. void InitializeAttrFromString(const std::string &name, const std::string &strval, TStringEnumAttr& val); } // namespace Experimental } // namespace ROOT #endif <commit_msg>Do not stream the StringSet reference; this is not supposed to be read.<commit_after>/// \file ROOT/TStringAttr.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2018-02-08 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TStringEnumAttr #define ROOT7_TStringEnumAttr #include <algorithm> #include <initializer_list> #include <string> #include <vector> namespace ROOT { namespace Experimental { /** \class ROOT::Experimental::TStringAttrSet Graphics attribute that consists of a string, selected from a set of options. This is the set of options. It's expected to be of static storage duration. */ class TStringEnumAttrSet { std::vector<std::string> fOptSet; ///< The set of options. public: TStringEnumAttrSet(std::initializer_list<const char*> il) { fOptSet.insert(fOptSet.end(), il.begin(), il.end()); } const std::vector<std::string>& GetSet() const { return fOptSet; } std::size_t Find(const std::string &opt) const { auto iter = std::find(fOptSet.begin(), fOptSet.end(), opt); if (iter != fOptSet.end()) return (std::size_t)(iter - fOptSet.begin()); return (std::size_t) -1; } const std::string &operator[](std::size_t idx) const { return fOptSet[idx]; } }; /** \class ROOT::Experimental::TStringEnumAttr Graphics attribute that consists of a string, selected from a set of options. */ class TStringEnumAttr { std::size_t fIdx; ///< Selected option from fStringSet. /// Reference to the set of options. const TStringEnumAttrSet &fStringSet; //! public: /// Construct the option from the set of strings and the selected option index. TStringEnumAttr(std::size_t idx, const TStringEnumAttrSet &strSet): fIdx(idx), fStringSet(strSet) {} /// Set the index of the selected option. void SetIndex(int idx) { fIdx = idx; } /// Get the string representing the selected option. const std::string& GetAsString() const { return fStringSet[fIdx]; } /// Get the index of the selected option. std::size_t GetIndex() const { return fIdx; } }; /// Initialize an attribute `val` from a string value. /// ///\param[in] name - the attribute name, for diagnostic purposes. ///\param[in] strval - the attribute value as a string. ///\param[out] val - the value to be initialized. void InitializeAttrFromString(const std::string &name, const std::string &strval, TStringEnumAttr& val); } // namespace Experimental } // namespace ROOT #endif <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <ctime> #include <string> #include <unistd.h> #include "s91k2048_outils_terminal.h" #include "projet_termites_common.h" #include "projet_termites.h" #include "termite.h" using namespace std; void placeVide(Place &p) { p.type = PLACE_TYPE_VIDE; } int typePlace(Place p) { return p.type; } void changerTypePlace(Place &p, int type) { p.type = type; } void echangerPlaces(Place &p1, Place &p2) { int ancien_type_p1 = p1.type; p1.type = p2.type; p2.type = ancien_type_p1; if (p2.type == PLACE_TYPE_TERMITE) { if (p1.type == PLACE_TYPE_TERMITE) { // si les 2 places contiennent des termites, on échange les indtermites int ancien_indtermite_p1 = p1.indtermite; p1.indtermite = p2.indtermite; p2.indtermite = ancien_indtermite_p1; } else { // si p2 va contenir un termite, on lui donne l'indtermite de p1 p2.indtermite = p1.indtermite; } } else if (p1.type == PLACE_TYPE_TERMITE) { // si p1 va contenir un termite, on lui donne l'indtermite de p2 p1.indtermite = p2.indtermite; } } bool contientTermite(Place p) { return typePlace(p) == PLACE_TYPE_TERMITE; } bool contientBrindille(Place p) { return typePlace(p) == PLACE_TYPE_BRINDILLE; } bool estVide(Place p) { return typePlace(p) == PLACE_TYPE_VIDE; } Place& coord2Place(Terrain &t, Coord coord) { return t.places[coord.y][coord.x]; } void initialiseTerrain(Terrain &t) { t.nbtermites = 0; for (int y = 0; y < TAILLE; y++) { for (int x = 0; x < TAILLE; x++) { if (aleatoire(POURCENTAGE_TERMITES/100.)) { // aleatoire est entre 0 et 1 Place p = t.places[y][x]; p.type = PLACE_TYPE_TERMITE; p.indtermite = t.nbtermites; t.places[y][x] = p; t.termites[p.indtermite] = creerTermite(p.indtermite, x, y); t.nbtermites++; } else { if (aleatoire(POURCENTAGE_BRINDILLES/100)) { t.places[y][x].type = PLACE_TYPE_BRINDILLE; } else { t.places[y][x].type = PLACE_TYPE_VIDE; } } } } } void afficheTerrain(Terrain t) { for (int y = 0; y < TAILLE; y++) { cout << "\x1B[1m"; // gras if (y) cout << endl; for (int x = 0; x < TAILLE; x++) { Place &p = coord2Place(t, creerCoord(x, y)); switch (typePlace(p)){ case PLACE_TYPE_VIDE:{ cout << "\x1B[44m"; // couleur bleue cout << ' '; break; } case PLACE_TYPE_BRINDILLE:{ cout << "\x1B[47m"; // couleur blanche cout << '0'; break; } case PLACE_TYPE_TERMITE:{ Termite m = t.termites[p.indtermite]; cout << (porteBrindilleTermite(m) ? "\x1B[43m" : "\x1B[42m"); // couleur orange / verte afficheTermite(m); break; } default: cout << "?"; } // cout << " "; // décommenter pour que les places soient des carrés et pas des rectangles } cout << "\x1B[0m"; // reset couleurs } cout << endl; } void chargerBrindilleTermitePlace(Termite &m, Place &p) { placeVide(p); chargerBrindilleTermite(m); } void dechargerBrindilleTermitePlace(Termite &m, Place &p) { changerTypePlace(p, PLACE_TYPE_BRINDILLE); dechargerBrindilleTermite(m); } void deplaceTermiteDansTerrain(Terrain &t, Termite &m, Coord coord) { Place &ancienne_place_termite = coord2Place(t, m.coord); Place &nouvelle_place_termite = coord2Place(t, coord); echangerPlaces(ancienne_place_termite, nouvelle_place_termite); teleporterTermite(m, coord); } void actionPlaceTermite(Terrain &t, Termite &m, Coord coord) { Place &p = coord2Place(t, coord); switch (typePlace(p)) { case PLACE_TYPE_TERMITE: definirSensRotationTermite(m, sensRotationAleatoire()); tourneTermite(m); break; case PLACE_TYPE_BRINDILLE: if (actionsAvecBrindillesBloqueesTermite(m)) { tourneTermite(m); } else if (porteBrindilleTermite(m)) { tourneTermite(m); // le termite tourne une fois sur place, definirModeTournerSurPlaceTermite(m, true); // et il va le faire à chaque tour jusqu'à ce qu'il trouve une // place vide pour poser sa brindille } else { // tout est ok, il peut donc chargerBrindilleTermitePlace(m, p); // charger la brindille, retourneProgressivementTermite(m, NB_DIRECTIONS/2); // et se retourner // le termite va tourner automatiquement pendant NB_DIRECTIONS/2 tours } break; case PLACE_TYPE_VIDE: default: if (doitTournerSurPlaceTermite(m) && !egalCoord(coord, m.ancien_coord)) { // si le termite veut déposer sa brindille sur // la place vide la plus proche, // et si ce n'est pas sa case d'entrée.. // => on préserve la liberté des termites dechargerBrindilleTermitePlace(m, p); // il décharge sa brindille sur la place vide devant lui, retourneProgressivementTermite(m, NB_DIRECTIONS/2-1); // et se retourne // on peut aussi mettre NB_DIRECTIONS/2-1 au // lieu de NB_DIRECTIONS/2 (alternative à bool vient_de_se_retourner, // mais il ne va pas se retourner complètement) // unmod definirModeTournerSurPlaceTermite(m, false); } else if (aleatoire(0.1)) { // ..le termite a 1 chance sur 10 de tourner dans une direction aléatoire.. definirSensRotationTermite(m, sensRotationAleatoire()); tourneTermite(m); } else { // ..sinon, deplaceTermiteDansTerrain(t, m, coord); // le termite avance } debloquerActionsAvecBrindillesSiNecessaireTermite(m); break; } } void rassemblerBrindilles(Terrain &t, Termite &m) { if (estSablierActifTermite(m)) { // ...sinon, si son sablier est positif... tourneTermite(m); // il tourne automatiquement, decrementerSablierTermite(m); // et décrémente son sablier } else { Coord coord = coordDevantTermite(m); // on récupère les coordonnées de la place se trouvant devant lui if (!estValideCoord(coord)) { // le termite est arrivé au bord du terrain, il tourne... definirSensRotationTermite(m, sensRotationAleatoire()); tourneTermite(m); } else { // ...sinon, la place existe, actionPlaceTermite(t, m, coord); // et le termite agir selon son type } } } void mouvementTermites(Terrain &t) { for (int i = 0; i < t.nbtermites; i++) { // on parcourt le tableau contenant tous les termites du terrain Termite &m = t.termites[i]; // on prend le termite courant rassemblerBrindilles(t, m); } } int main() { srand(time(NULL)); definirModeTerminal(true); // on prend le contrôle du terminal, pour que getchar() // n'attende pas que l'utilisateur ait saisi une touche cout << endl; Terrain t; initialiseTerrain(t); afficheTerrain(t); bool mouvement_automatique = false; char c; while (true) { if (mouvement_automatique) { // mouvement automatique... do { c = toupper(getchar()); if (c == 'C') { quitterApplication(); break; } else if (c == 'P') { mouvement_automatique = false; } else { cout << "\x1B[1mAppuyer sur C pour quitter\x1B[0m | P : désactiver le mode automatique" << endl; usleep(75000); mouvementTermites(t); afficheTerrain(t); } } while (mouvement_automatique); } else { // ...mouvement non automatique do { cout << "\x1B[1mAppuyer sur C pour quitter\x1B[0m | Entrée : avancer ; Q...J : avance rapide ; P : mode auto | " << "Entrer commande : "; int nb_passes = 1; while (true) { c = toupper(getchar()); // On obtient la touche saisie par l'utilisateur... if (c == 'C') { // la touche c quitte l'application quitterApplication(); break; } else if (c == '\n') { usleep(30000); // si on appuie sur entrée, attendre 35ms puis faire une passe (Entrée : avance frame à frame) break; } else if (c == 'Q') { usleep(20000); // si on appuie sur 'q', attendre 20ms puis faire une passe break; } else if (c == 'S') { usleep(10000); // si on appuie sur 's', attendre 10ms puis faire une passe break; } else if (c == 'D') { usleep(5000); // si on appuie sur 'd', faire une passe break; } else if (c == 'F') { nb_passes = 50; // si on appuie sur 'f', faire 50 passes break; } else if (c == 'G') { nb_passes = 250; // si on appuie sur 'g', faire 250 passes break; } else if (c == 'H') { nb_passes = 500; // si on appuie sur 'h', faire 500 passes break; } else if (c == 'J') { nb_passes = 1000; break; } else if (c == 'P') { mouvement_automatique = true; break; } } cout << endl; for (int i = 0; i < nb_passes; i++) { mouvementTermites(t); // on continue l'animation } afficheTerrain(t); usleep(25000); // on attend 25ms pour que l'animation soit fluide et pour éviter que le terminal freeze while (getchar() != EOF) {} // on supprime les touches pressées pendant le temps d'attente } while (!mouvement_automatique); } } quitterApplication(); return 0; } <commit_msg>Animation plus fluide<commit_after>#include <iostream> #include <cstdlib> #include <ctime> #include <string> #include <unistd.h> #include "s91k2048_outils_terminal.h" #include "projet_termites_common.h" #include "projet_termites.h" #include "termite.h" using namespace std; void placeVide(Place &p) { p.type = PLACE_TYPE_VIDE; } int typePlace(Place p) { return p.type; } void changerTypePlace(Place &p, int type) { p.type = type; } void echangerPlaces(Place &p1, Place &p2) { int ancien_type_p1 = p1.type; p1.type = p2.type; p2.type = ancien_type_p1; if (p2.type == PLACE_TYPE_TERMITE) { if (p1.type == PLACE_TYPE_TERMITE) { // si les 2 places contiennent des termites, on échange les indtermites int ancien_indtermite_p1 = p1.indtermite; p1.indtermite = p2.indtermite; p2.indtermite = ancien_indtermite_p1; } else { // si p2 va contenir un termite, on lui donne l'indtermite de p1 p2.indtermite = p1.indtermite; } } else if (p1.type == PLACE_TYPE_TERMITE) { // si p1 va contenir un termite, on lui donne l'indtermite de p2 p1.indtermite = p2.indtermite; } } bool contientTermite(Place p) { return typePlace(p) == PLACE_TYPE_TERMITE; } bool contientBrindille(Place p) { return typePlace(p) == PLACE_TYPE_BRINDILLE; } bool estVide(Place p) { return typePlace(p) == PLACE_TYPE_VIDE; } Place& coord2Place(Terrain &t, Coord coord) { return t.places[coord.y][coord.x]; } void initialiseTerrain(Terrain &t) { t.nbtermites = 0; for (int y = 0; y < TAILLE; y++) { for (int x = 0; x < TAILLE; x++) { if (aleatoire(POURCENTAGE_TERMITES/100.)) { // aleatoire est entre 0 et 1 Place p = t.places[y][x]; p.type = PLACE_TYPE_TERMITE; p.indtermite = t.nbtermites; t.places[y][x] = p; t.termites[p.indtermite] = creerTermite(p.indtermite, x, y); t.nbtermites++; } else { if (aleatoire(POURCENTAGE_BRINDILLES/100)) { t.places[y][x].type = PLACE_TYPE_BRINDILLE; } else { t.places[y][x].type = PLACE_TYPE_VIDE; } } } } } void afficheTerrain(Terrain t) { for (int y = 0; y < TAILLE; y++) { cout << "\x1B[1m"; // gras if (y) cout << endl; for (int x = 0; x < TAILLE; x++) { Place &p = coord2Place(t, creerCoord(x, y)); switch (typePlace(p)){ case PLACE_TYPE_VIDE:{ cout << "\x1B[44m"; // couleur bleue cout << ' '; break; } case PLACE_TYPE_BRINDILLE:{ cout << "\x1B[47m"; // couleur blanche cout << '0'; break; } case PLACE_TYPE_TERMITE:{ Termite m = t.termites[p.indtermite]; cout << (porteBrindilleTermite(m) ? "\x1B[43m" : "\x1B[42m"); // couleur orange / verte afficheTermite(m); break; } default: cout << "?"; } // cout << " "; // décommenter pour que les places soient des carrés et pas des rectangles } cout << "\x1B[0m"; // reset couleurs } cout << endl; } void chargerBrindilleTermitePlace(Termite &m, Place &p) { placeVide(p); chargerBrindilleTermite(m); } void dechargerBrindilleTermitePlace(Termite &m, Place &p) { changerTypePlace(p, PLACE_TYPE_BRINDILLE); dechargerBrindilleTermite(m); } void deplaceTermiteDansTerrain(Terrain &t, Termite &m, Coord coord) { Place &ancienne_place_termite = coord2Place(t, m.coord); Place &nouvelle_place_termite = coord2Place(t, coord); echangerPlaces(ancienne_place_termite, nouvelle_place_termite); teleporterTermite(m, coord); } void actionPlaceTermite(Terrain &t, Termite &m, Coord coord) { Place &p = coord2Place(t, coord); switch (typePlace(p)) { case PLACE_TYPE_TERMITE: definirSensRotationTermite(m, sensRotationAleatoire()); tourneTermite(m); break; case PLACE_TYPE_BRINDILLE: if (actionsAvecBrindillesBloqueesTermite(m)) { tourneTermite(m); } else if (porteBrindilleTermite(m)) { tourneTermite(m); // le termite tourne une fois sur place, definirModeTournerSurPlaceTermite(m, true); // et il va le faire à chaque tour jusqu'à ce qu'il trouve une // place vide pour poser sa brindille } else { // tout est ok, il peut donc chargerBrindilleTermitePlace(m, p); // charger la brindille, retourneProgressivementTermite(m, NB_DIRECTIONS/2); // et se retourner // le termite va tourner automatiquement pendant NB_DIRECTIONS/2 tours } break; case PLACE_TYPE_VIDE: default: if (doitTournerSurPlaceTermite(m) && !egalCoord(coord, m.ancien_coord)) { // si le termite veut déposer sa brindille sur // la place vide la plus proche, // et si ce n'est pas sa case d'entrée.. // => on préserve la liberté des termites dechargerBrindilleTermitePlace(m, p); // il décharge sa brindille sur la place vide devant lui, retourneProgressivementTermite(m, NB_DIRECTIONS/2-1); // et se retourne // on peut aussi mettre NB_DIRECTIONS/2-1 au // lieu de NB_DIRECTIONS/2 (alternative à bool vient_de_se_retourner, // mais il ne va pas se retourner complètement) // unmod definirModeTournerSurPlaceTermite(m, false); } else if (aleatoire(0.1)) { // ..le termite a 1 chance sur 10 de tourner dans une direction aléatoire.. definirSensRotationTermite(m, sensRotationAleatoire()); tourneTermite(m); } else { // ..sinon, deplaceTermiteDansTerrain(t, m, coord); // le termite avance } debloquerActionsAvecBrindillesSiNecessaireTermite(m); break; } } void rassemblerBrindilles(Terrain &t, Termite &m) { if (estSablierActifTermite(m)) { // ...sinon, si son sablier est positif... tourneTermite(m); // il tourne automatiquement, decrementerSablierTermite(m); // et décrémente son sablier } else { Coord coord = coordDevantTermite(m); // on récupère les coordonnées de la place se trouvant devant lui if (!estValideCoord(coord)) { // le termite est arrivé au bord du terrain, il tourne... definirSensRotationTermite(m, sensRotationAleatoire()); tourneTermite(m); } else { // ...sinon, la place existe, actionPlaceTermite(t, m, coord); // et le termite agir selon son type } } } void mouvementTermites(Terrain &t) { for (int i = 0; i < t.nbtermites; i++) { // on parcourt le tableau contenant tous les termites du terrain Termite &m = t.termites[i]; // on prend le termite courant rassemblerBrindilles(t, m); } } int main() { srand(time(NULL)); definirModeTerminal(true); // on prend le contrôle du terminal, pour que getchar() // n'attende pas que l'utilisateur ait saisi une touche cout << endl; Terrain t; initialiseTerrain(t); afficheTerrain(t); bool mouvement_automatique = false; char c; while (true) { if (mouvement_automatique) { // mouvement automatique... do { c = toupper(getchar()); if (c == 'C') { quitterApplication(); break; } else if (c == 'P') { mouvement_automatique = false; } else { cout << "\x1B[1mAppuyer sur C pour quitter\x1B[0m | P : désactiver le mode automatique" << endl; usleep(75000); mouvementTermites(t); afficheTerrain(t); } } while (mouvement_automatique); } else { // ...mouvement non automatique do { cout << "\x1B[1mAppuyer sur C pour quitter\x1B[0m | Entrée : avancer ; Q...J : avance rapide ; P : mode auto | " << "Entrer commande : "; int nb_passes = 1; while (true) { c = toupper(getchar()); // On obtient la touche saisie par l'utilisateur... if (c == 'C') { // la touche c quitte l'application quitterApplication(); break; } else if (c == '\n') { usleep(60000); // si on appuie sur entrée, attendre 60ms puis faire une passe (Entrée : avance frame à frame) break; } else if (c == 'Q') { usleep(20000); // si on appuie sur 'q', attendre 20ms puis faire une passe break; } else if (c == 'S') { usleep(10000); // si on appuie sur 's', attendre 10ms puis faire une passe break; } else if (c == 'D') { usleep(5000); // si on appuie sur 'd', faire une passe break; } else if (c == 'F') { nb_passes = 50; // si on appuie sur 'f', faire 50 passes break; } else if (c == 'G') { nb_passes = 250; // si on appuie sur 'g', faire 250 passes break; } else if (c == 'H') { nb_passes = 500; // si on appuie sur 'h', faire 500 passes break; } else if (c == 'J') { nb_passes = 1000; // si on appuie sur 'h', faire 500 passes break; } else if (c == 'P') { mouvement_automatique = true; break; } } cout << endl; for (int i = 0; i < nb_passes; i++) { mouvementTermites(t); // on continue l'animation } afficheTerrain(t); usleep(25000); // on attend 25ms pour que l'animation soit fluide et pour éviter que le terminal freeze while (getchar() != EOF) {} // on supprime les touches pressées pendant le temps d'attente } while (!mouvement_automatique); } } quitterApplication(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/page_click_tracker.h" #include "chrome/renderer/page_click_listener.h" #include "chrome/renderer/render_view.h" #include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/WebKit/chromium/public/WebDOMMouseEvent.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebInputElement.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" using WebKit::WebDOMEvent; using WebKit::WebDOMMouseEvent; using WebKit::WebElement; using WebKit::WebFormControlElement; using WebKit::WebFrame; using WebKit::WebInputElement; using WebKit::WebInputEvent; using WebKit::WebMouseEvent; using WebKit::WebNode; using WebKit::WebString; using WebKit::WebView; PageClickTracker::PageClickTracker(RenderView* render_view) : render_view_(render_view), was_focused_(false) { } PageClickTracker::~PageClickTracker() { // Note that even though RenderView calls StopTrackingFrame when notified that // a frame was closed, it might not always get that notification from WebKit // for all frames. // By the time we get here, the frame could have been destroyed so we cannot // unregister listeners in frames remaining in tracked_frames_ as they might // be invalid. } void PageClickTracker::StartTrackingFrame(WebFrame* frame) { tracked_frames_.push_back(frame); frame->document().addEventListener("mousedown", this, false); } void PageClickTracker::StopTrackingFrame(WebFrame* frame, bool frame_detached) { FrameList::iterator iter = std::find(tracked_frames_.begin(), tracked_frames_.end(), frame); if (iter == tracked_frames_.end()) { // Some frames might never load contents so we may not have a listener on // them. Calling removeEventListener() on them would trigger an assert, so // we need to keep track of which frames we are listening to. return; } tracked_frames_.erase(iter); // If the frame has been detached, all event listeners have already been // removed. if (!frame_detached) frame->document().removeEventListener("mousedown", this, false); } void PageClickTracker::DidHandleMouseEvent(const WebMouseEvent& event) { if (event.type != WebInputEvent::MouseDown || last_node_clicked_.isNull()) { return; } // We are only interested in text field clicks. if (!last_node_clicked_.isElementNode()) return; const WebElement& element = last_node_clicked_.toConst<WebElement>(); if (!element.isFormControlElement()) return; const WebFormControlElement& control = element.toConst<WebFormControlElement>(); if (control.formControlType() != WebString::fromUTF8("text")) return; const WebInputElement& input_element = element.toConst<WebInputElement>(); bool is_focused = (last_node_clicked_ == GetFocusedNode()); ObserverListBase<PageClickListener>::Iterator it(listeners_); PageClickListener* listener; while ((listener = it.GetNext()) != NULL) { if (listener->InputElementClicked(input_element, was_focused_, is_focused)) break; } last_node_clicked_.reset(); } void PageClickTracker::AddListener(PageClickListener* listener) { listeners_.AddObserver(listener); } void PageClickTracker::RemoveListener(PageClickListener* listener) { listeners_.RemoveObserver(listener); } void PageClickTracker::handleEvent(const WebDOMEvent& event) { last_node_clicked_.reset(); DCHECK(event.isMouseEvent()); const WebDOMMouseEvent mouse_event = event.toConst<WebDOMMouseEvent>(); DCHECK(mouse_event.buttonDown()); if (mouse_event.button() != 0) return; // We are only interested in left clicks. // Remember which node has focus before the click is processed. // We'll get a notification once the mouse event has been processed // (DidHandleMouseEvent), we'll notify the listener at that point. last_node_clicked_ = mouse_event.target(); was_focused_ = (GetFocusedNode() == last_node_clicked_); } WebNode PageClickTracker::GetFocusedNode() { WebView* web_view = render_view_->webview(); if (!web_view) return WebNode(); WebFrame* web_frame = web_view->focusedFrame(); if (!web_frame) return WebNode(); return web_frame->document().focusedNode(); } <commit_msg>Added check in page click tracker to ensure events passed in are mouse events<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/page_click_tracker.h" #include "chrome/renderer/page_click_listener.h" #include "chrome/renderer/render_view.h" #include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/WebKit/chromium/public/WebDOMMouseEvent.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebInputElement.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" using WebKit::WebDOMEvent; using WebKit::WebDOMMouseEvent; using WebKit::WebElement; using WebKit::WebFormControlElement; using WebKit::WebFrame; using WebKit::WebInputElement; using WebKit::WebInputEvent; using WebKit::WebMouseEvent; using WebKit::WebNode; using WebKit::WebString; using WebKit::WebView; PageClickTracker::PageClickTracker(RenderView* render_view) : render_view_(render_view), was_focused_(false) { } PageClickTracker::~PageClickTracker() { // Note that even though RenderView calls StopTrackingFrame when notified that // a frame was closed, it might not always get that notification from WebKit // for all frames. // By the time we get here, the frame could have been destroyed so we cannot // unregister listeners in frames remaining in tracked_frames_ as they might // be invalid. } void PageClickTracker::StartTrackingFrame(WebFrame* frame) { tracked_frames_.push_back(frame); frame->document().addEventListener("mousedown", this, false); } void PageClickTracker::StopTrackingFrame(WebFrame* frame, bool frame_detached) { FrameList::iterator iter = std::find(tracked_frames_.begin(), tracked_frames_.end(), frame); if (iter == tracked_frames_.end()) { // Some frames might never load contents so we may not have a listener on // them. Calling removeEventListener() on them would trigger an assert, so // we need to keep track of which frames we are listening to. return; } tracked_frames_.erase(iter); // If the frame has been detached, all event listeners have already been // removed. if (!frame_detached) frame->document().removeEventListener("mousedown", this, false); } void PageClickTracker::DidHandleMouseEvent(const WebMouseEvent& event) { if (event.type != WebInputEvent::MouseDown || last_node_clicked_.isNull()) { return; } // We are only interested in text field clicks. if (!last_node_clicked_.isElementNode()) return; const WebElement& element = last_node_clicked_.toConst<WebElement>(); if (!element.isFormControlElement()) return; const WebFormControlElement& control = element.toConst<WebFormControlElement>(); if (control.formControlType() != WebString::fromUTF8("text")) return; const WebInputElement& input_element = element.toConst<WebInputElement>(); bool is_focused = (last_node_clicked_ == GetFocusedNode()); ObserverListBase<PageClickListener>::Iterator it(listeners_); PageClickListener* listener; while ((listener = it.GetNext()) != NULL) { if (listener->InputElementClicked(input_element, was_focused_, is_focused)) break; } last_node_clicked_.reset(); } void PageClickTracker::AddListener(PageClickListener* listener) { listeners_.AddObserver(listener); } void PageClickTracker::RemoveListener(PageClickListener* listener) { listeners_.RemoveObserver(listener); } void PageClickTracker::handleEvent(const WebDOMEvent& event) { last_node_clicked_.reset(); if (!event.isMouseEvent()) return; const WebDOMMouseEvent mouse_event = event.toConst<WebDOMMouseEvent>(); DCHECK(mouse_event.buttonDown()); if (mouse_event.button() != 0) return; // We are only interested in left clicks. // Remember which node has focus before the click is processed. // We'll get a notification once the mouse event has been processed // (DidHandleMouseEvent), we'll notify the listener at that point. last_node_clicked_ = mouse_event.target(); was_focused_ = (GetFocusedNode() == last_node_clicked_); } WebNode PageClickTracker::GetFocusedNode() { WebView* web_view = render_view_->webview(); if (!web_view) return WebNode(); WebFrame* web_frame = web_view->focusedFrame(); if (!web_frame) return WebNode(); return web_frame->document().focusedNode(); } <|endoftext|>
<commit_before>#ifndef _CRYPTL_BLESS_HPP_ #define _CRYPTL_BLESS_HPP_ #include <array> #include <climits> #include <cstdint> #include <istream> namespace cryptl { //////////////////////////////////////////////////////////////////////////////// // blessing (initialize variables) // // 8/32/64-bit values from input stream template <typename T> bool bless(T& a, std::istream& is) { a = 0; char c; for (std::size_t i = 0; i < sizeof(T); ++i) { if (is.eof() || !is.get(c)) return false; else a = (a << CHAR_BIT) | static_cast<std::uint8_t>(c); } return true; } // array from input stream template <typename T, std::size_t N> bool bless(std::array<T, N>& a, std::istream& is) { for (auto& x : a) { if (! bless(x, is)) return false; } return true; } } // namespace cryptl #endif <commit_msg>unambiguous blessing, bless arrays with lambda<commit_after>#ifndef _CRYPTL_BLESS_HPP_ #define _CRYPTL_BLESS_HPP_ #include <array> #include <climits> #include <cstdint> #include <functional> #include <istream> namespace cryptl { //////////////////////////////////////////////////////////////////////////////// // blessing (initialize variables) // template <typename T> bool bless_internal(T& a, std::istream& is) { a = 0; char c; for (std::size_t i = 0; i < sizeof(T); ++i) { if (is.eof() || !is.get(c)) return false; else a = (a << CHAR_BIT) | static_cast<std::uint8_t>(c); } return true; } // 8-bit values from input stream template <typename T> bool bless(std::uint8_t& a, T& is) { return bless_internal(a, is); } // 32-bit values from input stream template <typename T> bool bless(std::uint32_t& a, T& is) { return bless_internal(a, is); } // 64-bit values from input stream template <typename T> bool bless(std::uint64_t& a, T& is) { return bless_internal(a, is); } // array from input stream template <typename T, std::size_t N> bool bless(std::array<T, N>& a, std::istream& is, std::function<bool (T&, std::istream&)> func) { for (auto& x : a) { if (! func(x, is)) return false; } return true; } } // namespace cryptl #endif <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/nacl/nacl_sandbox_test.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "chrome/common/chrome_switches.h" namespace { // Base url is specified in nacl_test. // We just need to visit a page that will trigger the NaCl loader. const FilePath::CharType kANaClHtmlFile[] = FILE_PATH_LITERAL("srpc_hw_ppapi.html"); } // namespace NaClSandboxTest::NaClSandboxTest() { // Append the --test-nacl-sandbox=$TESTDLL flag before launching. FilePath dylib_dir; PathService::Get(base::DIR_EXE, &dylib_dir); #if defined(OS_MACOSX) dylib_dir = dylib_dir.AppendASCII("libnacl_security_tests.dylib"); launch_arguments_.AppendSwitchPath(switches::kTestNaClSandbox, dylib_dir); #elif defined(OS_WIN) // Let the NaCl process detect if it is 64-bit or not and hack on // the appropriate suffix to this dll. dylib_dir = dylib_dir.AppendASCII("nacl_security_tests"); launch_arguments_.AppendSwitchPath(switches::kTestNaClSandbox, dylib_dir); #elif defined(OS_LINUX) // We currently do not test the Chrome Linux SUID or seccomp sandboxes. #endif } NaClSandboxTest::~NaClSandboxTest() { } TEST_F(NaClSandboxTest, NaClOuterSBTest) { // Load a helloworld .nexe to trigger the nacl loader test. FilePath test_file(kANaClHtmlFile); RunTest(test_file, TestTimeouts::action_max_timeout_ms()); } <commit_msg>Disabling sandbox test temporarily.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/nacl/nacl_sandbox_test.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "chrome/common/chrome_switches.h" namespace { // Base url is specified in nacl_test. // We just need to visit a page that will trigger the NaCl loader. const FilePath::CharType kANaClHtmlFile[] = FILE_PATH_LITERAL("srpc_hw_ppapi.html"); } // namespace NaClSandboxTest::NaClSandboxTest() { // Append the --test-nacl-sandbox=$TESTDLL flag before launching. FilePath dylib_dir; PathService::Get(base::DIR_EXE, &dylib_dir); #if defined(OS_MACOSX) dylib_dir = dylib_dir.AppendASCII("libnacl_security_tests.dylib"); launch_arguments_.AppendSwitchPath(switches::kTestNaClSandbox, dylib_dir); #elif defined(OS_WIN) // Let the NaCl process detect if it is 64-bit or not and hack on // the appropriate suffix to this dll. dylib_dir = dylib_dir.AppendASCII("nacl_security_tests"); launch_arguments_.AppendSwitchPath(switches::kTestNaClSandbox, dylib_dir); #elif defined(OS_LINUX) // We currently do not test the Chrome Linux SUID or seccomp sandboxes. #endif } NaClSandboxTest::~NaClSandboxTest() { } TEST_F(NaClSandboxTest, DISABLED_NaClOuterSBTest) { // Load a helloworld .nexe to trigger the nacl loader test. FilePath test_file(kANaClHtmlFile); RunTest(test_file, TestTimeouts::action_max_timeout_ms()); } <|endoftext|>
<commit_before>// Copyright 2013 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/test/nacl/pnacl_header_test.h" #include "base/bind.h" #include "base/path_service.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/nacl/nacl_browsertest_util.h" #include "content/public/browser/web_contents.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" using net::test_server::BasicHttpResponse; using net::test_server::EmbeddedTestServer; using net::test_server::HttpRequest; using net::test_server::HttpResponse; PnaclHeaderTest::PnaclHeaderTest() : noncors_loads_(0), cors_loads_(0) {} PnaclHeaderTest::~PnaclHeaderTest() {} void PnaclHeaderTest::SetUp() { ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); // For most requests, just serve files, but register a special test handler // that watches for the .pexe fetch also. base::FilePath test_data_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir)); embedded_test_server()->RegisterRequestHandler( base::Bind(&PnaclHeaderTest::WatchForPexeFetch, base::Unretained(this))); embedded_test_server()->ServeFilesFromDirectory(test_data_dir); noncors_loads_ = 0; cors_loads_ = 0; InProcessBrowserTest::SetUp(); } void PnaclHeaderTest::TearDown() { ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete()); InProcessBrowserTest::TearDown(); } void PnaclHeaderTest::RunLoadTest(const std::string& url, int expected_noncors, int expected_cors) { ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL(url)); // Wait until the NMF and pexe are also loaded, not just the HTML. // Do this by waiting till the LoadTestMessageHandler responds. LoadTestMessageHandler handler; JavascriptTestObserver observer( browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost(), &handler); EXPECT_TRUE(observer.Run()) << handler.error_message(); EXPECT_TRUE(handler.test_passed()) << "Test failed."; EXPECT_EQ(expected_noncors, noncors_loads_); EXPECT_EQ(expected_cors, cors_loads_); } scoped_ptr<HttpResponse> PnaclHeaderTest::WatchForPexeFetch( const HttpRequest& request) { // Avoid favicon.ico warning by giving it a dummy icon. if (request.relative_url.find("favicon.ico") != std::string::npos) { scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); http_response->set_code(net::HTTP_OK); http_response->set_content(""); http_response->set_content_type("application/octet-stream"); return http_response.PassAs<HttpResponse>(); } // Skip other non-pexe files and let ServeFilesFromDirectory handle it. GURL absolute_url = embedded_test_server()->GetURL(request.relative_url); if (absolute_url.path().find(".pexe") == std::string::npos) return scoped_ptr<HttpResponse>(); // For pexe files, check for the special Accept header. // This must match whatever is in: // ppapi/native_client/src/trusted/plugin/pnacl_coordinator.cc EXPECT_NE(0U, request.headers.count("Accept")); std::map<std::string, std::string>::const_iterator it = request.headers.find("Accept"); EXPECT_NE(std::string::npos, it->second.find("application/x-pnacl")); EXPECT_NE(std::string::npos, it->second.find("*/*")); // Also make sure that other headers like CORS-related headers // are preserved when injecting the special Accept header. if (absolute_url.path().find("cors") == std::string::npos) { EXPECT_EQ(0U, request.headers.count("Origin")); noncors_loads_ += 1; } else { EXPECT_EQ(1U, request.headers.count("Origin")); cors_loads_ += 1; } // After checking the header, just return a 404. We don't need to actually // compile and stopping with a 404 is faster. scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); http_response->set_code(net::HTTP_NOT_FOUND); http_response->set_content("PEXE ... not found"); http_response->set_content_type("application/octet-stream"); return http_response.PassAs<HttpResponse>(); } IN_PROC_BROWSER_TEST_F(PnaclHeaderTest, TestHasPnaclHeader) { // Load 2 pexes, one same origin and one cross orgin. RunLoadTest("/nacl/pnacl_request_header/pnacl_request_header.html", 1, 1); } <commit_msg>Disable PnaclHeaderTest.TestHasPnaclHeader.<commit_after>// Copyright 2013 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/test/nacl/pnacl_header_test.h" #include "base/bind.h" #include "base/path_service.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/nacl/nacl_browsertest_util.h" #include "content/public/browser/web_contents.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" using net::test_server::BasicHttpResponse; using net::test_server::EmbeddedTestServer; using net::test_server::HttpRequest; using net::test_server::HttpResponse; PnaclHeaderTest::PnaclHeaderTest() : noncors_loads_(0), cors_loads_(0) {} PnaclHeaderTest::~PnaclHeaderTest() {} void PnaclHeaderTest::SetUp() { ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); // For most requests, just serve files, but register a special test handler // that watches for the .pexe fetch also. base::FilePath test_data_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir)); embedded_test_server()->RegisterRequestHandler( base::Bind(&PnaclHeaderTest::WatchForPexeFetch, base::Unretained(this))); embedded_test_server()->ServeFilesFromDirectory(test_data_dir); noncors_loads_ = 0; cors_loads_ = 0; InProcessBrowserTest::SetUp(); } void PnaclHeaderTest::TearDown() { ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete()); InProcessBrowserTest::TearDown(); } void PnaclHeaderTest::RunLoadTest(const std::string& url, int expected_noncors, int expected_cors) { ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL(url)); // Wait until the NMF and pexe are also loaded, not just the HTML. // Do this by waiting till the LoadTestMessageHandler responds. LoadTestMessageHandler handler; JavascriptTestObserver observer( browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost(), &handler); EXPECT_TRUE(observer.Run()) << handler.error_message(); EXPECT_TRUE(handler.test_passed()) << "Test failed."; EXPECT_EQ(expected_noncors, noncors_loads_); EXPECT_EQ(expected_cors, cors_loads_); } scoped_ptr<HttpResponse> PnaclHeaderTest::WatchForPexeFetch( const HttpRequest& request) { // Avoid favicon.ico warning by giving it a dummy icon. if (request.relative_url.find("favicon.ico") != std::string::npos) { scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); http_response->set_code(net::HTTP_OK); http_response->set_content(""); http_response->set_content_type("application/octet-stream"); return http_response.PassAs<HttpResponse>(); } // Skip other non-pexe files and let ServeFilesFromDirectory handle it. GURL absolute_url = embedded_test_server()->GetURL(request.relative_url); if (absolute_url.path().find(".pexe") == std::string::npos) return scoped_ptr<HttpResponse>(); // For pexe files, check for the special Accept header. // This must match whatever is in: // ppapi/native_client/src/trusted/plugin/pnacl_coordinator.cc EXPECT_NE(0U, request.headers.count("Accept")); std::map<std::string, std::string>::const_iterator it = request.headers.find("Accept"); EXPECT_NE(std::string::npos, it->second.find("application/x-pnacl")); EXPECT_NE(std::string::npos, it->second.find("*/*")); // Also make sure that other headers like CORS-related headers // are preserved when injecting the special Accept header. if (absolute_url.path().find("cors") == std::string::npos) { EXPECT_EQ(0U, request.headers.count("Origin")); noncors_loads_ += 1; } else { EXPECT_EQ(1U, request.headers.count("Origin")); cors_loads_ += 1; } // After checking the header, just return a 404. We don't need to actually // compile and stopping with a 404 is faster. scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); http_response->set_code(net::HTTP_NOT_FOUND); http_response->set_content("PEXE ... not found"); http_response->set_content_type("application/octet-stream"); return http_response.PassAs<HttpResponse>(); } // Disabled: http://crbug.com/315328. IN_PROC_BROWSER_TEST_F(PnaclHeaderTest, DISABLED_TestHasPnaclHeader) { // Load 2 pexes, one same origin and one cross orgin. RunLoadTest("/nacl/pnacl_request_header/pnacl_request_header.html", 1, 1); } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgViewer/SimpleViewer> using namespace osgViewer; SimpleViewer::SimpleViewer(): _firstFrame(true) { _sceneView = new osgUtil::SceneView; _sceneView->setDefaults(); _sceneView->getState()->setContextID(osg::GraphicsContext::createNewContextID()); _startTick = osg::Timer::instance()->tick(); _frameStamp = new osg::FrameStamp; _frameStamp->setFrameNumber(0); _frameStamp->setReferenceTime(0); _eventQueue->setStartTick(_startTick); _eventVisitor = new osgGA::EventVisitor; setDatabasePager(new osgDB::DatabasePager); } SimpleViewer::~SimpleViewer() { _sceneView->releaseAllGLObjects(); osg::GraphicsContext::decrementContextIDUsageCount(_sceneView->getState()->getContextID()); } void SimpleViewer::setSceneData(osg::Node* node) { _sceneView->setSceneData(node); if (_cameraManipulator.valid()) { _cameraManipulator->setNode(node); osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent(); _cameraManipulator->home(*dummyEvent, *this); } if (_databasePager.valid()) { // register any PagedLOD that need to be tracked in the scene graph _databasePager->registerPagedLODs(node); } } osg::Node* SimpleViewer::getSceneData() { return _sceneView->getSceneData(); } const osg::Node* SimpleViewer::getSceneData() const { return _sceneView->getSceneData(); } osg::CameraNode* SimpleViewer::getCamera() { return _sceneView->getCamera(); } const osg::CameraNode* SimpleViewer::getCamera() const { return _sceneView->getCamera(); } void SimpleViewer::setCameraManipulator(osgGA::MatrixManipulator* manipulator) { if (_cameraManipulator == manipulator) return; _cameraManipulator = manipulator; if (_cameraManipulator.valid()) { _cameraManipulator->setNode(_sceneView->getSceneData()); osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent(); _cameraManipulator->home(*dummyEvent, *this); } } void SimpleViewer::addEventHandler(osgGA::GUIEventHandler* eventHandler) { _eventHandlers.push_back(eventHandler); } void SimpleViewer::setDatabasePager(osgDB::DatabasePager* dp) { _databasePager = dp; if (dp && _sceneView.valid()) { // need to register the DatabasePager with the SceneView's CullVisitor so it can pass on request // for files to be loaded. _sceneView->getCullVisitor()->setDatabaseRequestHandler(_databasePager.get()); } } void SimpleViewer::init() { osg::ref_ptr<osgGA::GUIEventAdapter> initEvent = _eventQueue->createEvent(); initEvent->setEventType(osgGA::GUIEventAdapter::FRAME); if (_cameraManipulator.valid()) { _cameraManipulator->init(*initEvent, *this); } } void SimpleViewer::frame() { if (_firstFrame) { init(); _firstFrame = false; } frameAdvance(); frameEventTraversal(); frameUpdateTraversal(); frameCullTraversal(); frameDrawTraversal(); } void SimpleViewer::frameAdvance() { osg::Timer_t currentTick = osg::Timer::instance()->tick(); _frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(_startTick,currentTick)); _frameStamp->setFrameNumber(_frameStamp->getFrameNumber()+1); _sceneView->setFrameStamp(_frameStamp.get()); } void SimpleViewer::frameEventTraversal() { _eventQueue->frame( _frameStamp->getReferenceTime() ); osgGA::EventQueue::Events events; _eventQueue->takeEvents(events); if (_eventVisitor.valid()) { _eventVisitor->setTraversalNumber(_frameStamp->getFrameNumber()); } for(osgGA::EventQueue::Events::iterator itr = events.begin(); itr != events.end(); ++itr) { osgGA::GUIEventAdapter* event = itr->get(); bool handled = false; if (_eventVisitor.valid()) { _eventVisitor->reset(); _eventVisitor->addEvent( event ); getSceneData()->accept(*_eventVisitor); if (_eventVisitor->getEventHandled()) handled = true; } if (_cameraManipulator.valid()) { _cameraManipulator->handle( *event, *this ); } for(EventHandlers::iterator hitr = _eventHandlers.begin(); hitr != _eventHandlers.end() && !handled; ++hitr) { handled = (*hitr)->handle( *event, *this, 0, 0); } } } void SimpleViewer::frameUpdateTraversal() { double previousAspectRatio = ( static_cast<double>(_sceneView->getViewport()->width())/ static_cast<double>(_sceneView->getViewport()->height()) ); // update the viewport int width = _eventQueue->getCurrentEventState()->getWindowWidth(); int height = _eventQueue->getCurrentEventState()->getWindowHeight(); _sceneView->setViewport(0,0,width,height); double newAspectRatio = ( static_cast<double>(_sceneView->getViewport()->width())/ static_cast<double>(_sceneView->getViewport()->height()) ); // if aspect ratio adjusted change the project matrix to suit. if (previousAspectRatio != newAspectRatio) { osg::Matrixd& pm = _sceneView->getProjectionMatrix(); bool orthographicCamera = (pm(0,3)==0.0) && (pm(0,3)==0.0) && (pm(0,3)==0.0) && (pm(0,3)==1.0); if (orthographicCamera) { double left, right, bottom, top, zNear, zFar; _sceneView->getProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar); double mid = (right+left)*0.5; double halfWidth = (right-left)*0.5; left = mid - halfWidth * (newAspectRatio/previousAspectRatio); right = mid + halfWidth * (newAspectRatio/previousAspectRatio); _sceneView->setProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar); } else { double left, right, bottom, top, zNear, zFar; _sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar); double mid = (right+left)*0.5; double halfWidth = (right-left)*0.5; left = mid - halfWidth * (newAspectRatio/previousAspectRatio); right = mid + halfWidth * (newAspectRatio/previousAspectRatio); _sceneView->setProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar); } } if (_cameraManipulator.valid()) { _sceneView->setViewMatrix(_cameraManipulator->getInverseMatrix()); } if (_databasePager.valid()) { // tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame _databasePager->signalBeginFrame(_frameStamp.get()); // syncronize changes required by the DatabasePager thread to the scene graph _databasePager->updateSceneGraph(_frameStamp->getReferenceTime()); } _sceneView->update(); } void SimpleViewer::frameCullTraversal() { _sceneView->cull(); } void SimpleViewer::frameDrawTraversal() { _sceneView->draw(); if (_databasePager.valid()) { // tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame _databasePager->signalEndFrame(); // clean up and compile gl objects with a specified limit double availableTime = 0.0025; // 2.5 ms // compile any GL objects that are required. _databasePager->compileGLObjects(*(_sceneView->getState()),availableTime); // flush deleted GL objects. _sceneView->flushDeletedGLObjects(availableTime); } } void SimpleViewer::releaseAllGLObjects() { for(EventHandlers::iterator hitr = _eventHandlers.begin(); hitr != _eventHandlers.end(); ++hitr) { (*hitr)->releaseGLObjects(_sceneView->getState()); } if (_databasePager.valid()) { // clear the database pager so its starts a fresh on the next update/cull/draw traversals _databasePager->clear(); } // release the GL objects stored in the scene graph. _sceneView->releaseAllGLObjects(); } void SimpleViewer::cleanup() { releaseAllGLObjects(); // do a flush to delete all the OpenGL objects that have been deleted or released from the scene graph. _sceneView->flushAllDeletedGLObjects(); } <commit_msg>Added check against null SceneData to prevent crash with empty models<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgViewer/SimpleViewer> using namespace osgViewer; SimpleViewer::SimpleViewer(): _firstFrame(true) { _sceneView = new osgUtil::SceneView; _sceneView->setDefaults(); _sceneView->getState()->setContextID(osg::GraphicsContext::createNewContextID()); _startTick = osg::Timer::instance()->tick(); _frameStamp = new osg::FrameStamp; _frameStamp->setFrameNumber(0); _frameStamp->setReferenceTime(0); _eventQueue->setStartTick(_startTick); _eventVisitor = new osgGA::EventVisitor; setDatabasePager(new osgDB::DatabasePager); } SimpleViewer::~SimpleViewer() { _sceneView->releaseAllGLObjects(); osg::GraphicsContext::decrementContextIDUsageCount(_sceneView->getState()->getContextID()); } void SimpleViewer::setSceneData(osg::Node* node) { _sceneView->setSceneData(node); if (_cameraManipulator.valid()) { _cameraManipulator->setNode(node); osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent(); _cameraManipulator->home(*dummyEvent, *this); } if (_databasePager.valid()) { // register any PagedLOD that need to be tracked in the scene graph _databasePager->registerPagedLODs(node); } } osg::Node* SimpleViewer::getSceneData() { return _sceneView->getSceneData(); } const osg::Node* SimpleViewer::getSceneData() const { return _sceneView->getSceneData(); } osg::CameraNode* SimpleViewer::getCamera() { return _sceneView->getCamera(); } const osg::CameraNode* SimpleViewer::getCamera() const { return _sceneView->getCamera(); } void SimpleViewer::setCameraManipulator(osgGA::MatrixManipulator* manipulator) { if (_cameraManipulator == manipulator) return; _cameraManipulator = manipulator; if (_cameraManipulator.valid()) { _cameraManipulator->setNode(_sceneView->getSceneData()); osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent(); _cameraManipulator->home(*dummyEvent, *this); } } void SimpleViewer::addEventHandler(osgGA::GUIEventHandler* eventHandler) { _eventHandlers.push_back(eventHandler); } void SimpleViewer::setDatabasePager(osgDB::DatabasePager* dp) { _databasePager = dp; if (dp && _sceneView.valid()) { // need to register the DatabasePager with the SceneView's CullVisitor so it can pass on request // for files to be loaded. _sceneView->getCullVisitor()->setDatabaseRequestHandler(_databasePager.get()); } } void SimpleViewer::init() { osg::ref_ptr<osgGA::GUIEventAdapter> initEvent = _eventQueue->createEvent(); initEvent->setEventType(osgGA::GUIEventAdapter::FRAME); if (_cameraManipulator.valid()) { _cameraManipulator->init(*initEvent, *this); } } void SimpleViewer::frame() { if (_firstFrame) { init(); _firstFrame = false; } frameAdvance(); frameEventTraversal(); frameUpdateTraversal(); frameCullTraversal(); frameDrawTraversal(); } void SimpleViewer::frameAdvance() { osg::Timer_t currentTick = osg::Timer::instance()->tick(); _frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(_startTick,currentTick)); _frameStamp->setFrameNumber(_frameStamp->getFrameNumber()+1); _sceneView->setFrameStamp(_frameStamp.get()); } void SimpleViewer::frameEventTraversal() { _eventQueue->frame( _frameStamp->getReferenceTime() ); osgGA::EventQueue::Events events; _eventQueue->takeEvents(events); if (_eventVisitor.valid()) { _eventVisitor->setTraversalNumber(_frameStamp->getFrameNumber()); } for(osgGA::EventQueue::Events::iterator itr = events.begin(); itr != events.end(); ++itr) { osgGA::GUIEventAdapter* event = itr->get(); bool handled = false; if (_eventVisitor.valid() && getSceneData()) { _eventVisitor->reset(); _eventVisitor->addEvent( event ); getSceneData()->accept(*_eventVisitor); if (_eventVisitor->getEventHandled()) handled = true; } if (_cameraManipulator.valid()) { _cameraManipulator->handle( *event, *this ); } for(EventHandlers::iterator hitr = _eventHandlers.begin(); hitr != _eventHandlers.end() && !handled; ++hitr) { handled = (*hitr)->handle( *event, *this, 0, 0); } } } void SimpleViewer::frameUpdateTraversal() { double previousAspectRatio = ( static_cast<double>(_sceneView->getViewport()->width())/ static_cast<double>(_sceneView->getViewport()->height()) ); // update the viewport int width = _eventQueue->getCurrentEventState()->getWindowWidth(); int height = _eventQueue->getCurrentEventState()->getWindowHeight(); _sceneView->setViewport(0,0,width,height); double newAspectRatio = ( static_cast<double>(_sceneView->getViewport()->width())/ static_cast<double>(_sceneView->getViewport()->height()) ); // if aspect ratio adjusted change the project matrix to suit. if (previousAspectRatio != newAspectRatio) { osg::Matrixd& pm = _sceneView->getProjectionMatrix(); bool orthographicCamera = (pm(0,3)==0.0) && (pm(0,3)==0.0) && (pm(0,3)==0.0) && (pm(0,3)==1.0); if (orthographicCamera) { double left, right, bottom, top, zNear, zFar; _sceneView->getProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar); double mid = (right+left)*0.5; double halfWidth = (right-left)*0.5; left = mid - halfWidth * (newAspectRatio/previousAspectRatio); right = mid + halfWidth * (newAspectRatio/previousAspectRatio); _sceneView->setProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar); } else { double left, right, bottom, top, zNear, zFar; _sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar); double mid = (right+left)*0.5; double halfWidth = (right-left)*0.5; left = mid - halfWidth * (newAspectRatio/previousAspectRatio); right = mid + halfWidth * (newAspectRatio/previousAspectRatio); _sceneView->setProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar); } } if (_cameraManipulator.valid()) { _sceneView->setViewMatrix(_cameraManipulator->getInverseMatrix()); } if (_databasePager.valid()) { // tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame _databasePager->signalBeginFrame(_frameStamp.get()); // syncronize changes required by the DatabasePager thread to the scene graph _databasePager->updateSceneGraph(_frameStamp->getReferenceTime()); } _sceneView->update(); } void SimpleViewer::frameCullTraversal() { _sceneView->cull(); } void SimpleViewer::frameDrawTraversal() { _sceneView->draw(); if (_databasePager.valid()) { // tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame _databasePager->signalEndFrame(); // clean up and compile gl objects with a specified limit double availableTime = 0.0025; // 2.5 ms // compile any GL objects that are required. _databasePager->compileGLObjects(*(_sceneView->getState()),availableTime); // flush deleted GL objects. _sceneView->flushDeletedGLObjects(availableTime); } } void SimpleViewer::releaseAllGLObjects() { for(EventHandlers::iterator hitr = _eventHandlers.begin(); hitr != _eventHandlers.end(); ++hitr) { (*hitr)->releaseGLObjects(_sceneView->getState()); } if (_databasePager.valid()) { // clear the database pager so its starts a fresh on the next update/cull/draw traversals _databasePager->clear(); } // release the GL objects stored in the scene graph. _sceneView->releaseAllGLObjects(); } void SimpleViewer::cleanup() { releaseAllGLObjects(); // do a flush to delete all the OpenGL objects that have been deleted or released from the scene graph. _sceneView->flushAllDeletedGLObjects(); } <|endoftext|>
<commit_before>/** * @author Mike Bogochow * @version 2.4.0, Dec 8, 2015 * * @file Auctioneer.cpp * * Auctioneer class implementation */ #include "Auctioneer.h" #include "../lib_graphs/defs.h" #include "../lib_auction/AuctionDefs.h" #include "../lib_auction/DebugPrinter.h" #include "MBUtils.h" #include <boost/algorithm/string/predicate.hpp> // starts_with #include <boost/lexical_cast.hpp> Auctioneer::Auctioneer(void) { m_iterations = 0; roundNumber = 0; numberOfBidders = -1; bids = nullptr; numReceivedBids = 0; } Auctioneer::~Auctioneer(void) { if (bids != nullptr) delete bids; } bool Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail) { bool ret = AuctionMOOSApp::OnNewMail(NewMail); dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes); if (roundNumber < __num_nodes) //TODO come up with better solution of stopping auctioneer { MOOSMSG_LIST::reverse_iterator p; for(p = NewMail.rbegin(); p!=NewMail.rend(); p++) { CMOOSMsg &msg = *p; std::string key = msg.GetKey(); MOOSTrace("key=%s\n", key.c_str()); if (boost::starts_with(key, MVAR_BID_HEADER)) { int bidder = getBidder(key); bids[bidder] = bidFromString(msg.GetString()); numReceivedBids += 1; dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", key.c_str(), msg.GetString().c_str()); } } } return ret; } bool Auctioneer::Iterate(void) { bool ret = AuctionMOOSApp::Iterate(); dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes); if (roundNumber < __num_nodes) //TODO come up with better solution of stopping auctioneer { dp.dprintf(LVL_MIN_VERB, "numReceivedBids=%i\n", numReceivedBids); if (roundNumber == 0) doNotify(MVAR_BID_START, ++roundNumber); else if (numReceivedBids == numberOfBidders) { // All bids received for round WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT }; // Calculate winner for (int i = 0; i < numberOfBidders; i++) { if (bids[i].second < winner.bid) { winner.winner = i; winner.target = bids[i].first; winner.bid = bids[i].second; } } // Send winner doNotify(MVAR_BID_WINNER, winningBidToString(winner)); doNotify(MVAR_BID_START, ++roundNumber); numReceivedBids = 0; } } return ret; } bool Auctioneer::OnStartUp(void) { bool ret; // Read the DebugOutput configuration field int debugLevel; if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel)) debugLevel = LVL_OFF; dp.setLevel((DebugLevel)debugLevel); MOOSTrace("dbgLvl: %i\n", debugLevel); ret = AuctionMOOSApp::OnStartUp(); if (!m_MissionReader.GetConfigurationParam("NumBidders", numberOfBidders)) { MOOSTrace("Warning: parameter 'NumBidders' not specified.\n"); MOOSTrace("Terminating\n"); exit(-1); } else this->bids = new Bid[numberOfBidders]; MOOSTrace("NumBidders: %i\n", numberOfBidders); RegisterVariables(); return ret; } bool Auctioneer::OnConnectToServer(void) { bool ret = AuctionMOOSApp::OnConnectToServer(); RegisterVariables(); return ret; } void Auctioneer::RegisterVariables(void) { for (int i = 0; i < numberOfBidders; i++) { std::string key = getBidVar(i); dp.dprintf(LVL_MIN_VERB, "Registering %s\n", key); m_Comms.Register(key, 0); } } <commit_msg>fixed output<commit_after>/** * @author Mike Bogochow * @version 2.4.0, Dec 8, 2015 * * @file Auctioneer.cpp * * Auctioneer class implementation */ #include "Auctioneer.h" #include "../lib_graphs/defs.h" #include "../lib_auction/AuctionDefs.h" #include "../lib_auction/DebugPrinter.h" #include "MBUtils.h" #include <boost/algorithm/string/predicate.hpp> // starts_with #include <boost/lexical_cast.hpp> Auctioneer::Auctioneer(void) { m_iterations = 0; roundNumber = 0; numberOfBidders = -1; bids = nullptr; numReceivedBids = 0; } Auctioneer::~Auctioneer(void) { if (bids != nullptr) delete bids; } bool Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail) { bool ret = AuctionMOOSApp::OnNewMail(NewMail); dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes); if (roundNumber < __num_nodes) //TODO come up with better solution of stopping auctioneer { MOOSMSG_LIST::reverse_iterator p; for(p = NewMail.rbegin(); p!=NewMail.rend(); p++) { CMOOSMsg &msg = *p; std::string key = msg.GetKey(); MOOSTrace("key=%s\n", key.c_str()); if (boost::starts_with(key, MVAR_BID_HEADER)) { int bidder = getBidder(key); bids[bidder] = bidFromString(msg.GetString()); numReceivedBids += 1; dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", key.c_str(), msg.GetString().c_str()); } } } return ret; } bool Auctioneer::Iterate(void) { bool ret = AuctionMOOSApp::Iterate(); dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes); if (roundNumber < __num_nodes) //TODO come up with better solution of stopping auctioneer { dp.dprintf(LVL_MIN_VERB, "numReceivedBids=%i\n", numReceivedBids); if (roundNumber == 0) doNotify(MVAR_BID_START, ++roundNumber); else if (numReceivedBids == numberOfBidders) { // All bids received for round WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT }; // Calculate winner for (int i = 0; i < numberOfBidders; i++) { if (bids[i].second < winner.bid) { winner.winner = i; winner.target = bids[i].first; winner.bid = bids[i].second; } } // Send winner doNotify(MVAR_BID_WINNER, winningBidToString(winner)); doNotify(MVAR_BID_START, ++roundNumber); numReceivedBids = 0; } } return ret; } bool Auctioneer::OnStartUp(void) { bool ret; // Read the DebugOutput configuration field int debugLevel; if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel)) debugLevel = LVL_OFF; dp.setLevel((DebugLevel)debugLevel); MOOSTrace("dbgLvl: %i\n", debugLevel); ret = AuctionMOOSApp::OnStartUp(); if (!m_MissionReader.GetConfigurationParam("NumBidders", numberOfBidders)) { MOOSTrace("Warning: parameter 'NumBidders' not specified.\n"); MOOSTrace("Terminating\n"); exit(-1); } else this->bids = new Bid[numberOfBidders]; MOOSTrace("NumBidders: %i\n", numberOfBidders); RegisterVariables(); return ret; } bool Auctioneer::OnConnectToServer(void) { bool ret = AuctionMOOSApp::OnConnectToServer(); RegisterVariables(); return ret; } void Auctioneer::RegisterVariables(void) { for (int i = 0; i < numberOfBidders; i++) { std::string key = getBidVar(i); dp.dprintf(LVL_MIN_VERB, "Registering %s\n", key.c_str()); m_Comms.Register(key, 0); } } <|endoftext|>
<commit_before>/** * @author Mike Bogochow * @version 2.4.0, Dec 8, 2015 * * @file Auctioneer.cpp * * Auctioneer class implementation */ #include "Auctioneer.h" #include "../lib_graphs/defs.h" #include "../lib_auction/AuctionDefs.h" #include "../lib_auction/DebugPrinter.h" #include "MBUtils.h" #include <boost/algorithm/string/predicate.hpp> // starts_with Auctioneer::Auctioneer(void) { m_iterations = 0; roundNumber = 0; numberOfBidders = -1; bids = nullptr; numReceivedBids = 0; } Auctioneer::~Auctioneer(void) { if (bids != nullptr) delete bids; } bool Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail) { bool ret = AuctionMOOSApp::OnNewMail(NewMail); dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes); if (roundNumber <= __num_nodes) //TODO come up with better solution of stopping auctioneer { MOOSMSG_LIST::reverse_iterator p; for(p = NewMail.rbegin(); p!=NewMail.rend(); p++) { CMOOSMsg &msg = *p; std::string key = msg.GetKey(); if (boost::starts_with(key, MVAR_BID_HEADER)) { int bidder = getBidder(key); bids[bidder] = bidFromString(msg.GetString()); numReceivedBids += 1; dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", key.c_str(), msg.GetString().c_str()); } } } return ret; } bool Auctioneer::Iterate(void) { bool ret = AuctionMOOSApp::Iterate(); dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes); if (roundNumber <= __num_nodes) //TODO come up with better solution of stopping auctioneer { dp.dprintf(LVL_MIN_VERB, "numReceivedBids=%i\n", numReceivedBids); if (roundNumber == 0) doNotify(MVAR_BID_START, ++roundNumber); else if (numReceivedBids == numberOfBidders) { // All bids received for round WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT }; // Calculate winner for (int i = 0; i < numberOfBidders; i++) { if (bids[i].second < winner.bid) { winner.winner = i; winner.target = bids[i].first; winner.bid = bids[i].second; } } // Send winner doNotify(MVAR_BID_WINNER, winningBidToString(winner)); doNotify(MVAR_BID_START, ++roundNumber); numReceivedBids = 0; } else doNotify(MVAR_BID_START, roundNumber); } else { // Exit pAuctioneer doNotify("EXITED_NORMALLY", "pAuctioneer"); // // Ensure data is passed to auctioneer std::this_thread::sleep_for(std::chrono::milliseconds(1000 * 10)); exit(0); } return ret; } bool Auctioneer::OnStartUp(void) { bool ret; // Read the DebugOutput configuration field int debugLevel; if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel)) debugLevel = LVL_OFF; dp.setLevel((DebugLevel)debugLevel); ret = AuctionMOOSApp::OnStartUp(); if (!m_MissionReader.GetConfigurationParam("NumBidders", numberOfBidders)) { MOOSTrace("Warning: parameter 'NumBidders' not specified.\n"); MOOSTrace("Terminating\n"); exit(-1); } else this->bids = new Bid[numberOfBidders]; RegisterVariables(); return ret; } bool Auctioneer::OnConnectToServer(void) { bool ret = AuctionMOOSApp::OnConnectToServer(); RegisterVariables(); return ret; } void Auctioneer::RegisterVariables(void) { for (int i = 0; i < numberOfBidders; i++) { std::string key = getBidVar(i); dp.dprintf(LVL_MIN_VERB, "Registering %s\n", key.c_str()); m_Comms.Register(key, 0); } } <commit_msg>Added headers<commit_after>/** * @author Mike Bogochow * @version 2.4.0, Dec 8, 2015 * * @file Auctioneer.cpp * * Auctioneer class implementation */ #include "Auctioneer.h" #include "../lib_graphs/defs.h" #include "../lib_auction/AuctionDefs.h" #include "../lib_auction/DebugPrinter.h" #include "MBUtils.h" #include <boost/algorithm/string/predicate.hpp> // starts_with #include <chrono> #include <thread> Auctioneer::Auctioneer(void) { m_iterations = 0; roundNumber = 0; numberOfBidders = -1; bids = nullptr; numReceivedBids = 0; } Auctioneer::~Auctioneer(void) { if (bids != nullptr) delete bids; } bool Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail) { bool ret = AuctionMOOSApp::OnNewMail(NewMail); dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes); if (roundNumber <= __num_nodes) //TODO come up with better solution of stopping auctioneer { MOOSMSG_LIST::reverse_iterator p; for(p = NewMail.rbegin(); p!=NewMail.rend(); p++) { CMOOSMsg &msg = *p; std::string key = msg.GetKey(); if (boost::starts_with(key, MVAR_BID_HEADER)) { int bidder = getBidder(key); bids[bidder] = bidFromString(msg.GetString()); numReceivedBids += 1; dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", key.c_str(), msg.GetString().c_str()); } } } return ret; } bool Auctioneer::Iterate(void) { bool ret = AuctionMOOSApp::Iterate(); dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes); if (roundNumber <= __num_nodes) //TODO come up with better solution of stopping auctioneer { dp.dprintf(LVL_MIN_VERB, "numReceivedBids=%i\n", numReceivedBids); if (roundNumber == 0) doNotify(MVAR_BID_START, ++roundNumber); else if (numReceivedBids == numberOfBidders) { // All bids received for round WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT }; // Calculate winner for (int i = 0; i < numberOfBidders; i++) { if (bids[i].second < winner.bid) { winner.winner = i; winner.target = bids[i].first; winner.bid = bids[i].second; } } // Send winner doNotify(MVAR_BID_WINNER, winningBidToString(winner)); doNotify(MVAR_BID_START, ++roundNumber); numReceivedBids = 0; } else doNotify(MVAR_BID_START, roundNumber); } else { // Exit pAuctioneer doNotify("EXITED_NORMALLY", "pAuctioneer"); // // Ensure data is passed to auctioneer std::this_thread::sleep_for(std::chrono::milliseconds(1000 * 10)); exit(0); } return ret; } bool Auctioneer::OnStartUp(void) { bool ret; // Read the DebugOutput configuration field int debugLevel; if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel)) debugLevel = LVL_OFF; dp.setLevel((DebugLevel)debugLevel); ret = AuctionMOOSApp::OnStartUp(); if (!m_MissionReader.GetConfigurationParam("NumBidders", numberOfBidders)) { MOOSTrace("Warning: parameter 'NumBidders' not specified.\n"); MOOSTrace("Terminating\n"); exit(-1); } else this->bids = new Bid[numberOfBidders]; RegisterVariables(); return ret; } bool Auctioneer::OnConnectToServer(void) { bool ret = AuctionMOOSApp::OnConnectToServer(); RegisterVariables(); return ret; } void Auctioneer::RegisterVariables(void) { for (int i = 0; i < numberOfBidders; i++) { std::string key = getBidVar(i); dp.dprintf(LVL_MIN_VERB, "Registering %s\n", key.c_str()); m_Comms.Register(key, 0); } } <|endoftext|>
<commit_before>#include <Empathy/Empathy/Empathy.h> #include <Empathy/empathy-linear/linear_empathy.h> #include <irrKlang.h> #include <GLFW/glfw3.h> #include <muParser.h> #include <Empathy/Brain/CustomLogic/Calming_1.h> #define FULL_SCREEN false #if FULL_SCREEN #define RENDER_SIZE 768 #define SC_SIZE_X 1366 #define SC_SIZE_Y 768 #else #define RENDER_SIZE 690 #define SC_SIZE_X 700 #define SC_SIZE_Y 700 #endif using namespace std; static GLFWwindow * window; static GLfloat mouseX,mouseY; irrklang::ISoundEngine* engine; static GLdouble lastPressTime; static GLdouble thresholdTime=0.2; static GLboolean mousePressed=GL_FALSE; void createClickEvent(int button=GLFW_MOUSE_BUTTON_LEFT){ empathy::radio::Event event(EMPATHY_EVENT_ACTION_NONE); if(button==GLFW_MOUSE_BUTTON_LEFT ){ event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_LEFT_KEY_PRESS); }else if(button==GLFW_MOUSE_BUTTON_RIGHT){ event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_RIGHT_KEY_PRESS); } event.putDouble(EMPATHY_MOUSE_XPOS,mouseX); event.putDouble(EMPATHY_MOUSE_YPOS,RENDER_SIZE-mouseY); empathy::radio::BroadcastStation::emit(event); } void mouse_input_callback(GLFWwindow *window, int button, int action, int mods) { if(action==GLFW_PRESS){ createClickEvent(button); lastPressTime=glfwGetTime(); mousePressed=GL_TRUE; }else if(action==GLFW_RELEASE){ lastPressTime=0; mousePressed=GL_FALSE; } } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { // std::cout<<"key call back received"<<action<<std::endl; // When a user presses the escape key, we set the WindowShouldClose property to true, // closing the application if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ // glfwSetWindowShouldClose(instance->window, GL_TRUE); empathy_linear::makeReadyToClose(); return; } std::string myAction=""; if(action==GLFW_PRESS){ myAction=EMPATHY_EVENT_INPUT_KEY_PRESS; }else if(action==GLFW_RELEASE){ myAction=EMPATHY_EVENT_INPUT_KEY_RELEASE; }else if(action==GLFW_REPEAT){ myAction=EMPATHY_EVENT_INPUT_KEY_REPEAT; } if(myAction != ""){ empathy::radio::Event event(myAction); event.putInt(EMPATHY_EVENT_INPUT_KEY,key); empathy::radio::BroadcastStation::emit(event); } } void mouse_position_callback(GLFWwindow *window, double xpos, double ypos) { mouseX= xpos -(SC_SIZE_X-RENDER_SIZE)/2;; mouseY = ypos - (SC_SIZE_Y-RENDER_SIZE)/2; } void initGlfw() { // cout<<"glfwInit"<<endl; glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //Create a GLFW window window = glfwCreateWindow((GLuint)SC_SIZE_X, (GLuint)SC_SIZE_Y, "Empathy | <3", FULL_SCREEN ? glfwGetPrimaryMonitor(): nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); //set event receiver call backs. glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window,mouse_input_callback); glfwSetCursorPosCallback(window,mouse_position_callback); } void init(){ initGlfw(); empathy_linear::init(); empathy_linear::setScreenMargins( (SC_SIZE_X-RENDER_SIZE)/2 , (SC_SIZE_Y-RENDER_SIZE)/2); empathy_linear::setScreenSize(RENDER_SIZE); // empathy_linear::addJsonBrain("brains/Calming_1.json"); empathy_linear::addBrain(new empathy::brain::Calming_1()); // empathy_linear::addJsonBrain("brains/CanonInD.json"); // empathy_linear::addEmotionBrain(); empathy_linear::addDummyTouchBrain(); engine = irrklang::createIrrKlangDevice(); if (!engine) { printf("Could not startup engine\n"); exit(EXIT_FAILURE); } engine->setSoundVolume(0.4f); } void loop(){ while(! empathy_linear::shouldClose() && !glfwWindowShouldClose(window)){ std::stack<empathy::moonlight::BasicNote> audioEvents= empathy_linear::getMusicalKeyboardEvents(); while(! audioEvents.empty()){ empathy::moonlight::BasicNote playableItem=audioEvents.top(); std::string fileName=playableItem.getNote(); fileName += playableItem.getOctave()<=1?"":std::to_string(playableItem.getOctave()-1); if(playableItem.isSharp()){ fileName="#"+fileName; } std::string path=empathy::getAssetPath("audio/keyboard/music/"+fileName+".mp3"); try{ // cout<<"Playing audio "<<fileName<<endl; engine->play2D(path.c_str()); }catch (int i){ cout<<"Could not play "<<path<<endl; continue; } audioEvents.pop(); } if(mousePressed && glfwGetTime()-lastPressTime>thresholdTime){ createClickEvent(); } glfwPollEvents(); empathy_linear::loop(); empathy_linear::setTime((GLfloat ) glfwGetTime()); glfwSwapBuffers(window); } } void flush(){ engine->drop(); empathy_linear::flush(); if(window!= nullptr) glfwSetWindowShouldClose(window,true); glfwTerminate(); } int main() { init(); loop(); flush(); } <commit_msg>Updated __Main__.cpp to accept standard text input from system using GLFW::character_callback.<commit_after>#include <Empathy/Empathy/Empathy.h> #include <Empathy/empathy-linear/linear_empathy.h> #include <irrKlang.h> #include <GLFW/glfw3.h> #include <muParser.h> #include <Empathy/Brain/CustomLogic/Calming_1.h> #define FULL_SCREEN false #if FULL_SCREEN #define RENDER_SIZE 768 #define SC_SIZE_X 1366 #define SC_SIZE_Y 768 #else #define RENDER_SIZE 690 #define SC_SIZE_X 700 #define SC_SIZE_Y 700 #endif using namespace std; static GLFWwindow * window; static GLfloat mouseX,mouseY; irrklang::ISoundEngine* engine; static GLdouble lastPressTime; static GLdouble thresholdTime=0.2; static GLboolean mousePressed=GL_FALSE; void createClickEvent(int button=GLFW_MOUSE_BUTTON_LEFT){ empathy::radio::Event event(EMPATHY_EVENT_ACTION_NONE); if(button==GLFW_MOUSE_BUTTON_LEFT ){ event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_LEFT_KEY_PRESS); }else if(button==GLFW_MOUSE_BUTTON_RIGHT){ event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_RIGHT_KEY_PRESS); } event.putDouble(EMPATHY_MOUSE_XPOS,mouseX); event.putDouble(EMPATHY_MOUSE_YPOS,RENDER_SIZE-mouseY); empathy::radio::BroadcastStation::emit(event); } void mouse_input_callback(GLFWwindow *window, int button, int action, int mods) { if(action==GLFW_PRESS){ createClickEvent(button); lastPressTime=glfwGetTime(); mousePressed=GL_TRUE; }else if(action==GLFW_RELEASE){ lastPressTime=0; mousePressed=GL_FALSE; } } void character_callback(GLFWwindow* window, unsigned int codepoint){ std::string myAction=EMPATHY_EVENT_INPUT_KEY_PRESS; empathy::radio::Event event(myAction); event.putInt(EMPATHY_EVENT_INPUT_KEY, codepoint); empathy::radio::BroadcastStation::emit(event); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { // std::cout<<"key call back received"<<action<<std::endl; // When a user presses the escape key, we set the WindowShouldClose property to true, // closing the application if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ // glfwSetWindowShouldClose(instance->window, GL_TRUE); empathy_linear::makeReadyToClose(); return; } if(key == GLFW_KEY_ENTER){ empathy::radio::Event event(EMPATHY_EVENT_INPUT_KEY_PRESS); event.putInt(EMPATHY_EVENT_INPUT_KEY,key); empathy::radio::BroadcastStation::emit(event); } } void mouse_position_callback(GLFWwindow *window, double xpos, double ypos) { mouseX= xpos -(SC_SIZE_X-RENDER_SIZE)/2;; mouseY = ypos - (SC_SIZE_Y-RENDER_SIZE)/2; } void initGlfw() { // cout<<"glfwInit"<<endl; glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //Create a GLFW window window = glfwCreateWindow((GLuint)SC_SIZE_X, (GLuint)SC_SIZE_Y, "Empathy | <3", FULL_SCREEN ? glfwGetPrimaryMonitor(): nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSetCharCallback(window, character_callback); //set event receiver call backs. glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window,mouse_input_callback); glfwSetCursorPosCallback(window,mouse_position_callback); } void init(){ initGlfw(); empathy_linear::init(); empathy_linear::setScreenMargins( (SC_SIZE_X-RENDER_SIZE)/2 , (SC_SIZE_Y-RENDER_SIZE)/2); empathy_linear::setScreenSize(RENDER_SIZE); // empathy_linear::addJsonBrain("brains/Calming_1.json"); empathy_linear::addBrain(new empathy::brain::Calming_1()); // empathy_linear::addJsonBrain("brains/CanonInD.json"); // empathy_linear::addEmotionBrain(); empathy_linear::addDummyTouchBrain(); engine = irrklang::createIrrKlangDevice(); if (!engine) { printf("Could not startup engine\n"); exit(EXIT_FAILURE); } engine->setSoundVolume(0.4f); } void loop(){ while(! empathy_linear::shouldClose() && !glfwWindowShouldClose(window)){ std::stack<empathy::moonlight::BasicNote> audioEvents= empathy_linear::getMusicalKeyboardEvents(); while(! audioEvents.empty()){ empathy::moonlight::BasicNote playableItem=audioEvents.top(); std::string fileName=playableItem.getNote(); fileName += playableItem.getOctave()<=1?"":std::to_string(playableItem.getOctave()-1); if(playableItem.isSharp()){ fileName="#"+fileName; } std::string path=empathy::getAssetPath("audio/keyboard/music/"+fileName+".mp3"); try{ // cout<<"Playing audio "<<fileName<<endl; engine->play2D(path.c_str()); }catch (int i){ cout<<"Could not play "<<path<<endl; continue; } audioEvents.pop(); } if(mousePressed && glfwGetTime()-lastPressTime>thresholdTime){ createClickEvent(); } glfwPollEvents(); empathy_linear::loop(); empathy_linear::setTime((GLfloat ) glfwGetTime()); glfwSwapBuffers(window); } } void flush(){ engine->drop(); empathy_linear::flush(); if(window!= nullptr) glfwSetWindowShouldClose(window,true); glfwTerminate(); } int main() { init(); loop(); flush(); } <|endoftext|>
<commit_before>//---------------------------- crash_10.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2005, 2006 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- crash_10.cc --------------------------- // a version of hp_hanging_node_02 that crashed at the time // of writing the time #include <base/logstream.h> #include <grid/tria.h> #include <dofs/dof_handler.h> #include <dofs/dof_constraints.h> #include <grid/grid_generator.h> #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <fe/fe_q.h> #include <dofs/dof_tools.h> #include <fstream> std::ofstream logfile("crash_10/output"); template <int dim> void test () { Triangulation<dim> triangulation; hp::FECollection<dim> fe; hp::DoFHandler<dim> dof_handler(triangulation); ConstraintMatrix hanging_node_constraints; FE_Q<dim> fe_1 (1), fe_2 (2), fe_3 (3), fe_4 (4); fe.push_back (fe_1); fe.push_back (fe_2); fe.push_back (fe_3); fe.push_back (fe_4); GridGenerator::hyper_cube (triangulation, -1, 1); triangulation.refine_global (5-dim); deallog << "Number of active cells: " << triangulation.n_active_cells() << std::endl; deallog << "Total number of cells: " << triangulation.n_cells() << std::endl; // Now to the p-Method. Assign // random active_fe_indices to the // different cells. typename hp::DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active (), endc = dof_handler.end (); for (; cell != endc; ++cell) cell->set_active_fe_index (random() % 4); dof_handler.distribute_dofs (fe); DoFTools::make_hanging_node_constraints (dof_handler, hanging_node_constraints); hanging_node_constraints.print (deallog.get_file_stream ()); hanging_node_constraints.close (); } int main () { logfile.precision(2); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); // this test depends on the right // starting value of the random // number generator. set it to the // same value it has in // hp_hanging_nodes_02 for (unsigned int i=0; i<64; ++i) random (); test<3> (); return 0; } <commit_msg>Minor changes without net effect<commit_after>//---------------------------- crash_10.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2005, 2006 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- crash_10.cc --------------------------- // a version of hp_hanging_node_02 that crashed at the time // of writing the time #include <base/logstream.h> #include <grid/tria.h> #include <dofs/dof_handler.h> #include <dofs/dof_constraints.h> #include <grid/grid_generator.h> #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <fe/fe_q.h> #include <dofs/dof_tools.h> #include <fstream> std::ofstream logfile("crash_10/output"); template <int dim> void test () { Triangulation<dim> triangulation; hp::FECollection<dim> fe; hp::DoFHandler<dim> dof_handler(triangulation); ConstraintMatrix hanging_node_constraints; FE_Q<dim> fe_1 (1), fe_2 (2), fe_3 (3), fe_4 (4); fe.push_back (fe_1); fe.push_back (fe_2); fe.push_back (fe_3); fe.push_back (fe_4); GridGenerator::hyper_cube (triangulation, -1, 1); triangulation.refine_global (2); deallog << "Number of active cells: " << triangulation.n_active_cells() << std::endl; deallog << "Total number of cells: " << triangulation.n_cells() << std::endl; // Now to the p-Method. Assign // random active_fe_indices to the // different cells. typename hp::DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active (), endc = dof_handler.end (); for (; cell != endc; ++cell) cell->set_active_fe_index (random() % fe.size()); dof_handler.distribute_dofs (fe); DoFTools::make_hanging_node_constraints (dof_handler, hanging_node_constraints); hanging_node_constraints.print (deallog.get_file_stream ()); hanging_node_constraints.close (); } int main () { logfile.precision(2); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); // this test depends on the right // starting value of the random // number generator. set it to the // same value it has in // hp_hanging_nodes_02 for (unsigned int i=0; i<64; ++i) random (); test<3> (); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sysdata.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 _SV_SYSDATA_HXX #define _SV_SYSDATA_HXX // ----------------- // - SystemEnvData - // ----------------- struct SystemEnvData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) || defined( OS2 ) HWND hWnd; // the window hwnd #elif defined( QUARTZ ) NSView* pView; // the cocoa view ptr implementing this object #elif defined( UNX ) void* pDisplay; // the relevant display connection long aWindow; // the window of the object void* pSalFrame; // contains a salframe, if object has one void* pWidget; // the corresponding widget void* pVisual; // the visual in use int nDepth; // depth of said visual long aColormap; // the colormap being used void* pAppContext; // the application context in use long aShellWindow; // the window of the frame's shell void* pShellWidget; // the frame's shell widget #endif }; #define SystemChildData SystemEnvData // -------------------- // - SystemParentData - // -------------------- struct SystemParentData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) || defined( OS2 ) HWND hWnd; // the window hwnd #elif defined( QUARTZ ) NSView* pView; // the cocoa view ptr implementing this object #elif defined( UNX ) long aWindow; // the window of the object bool bXEmbedSupport:1; // decides whether the object in question // should support the XEmbed protocol #endif }; // -------------------- // - SystemMenuData - // -------------------- struct SystemMenuData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) HMENU hMenu; // the menu handle of the menu bar #elif defined( UNX ) long aMenu; // ??? #endif }; // -------------------- // - SystemGraphicsData - // -------------------- struct SystemGraphicsData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) HDC hDC; // handle to a device context #elif defined( QUARTZ ) CGContextRef rCGContext; // QUARTZ graphic context #elif defined( UNX ) long hDrawable; // a drawable void* pRenderFormat; // render format for drawable #endif }; // -------------------- // - SystemWindowData - // -------------------- struct SystemWindowData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) // meaningless on Windows #elif defined( QUARTZ ) // meaningless on Mac OS X / Quartz #elif defined( UNX ) void* pVisual; // the visual to be used #endif }; #endif // _SV_SYSDATA_HXX <commit_msg>INTEGRATION: CWS aquabmpfix01 (1.7.74); FILE MERGED 2008/05/15 08:26:06 hdu 1.7.74.4: #i89495# Aqua: better integration with quartz-cairo-canvas 2008/05/09 11:09:05 hdu 1.7.74.3: RESYNC: (1.7-1.8); FILE MERGED 2008/04/26 05:43:16 mox 1.7.74.2: Follow the sysdata.hxx naming conventions (and distinguish from internal mxLayer variable) 2008/04/25 15:42:06 hdu 1.7.74.1: #i87689# refactor AquaSalGraphic to avoid excessive Quartz bitmap operations<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: sysdata.hxx,v $ * $Revision: 1.9 $ * * 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 _SV_SYSDATA_HXX #define _SV_SYSDATA_HXX // ----------------- // - SystemEnvData - // ----------------- struct SystemEnvData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) || defined( OS2 ) HWND hWnd; // the window hwnd #elif defined( QUARTZ ) NSView* pView; // the cocoa view ptr implementing this object #elif defined( UNX ) void* pDisplay; // the relevant display connection long aWindow; // the window of the object void* pSalFrame; // contains a salframe, if object has one void* pWidget; // the corresponding widget void* pVisual; // the visual in use int nDepth; // depth of said visual long aColormap; // the colormap being used void* pAppContext; // the application context in use long aShellWindow; // the window of the frame's shell void* pShellWidget; // the frame's shell widget #endif }; #define SystemChildData SystemEnvData // -------------------- // - SystemParentData - // -------------------- struct SystemParentData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) || defined( OS2 ) HWND hWnd; // the window hwnd #elif defined( QUARTZ ) NSView* pView; // the cocoa view ptr implementing this object #elif defined( UNX ) long aWindow; // the window of the object bool bXEmbedSupport:1; // decides whether the object in question // should support the XEmbed protocol #endif }; // -------------------- // - SystemMenuData - // -------------------- struct SystemMenuData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) HMENU hMenu; // the menu handle of the menu bar #elif defined( UNX ) long aMenu; // ??? #endif }; // -------------------- // - SystemGraphicsData - // -------------------- struct SystemGraphicsData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) HDC hDC; // handle to a device context #elif defined( QUARTZ ) CGContextRef rCGContext; // QUARTZ graphic context #elif defined( UNX ) long hDrawable; // a drawable void* pRenderFormat; // render format for drawable #endif }; // -------------------- // - SystemWindowData - // -------------------- struct SystemWindowData { unsigned long nSize; // size in bytes of this structure #if defined( WNT ) // meaningless on Windows #elif defined( QUARTZ ) // meaningless on Mac OS X / Quartz #elif defined( UNX ) void* pVisual; // the visual to be used #endif }; #endif // _SV_SYSDATA_HXX <|endoftext|>
<commit_before>/* * Shared memory for sharing data between worker processes. * * author: Max Kellermann <mk@cm4all.com> */ #include "shm.hxx" #include "lock.h" #include "util/RefCount.hxx" #include <inline/poison.h> #include <inline/list.h> #include <daemon/log.h> #include <assert.h> #include <stdint.h> #include <sys/mman.h> #include <errno.h> #include <string.h> struct page { struct list_head siblings; unsigned num_pages; uint8_t *data; }; struct shm { RefCount ref; size_t page_size; unsigned num_pages; /** this lock protects the linked list */ struct lock lock; struct list_head available; struct page pages[1]; }; static inline unsigned calc_header_pages(size_t page_size, unsigned num_pages) { size_t header_size = sizeof(struct shm) + (num_pages - 1) * sizeof(struct page); return (header_size + page_size - 1) / page_size; } gcc_const static uint8_t * shm_at(struct shm *shm, size_t offset) { return (uint8_t *)shm + offset; } static uint8_t * shm_data(struct shm *shm) { unsigned header_pages = calc_header_pages(shm->page_size, shm->num_pages); return shm_at(shm, shm->page_size * header_pages); } struct shm * shm_new(size_t page_size, unsigned num_pages) { assert(page_size >= sizeof(size_t)); assert(num_pages > 0); const unsigned header_pages = calc_header_pages(page_size, num_pages); void *p = mmap(nullptr, page_size * (header_pages + num_pages), PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0); if (p == (void *)-1) return nullptr; struct shm *shm = (struct shm *)p; shm->ref.Init(); shm->page_size = page_size; shm->num_pages = num_pages; lock_init(&shm->lock); list_init(&shm->available); list_add(&shm->pages[0].siblings, &shm->available); shm->pages[0].num_pages = num_pages; shm->pages[0].data = shm_data(shm); #if 0 /* disabled because this causes page faults and immediately allocates physical memory for the areas that aren't used yet */ poison_noaccess(shm_data(shm), page_size * num_pages); #endif return shm; } void shm_ref(struct shm *shm) { assert(shm != nullptr); shm->ref.Get(); } void shm_close(struct shm *shm) { unsigned header_pages; int ret; assert(shm != nullptr); if (shm->ref.Put()) lock_destroy(&shm->lock); header_pages = calc_header_pages(shm->page_size, shm->num_pages); ret = munmap(shm, shm->page_size * (header_pages + shm->num_pages)); if (ret < 0) daemon_log(1, "munmap() failed: %s\n", strerror(errno)); } size_t shm_page_size(const struct shm *shm) { return shm->page_size; } static struct page * shm_find_available(struct shm *shm, unsigned num_pages) { for (struct page *page = (struct page *)shm->available.next; &page->siblings != &shm->available; page = (struct page *)page->siblings.next) if (page->num_pages >= num_pages) return page; return nullptr; } static struct page * shm_split_page(const struct shm *shm, struct page *page, unsigned num_pages) { assert(page->num_pages > num_pages); page->num_pages -= num_pages; page[page->num_pages].data = page->data + shm->page_size * page->num_pages; page += page->num_pages; page->num_pages = num_pages; return page; } void * shm_alloc(struct shm *shm, unsigned num_pages) { assert(num_pages > 0); lock_lock(&shm->lock); struct page *page = shm_find_available(shm, num_pages); if (page == nullptr) { lock_unlock(&shm->lock); return nullptr; } assert(page->num_pages >= num_pages); if (page->num_pages == num_pages) { list_remove(&page->siblings); lock_unlock(&shm->lock); poison_undefined(page->data, shm->page_size * num_pages); return page->data; } else { page = shm_split_page(shm, page, num_pages); lock_unlock(&shm->lock); poison_undefined(page->data, shm->page_size * num_pages); return page->data; } } static unsigned shm_page_number(struct shm *shm, const void *p) { ptrdiff_t difference = (const uint8_t *)p - shm_data(shm); unsigned page_number = difference / shm->page_size; assert(difference % shm->page_size == 0); assert(page_number < shm->num_pages); return page_number; } /** merge this page with its adjacent pages if possible, to create bigger "available" areas */ static void shm_merge(struct shm *shm, struct page *page) { unsigned page_number = shm_page_number(shm, page->data); /* merge with previous page? */ struct page *other = (struct page *)page->siblings.prev; if (&other->siblings != &shm->available && shm_page_number(shm, other->data) + other->num_pages == page_number) { other->num_pages += page->num_pages; list_remove(&page->siblings); page = other; } /* merge with next page? */ other = (struct page *)page->siblings.next; if (&other->siblings != &shm->available && page_number + page->num_pages == shm_page_number(shm, other->data)) { page->num_pages += other->num_pages; list_remove(&other->siblings); } } void shm_free(struct shm *shm, const void *p) { unsigned page_number = shm_page_number(shm, p); struct page *page = &shm->pages[page_number]; struct page *prev; poison_noaccess(page->data, shm->page_size * page->num_pages); lock_lock(&shm->lock); for (prev = (struct page *)&shm->available; prev->siblings.next != &shm->available; prev = (struct page *)prev->siblings.next) { } list_add(&page->siblings, &prev->siblings); shm_merge(shm, page); lock_unlock(&shm->lock); } <commit_msg>shm/shm: retain linked list order in shm_free()<commit_after>/* * Shared memory for sharing data between worker processes. * * author: Max Kellermann <mk@cm4all.com> */ #include "shm.hxx" #include "lock.h" #include "util/RefCount.hxx" #include <inline/poison.h> #include <inline/list.h> #include <daemon/log.h> #include <assert.h> #include <stdint.h> #include <sys/mman.h> #include <errno.h> #include <string.h> struct page { struct list_head siblings; unsigned num_pages; uint8_t *data; }; struct shm { RefCount ref; size_t page_size; unsigned num_pages; /** this lock protects the linked list */ struct lock lock; struct list_head available; struct page pages[1]; }; static inline unsigned calc_header_pages(size_t page_size, unsigned num_pages) { size_t header_size = sizeof(struct shm) + (num_pages - 1) * sizeof(struct page); return (header_size + page_size - 1) / page_size; } gcc_const static uint8_t * shm_at(struct shm *shm, size_t offset) { return (uint8_t *)shm + offset; } static uint8_t * shm_data(struct shm *shm) { unsigned header_pages = calc_header_pages(shm->page_size, shm->num_pages); return shm_at(shm, shm->page_size * header_pages); } struct shm * shm_new(size_t page_size, unsigned num_pages) { assert(page_size >= sizeof(size_t)); assert(num_pages > 0); const unsigned header_pages = calc_header_pages(page_size, num_pages); void *p = mmap(nullptr, page_size * (header_pages + num_pages), PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0); if (p == (void *)-1) return nullptr; struct shm *shm = (struct shm *)p; shm->ref.Init(); shm->page_size = page_size; shm->num_pages = num_pages; lock_init(&shm->lock); list_init(&shm->available); list_add(&shm->pages[0].siblings, &shm->available); shm->pages[0].num_pages = num_pages; shm->pages[0].data = shm_data(shm); #if 0 /* disabled because this causes page faults and immediately allocates physical memory for the areas that aren't used yet */ poison_noaccess(shm_data(shm), page_size * num_pages); #endif return shm; } void shm_ref(struct shm *shm) { assert(shm != nullptr); shm->ref.Get(); } void shm_close(struct shm *shm) { unsigned header_pages; int ret; assert(shm != nullptr); if (shm->ref.Put()) lock_destroy(&shm->lock); header_pages = calc_header_pages(shm->page_size, shm->num_pages); ret = munmap(shm, shm->page_size * (header_pages + shm->num_pages)); if (ret < 0) daemon_log(1, "munmap() failed: %s\n", strerror(errno)); } size_t shm_page_size(const struct shm *shm) { return shm->page_size; } static struct page * shm_find_available(struct shm *shm, unsigned num_pages) { for (struct page *page = (struct page *)shm->available.next; &page->siblings != &shm->available; page = (struct page *)page->siblings.next) if (page->num_pages >= num_pages) return page; return nullptr; } static struct page * shm_split_page(const struct shm *shm, struct page *page, unsigned num_pages) { assert(page->num_pages > num_pages); page->num_pages -= num_pages; page[page->num_pages].data = page->data + shm->page_size * page->num_pages; page += page->num_pages; page->num_pages = num_pages; return page; } void * shm_alloc(struct shm *shm, unsigned num_pages) { assert(num_pages > 0); lock_lock(&shm->lock); struct page *page = shm_find_available(shm, num_pages); if (page == nullptr) { lock_unlock(&shm->lock); return nullptr; } assert(page->num_pages >= num_pages); if (page->num_pages == num_pages) { list_remove(&page->siblings); lock_unlock(&shm->lock); poison_undefined(page->data, shm->page_size * num_pages); return page->data; } else { page = shm_split_page(shm, page, num_pages); lock_unlock(&shm->lock); poison_undefined(page->data, shm->page_size * num_pages); return page->data; } } static unsigned shm_page_number(struct shm *shm, const void *p) { ptrdiff_t difference = (const uint8_t *)p - shm_data(shm); unsigned page_number = difference / shm->page_size; assert(difference % shm->page_size == 0); assert(page_number < shm->num_pages); return page_number; } /** merge this page with its adjacent pages if possible, to create bigger "available" areas */ static void shm_merge(struct shm *shm, struct page *page) { unsigned page_number = shm_page_number(shm, page->data); /* merge with previous page? */ struct page *other = (struct page *)page->siblings.prev; if (&other->siblings != &shm->available && shm_page_number(shm, other->data) + other->num_pages == page_number) { other->num_pages += page->num_pages; list_remove(&page->siblings); page = other; } /* merge with next page? */ other = (struct page *)page->siblings.next; if (&other->siblings != &shm->available && page_number + page->num_pages == shm_page_number(shm, other->data)) { page->num_pages += other->num_pages; list_remove(&other->siblings); } } void shm_free(struct shm *shm, const void *p) { unsigned page_number = shm_page_number(shm, p); struct page *page = &shm->pages[page_number]; struct page *prev; poison_noaccess(page->data, shm->page_size * page->num_pages); lock_lock(&shm->lock); /* to keep the linked list sorted, search for the right item to insert after */ for (prev = (struct page *)&shm->available; prev->siblings.next != &shm->available && prev->siblings.next < &page->siblings; prev = (struct page *)prev->siblings.next) { } list_add(&page->siblings, &prev->siblings); shm_merge(shm, page); lock_unlock(&shm->lock); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <cstdlib> #include <cstring> #include <climits> #include <cerrno> #include "GameGrid.h" #include "Rect.h" #include "Point.h" typedef enum { CONVERSION_SUCCESS, CONVERSION_MEMORY, CONVERSION_OVERFLOW, CONVERSION_UNDERFLOW, CONVERSION_INVALID } conversionStatus_t; typedef enum { CMDPARSE_SUCCESS, CMDPARSE_NO_FILE, CMDPARSE_EXPECTED_VALUES, CMDPARSE_BAD_VALUES, CMDPARSE_MEMORY } cmdParseStatus_t; /* Converts str (two comma-separated integers: ex. "123,123") into two integers and puts them in i1 and i2, respectively. */ conversionStatus_t handleSwitchIntInt(char* str, int& i1, int& i2); /** Parse the command line args and fills references passed in. */ cmdParseStatus_t readCommandLineArgs(int argc, char** argv, bool& autOutput, bool& dispHelp, bool& txGiven, bool& tyGiven, bool& wxGiven, bool& wyGiven, bool& genGiven, int& numGenerations, int& txLow, int& txHigh, int& tyLow, int& tyHigh, int& wxLow, int& wxHigh, int& wyLow, int& wyHigh, std::string& inputFile); /** Convert str to an int and put it in intConv. The resulting conversionStatus_t is returned. */ conversionStatus_t strToInt(int& intConv, const char* str); /** Prints the error message in parseStatus. If parseStatus == CMDPARSE_SUCCESS, then does nothing. */ void printCmdParseError(cmdParseStatus_t parseStatus); /** Prints help screen for this program. */ void printHelp(char* cmd); int main(int argc, char** argv) { bool autOutput, dispHelp, txGiven, tyGiven, wxGiven, wyGiven, genGiven; int numGenerations; int txLow, txHigh, tyLow, tyHigh, wxLow, wxHigh, wyLow, wyHigh; std::string inputFile; cmdParseStatus_t cmdStatus; cmdStatus = readCommandLineArgs(argc, argv, autOutput, dispHelp, txGiven, tyGiven, wxGiven, wyGiven, genGiven, numGenerations, txLow, txHigh, tyLow, tyHigh, wxLow, wxHigh, wyLow, wyHigh, inputFile); if(cmdStatus != CMDPARSE_SUCCESS) { printCmdParseError(cmdStatus); exit(1); } if(dispHelp) { printHelp(argv[0]); exit(0); } Point wbl(txLow, tyLow); Point wtr(txHigh, tyHigh); if(!genGiven) { numGenerations = 0; } if(wxGiven) { wbl.setX(wxLow); wtr.setX(wxHigh); } if(wyGiven) { wbl.setY(wyLow); wtr.setY(wyHigh); } Point bl(txLow, tyLow); Point tr(txHigh, tyHigh); GameGrid gg(Rect(bl, tr), Rect(wbl, wtr)); gg.setSquare(Point(0,0), true); gg.setSquare(Point(0,1), true); gg.setSquare(Point(1,0), true); gg.setSquare(Point(-1,-1), true); gg.printToFile(std::cout, false); } cmdParseStatus_t readCommandLineArgs(int argc, char** argv, bool& autOutput, bool& dispHelp, bool& txGiven, bool& tyGiven, bool& wxGiven, bool& wyGiven, bool& genGiven, int& numGenerations, int& txLow, int& txHigh, int& tyLow, int& tyHigh, int& wxLow, int& wxHigh, int& wyLow, int& wyHigh, std::string& inputFile) { conversionStatus_t convStatus; autOutput = dispHelp = txGiven = tyGiven = wxGiven = wyGiven = genGiven = false; inputFile = ""; numGenerations = 0; for(int i = 1; i < argc; i++) { if(argv[i][0] == '-') { if(argv[i][1] == 'a') { autOutput = true; } else if(argv[i][1] == 'h') { dispHelp = true; } else if(argv[i][1] == 'g') { if(argc <= i + 1) { return CMDPARSE_EXPECTED_VALUES; } convStatus = strToInt(numGenerations, argv[i+1]); if(convStatus != CONVERSION_SUCCESS) { return CMDPARSE_BAD_VALUES; } genGiven = true; ++i; /* don't parse argv[i+1] again */ } else if(strcmp(argv[i], "-tx") == 0 || strcmp(argv[i], "-ty") == 0 || strcmp(argv[i], "-wx") == 0 || strcmp(argv[i], "-wy") == 0) { int *lowPtr, *highPtr; if(argc <= i + 1) { return CMDPARSE_EXPECTED_VALUES; } if(strcmp(argv[i], "-tx") == 0) { lowPtr = &txLow; highPtr = &txHigh; txGiven = true; } else if(strcmp(argv[i], "-ty") == 0) { lowPtr = &tyLow; highPtr = &tyHigh; tyGiven = true; } else if(strcmp(argv[i], "-wx") == 0) { lowPtr = &wxLow; highPtr = &wxHigh; wxGiven = true; } else if(strcmp(argv[i], "-wy") == 0) { lowPtr = &wyLow; highPtr = &wyHigh; wyGiven = true; } convStatus = handleSwitchIntInt(argv[i+1], *lowPtr, *highPtr); if(convStatus != CONVERSION_SUCCESS) { return CMDPARSE_BAD_VALUES; } /* don't parse argv[i+1] again */ i+=1; } } else { inputFile = std::string(argv[i]); } } return CMDPARSE_SUCCESS; } conversionStatus_t handleSwitchIntInt(char* str, int& i1, int&i2) { conversionStatus_t convStat; char *iStr; iStr = strtok(str, ","); convStat = strToInt(i1, iStr); if(convStat != CONVERSION_SUCCESS) { return convStat; } iStr = strtok(NULL, ""); convStat = strToInt(i2, iStr); return convStat; } conversionStatus_t strToInt(int& intConv, const char* string) { char* afterNum; long longConv; errno = 0; longConv = strtol(string, &afterNum, 10); if( (errno == ERANGE && longConv == LONG_MAX) || longConv > INT_MAX) { return CONVERSION_OVERFLOW; } else if( (errno == ERANGE && longConv == LONG_MIN) || longConv < INT_MIN) { return CONVERSION_UNDERFLOW; } else if(string[0] == '\0' || afterNum[0] != '\0') { return CONVERSION_INVALID; } intConv = longConv; return CONVERSION_SUCCESS; } void printCmdParseError(cmdParseStatus_t parseStatus) { if(parseStatus == CMDPARSE_SUCCESS) { return; } else if(parseStatus == CMDPARSE_NO_FILE) { std::cerr << "Input file not found in command line args. (-h for usage) \n"; } else if(parseStatus == CMDPARSE_EXPECTED_VALUES) { std::cerr << "One or more values were not provided for certain switches (ex. "; std::cerr << "-tx expects xLow\n"; std::cerr << "and xHigh, but only xLow was given)\n"; } else if(parseStatus == CMDPARSE_BAD_VALUES) { std::cerr << "One or more values could not be converted to integers\n"; } else if(parseStatus == CMDPARSE_MEMORY) { std::cerr << "Memory allocation failed\n"; } } void printHelp(char* cmd) { std::cout << "\nShowgen reads an aut file, simulates a given number of "; std::cout << "generations (defaults to 0),\nand prints the result\n\n"; std::cout << "Usage: " << cmd << " [options] file.aut\n"; std::cout << "\n"; std::cout << "Options:\n"; std::cout << "-a\t\toutput as aut file (otherwise ASCII display)\n"; std::cout << "-g n\t\tsimulate n generations\n"; std::cout << "-tx l,h\t\tset x range of terrain (overrides aut bounds)\n"; std::cout << "-ty l,h\t\tset y range of terrain (overrides aut bounds)\n"; std::cout << "-wx l,h\t\tset x range for output window (defaults to terrain x bounds)\n"; std::cout << "-wy l,h\t\tset y range for output window (defaults to terrain y bounds\n"; std::cout << "\n"; } <commit_msg>Changed main to test text parsing<commit_after>#include <iostream> #include <string> #include <cstdlib> #include <cstring> #include <climits> #include <cerrno> #include "GameGrid.h" #include "Rect.h" #include "Point.h" #include "AutParser.h" typedef enum { CONVERSION_SUCCESS, CONVERSION_MEMORY, CONVERSION_OVERFLOW, CONVERSION_UNDERFLOW, CONVERSION_INVALID } conversionStatus_t; typedef enum { CMDPARSE_SUCCESS, CMDPARSE_NO_FILE, CMDPARSE_EXPECTED_VALUES, CMDPARSE_BAD_VALUES, CMDPARSE_MEMORY } cmdParseStatus_t; /* Converts str (two comma-separated integers: ex. "123,123") into two integers and puts them in i1 and i2, respectively. */ conversionStatus_t handleSwitchIntInt(char* str, int& i1, int& i2); /** Parse the command line args and fills references passed in. */ cmdParseStatus_t readCommandLineArgs(int argc, char** argv, bool& autOutput, bool& dispHelp, bool& txGiven, bool& tyGiven, bool& wxGiven, bool& wyGiven, bool& genGiven, int& numGenerations, int& txLow, int& txHigh, int& tyLow, int& tyHigh, int& wxLow, int& wxHigh, int& wyLow, int& wyHigh, std::string& inputFile); /** Convert str to an int and put it in intConv. The resulting conversionStatus_t is returned. */ conversionStatus_t strToInt(int& intConv, const char* str); /** Prints the error message in parseStatus. If parseStatus == CMDPARSE_SUCCESS, then does nothing. */ void printCmdParseError(cmdParseStatus_t parseStatus); /** Prints help screen for this program. */ void printHelp(char* cmd); int main(int argc, char** argv) { bool autOutput, dispHelp, txGiven, tyGiven, wxGiven, wyGiven, genGiven; int numGenerations; int txLow, txHigh, tyLow, tyHigh, wxLow, wxHigh, wyLow, wyHigh; std::string inputFile; cmdParseStatus_t cmdStatus; cmdStatus = readCommandLineArgs(argc, argv, autOutput, dispHelp, txGiven, tyGiven, wxGiven, wyGiven, genGiven, numGenerations, txLow, txHigh, tyLow, tyHigh, wxLow, wxHigh, wyLow, wyHigh, inputFile); if(cmdStatus != CMDPARSE_SUCCESS) { printCmdParseError(cmdStatus); exit(1); } if(dispHelp) { printHelp(argv[0]); exit(0); } Point wbl(txLow, tyLow); Point wtr(txHigh, tyHigh); if(!genGiven) { numGenerations = 0; } Point bl; Point tr; std::string fileContents = "\ Xrange -10 10;\n\ Yrange -5 5;\n\ Initial {\n\ Y = 2 : -1;\n\ Y = 1 : -2, 1;\n\ Y = -1 : 2, 3, 4;\n\ };\n"; GameGrid gg; AutParser::parse(fileContents, gg); bl.setX(gg.getTerrainBounds().getBottomLeft().getX()); bl.setY(gg.getTerrainBounds().getBottomLeft().getY()); tr.setX(gg.getTerrainBounds().getTopRight().getX()); tr.setY(gg.getTerrainBounds().getTopRight().getY()); if(txGiven) { bl.setX(txLow); tr.setX(txHigh); } if(tyGiven) { bl.setY(tyLow); tr.setY(tyHigh); } gg.setTerrainBounds(Rect(bl, tr)); wbl.setX(gg.getTerrainBounds().getBottomLeft().getX()); wbl.setY(gg.getTerrainBounds().getBottomLeft().getY()); wtr.setX(gg.getTerrainBounds().getTopRight().getX()); wtr.setY(gg.getTerrainBounds().getTopRight().getY()); if(wxGiven) { wbl.setX(wxLow); wtr.setX(wxHigh); } if(wyGiven) { wbl.setY(wyLow); wtr.setY(wyHigh); } gg.setWindowBounds(Rect(wbl, wtr)); gg.printToFile(std::cout, false); } cmdParseStatus_t readCommandLineArgs(int argc, char** argv, bool& autOutput, bool& dispHelp, bool& txGiven, bool& tyGiven, bool& wxGiven, bool& wyGiven, bool& genGiven, int& numGenerations, int& txLow, int& txHigh, int& tyLow, int& tyHigh, int& wxLow, int& wxHigh, int& wyLow, int& wyHigh, std::string& inputFile) { conversionStatus_t convStatus; autOutput = dispHelp = txGiven = tyGiven = wxGiven = wyGiven = genGiven = false; inputFile = ""; numGenerations = 0; for(int i = 1; i < argc; i++) { if(argv[i][0] == '-') { if(argv[i][1] == 'a') { autOutput = true; } else if(argv[i][1] == 'h') { dispHelp = true; } else if(argv[i][1] == 'g') { if(argc <= i + 1) { return CMDPARSE_EXPECTED_VALUES; } convStatus = strToInt(numGenerations, argv[i+1]); if(convStatus != CONVERSION_SUCCESS) { return CMDPARSE_BAD_VALUES; } genGiven = true; ++i; /* don't parse argv[i+1] again */ } else if(strcmp(argv[i], "-tx") == 0 || strcmp(argv[i], "-ty") == 0 || strcmp(argv[i], "-wx") == 0 || strcmp(argv[i], "-wy") == 0) { int *lowPtr, *highPtr; if(argc <= i + 1) { return CMDPARSE_EXPECTED_VALUES; } if(strcmp(argv[i], "-tx") == 0) { lowPtr = &txLow; highPtr = &txHigh; txGiven = true; } else if(strcmp(argv[i], "-ty") == 0) { lowPtr = &tyLow; highPtr = &tyHigh; tyGiven = true; } else if(strcmp(argv[i], "-wx") == 0) { lowPtr = &wxLow; highPtr = &wxHigh; wxGiven = true; } else if(strcmp(argv[i], "-wy") == 0) { lowPtr = &wyLow; highPtr = &wyHigh; wyGiven = true; } convStatus = handleSwitchIntInt(argv[i+1], *lowPtr, *highPtr); if(convStatus != CONVERSION_SUCCESS) { return CMDPARSE_BAD_VALUES; } /* don't parse argv[i+1] again */ i+=1; } } else { inputFile = std::string(argv[i]); } } return CMDPARSE_SUCCESS; } conversionStatus_t handleSwitchIntInt(char* str, int& i1, int&i2) { conversionStatus_t convStat; char *iStr; iStr = strtok(str, ","); convStat = strToInt(i1, iStr); if(convStat != CONVERSION_SUCCESS) { return convStat; } iStr = strtok(NULL, ""); convStat = strToInt(i2, iStr); return convStat; } conversionStatus_t strToInt(int& intConv, const char* string) { char* afterNum; long longConv; errno = 0; longConv = strtol(string, &afterNum, 10); if( (errno == ERANGE && longConv == LONG_MAX) || longConv > INT_MAX) { return CONVERSION_OVERFLOW; } else if( (errno == ERANGE && longConv == LONG_MIN) || longConv < INT_MIN) { return CONVERSION_UNDERFLOW; } else if(string[0] == '\0' || afterNum[0] != '\0') { return CONVERSION_INVALID; } intConv = longConv; return CONVERSION_SUCCESS; } void printCmdParseError(cmdParseStatus_t parseStatus) { if(parseStatus == CMDPARSE_SUCCESS) { return; } else if(parseStatus == CMDPARSE_NO_FILE) { std::cerr << "Input file not found in command line args. (-h for usage) \n"; } else if(parseStatus == CMDPARSE_EXPECTED_VALUES) { std::cerr << "One or more values were not provided for certain switches (ex. "; std::cerr << "-tx expects xLow\n"; std::cerr << "and xHigh, but only xLow was given)\n"; } else if(parseStatus == CMDPARSE_BAD_VALUES) { std::cerr << "One or more values could not be converted to integers\n"; } else if(parseStatus == CMDPARSE_MEMORY) { std::cerr << "Memory allocation failed\n"; } } void printHelp(char* cmd) { std::cout << "\nShowgen reads an aut file, simulates a given number of "; std::cout << "generations (defaults to 0),\nand prints the result\n\n"; std::cout << "Usage: " << cmd << " [options] file.aut\n"; std::cout << "\n"; std::cout << "Options:\n"; std::cout << "-a\t\toutput as aut file (otherwise ASCII display)\n"; std::cout << "-g n\t\tsimulate n generations\n"; std::cout << "-tx l,h\t\tset x range of terrain (overrides aut bounds)\n"; std::cout << "-ty l,h\t\tset y range of terrain (overrides aut bounds)\n"; std::cout << "-wx l,h\t\tset x range for output window (defaults to terrain x bounds)\n"; std::cout << "-wy l,h\t\tset y range for output window (defaults to terrain y bounds\n"; std::cout << "\n"; } <|endoftext|>
<commit_before>/**************************************************************************** ** Copyright (C) 2001-2006 Klarälvdalens Datakonsult AB. All rights reserved. ** ** This file is part of the KD Gantt library. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid commercial KD Gantt licenses may use this file in ** accordance with the KD Gantt Commercial License Agreement provided with ** the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.kdab.net/kdgantt for ** information about KD Gantt Commercial License Agreements. ** ** Contact info@kdab.net if any conditions of this ** licensing are not clear to you. ** **********************************************************************/ #include "kdganttdatetimegrid.h" #include "kdganttdatetimegrid_p.h" #include "kdganttabstractrowcontroller.h" #include <QApplication> #include <QDateTime> #include <QPainter> #include <QStyle> #include <QStyleOptionHeader> #include <QWidget> #include <QDebug> #include <cassert> using namespace KDGantt; /*!\class KDGantt::DateTimeGrid * \ingroup KDGantt * * This implementation of AbstractGrid works with QDateTime * and shows days and week numbers in the header * * \todo Extend to work with hours, minutes,... as units too. */ // TODO: I think maybe this class should be responsible // for unit-transformation of the scene... qreal DateTimeGrid::Private::dateTimeToChartX( const QDateTime& dt ) const { assert( startDateTime.isValid() ); qreal result = startDateTime.date().daysTo(dt.date())*24.*60.*60.; result += startDateTime.time().msecsTo(dt.time())/1000.; result *= dayWidth/( 24.*60.*60. ); return result; } QDateTime DateTimeGrid::Private::chartXtoDateTime( qreal x ) const { // TODO assert( startDateTime.isValid() ); int days = static_cast<int>( x/dayWidth ); qreal secs = x*( 24.*60.*60. )/dayWidth; QDateTime dt = startDateTime; QDateTime result = dt.addDays( days ).addSecs( static_cast<int>(secs-(days*24.*60.*60.) ) ); return result; } #define d d_func() DateTimeGrid::DateTimeGrid() : AbstractGrid( new Private ) { } DateTimeGrid::~DateTimeGrid() { } QDateTime DateTimeGrid::startDateTime() const { return d->startDateTime; } void DateTimeGrid::setStartDateTime( const QDateTime& dt ) { d->startDateTime = dt; emit gridChanged(); } qreal DateTimeGrid::dayWidth() const { return d->dayWidth; } void DateTimeGrid::setDayWidth( qreal w ) { d->dayWidth = w; emit gridChanged(); } void DateTimeGrid::setScale( Scale s ) { d->scale = s; emit gridChanged(); } DateTimeGrid::Scale DateTimeGrid::scale() const { return d->scale; } void DateTimeGrid::setWeekStart( Qt::DayOfWeek ws ) { d->weekStart = ws; emit gridChanged(); } Qt::DayOfWeek DateTimeGrid::weekStart() const { return d->weekStart; } void DateTimeGrid::setFreeDays( const QSet<Qt::DayOfWeek>& fd ) { d->freeDays = fd; emit gridChanged(); } QSet<Qt::DayOfWeek> DateTimeGrid::freeDays() const { return d->freeDays; } bool DateTimeGrid::rowSeparators() const { return d->rowSeparators; } void DateTimeGrid::setRowSeparators( bool enable ) { d->rowSeparators = enable; } Span DateTimeGrid::mapToChart( const QModelIndex& idx ) const { assert( model() ); if ( !idx.isValid() ) return Span(); assert( idx.model()==model() ); const QVariant sv = model()->data( idx, StartTimeRole ); const QVariant ev = model()->data( idx, EndTimeRole ); if( qVariantCanConvert<QDateTime>(sv) && qVariantCanConvert<QDateTime>(ev) && !(sv.type() == QVariant::String && qVariantValue<QString>(sv).isEmpty()) && !(ev.type() == QVariant::String && qVariantValue<QString>(ev).isEmpty()) ) { QDateTime st = sv.toDateTime(); QDateTime et = ev.toDateTime(); if ( et.isValid() && st.isValid() ) { qreal sx = d->dateTimeToChartX( st ); qreal ex = d->dateTimeToChartX( et )-sx; return Span( sx, ex); } } return Span(); } static void debug_print_idx( const QModelIndex& idx ) { if ( !idx.isValid() ) { qDebug() << "[Invalid]"; return; } QDateTime st = idx.data( StartTimeRole ).toDateTime(); QDateTime et = idx.data( StartTimeRole ).toDateTime(); qDebug() << idx << "["<<st<<et<<"]"; } bool DateTimeGrid::mapFromChart( const Span& span, const QModelIndex& idx, const QList<Constraint>& constraints ) const { assert( model() ); if ( !idx.isValid() ) return false; assert( idx.model()==model() ); QDateTime st = d->chartXtoDateTime(span.start()); QDateTime et = d->chartXtoDateTime(span.start()+span.length()); Q_FOREACH( const Constraint& c, constraints ) { if ( c.type() != Constraint::TypeHard || !isSatisfiedConstraint( c )) continue; if ( c.startIndex() == idx ) { QDateTime tmpst = model()->data( c.endIndex(), StartTimeRole ).toDateTime(); //qDebug() << tmpst << "<" << et <<"?"; if ( tmpst<et ) return false; } else if ( c.endIndex() == idx ) { QDateTime tmpet = model()->data( c.startIndex(), EndTimeRole ).toDateTime(); //qDebug() << tmpet << ">" << st <<"?"; if ( tmpet>st ) return false; } } return model()->setData( idx, qVariantFromValue(st), StartTimeRole ) && model()->setData( idx, qVariantFromValue(et), EndTimeRole ); } void DateTimeGrid::paintGrid( QPainter* painter, const QRectF& sceneRect, const QRectF& exposedRect, AbstractRowController* rowController, QWidget* widget ) { // TODO: Support hours QDateTime dt = d->chartXtoDateTime( exposedRect.left() ); dt.setTime( QTime( 0, 0, 0, 0 ) ); for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right(); dt = dt.addDays( 1 ),x=d->dateTimeToChartX( dt ) ) { QPen pen = painter->pen(); pen.setBrush( QApplication::palette().dark() ); if ( dt.date().dayOfWeek() == d->weekStart ) { pen.setStyle( Qt::SolidLine ); } else { pen.setStyle( Qt::DashLine ); } painter->setPen( pen ); if ( d->freeDays.contains( static_cast<Qt::DayOfWeek>( dt.date().dayOfWeek() ) ) ) { painter->setBrush( widget?widget->palette().alternateBase() :QApplication::palette().alternateBase() ); painter->fillRect( QRectF( x, exposedRect.top(), dayWidth(), exposedRect.height() ), painter->brush() ); } painter->drawLine( QPointF( x, sceneRect.top() ), QPointF( x, sceneRect.bottom() ) ); } if ( rowController && d->rowSeparators ) { // First draw the rows QPen pen = painter->pen(); pen.setBrush( QApplication::palette().dark() ); pen.setStyle( Qt::DashLine ); painter->setPen( pen ); QModelIndex idx = rowController->indexAt( exposedRect.top() ); int y = 0; while ( y < exposedRect.bottom() && idx.isValid() ) { const Span s = rowController->rowGeometry( idx ); y = s.start()+s.length(); painter->drawLine( QPointF( sceneRect.left(), y ), QPointF( sceneRect.right(), y ) ); // Is alternating background better? //if ( idx.row()%2 ) painter->fillRect( QRectF( exposedRect.x(), s.start(), exposedRect.width(), s.length() ), QApplication::palette().alternateBase() ); idx = rowController->indexBelow( idx ); } } } void DateTimeGrid::paintHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect, qreal offset, QWidget* widget ) { switch(scale()) { case ScaleHour: paintHourScaleHeader(painter,headerRect,exposedRect,offset,widget); break; case ScaleDay: paintDayScaleHeader(painter,headerRect,exposedRect,offset,widget); break; case ScaleAuto: if(dayWidth()>500) paintHourScaleHeader(painter,headerRect,exposedRect,offset,widget); else paintDayScaleHeader(painter,headerRect,exposedRect,offset,widget); break; } } void DateTimeGrid::paintHourScaleHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect, qreal offset, QWidget* widget ) { QStyle* style = widget?widget->style():QApplication::style(); // Paint a section for each hour QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() ); dt.setTime( QTime( dt.time().hour(), 0, 0, 0 ) ); for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset; dt = dt.addSecs( 60*60 /*1 hour*/ ),x=d->dateTimeToChartX( dt ) ) { QStyleOptionHeader opt; opt.init( widget ); opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth()/24., headerRect.height()/2. ).toRect(); opt.text = dt.time().toString( QString::fromAscii( "hh" ) ); opt.textAlignment = Qt::AlignCenter; style->drawControl(QStyle::CE_Header, &opt, painter, widget); } dt = d->chartXtoDateTime( offset+exposedRect.left() ); dt.setTime( QTime( 0, 0, 0, 0 ) ); // Paint a section for each day for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset; dt = dt.addDays( 1 ),x2=d->dateTimeToChartX( dt ) ) { QStyleOptionHeader opt; opt.init( widget ); opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth(), headerRect.height()/2. ).toRect(); opt.text = QString::number( dt.date().weekNumber() ); opt.textAlignment = Qt::AlignCenter; style->drawControl(QStyle::CE_Header, &opt, painter, widget); } } void DateTimeGrid::paintDayScaleHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect, qreal offset, QWidget* widget ) { // For starters, support only the regular tab-per-day look QStyle* style = widget?widget->style():QApplication::style(); // Paint a section for each day QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() ); dt.setTime( QTime( 0, 0, 0, 0 ) ); for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset; dt = dt.addDays( 1 ),x=d->dateTimeToChartX( dt ) ) { QStyleOptionHeader opt; opt.init( widget ); opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth(), headerRect.height()/2. ).toRect(); opt.text = dt.toString( QString::fromAscii( "ddd" ) ).left( 1 ); opt.textAlignment = Qt::AlignCenter; style->drawControl(QStyle::CE_Header, &opt, painter, widget); } dt = d->chartXtoDateTime( offset+exposedRect.left() ); dt.setTime( QTime( 0, 0, 0, 0 ) ); // Go backwards until start of week while ( dt.date().dayOfWeek() != d->weekStart ) dt = dt.addDays( -1 ); // Paint a section for each week for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset; dt = dt.addDays( 7 ),x2=d->dateTimeToChartX( dt ) ) { QStyleOptionHeader opt; opt.init( widget ); opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth()*7., headerRect.height()/2. ).toRect(); opt.text = QString::number( dt.date().weekNumber() ); opt.textAlignment = Qt::AlignCenter; style->drawControl(QStyle::CE_Header, &opt, painter, widget); } } #undef d #ifndef KDAB_NO_UNIT_TESTS #include <QStandardItemModel> #include "unittest/test.h" namespace { std::ostream& operator<<( std::ostream& os, const QDateTime& dt ) { os << dt.toString().toStdString(); return os; } } KDAB_SCOPED_UNITTEST_SIMPLE( KDGantt, DateTimeGrid, "test" ) { QStandardItemModel model( 3, 2 ); DateTimeGrid grid; QDateTime dt = QDateTime::currentDateTime(); grid.setModel( &model ); grid.setStartDateTime( dt.addDays( -10 ) ); model.setData( model.index( 0, 0 ), dt, StartTimeRole ); model.setData( model.index( 0, 0 ), dt.addDays( 17 ), EndTimeRole ); model.setData( model.index( 2, 0 ), dt.addDays( 18 ), StartTimeRole ); model.setData( model.index( 2, 0 ), dt.addDays( 19 ), EndTimeRole ); Span s = grid.mapToChart( model.index( 0, 0 ) ); qDebug() << "span="<<s; assertTrue( s.start()>0 ); assertTrue( s.length()>0 ); grid.mapFromChart( s, model.index( 1, 0 ) ); QDateTime s1 = model.data( model.index( 0, 0 ), StartTimeRole ).toDateTime(); QDateTime e1 = model.data( model.index( 0, 0 ), EndTimeRole ).toDateTime(); QDateTime s2 = model.data( model.index( 1, 0 ), StartTimeRole ).toDateTime(); QDateTime e2 = model.data( model.index( 1, 0 ), EndTimeRole ).toDateTime(); assertTrue( s1.isValid() ); assertTrue( e1.isValid() ); assertTrue( s2.isValid() ); assertTrue( e2.isValid() ); assertEqual( s1, s2 ); assertEqual( e1, e2 ); assertTrue( grid.isSatisfiedConstraint( Constraint( model.index( 0, 0 ), model.index( 2, 0 ) ) ) ); assertFalse( grid.isSatisfiedConstraint( Constraint( model.index( 2, 0 ), model.index( 0, 0 ) ) ) ); } #endif /* KDAB_NO_UNIT_TESTS */ #include "moc_kdganttdatetimegrid.cpp" <commit_msg>Apply kdab SVN commit 8007 by steffen: fixed rounding bug in QDateTime conversion<commit_after>/**************************************************************************** ** Copyright (C) 2001-2006 Klarälvdalens Datakonsult AB. All rights reserved. ** ** This file is part of the KD Gantt library. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid commercial KD Gantt licenses may use this file in ** accordance with the KD Gantt Commercial License Agreement provided with ** the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.kdab.net/kdgantt for ** information about KD Gantt Commercial License Agreements. ** ** Contact info@kdab.net if any conditions of this ** licensing are not clear to you. ** **********************************************************************/ #include "kdganttdatetimegrid.h" #include "kdganttdatetimegrid_p.h" #include "kdganttabstractrowcontroller.h" #include <QApplication> #include <QDateTime> #include <QPainter> #include <QStyle> #include <QStyleOptionHeader> #include <QWidget> #include <QDebug> #include <cassert> using namespace KDGantt; /*!\class KDGantt::DateTimeGrid * \ingroup KDGantt * * This implementation of AbstractGrid works with QDateTime * and shows days and week numbers in the header * * \todo Extend to work with hours, minutes,... as units too. */ // TODO: I think maybe this class should be responsible // for unit-transformation of the scene... qreal DateTimeGrid::Private::dateTimeToChartX( const QDateTime& dt ) const { assert( startDateTime.isValid() ); qreal result = startDateTime.date().daysTo(dt.date())*24.*60.*60.; result += startDateTime.time().msecsTo(dt.time())/1000.; result *= dayWidth/( 24.*60.*60. ); return result; } QDateTime DateTimeGrid::Private::chartXtoDateTime( qreal x ) const { // TODO assert( startDateTime.isValid() ); int days = static_cast<int>( x/dayWidth ); qreal secs = x*( 24.*60.*60. )/dayWidth; QDateTime dt = startDateTime; QDateTime result = dt.addDays( days ).addSecs( qRound(secs-(days*24.*60.*60.) ) ); return result; } #define d d_func() DateTimeGrid::DateTimeGrid() : AbstractGrid( new Private ) { } DateTimeGrid::~DateTimeGrid() { } QDateTime DateTimeGrid::startDateTime() const { return d->startDateTime; } void DateTimeGrid::setStartDateTime( const QDateTime& dt ) { d->startDateTime = dt; emit gridChanged(); } qreal DateTimeGrid::dayWidth() const { return d->dayWidth; } void DateTimeGrid::setDayWidth( qreal w ) { d->dayWidth = w; emit gridChanged(); } void DateTimeGrid::setScale( Scale s ) { d->scale = s; emit gridChanged(); } DateTimeGrid::Scale DateTimeGrid::scale() const { return d->scale; } void DateTimeGrid::setWeekStart( Qt::DayOfWeek ws ) { d->weekStart = ws; emit gridChanged(); } Qt::DayOfWeek DateTimeGrid::weekStart() const { return d->weekStart; } void DateTimeGrid::setFreeDays( const QSet<Qt::DayOfWeek>& fd ) { d->freeDays = fd; emit gridChanged(); } QSet<Qt::DayOfWeek> DateTimeGrid::freeDays() const { return d->freeDays; } bool DateTimeGrid::rowSeparators() const { return d->rowSeparators; } void DateTimeGrid::setRowSeparators( bool enable ) { d->rowSeparators = enable; } Span DateTimeGrid::mapToChart( const QModelIndex& idx ) const { assert( model() ); if ( !idx.isValid() ) return Span(); assert( idx.model()==model() ); const QVariant sv = model()->data( idx, StartTimeRole ); const QVariant ev = model()->data( idx, EndTimeRole ); if( qVariantCanConvert<QDateTime>(sv) && qVariantCanConvert<QDateTime>(ev) && !(sv.type() == QVariant::String && qVariantValue<QString>(sv).isEmpty()) && !(ev.type() == QVariant::String && qVariantValue<QString>(ev).isEmpty()) ) { QDateTime st = sv.toDateTime(); QDateTime et = ev.toDateTime(); if ( et.isValid() && st.isValid() ) { qreal sx = d->dateTimeToChartX( st ); qreal ex = d->dateTimeToChartX( et )-sx; return Span( sx, ex); } } return Span(); } static void debug_print_idx( const QModelIndex& idx ) { if ( !idx.isValid() ) { qDebug() << "[Invalid]"; return; } QDateTime st = idx.data( StartTimeRole ).toDateTime(); QDateTime et = idx.data( StartTimeRole ).toDateTime(); qDebug() << idx << "["<<st<<et<<"]"; } bool DateTimeGrid::mapFromChart( const Span& span, const QModelIndex& idx, const QList<Constraint>& constraints ) const { assert( model() ); if ( !idx.isValid() ) return false; assert( idx.model()==model() ); QDateTime st = d->chartXtoDateTime(span.start()); QDateTime et = d->chartXtoDateTime(span.start()+span.length()); Q_FOREACH( const Constraint& c, constraints ) { if ( c.type() != Constraint::TypeHard || !isSatisfiedConstraint( c )) continue; if ( c.startIndex() == idx ) { QDateTime tmpst = model()->data( c.endIndex(), StartTimeRole ).toDateTime(); //qDebug() << tmpst << "<" << et <<"?"; if ( tmpst<et ) return false; } else if ( c.endIndex() == idx ) { QDateTime tmpet = model()->data( c.startIndex(), EndTimeRole ).toDateTime(); //qDebug() << tmpet << ">" << st <<"?"; if ( tmpet>st ) return false; } } return model()->setData( idx, qVariantFromValue(st), StartTimeRole ) && model()->setData( idx, qVariantFromValue(et), EndTimeRole ); } void DateTimeGrid::paintGrid( QPainter* painter, const QRectF& sceneRect, const QRectF& exposedRect, AbstractRowController* rowController, QWidget* widget ) { // TODO: Support hours QDateTime dt = d->chartXtoDateTime( exposedRect.left() ); dt.setTime( QTime( 0, 0, 0, 0 ) ); for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right(); dt = dt.addDays( 1 ),x=d->dateTimeToChartX( dt ) ) { QPen pen = painter->pen(); pen.setBrush( QApplication::palette().dark() ); if ( dt.date().dayOfWeek() == d->weekStart ) { pen.setStyle( Qt::SolidLine ); } else { pen.setStyle( Qt::DashLine ); } painter->setPen( pen ); if ( d->freeDays.contains( static_cast<Qt::DayOfWeek>( dt.date().dayOfWeek() ) ) ) { painter->setBrush( widget?widget->palette().alternateBase() :QApplication::palette().alternateBase() ); painter->fillRect( QRectF( x, exposedRect.top(), dayWidth(), exposedRect.height() ), painter->brush() ); } painter->drawLine( QPointF( x, sceneRect.top() ), QPointF( x, sceneRect.bottom() ) ); } if ( rowController && d->rowSeparators ) { // First draw the rows QPen pen = painter->pen(); pen.setBrush( QApplication::palette().dark() ); pen.setStyle( Qt::DashLine ); painter->setPen( pen ); QModelIndex idx = rowController->indexAt( qRound( exposedRect.top() ) ); qreal y = 0; while ( y < exposedRect.bottom() && idx.isValid() ) { const Span s = rowController->rowGeometry( idx ); y = s.start()+s.length(); painter->drawLine( QPointF( sceneRect.left(), y ), QPointF( sceneRect.right(), y ) ); // Is alternating background better? //if ( idx.row()%2 ) painter->fillRect( QRectF( exposedRect.x(), s.start(), exposedRect.width(), s.length() ), QApplication::palette().alternateBase() ); idx = rowController->indexBelow( idx ); } } } void DateTimeGrid::paintHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect, qreal offset, QWidget* widget ) { switch(scale()) { case ScaleHour: paintHourScaleHeader(painter,headerRect,exposedRect,offset,widget); break; case ScaleDay: paintDayScaleHeader(painter,headerRect,exposedRect,offset,widget); break; case ScaleAuto: if(dayWidth()>500) paintHourScaleHeader(painter,headerRect,exposedRect,offset,widget); else paintDayScaleHeader(painter,headerRect,exposedRect,offset,widget); break; } } void DateTimeGrid::paintHourScaleHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect, qreal offset, QWidget* widget ) { QStyle* style = widget?widget->style():QApplication::style(); // Paint a section for each hour QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() ); dt.setTime( QTime( dt.time().hour(), 0, 0, 0 ) ); for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset; dt = dt.addSecs( 60*60 /*1 hour*/ ),x=d->dateTimeToChartX( dt ) ) { QStyleOptionHeader opt; opt.init( widget ); opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth()/24., headerRect.height()/2. ).toRect(); opt.text = dt.time().toString( QString::fromAscii( "hh" ) ); opt.textAlignment = Qt::AlignCenter; style->drawControl(QStyle::CE_Header, &opt, painter, widget); } dt = d->chartXtoDateTime( offset+exposedRect.left() ); dt.setTime( QTime( 0, 0, 0, 0 ) ); // Paint a section for each day for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset; dt = dt.addDays( 1 ),x2=d->dateTimeToChartX( dt ) ) { QStyleOptionHeader opt; opt.init( widget ); opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth(), headerRect.height()/2. ).toRect(); opt.text = QString::number( dt.date().weekNumber() ); opt.textAlignment = Qt::AlignCenter; style->drawControl(QStyle::CE_Header, &opt, painter, widget); } } void DateTimeGrid::paintDayScaleHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect, qreal offset, QWidget* widget ) { // For starters, support only the regular tab-per-day look QStyle* style = widget?widget->style():QApplication::style(); // Paint a section for each day QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() ); dt.setTime( QTime( 0, 0, 0, 0 ) ); for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset; dt = dt.addDays( 1 ),x=d->dateTimeToChartX( dt ) ) { QStyleOptionHeader opt; opt.init( widget ); opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth(), headerRect.height()/2. ).toRect(); opt.text = dt.toString( QString::fromAscii( "ddd" ) ).left( 1 ); opt.textAlignment = Qt::AlignCenter; style->drawControl(QStyle::CE_Header, &opt, painter, widget); } dt = d->chartXtoDateTime( offset+exposedRect.left() ); dt.setTime( QTime( 0, 0, 0, 0 ) ); // Go backwards until start of week while ( dt.date().dayOfWeek() != d->weekStart ) dt = dt.addDays( -1 ); // Paint a section for each week for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset; dt = dt.addDays( 7 ),x2=d->dateTimeToChartX( dt ) ) { QStyleOptionHeader opt; opt.init( widget ); opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth()*7., headerRect.height()/2. ).toRect(); opt.text = QString::number( dt.date().weekNumber() ); opt.textAlignment = Qt::AlignCenter; style->drawControl(QStyle::CE_Header, &opt, painter, widget); } } #undef d #ifndef KDAB_NO_UNIT_TESTS #include <QStandardItemModel> #include "unittest/test.h" namespace { std::ostream& operator<<( std::ostream& os, const QDateTime& dt ) { os << dt.toString().toStdString(); return os; } } KDAB_SCOPED_UNITTEST_SIMPLE( KDGantt, DateTimeGrid, "test" ) { QStandardItemModel model( 3, 2 ); DateTimeGrid grid; QDateTime dt = QDateTime::currentDateTime(); grid.setModel( &model ); grid.setStartDateTime( dt.addDays( -10 ) ); model.setData( model.index( 0, 0 ), dt, StartTimeRole ); model.setData( model.index( 0, 0 ), dt.addDays( 17 ), EndTimeRole ); model.setData( model.index( 2, 0 ), dt.addDays( 18 ), StartTimeRole ); model.setData( model.index( 2, 0 ), dt.addDays( 19 ), EndTimeRole ); Span s = grid.mapToChart( model.index( 0, 0 ) ); qDebug() << "span="<<s; assertTrue( s.start()>0 ); assertTrue( s.length()>0 ); grid.mapFromChart( s, model.index( 1, 0 ) ); QDateTime s1 = model.data( model.index( 0, 0 ), StartTimeRole ).toDateTime(); QDateTime e1 = model.data( model.index( 0, 0 ), EndTimeRole ).toDateTime(); QDateTime s2 = model.data( model.index( 1, 0 ), StartTimeRole ).toDateTime(); QDateTime e2 = model.data( model.index( 1, 0 ), EndTimeRole ).toDateTime(); assertTrue( s1.isValid() ); assertTrue( e1.isValid() ); assertTrue( s2.isValid() ); assertTrue( e2.isValid() ); assertEqual( s1, s2 ); assertEqual( e1, e2 ); assertTrue( grid.isSatisfiedConstraint( Constraint( model.index( 0, 0 ), model.index( 2, 0 ) ) ) ); assertFalse( grid.isSatisfiedConstraint( Constraint( model.index( 2, 0 ), model.index( 0, 0 ) ) ) ); } #endif /* KDAB_NO_UNIT_TESTS */ #include "moc_kdganttdatetimegrid.cpp" <|endoftext|>
<commit_before>#include "libs/catch/include/catch.hpp" #include <atomic> #include <chrono> #include <memory> #include <thread> #include <iostream> #include "src/client.h" #include "src/config.h" #include "src/file.h" void aux_read_test_worker(std::shared_ptr<giga::File> file, std::shared_ptr<std::atomic<int>> result) { std::shared_ptr<giga::Client> c = file->open(); std::shared_ptr<std::string> buffer (new std::string); int res = 0; res += (c->get_pos() == 0); res += (c->read(buffer, 0) == 0); res += (buffer->compare("") == 0); res += (c->read(buffer, 1) == 1); res += (buffer->compare("a") == 0); res += (c->read(buffer, 10) == 4); res += (buffer->compare("bcd\n") == 0); res += (c->read(buffer, 1) == 0); res += (buffer->compare("") == 0); file->close(c); int expected = 9; *result += (int) (res == expected); } TEST_CASE("concurrent|read") { int n_threads = 20; int n_attempts = 100; std::shared_ptr<std::atomic<int>> result (new std::atomic<int>()); for(int attempt = 0; attempt < n_attempts; attempt++) { std::shared_ptr<std::string> buffer (new std::string); std::vector<std::thread> threads; std::shared_ptr<giga::File> file (new giga::File("test/files/five.txt", "r", std::shared_ptr<giga::Config> (new giga::Config(2, 1)))); for(int i = 0; i < n_threads; i++) { threads.push_back(std::thread (aux_read_test_worker, file, result)); } std::this_thread::sleep_for(std::chrono::milliseconds(1)); while(file->get_n_clients()) { // cf. http://bit.ly/1pLvXct std::this_thread::sleep_for(std::chrono::milliseconds(1)); } for(int i = 0; i < n_threads; i++) { threads.at(i).join(); } } REQUIRE(*result == n_attempts * n_threads); } <commit_msg>found possible concurrency bug<commit_after>#include "libs/catch/include/catch.hpp" #include <atomic> #include <chrono> #include <memory> #include <thread> #include <iostream> #include "src/client.h" #include "src/config.h" #include "src/file.h" void aux_read_test_worker(std::shared_ptr<giga::File> file, std::shared_ptr<std::atomic<int>> result) { std::shared_ptr<giga::Client> c = file->open(); std::shared_ptr<std::string> buffer (new std::string); int res = 0; res += (c->get_pos() == 0); res += (c->read(buffer, 0) == 0); res += (buffer->compare("") == 0); res += (c->read(buffer, 1) == 1); res += (buffer->compare("a") == 0); res += (c->read(buffer, 10) == 4); res += (buffer->compare("bcd\n") == 0); res += (c->read(buffer, 1) == 0); res += (buffer->compare("") == 0); file->close(c); int expected = 9; *result += (int) (res == expected); } TEST_CASE("concurrent|read") { int n_threads = 20; int n_attempts = 1000; std::shared_ptr<std::atomic<int>> result (new std::atomic<int>()); for(int attempt = 0; attempt < n_attempts; attempt++) { std::shared_ptr<std::string> buffer (new std::string); std::vector<std::thread> threads; std::shared_ptr<giga::File> file (new giga::File("test/files/five.txt", "r", std::shared_ptr<giga::Config> (new giga::Config(2, 1)))); for(int i = 0; i < n_threads; i++) { threads.push_back(std::thread (aux_read_test_worker, file, result)); } std::this_thread::sleep_for(std::chrono::milliseconds(10)); while(file->get_n_clients()) { // cf. http://bit.ly/1pLvXct std::this_thread::sleep_for(std::chrono::milliseconds(10)); } for(int i = 0; i < n_threads; i++) { threads.at(i).join(); } if(((attempt + 1) % 10) == 0) { std::cout << "attempt: " << attempt + 1 << "/" << n_attempts << std::endl; } } REQUIRE(*result == n_attempts * n_threads); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLEmbeddedObjectImportContext.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 14:39:19 $ * * 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 _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX #define _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif namespace com { namespace sun { namespace star { namespace lang { class XComponent; } } } } class XMLEmbeddedObjectImportContext : public SvXMLImportContext { ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > xHandler; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xComp; ::rtl::OUString sFilterService; // #100592# ::rtl::OUString sCLSID; public: TYPEINFO(); const ::rtl::OUString& GetFilterServiceName() const { return sFilterService; } // #100592# const ::rtl::OUString& GetFilterCLSID() const { return sCLSID; } XMLEmbeddedObjectImportContext( SvXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~XMLEmbeddedObjectImportContext(); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void EndElement(); virtual void Characters( const ::rtl::OUString& rChars ); sal_Bool SetComponent( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& rComp ); }; #endif // _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.5.162); FILE MERGED 2008/04/01 13:04:18 thb 1.5.162.2: #i85898# Stripping all external header guards 2008/03/31 16:27:53 rt 1.5.162.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: XMLEmbeddedObjectImportContext.hxx,v $ * $Revision: 1.6 $ * * 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 _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX #define _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #include <xmloff/xmlictxt.hxx> namespace com { namespace sun { namespace star { namespace lang { class XComponent; } } } } class XMLEmbeddedObjectImportContext : public SvXMLImportContext { ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > xHandler; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xComp; ::rtl::OUString sFilterService; // #100592# ::rtl::OUString sCLSID; public: TYPEINFO(); const ::rtl::OUString& GetFilterServiceName() const { return sFilterService; } // #100592# const ::rtl::OUString& GetFilterCLSID() const { return sCLSID; } XMLEmbeddedObjectImportContext( SvXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~XMLEmbeddedObjectImportContext(); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void EndElement(); virtual void Characters( const ::rtl::OUString& rChars ); sal_Bool SetComponent( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& rComp ); }; #endif // _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MergeElemTContext.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-19 18:53:15 $ * * 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 _XMLOFF_MERGEELEMTCONTEXT_HXX #include "MergeElemTContext.hxx" #endif #ifndef _XMLOFF_MUTABLEATTRLIST_HXX #include "MutableAttrList.hxx" #endif #ifndef _XMLOFF_TRANSFORMERBASE_HXX #include "TransformerBase.hxx" #endif #ifndef _XMLOFF_TRANSFORMERACTIONS_HXX #include "TransformerActions.hxx" #endif #ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX #include "AttrTransformerAction.hxx" #endif #ifndef _XMLOFF_ELEMTRANSFORMERACTION_HXX #include "ElemTransformerAction.hxx" #endif #ifndef _XMLOFF_IGNORETCONTEXT_HXX #include "IgnoreTContext.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif using ::rtl::OUString; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; using namespace ::xmloff::token; class XMLParagraphTransformerContext : public XMLTransformerContext { public: TYPEINFO(); XMLParagraphTransformerContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName ); virtual ~XMLParagraphTransformerContext(); // Create a childs element context. By default, the import's // CreateContext method is called to create a new default context. virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rQName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); // StartElement is called after a context has been constructed and // before a elements context is parsed. It may be used for actions that // require virtual methods. The default is to do nothing. virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); // EndElement is called before a context will be destructed, but // after a elements context has been parsed. It may be used for actions // that require virtual methods. The default is to do nothing. virtual void EndElement(); // This method is called for all characters that are contained in the // current element. The default is to ignore them. virtual void Characters( const ::rtl::OUString& rChars ); }; TYPEINIT1( XMLParagraphTransformerContext, XMLTransformerContext ); XMLParagraphTransformerContext::XMLParagraphTransformerContext( XMLTransformerBase& rImp, const OUString& rQName ) : XMLTransformerContext( rImp, rQName ) { } XMLParagraphTransformerContext::~XMLParagraphTransformerContext() { } XMLTransformerContext *XMLParagraphTransformerContext::CreateChildContext( sal_uInt16 /*nPrefix*/, const OUString& /*rLocalName*/, const OUString& rQName, const Reference< XAttributeList >& ) { XMLTransformerContext *pContext = 0; pContext = new XMLIgnoreTransformerContext( GetTransformer(), rQName, sal_True ); return pContext; } void XMLParagraphTransformerContext::StartElement( const Reference< XAttributeList >& rAttrList ) { XMLTransformerContext::StartElement( rAttrList ); } void XMLParagraphTransformerContext::EndElement() { XMLTransformerContext::EndElement(); } void XMLParagraphTransformerContext::Characters( const OUString& rChars ) { XMLTransformerContext::Characters( rChars ); } class XMLPersTextContentRNGTransformTContext : public XMLPersTextContentTContext { public: TYPEINFO(); XMLPersTextContentRNGTransformTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken ); virtual ~XMLPersTextContentRNGTransformTContext(); virtual void Characters( const ::rtl::OUString& rChars ); }; TYPEINIT1( XMLPersTextContentRNGTransformTContext, XMLPersAttrListTContext ); XMLPersTextContentRNGTransformTContext::XMLPersTextContentRNGTransformTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken ) : XMLPersTextContentTContext( rTransformer, rQName, nPrefix, eToken ) {} XMLPersTextContentRNGTransformTContext::~XMLPersTextContentRNGTransformTContext() {} void XMLPersTextContentRNGTransformTContext::Characters( const ::rtl::OUString& rChars ) { OUString aConvChars( rChars ); GetTransformer().ConvertRNGDateTimeToISO( aConvChars ); XMLPersTextContentTContext::Characters( aConvChars ); } TYPEINIT1( XMLMergeElemTransformerContext, XMLTransformerContext ); void XMLMergeElemTransformerContext::ExportStartElement() { XMLPersTextContentTContextVector::iterator aIter = m_aChildContexts.begin(); for( ; aIter != m_aChildContexts.end(); ++aIter ) { XMLPersTextContentTContext *pContext = (*aIter).get(); static_cast< XMLMutableAttributeList * >( m_xAttrList.get() ) ->AddAttribute( pContext->GetExportQName(), pContext->GetTextContent() ); } XMLTransformerContext::StartElement( m_xAttrList ); m_bStartElementExported = sal_True; } XMLMergeElemTransformerContext::XMLMergeElemTransformerContext( XMLTransformerBase& rImp, const OUString& rQName, sal_uInt16 nActionMap ) : XMLTransformerContext( rImp, rQName ), m_nActionMap( nActionMap ), m_bStartElementExported( sal_False ) { } XMLMergeElemTransformerContext::~XMLMergeElemTransformerContext() { } void XMLMergeElemTransformerContext::StartElement( const Reference< XAttributeList >& rAttrList ) { XMLMutableAttributeList *pMutableAttrList = new XMLMutableAttributeList( rAttrList, sal_True ); m_xAttrList = pMutableAttrList; sal_Int16 nAttrCount = m_xAttrList.is() ? m_xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rAttrName = m_xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); sal_Bool bRemove = sal_True; if( XML_NAMESPACE_OFFICE == nPrefix) { if (IsXMLToken( aLocalName, XML_DISPLAY ) ) bRemove = sal_False; else if (IsXMLToken( aLocalName, XML_AUTHOR ) ) bRemove = sal_False; else if (IsXMLToken( aLocalName, XML_CREATE_DATE ) ) bRemove = sal_False; else if (IsXMLToken( aLocalName, XML_CREATE_DATE_STRING ) ) bRemove = sal_False; } if (bRemove) { pMutableAttrList->RemoveAttributeByIndex( i ); --i; --nAttrCount; } } } XMLTransformerContext *XMLMergeElemTransformerContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const OUString& rQName, const Reference< XAttributeList >& rAttrList ) { XMLTransformerContext *pContext = 0; if( !m_bStartElementExported ) { XMLTransformerActions *pActions = GetTransformer().GetUserDefinedActions( m_nActionMap ); OSL_ENSURE( pActions, "go no actions" ); if( pActions ) { XMLTransformerActions::key_type aKey( nPrefix, rLocalName ); XMLTransformerActions::const_iterator aIter = pActions->find( aKey ); if( !(aIter == pActions->end()) ) { switch( (*aIter).second.m_nActionType ) { case XML_ATACTION_MOVE_FROM_ELEM_RNG2ISO_DATETIME: { XMLPersTextContentTContext *pTC = new XMLPersTextContentRNGTransformTContext( GetTransformer(), rQName, (*aIter).second.GetQNamePrefixFromParam1(), (*aIter).second.GetQNameTokenFromParam1() ); XMLPersTextContentTContextVector::value_type aVal(pTC); m_aChildContexts.push_back( aVal ); pContext = pTC; } break; case XML_ATACTION_MOVE_FROM_ELEM: { XMLPersTextContentTContext *pTC = new XMLPersTextContentTContext( GetTransformer(), rQName, (*aIter).second.GetQNamePrefixFromParam1(), (*aIter).second.GetQNameTokenFromParam1() ); XMLPersTextContentTContextVector::value_type aVal(pTC); m_aChildContexts.push_back( aVal ); pContext = pTC; } break; case XML_ETACTION_EXTRACT_CHARACTERS: { if( !m_bStartElementExported ) ExportStartElement(); XMLParagraphTransformerContext* pPTC = new XMLParagraphTransformerContext( GetTransformer(), rQName); pContext = pPTC; } break; default: OSL_ENSURE( !this, "unknown action" ); break; } } } } else { XMLTransformerActions *pActions = GetTransformer().GetUserDefinedActions( m_nActionMap ); OSL_ENSURE( pActions, "go no actions" ); if( pActions ) { XMLTransformerActions::key_type aKey( nPrefix, rLocalName ); XMLTransformerActions::const_iterator aIter = pActions->find( aKey ); if( !(aIter == pActions->end()) ) { switch( (*aIter).second.m_nActionType ) { case XML_ETACTION_EXTRACT_CHARACTERS: { if( !m_bStartElementExported ) ExportStartElement(); XMLParagraphTransformerContext* pPTC = new XMLParagraphTransformerContext( GetTransformer(), rQName); pContext = pPTC; } break; default: OSL_ENSURE( !this, "unknown action" ); break; } } } } // default is copying if( !pContext ) { if( !m_bStartElementExported ) ExportStartElement(); pContext = XMLTransformerContext::CreateChildContext( nPrefix, rLocalName, rQName, rAttrList ); } return pContext; } void XMLMergeElemTransformerContext::EndElement() { if( !m_bStartElementExported ) ExportStartElement(); XMLTransformerContext::EndElement(); } void XMLMergeElemTransformerContext::Characters( const OUString& ) { // ignore } <commit_msg>INTEGRATION: CWS pchfix02 (1.7.34); FILE MERGED 2006/09/01 18:00:16 kaib 1.7.34.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MergeElemTContext.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-17 11:25:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_MERGEELEMTCONTEXT_HXX #include "MergeElemTContext.hxx" #endif #ifndef _XMLOFF_MUTABLEATTRLIST_HXX #include "MutableAttrList.hxx" #endif #ifndef _XMLOFF_TRANSFORMERBASE_HXX #include "TransformerBase.hxx" #endif #ifndef _XMLOFF_TRANSFORMERACTIONS_HXX #include "TransformerActions.hxx" #endif #ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX #include "AttrTransformerAction.hxx" #endif #ifndef _XMLOFF_ELEMTRANSFORMERACTION_HXX #include "ElemTransformerAction.hxx" #endif #ifndef _XMLOFF_IGNORETCONTEXT_HXX #include "IgnoreTContext.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif using ::rtl::OUString; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; using namespace ::xmloff::token; class XMLParagraphTransformerContext : public XMLTransformerContext { public: TYPEINFO(); XMLParagraphTransformerContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName ); virtual ~XMLParagraphTransformerContext(); // Create a childs element context. By default, the import's // CreateContext method is called to create a new default context. virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rQName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); // StartElement is called after a context has been constructed and // before a elements context is parsed. It may be used for actions that // require virtual methods. The default is to do nothing. virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); // EndElement is called before a context will be destructed, but // after a elements context has been parsed. It may be used for actions // that require virtual methods. The default is to do nothing. virtual void EndElement(); // This method is called for all characters that are contained in the // current element. The default is to ignore them. virtual void Characters( const ::rtl::OUString& rChars ); }; TYPEINIT1( XMLParagraphTransformerContext, XMLTransformerContext ); XMLParagraphTransformerContext::XMLParagraphTransformerContext( XMLTransformerBase& rImp, const OUString& rQName ) : XMLTransformerContext( rImp, rQName ) { } XMLParagraphTransformerContext::~XMLParagraphTransformerContext() { } XMLTransformerContext *XMLParagraphTransformerContext::CreateChildContext( sal_uInt16 /*nPrefix*/, const OUString& /*rLocalName*/, const OUString& rQName, const Reference< XAttributeList >& ) { XMLTransformerContext *pContext = 0; pContext = new XMLIgnoreTransformerContext( GetTransformer(), rQName, sal_True ); return pContext; } void XMLParagraphTransformerContext::StartElement( const Reference< XAttributeList >& rAttrList ) { XMLTransformerContext::StartElement( rAttrList ); } void XMLParagraphTransformerContext::EndElement() { XMLTransformerContext::EndElement(); } void XMLParagraphTransformerContext::Characters( const OUString& rChars ) { XMLTransformerContext::Characters( rChars ); } class XMLPersTextContentRNGTransformTContext : public XMLPersTextContentTContext { public: TYPEINFO(); XMLPersTextContentRNGTransformTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken ); virtual ~XMLPersTextContentRNGTransformTContext(); virtual void Characters( const ::rtl::OUString& rChars ); }; TYPEINIT1( XMLPersTextContentRNGTransformTContext, XMLPersAttrListTContext ); XMLPersTextContentRNGTransformTContext::XMLPersTextContentRNGTransformTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken ) : XMLPersTextContentTContext( rTransformer, rQName, nPrefix, eToken ) {} XMLPersTextContentRNGTransformTContext::~XMLPersTextContentRNGTransformTContext() {} void XMLPersTextContentRNGTransformTContext::Characters( const ::rtl::OUString& rChars ) { OUString aConvChars( rChars ); GetTransformer().ConvertRNGDateTimeToISO( aConvChars ); XMLPersTextContentTContext::Characters( aConvChars ); } TYPEINIT1( XMLMergeElemTransformerContext, XMLTransformerContext ); void XMLMergeElemTransformerContext::ExportStartElement() { XMLPersTextContentTContextVector::iterator aIter = m_aChildContexts.begin(); for( ; aIter != m_aChildContexts.end(); ++aIter ) { XMLPersTextContentTContext *pContext = (*aIter).get(); static_cast< XMLMutableAttributeList * >( m_xAttrList.get() ) ->AddAttribute( pContext->GetExportQName(), pContext->GetTextContent() ); } XMLTransformerContext::StartElement( m_xAttrList ); m_bStartElementExported = sal_True; } XMLMergeElemTransformerContext::XMLMergeElemTransformerContext( XMLTransformerBase& rImp, const OUString& rQName, sal_uInt16 nActionMap ) : XMLTransformerContext( rImp, rQName ), m_nActionMap( nActionMap ), m_bStartElementExported( sal_False ) { } XMLMergeElemTransformerContext::~XMLMergeElemTransformerContext() { } void XMLMergeElemTransformerContext::StartElement( const Reference< XAttributeList >& rAttrList ) { XMLMutableAttributeList *pMutableAttrList = new XMLMutableAttributeList( rAttrList, sal_True ); m_xAttrList = pMutableAttrList; sal_Int16 nAttrCount = m_xAttrList.is() ? m_xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rAttrName = m_xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); sal_Bool bRemove = sal_True; if( XML_NAMESPACE_OFFICE == nPrefix) { if (IsXMLToken( aLocalName, XML_DISPLAY ) ) bRemove = sal_False; else if (IsXMLToken( aLocalName, XML_AUTHOR ) ) bRemove = sal_False; else if (IsXMLToken( aLocalName, XML_CREATE_DATE ) ) bRemove = sal_False; else if (IsXMLToken( aLocalName, XML_CREATE_DATE_STRING ) ) bRemove = sal_False; } if (bRemove) { pMutableAttrList->RemoveAttributeByIndex( i ); --i; --nAttrCount; } } } XMLTransformerContext *XMLMergeElemTransformerContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const OUString& rQName, const Reference< XAttributeList >& rAttrList ) { XMLTransformerContext *pContext = 0; if( !m_bStartElementExported ) { XMLTransformerActions *pActions = GetTransformer().GetUserDefinedActions( m_nActionMap ); OSL_ENSURE( pActions, "go no actions" ); if( pActions ) { XMLTransformerActions::key_type aKey( nPrefix, rLocalName ); XMLTransformerActions::const_iterator aIter = pActions->find( aKey ); if( !(aIter == pActions->end()) ) { switch( (*aIter).second.m_nActionType ) { case XML_ATACTION_MOVE_FROM_ELEM_RNG2ISO_DATETIME: { XMLPersTextContentTContext *pTC = new XMLPersTextContentRNGTransformTContext( GetTransformer(), rQName, (*aIter).second.GetQNamePrefixFromParam1(), (*aIter).second.GetQNameTokenFromParam1() ); XMLPersTextContentTContextVector::value_type aVal(pTC); m_aChildContexts.push_back( aVal ); pContext = pTC; } break; case XML_ATACTION_MOVE_FROM_ELEM: { XMLPersTextContentTContext *pTC = new XMLPersTextContentTContext( GetTransformer(), rQName, (*aIter).second.GetQNamePrefixFromParam1(), (*aIter).second.GetQNameTokenFromParam1() ); XMLPersTextContentTContextVector::value_type aVal(pTC); m_aChildContexts.push_back( aVal ); pContext = pTC; } break; case XML_ETACTION_EXTRACT_CHARACTERS: { if( !m_bStartElementExported ) ExportStartElement(); XMLParagraphTransformerContext* pPTC = new XMLParagraphTransformerContext( GetTransformer(), rQName); pContext = pPTC; } break; default: OSL_ENSURE( !this, "unknown action" ); break; } } } } else { XMLTransformerActions *pActions = GetTransformer().GetUserDefinedActions( m_nActionMap ); OSL_ENSURE( pActions, "go no actions" ); if( pActions ) { XMLTransformerActions::key_type aKey( nPrefix, rLocalName ); XMLTransformerActions::const_iterator aIter = pActions->find( aKey ); if( !(aIter == pActions->end()) ) { switch( (*aIter).second.m_nActionType ) { case XML_ETACTION_EXTRACT_CHARACTERS: { if( !m_bStartElementExported ) ExportStartElement(); XMLParagraphTransformerContext* pPTC = new XMLParagraphTransformerContext( GetTransformer(), rQName); pContext = pPTC; } break; default: OSL_ENSURE( !this, "unknown action" ); break; } } } } // default is copying if( !pContext ) { if( !m_bStartElementExported ) ExportStartElement(); pContext = XMLTransformerContext::CreateChildContext( nPrefix, rLocalName, rQName, rAttrList ); } return pContext; } void XMLMergeElemTransformerContext::EndElement() { if( !m_bStartElementExported ) ExportStartElement(); XMLTransformerContext::EndElement(); } void XMLMergeElemTransformerContext::Characters( const OUString& ) { // ignore } <|endoftext|>
<commit_before>#include <thectci/dispatcher.hpp> #include <igloo/igloo.h> #include <igloo/igloo_alt.h> using namespace igloo; namespace { struct EventA { add_polymorphic_ctci( "EventA" ); }; struct EventB : public EventA { add_polymorphic_ctci( "EventB" ); }; template < class Event > struct ListenerObject { typedef Event event_type; ListenerObject() : dispatched_event( nullptr ) { } void handle_event( const Event& event ) { assert( dispatched_event == nullptr ); dispatched_event = &event; } const Event* dispatched_event; ListenerObject( const ListenerObject& ) = delete; ListenerObject& operator=( const ListenerObject& ) = delete; }; typedef ListenerObject< EventA > AListener; typedef ListenerObject< EventB > BListener; template < class Listener > void register_listener( the::ctci::Dispatcher& dispatcher, Listener& listener ) { dispatcher.register_listener< typename Listener::event_type >( std::bind( &Listener::handle_event, &listener, std::placeholders::_1 ) ); } } Describe( a_dispatcher ) { void SetUp() { test_dispatcher.reset( new the::ctci::Dispatcher() ); } Spec( listeners_can_register_by_event_type ) { AListener listener; register_listener( *test_dispatcher, listener ); } It( dispatches_events_to_registered_listeners_by_event_type ) { AListener alistener; register_listener( *test_dispatcher, alistener ); AListener alistener2; register_listener( *test_dispatcher, alistener2 ); BListener blistener; register_listener( *test_dispatcher, blistener ); test_dispatcher->dispatch( aevent ); test_dispatcher->dispatch( bevent ); AssertThat( alistener.dispatched_event, Equals( &aevent ) ); AssertThat( alistener2.dispatched_event, Equals( &aevent ) ); AssertThat( blistener.dispatched_event, Equals( &bevent ) ); } It( dispatches_events_by_polymorphic_id ) { AListener alistener; register_listener( *test_dispatcher, alistener ); BListener blistener; register_listener( *test_dispatcher, blistener ); test_dispatcher->polymorphic_dispatch( aevent ); test_dispatcher->polymorphic_dispatch( static_cast<const EventA& >( bevent ) ); AssertThat( alistener.dispatched_event, Equals( &aevent ) ); AssertThat( blistener.dispatched_event, Equals( &bevent ) ); } It( forwards_events_to_subdispatchers ) { const EventA* dispatched_event{ nullptr }; the::ctci::Dispatcher sub_dispatcher; sub_dispatcher.register_listener< EventA >( [ &dispatched_event ]( const EventA& event ) { dispatched_event = &event; } ); test_dispatcher->register_dispatcher( sub_dispatcher ); test_dispatcher->dispatch( aevent ); AssertThat( dispatched_event, Equals( &aevent ) ); } It( forwards_events_to_subdispatchers_polymorphic ) { const EventB* dispatched_event{ nullptr }; the::ctci::Dispatcher sub_dispatcher; sub_dispatcher.register_listener< EventB >( [ &dispatched_event ]( const EventB& event ) { dispatched_event = &event; } ); test_dispatcher->register_dispatcher( sub_dispatcher ); test_dispatcher->polymorphic_dispatch( static_cast< const EventA& >( bevent ) ); AssertThat( dispatched_event, Equals( &bevent ) ); } It( sub_dispatchers_can_be_removed ) { const EventA* dispatched_event{ nullptr }; the::ctci::Dispatcher sub_dispatcher; sub_dispatcher.register_listener< EventA >( [ &dispatched_event ]( const EventA& event ) { dispatched_event = &event; } ); test_dispatcher->register_dispatcher( sub_dispatcher ); test_dispatcher->remove_dispatcher( sub_dispatcher ); test_dispatcher->dispatch( aevent ); AssertThat( dispatched_event == nullptr, Equals( true ) ); } std::unique_ptr< the::ctci::Dispatcher > test_dispatcher; EventA aevent; EventB bevent; }; <commit_msg>extract common code in dispatcher tests<commit_after>#include <thectci/dispatcher.hpp> #include <igloo/igloo.h> #include <igloo/igloo_alt.h> using namespace igloo; namespace { struct EventA { add_polymorphic_ctci( "EventA" ); }; struct EventB : public EventA { add_polymorphic_ctci( "EventB" ); }; template < class Event > struct ListenerObject { typedef Event event_type; ListenerObject() : dispatched_event( nullptr ) { } void handle_event( const Event& event ) { assert( dispatched_event == nullptr ); dispatched_event = &event; } const Event* dispatched_event; ListenerObject( const ListenerObject& ) = delete; ListenerObject& operator=( const ListenerObject& ) = delete; }; typedef ListenerObject< EventA > AListener; typedef ListenerObject< EventB > BListener; template < class Listener > void register_listener( the::ctci::Dispatcher& dispatcher, Listener& listener ) { dispatcher.register_listener< typename Listener::event_type >( std::bind( &Listener::handle_event, &listener, std::placeholders::_1 ) ); } } Describe( a_dispatcher ) { void SetUp() { test_dispatcher.reset( new the::ctci::Dispatcher() ); sub_dispatcher.reset( new the::ctci::Dispatcher() ); test_dispatcher->register_dispatcher( *sub_dispatcher ); } Spec( listeners_can_register_by_event_type ) { AListener listener; register_listener( *test_dispatcher, listener ); } It( dispatches_events_to_registered_listeners_by_event_type ) { AListener alistener; register_listener( *test_dispatcher, alistener ); AListener alistener2; register_listener( *test_dispatcher, alistener2 ); BListener blistener; register_listener( *test_dispatcher, blistener ); test_dispatcher->dispatch( aevent ); test_dispatcher->dispatch( bevent ); AssertThat( alistener.dispatched_event, Equals( &aevent ) ); AssertThat( alistener2.dispatched_event, Equals( &aevent ) ); AssertThat( blistener.dispatched_event, Equals( &bevent ) ); } It( dispatches_events_by_polymorphic_id ) { AListener alistener; register_listener( *test_dispatcher, alistener ); BListener blistener; register_listener( *test_dispatcher, blistener ); test_dispatcher->polymorphic_dispatch( aevent ); test_dispatcher->polymorphic_dispatch( static_cast<const EventA& >( bevent ) ); AssertThat( alistener.dispatched_event, Equals( &aevent ) ); AssertThat( blistener.dispatched_event, Equals( &bevent ) ); } It( forwards_events_to_subdispatchers ) { AListener alistener; register_listener( *sub_dispatcher, alistener ); test_dispatcher->dispatch( aevent ); AssertThat( alistener.dispatched_event, Equals( &aevent ) ); } It( forwards_events_to_subdispatchers_polymorphic ) { BListener blistener; register_listener( *sub_dispatcher, blistener ); test_dispatcher->polymorphic_dispatch( static_cast< const EventA& >( bevent ) ); AssertThat( blistener.dispatched_event, Equals( &bevent ) ); } It( sub_dispatchers_can_be_removed ) { AListener alistener; register_listener( *sub_dispatcher, alistener ); test_dispatcher->remove_dispatcher( *sub_dispatcher ); test_dispatcher->dispatch( aevent ); AssertThat( alistener.dispatched_event == nullptr, Equals( true ) ); } std::unique_ptr< the::ctci::Dispatcher > test_dispatcher; std::unique_ptr< the::ctci::Dispatcher > sub_dispatcher; EventA aevent; EventB bevent; }; <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* common headers */ #include "common.h" /* interface headers */ #include "EvdevJoystick.h" #ifdef HAVE_LINUX_INPUT_H /* system headers */ #include <vector> #include <string> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <dirent.h> #include <fcntl.h> #include <unistd.h> #include <linux/input.h> /* implementation headers */ #include "ErrorHandler.h" #define test_bit(nr, addr) \ (((1UL << ((nr) & 31)) & (((const unsigned int *) addr)[(nr) >> 5])) != 0) bool EvdevJoystick::isEvdevAvailable() { /* Test whether this driver should be used without actually * loading it. Will return false if no event devices can be * located, or if it has been specifically disabled by setting * the environment variable BZFLAG_ENABLE_EVDEV=0 */ char *envvar = getenv("BZFLAG_ENABLE_EVDEV"); if (envvar) return atoi(envvar) != 0; std::map<std::string,EvdevJoystickInfo> joysticks; scanForJoysticks(joysticks); return !joysticks.empty(); } EvdevJoystick::EvdevJoystick() { joystickfd = 0; currentJoystick = NULL; ff_rumble = new struct ff_effect; scanForJoysticks(joysticks); } EvdevJoystick::~EvdevJoystick() { initJoystick(""); delete ff_rumble; } void EvdevJoystick::scanForJoysticks(std::map<std::string, EvdevJoystickInfo> &joysticks) { joysticks.clear(); const std::string inputdirName = "/dev/input"; DIR* inputdir = opendir(inputdirName.c_str()); if (!inputdir) return; struct dirent *dent; while ((dent = readdir(inputdir))) { EvdevJoystickInfo info; /* Does it look like an event device? */ if (strncmp(dent->d_name, "event", 5)) continue; /* Can we open it? */ info.filename = inputdirName + "/" + dent->d_name; int fd = open(info.filename.c_str(), O_RDWR); if (!fd) continue; /* Does it look like a joystick? */ if (!(collectJoystickBits(fd, info) && isJoystick(info))) { close(fd); continue; } /* Can we get its name? */ char jsname[128]; if (ioctl(fd, EVIOCGNAME(sizeof(jsname)-1), jsname) < 0) { close(fd); continue; } jsname[sizeof(jsname)-1] = '\0'; close(fd); /* Yay, add it to our map. * * FIXME: we can't handle multiple joysticks with the same name yet. * This could be fixed by disambiguating jsname if it already * exists in 'joysticks', but the user would still have a hard * time knowing which device to pick. */ joysticks[jsname] = info; } closedir(inputdir); } bool EvdevJoystick::collectJoystickBits(int fd, struct EvdevJoystickInfo &info) { /* Collect all the bitfields we're interested in from an event device * at the given file descriptor. */ if (ioctl(fd, EVIOCGBIT(0, sizeof(info.evbit)), info.evbit) < 0) return false; if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(info.keybit)), info.keybit) < 0) return false; if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(info.absbit)), info.absbit) < 0) return false; if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(info.ffbit)), info.ffbit) < 0) return false; /* Collect information about our absolute axes */ int axis; for (axis=0; axis<2; axis++) { if (ioctl(fd, EVIOCGABS(axis + ABS_X), &info.axis_info[axis]) < 0) return false; } return true; } bool EvdevJoystick::isJoystick(struct EvdevJoystickInfo &info) { /* Look at the capability bitfields in the given EvdevJoystickInfo, and * decide whether the device is indeed a joystick. This uses the same criteria * that SDL does- it at least needs X and Y axes, and one joystick-like button. */ if (!test_bit(EV_KEY, info.evbit)) return false; if (!(test_bit(BTN_TRIGGER, info.keybit) || test_bit(BTN_A, info.keybit) || test_bit(BTN_1, info.keybit))) return false; if (!test_bit(EV_ABS, info.evbit)) return false; if (!(test_bit(ABS_X, info.absbit) && test_bit(ABS_Y, info.absbit))) return false; return true; } void EvdevJoystick::initJoystick(const char* joystickName) { /* Close the previous joystick */ ffResetRumble(); if (joystickfd > 0) close(joystickfd); currentJoystick = NULL; joystickfd = 0; if (!strcasecmp(joystickName, "off") || !strcmp(joystickName, "")) { /* No joystick configured, we're done */ return; } std::map<std::string,EvdevJoystickInfo>::iterator iter; iter = joysticks.find(joystickName); if (iter == joysticks.end()) { printError("The selected joystick no longer exists."); return; } /* Looks like we might have a valid joystick, try to open it */ EvdevJoystickInfo *info = &iter->second; joystickfd = open(info->filename.c_str(), O_RDWR | O_NONBLOCK); if (joystickfd > 0) { /* Yay, it worked */ currentJoystick = info; } else { printError("Error opening the selected joystick."); } buttons = 0; } bool EvdevJoystick::joystick() const { return currentJoystick != NULL; } void EvdevJoystick::poll() { /* Read as many input events as are available, and update our current state */ struct input_event ev; while (read(joystickfd, &ev, sizeof(ev)) > 0) { switch (ev.type) { case EV_ABS: switch (ev.code) { case ABS_X: currentJoystick->axis_info[0].value = ev.value; break; case ABS_Y: currentJoystick->axis_info[1].value = ev.value; break; } break; case EV_KEY: setButton(mapButton(ev.code), ev.value); break; } } } int EvdevJoystick::mapButton(int bit_num) { /* Given an evdev button number, map it back to a small integer that most * people would consider the button's actual number. This also ensures * that we can fit all buttons in "buttons" as long as the number of buttons * is less than the architecture's word size ;) * * We just scan through the joystick's keybits, counting how many * set bits we encounter before this one. If the indicated bit isn't * set in keybits, this is a bad event and we return -1. * If this linear scan becomes a noticeable performance drain, this could * easily be precomputed and stored in an std:map. */ int i; int button_num = 0; const int total_bits = sizeof(currentJoystick->keybit)*sizeof(unsigned long)*8; for (i=0; i<total_bits; i++) { if (i == bit_num) return button_num; if (test_bit(i, currentJoystick->keybit)) button_num++; } return -1; } void EvdevJoystick::setButton(int button_num, int state) { if (button_num >= 0) { int mask = 1<<button_num; if (state) buttons |= mask; else buttons &= ~mask; } } void EvdevJoystick::getJoy(int& x, int& y) { if (currentJoystick) { poll(); int axes[2]; int axis; int value; for (axis=0; axis<2; axis++) { /* Each axis gets scaled from evdev's reported minimum * and maximum into bzflag's [-1000, 1000] range. */ value = currentJoystick->axis_info[axis].value; value -= currentJoystick->axis_info[axis].minimum; value = value * 2000 / (currentJoystick->axis_info[axis].maximum - currentJoystick->axis_info[axis].minimum); value -= 1000; /* No cheating by modifying joystick drivers, or using some that rate * their maximum and minimum conservatively like the input spec allows. */ if (value < -1000) value = -1000; if (value > 1000) value = 1000; /* All the cool kids are doing it... */ value = (value * abs(value)) / 1000; axes[axis] = value; } x = axes[0]; y = axes[1]; } else { x = y = 0; } } unsigned long EvdevJoystick::getJoyButtons() { if (currentJoystick) { poll(); return buttons; } else { return 0; } } void EvdevJoystick::getJoyDevices(std::vector<std::string> &list) const { std::map<std::string,EvdevJoystickInfo>::const_iterator i; for (i = joysticks.begin(); i != joysticks.end(); ++i) list.push_back(i->first); } bool EvdevJoystick::ffHasRumble() const { #ifdef HAVE_FF_EFFECT_RUMBLE if (!currentJoystick) return false; else return test_bit(EV_FF, currentJoystick->evbit) && test_bit(FF_RUMBLE, currentJoystick->ffbit); #else return false; #endif } void EvdevJoystick::ffResetRumble() { #ifdef HAVE_FF_EFFECT_RUMBLE /* Erase old effects before closing a device, * if we had any, then initialize the ff_rumble struct. */ if (ffHasRumble() && ff_rumble->id != -1) { /* Stop the effect first */ struct input_event event; event.type = EV_FF; event.code = ff_rumble->id; event.value = 0; write(joystickfd, &event, sizeof(event)); /* Erase the downloaded effect */ ioctl(joystickfd, EVIOCRMFF, ff_rumble->id); } /* Reinit the ff_rumble struct. It starts out with * an id of -1, prompting the driver to assign us one. * Once that happens, we stick with the same effect slot * as long as we have the device open. */ memset(ff_rumble, 0, sizeof(*ff_rumble)); ff_rumble->type = FF_RUMBLE; ff_rumble->id = -1; #endif } #ifdef HAVE_FF_EFFECT_RUMBLE void EvdevJoystick::ffRumble(int count, float delay, float duration, float strong_motor, float weak_motor) { if (!ffHasRumble()) return; /* Stop the previous effect we were playing, if any */ if (ff_rumble->id != -1) { struct input_event event; event.type = EV_FF; event.code = ff_rumble->id; event.value = 0; write(joystickfd, &event, sizeof(event)); } if (count > 0) { /* Download an updated effect */ ff_rumble->u.rumble.strong_magnitude = (int) (0xFFFF * strong_motor + 0.5); ff_rumble->u.rumble.weak_magnitude = (int) (0xFFFF * weak_motor + 0.5); ff_rumble->replay.length = (int) (duration * 1000 + 0.5); ff_rumble->replay.delay = (int) (delay * 1000 + 0.5); ioctl(joystickfd, EVIOCSFF, ff_rumble); /* Play it the indicated number of times */ struct input_event event; event.type = EV_FF; event.code = ff_rumble->id; event.value = count; write(joystickfd, &event, sizeof(event)); } } #else void EvdevJoystick::ffRumble(int, float, float, float, float) { } #endif #endif /* HAVE_LINUX_INPUT_H */ // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>try opening event devices for read-only if we can't open them for read-write. most linux joysticks are not ff and don't need write perms. also add some debuggage.<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* common headers */ #include "common.h" /* interface headers */ #include "EvdevJoystick.h" #ifdef HAVE_LINUX_INPUT_H /* system headers */ #include <vector> #include <string> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <dirent.h> #include <fcntl.h> #include <unistd.h> #include <linux/input.h> /* implementation headers */ #include "ErrorHandler.h" #include "bzfio.h" #define test_bit(nr, addr) \ (((1UL << ((nr) & 31)) & (((const unsigned int *) addr)[(nr) >> 5])) != 0) bool EvdevJoystick::isEvdevAvailable() { /* Test whether this driver should be used without actually * loading it. Will return false if no event devices can be * located, or if it has been specifically disabled by setting * the environment variable BZFLAG_ENABLE_EVDEV=0 */ char *envvar = getenv("BZFLAG_ENABLE_EVDEV"); if (envvar) return atoi(envvar) != 0; std::map<std::string,EvdevJoystickInfo> joysticks; scanForJoysticks(joysticks); return !joysticks.empty(); } EvdevJoystick::EvdevJoystick() { joystickfd = 0; currentJoystick = NULL; ff_rumble = new struct ff_effect; scanForJoysticks(joysticks); } EvdevJoystick::~EvdevJoystick() { initJoystick(""); delete ff_rumble; } void EvdevJoystick::scanForJoysticks(std::map<std::string, EvdevJoystickInfo> &joysticks) { joysticks.clear(); const std::string inputdirName = "/dev/input"; DIR* inputdir = opendir(inputdirName.c_str()); if (!inputdir) return; struct dirent *dent; while ((dent = readdir(inputdir))) { EvdevJoystickInfo info; /* Does it look like an event device? */ if (strncmp(dent->d_name, "event", 5)) continue; /* Can we open it for r/w? */ info.filename = inputdirName + "/" + dent->d_name; int fd = open(info.filename.c_str(), O_RDWR); /* if we can't open read/write, try just read...if it's not ff it'll work anyhow */ if (!fd) { fd = open(info.filename.c_str(), O_RDONLY); if (fd) DEBUG3("Opened event device %s as read-only", info.filename.c_str()); } else { DEBUG3("Opened event device %s as read-write.", info.filename.c_str()); } /* no good, can't open it */ if (!fd) { DEBUG3("Can't open event device %s. Check permissions.", info.filename.c_str()); continue; } /* Does it look like a joystick? */ if (!(collectJoystickBits(fd, info) && isJoystick(info))) { DEBUG3("Device %s doesn't seem to be a joystick. Skipping.", info.filename.c_str()); close(fd); continue; } /* Can we get its name? */ char jsname[128]; if (ioctl(fd, EVIOCGNAME(sizeof(jsname)-1), jsname) < 0) { close(fd); continue; } jsname[sizeof(jsname)-1] = '\0'; close(fd); /* Yay, add it to our map. * * FIXME: we can't handle multiple joysticks with the same name yet. * This could be fixed by disambiguating jsname if it already * exists in 'joysticks', but the user would still have a hard * time knowing which device to pick. */ joysticks[jsname] = info; } closedir(inputdir); } bool EvdevJoystick::collectJoystickBits(int fd, struct EvdevJoystickInfo &info) { /* Collect all the bitfields we're interested in from an event device * at the given file descriptor. */ if (ioctl(fd, EVIOCGBIT(0, sizeof(info.evbit)), info.evbit) < 0) return false; if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(info.keybit)), info.keybit) < 0) return false; if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(info.absbit)), info.absbit) < 0) return false; if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(info.ffbit)), info.ffbit) < 0) return false; /* Collect information about our absolute axes */ int axis; for (axis=0; axis<2; axis++) { if (ioctl(fd, EVIOCGABS(axis + ABS_X), &info.axis_info[axis]) < 0) return false; } return true; } bool EvdevJoystick::isJoystick(struct EvdevJoystickInfo &info) { /* Look at the capability bitfields in the given EvdevJoystickInfo, and * decide whether the device is indeed a joystick. This uses the same criteria * that SDL does- it at least needs X and Y axes, and one joystick-like button. */ if (!test_bit(EV_KEY, info.evbit)) return false; if (!(test_bit(BTN_TRIGGER, info.keybit) || test_bit(BTN_A, info.keybit) || test_bit(BTN_1, info.keybit))) return false; if (!test_bit(EV_ABS, info.evbit)) return false; if (!(test_bit(ABS_X, info.absbit) && test_bit(ABS_Y, info.absbit))) return false; return true; } void EvdevJoystick::initJoystick(const char* joystickName) { /* Close the previous joystick */ ffResetRumble(); if (joystickfd > 0) close(joystickfd); currentJoystick = NULL; joystickfd = 0; if (!strcasecmp(joystickName, "off") || !strcmp(joystickName, "")) { /* No joystick configured, we're done */ return; } std::map<std::string,EvdevJoystickInfo>::iterator iter; iter = joysticks.find(joystickName); if (iter == joysticks.end()) { printError("The selected joystick no longer exists."); return; } /* Looks like we might have a valid joystick, try to open it */ EvdevJoystickInfo *info = &iter->second; joystickfd = open(info->filename.c_str(), O_RDWR | O_NONBLOCK); if (joystickfd > 0) { /* Yay, it worked */ currentJoystick = info; } else { printError("Error opening the selected joystick."); } buttons = 0; } bool EvdevJoystick::joystick() const { return currentJoystick != NULL; } void EvdevJoystick::poll() { /* Read as many input events as are available, and update our current state */ struct input_event ev; while (read(joystickfd, &ev, sizeof(ev)) > 0) { switch (ev.type) { case EV_ABS: switch (ev.code) { case ABS_X: currentJoystick->axis_info[0].value = ev.value; break; case ABS_Y: currentJoystick->axis_info[1].value = ev.value; break; } break; case EV_KEY: setButton(mapButton(ev.code), ev.value); break; } } } int EvdevJoystick::mapButton(int bit_num) { /* Given an evdev button number, map it back to a small integer that most * people would consider the button's actual number. This also ensures * that we can fit all buttons in "buttons" as long as the number of buttons * is less than the architecture's word size ;) * * We just scan through the joystick's keybits, counting how many * set bits we encounter before this one. If the indicated bit isn't * set in keybits, this is a bad event and we return -1. * If this linear scan becomes a noticeable performance drain, this could * easily be precomputed and stored in an std:map. */ int i; int button_num = 0; const int total_bits = sizeof(currentJoystick->keybit)*sizeof(unsigned long)*8; for (i=0; i<total_bits; i++) { if (i == bit_num) return button_num; if (test_bit(i, currentJoystick->keybit)) button_num++; } return -1; } void EvdevJoystick::setButton(int button_num, int state) { if (button_num >= 0) { int mask = 1<<button_num; if (state) buttons |= mask; else buttons &= ~mask; } } void EvdevJoystick::getJoy(int& x, int& y) { if (currentJoystick) { poll(); int axes[2]; int axis; int value; for (axis=0; axis<2; axis++) { /* Each axis gets scaled from evdev's reported minimum * and maximum into bzflag's [-1000, 1000] range. */ value = currentJoystick->axis_info[axis].value; value -= currentJoystick->axis_info[axis].minimum; value = value * 2000 / (currentJoystick->axis_info[axis].maximum - currentJoystick->axis_info[axis].minimum); value -= 1000; /* No cheating by modifying joystick drivers, or using some that rate * their maximum and minimum conservatively like the input spec allows. */ if (value < -1000) value = -1000; if (value > 1000) value = 1000; /* All the cool kids are doing it... */ value = (value * abs(value)) / 1000; axes[axis] = value; } x = axes[0]; y = axes[1]; } else { x = y = 0; } } unsigned long EvdevJoystick::getJoyButtons() { if (currentJoystick) { poll(); return buttons; } else { return 0; } } void EvdevJoystick::getJoyDevices(std::vector<std::string> &list) const { std::map<std::string,EvdevJoystickInfo>::const_iterator i; for (i = joysticks.begin(); i != joysticks.end(); ++i) list.push_back(i->first); } bool EvdevJoystick::ffHasRumble() const { #ifdef HAVE_FF_EFFECT_RUMBLE if (!currentJoystick) return false; else return test_bit(EV_FF, currentJoystick->evbit) && test_bit(FF_RUMBLE, currentJoystick->ffbit); #else return false; #endif } void EvdevJoystick::ffResetRumble() { #ifdef HAVE_FF_EFFECT_RUMBLE /* Erase old effects before closing a device, * if we had any, then initialize the ff_rumble struct. */ if (ffHasRumble() && ff_rumble->id != -1) { /* Stop the effect first */ struct input_event event; event.type = EV_FF; event.code = ff_rumble->id; event.value = 0; write(joystickfd, &event, sizeof(event)); /* Erase the downloaded effect */ ioctl(joystickfd, EVIOCRMFF, ff_rumble->id); } /* Reinit the ff_rumble struct. It starts out with * an id of -1, prompting the driver to assign us one. * Once that happens, we stick with the same effect slot * as long as we have the device open. */ memset(ff_rumble, 0, sizeof(*ff_rumble)); ff_rumble->type = FF_RUMBLE; ff_rumble->id = -1; #endif } #ifdef HAVE_FF_EFFECT_RUMBLE void EvdevJoystick::ffRumble(int count, float delay, float duration, float strong_motor, float weak_motor) { if (!ffHasRumble()) return; /* Stop the previous effect we were playing, if any */ if (ff_rumble->id != -1) { struct input_event event; event.type = EV_FF; event.code = ff_rumble->id; event.value = 0; write(joystickfd, &event, sizeof(event)); } if (count > 0) { /* Download an updated effect */ ff_rumble->u.rumble.strong_magnitude = (int) (0xFFFF * strong_motor + 0.5); ff_rumble->u.rumble.weak_magnitude = (int) (0xFFFF * weak_motor + 0.5); ff_rumble->replay.length = (int) (duration * 1000 + 0.5); ff_rumble->replay.delay = (int) (delay * 1000 + 0.5); ioctl(joystickfd, EVIOCSFF, ff_rumble); /* Play it the indicated number of times */ struct input_event event; event.type = EV_FF; event.code = ff_rumble->id; event.value = count; write(joystickfd, &event, sizeof(event)); } } #else void EvdevJoystick::ffRumble(int, float, float, float, float) { } #endif #endif /* HAVE_LINUX_INPUT_H */ // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/************************************************************************* * * Copyright 2016 Realm 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 "testsettings.hpp" #ifdef TEST_FILE_LOCKS #include <cassert> #include <map> #include <iostream> #include <functional> #include <thread> #include <realm/util/thread.hpp> #include <realm/util/file.hpp> #include <realm/util/features.h> #include "test.hpp" using namespace realm::util; using namespace realm::test_util; // Test independence and thread-safety // ----------------------------------- // // All tests must be thread safe and independent of each other. This // is required because it allows for both shuffling of the execution // order and for parallelized testing. // // In particular, avoid using std::rand() since it is not guaranteed // to be thread safe. Instead use the API offered in // `test/util/random.hpp`. // // All files created in tests must use the TEST_PATH macro (or one of // its friends) to obtain a suitable file system path. See // `test/util/test_path.hpp`. // // // Debugging and the ONLY() macro // ------------------------------ // // A simple way of disabling all tests except one called `Foo`, is to // replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the // test suite. Note that you can also use filtering by setting the // environment varible `UNITTEST_FILTER`. See `README.md` for more on // this. // // Another way to debug a particular test, is to copy that test into // `experiments/testcase.cpp` and then run `sh build.sh // check-testcase` (or one of its friends) from the command line. // The assumption is that if multiple processes try to place an // exclusive lock on a file in a non-blocking fashion, then at least // one will succeed (assuming that no one else interferes). This test // trys to verify that this is the case by repeatedly letting two // treads compete for the lock. This is by no means a "water tight" // test, but it is probably the best we can do. TEST(File_NoSpuriousTryLockFailures) { #if TEST_DURATION < 1 const int num_rounds = 1000; #elif TEST_DURATION < 2 const int num_rounds = 10000; #elif TEST_DURATION < 3 const int num_rounds = 100000; #else const int num_rounds = 1000000; #endif const int num_slaves = 2; Mutex mutex; CondVar cond; int num_slaves_ready = 0; int num_good_locks = 0; bool slaves_run[num_slaves] = {false}; std::map<int, int> results; bool terminate = false; auto kill_em_all = [&] { LockGuard l(mutex); terminate = true; cond.notify_all(); }; auto master = [&] { try { LockGuard l(mutex); for (int i = 0; i != num_rounds; ++i) { while (num_slaves_ready != num_slaves) { if (terminate) return; cond.wait(l); } num_slaves_ready = 0; ++results[num_good_locks]; num_good_locks = 0; for (int j = 0; j != num_slaves; ++j) slaves_run[j] = true; cond.notify_all(); } } catch (...) { kill_em_all(); throw; } }; auto slave = [&](int ndx, std::string path) { try { File file(path, File::mode_Write); for (int i = 0; i != num_rounds; ++i) { bool good_lock = file.try_lock_exclusive(); if (good_lock) file.unlock(); { LockGuard l(mutex); if (good_lock) ++num_good_locks; ++num_slaves_ready; cond.notify_all(); while (!slaves_run[ndx]) { if (terminate) return; cond.wait(l); } slaves_run[ndx] = false; } } } catch (...) { kill_em_all(); throw; } }; TEST_PATH(path); std::string str_path = path; ThreadWrapper slaves[num_slaves]; for (int i = 0; i != num_slaves; ++i) { slaves[i].start([=] { slave(i, str_path); }); } master(); for (int i = 0; i != num_slaves; ++i) CHECK(!slaves[i].join()); /* typedef std::map<int, int>::const_iterator iter; iter end = results.end(); for (iter i = results.begin(); i != end; ++i) std::cout << i->first << " -> " << i->second << "\n"; */ // Check that there are no cases where no one got the lock CHECK_EQUAL(0, results[0]); } // Same as above, but with busy waiting to increase the chance that try_lock is called simultaneously from // all the threads. Busy waiting is very slow in Valgrind and tsan, so don't run it there. TEST_IF(File_NoSpuriousTryLockFailures2, !(running_with_valgrind || running_with_tsan)) { #if TEST_DURATION < 1 const size_t num_rounds = 20; #elif TEST_DURATION < 2 const int num_rounds = 1000; #elif TEST_DURATION < 3 const int num_rounds = 10000; #else const int num_rounds = 100000; #endif // More threads than cores will give OS time slice yields at random places which is good for randomness size_t num_slaves = 2 * std::thread::hardware_concurrency(); // The number includes HyperThread cores std::atomic<size_t> lock_taken { 0 }; std::atomic<size_t> barrier_1 { 0 }; std::atomic<size_t> barrier_2 { 0 }; std::atomic<size_t> lock_not_taken { 0 }; auto slave = [&](std::string path) { File file(path, File::mode_Write); for(size_t t = 0; t < num_rounds; t++) { lock_taken = 0; lock_not_taken = 0; // Thread barrier barrier_1++; while(barrier_1 < num_slaves) { } // All threads race for the lock bool owns_lock = file.try_lock_exclusive(); barrier_2 = 0; if(owns_lock) { lock_taken++; } else { lock_not_taken++; } // Thread barrier while(lock_taken + lock_not_taken < num_slaves) { } CHECK_EQUAL(lock_taken, 1); if(owns_lock) { file.unlock(); } barrier_1 = 0; // Thread barrier. After this barrier, the file is guaranteed to be unlocked regardless who owned it. barrier_2++; while(barrier_2 < num_slaves) { } } }; TEST_PATH(path); std::string str_path = path; ThreadWrapper slaves[100]; for (size_t i = 0; i != num_slaves; ++i) { slaves[i].start([=] { slave(str_path); }); } for (size_t i = 0; i != num_slaves; ++i) CHECK(!slaves[i].join()); } #endif // TEST_FILE_LOCKS <commit_msg>Fix warning with gcc<commit_after>/************************************************************************* * * Copyright 2016 Realm 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 "testsettings.hpp" #ifdef TEST_FILE_LOCKS #include <cassert> #include <map> #include <iostream> #include <functional> #include <thread> #include <realm/util/thread.hpp> #include <realm/util/file.hpp> #include <realm/util/features.h> #include "test.hpp" using namespace realm::util; using namespace realm::test_util; // Test independence and thread-safety // ----------------------------------- // // All tests must be thread safe and independent of each other. This // is required because it allows for both shuffling of the execution // order and for parallelized testing. // // In particular, avoid using std::rand() since it is not guaranteed // to be thread safe. Instead use the API offered in // `test/util/random.hpp`. // // All files created in tests must use the TEST_PATH macro (or one of // its friends) to obtain a suitable file system path. See // `test/util/test_path.hpp`. // // // Debugging and the ONLY() macro // ------------------------------ // // A simple way of disabling all tests except one called `Foo`, is to // replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the // test suite. Note that you can also use filtering by setting the // environment varible `UNITTEST_FILTER`. See `README.md` for more on // this. // // Another way to debug a particular test, is to copy that test into // `experiments/testcase.cpp` and then run `sh build.sh // check-testcase` (or one of its friends) from the command line. // The assumption is that if multiple processes try to place an // exclusive lock on a file in a non-blocking fashion, then at least // one will succeed (assuming that no one else interferes). This test // trys to verify that this is the case by repeatedly letting two // treads compete for the lock. This is by no means a "water tight" // test, but it is probably the best we can do. TEST(File_NoSpuriousTryLockFailures) { #if TEST_DURATION < 1 const int num_rounds = 1000; #elif TEST_DURATION < 2 const int num_rounds = 10000; #elif TEST_DURATION < 3 const int num_rounds = 100000; #else const int num_rounds = 1000000; #endif const int num_slaves = 2; Mutex mutex; CondVar cond; int num_slaves_ready = 0; int num_good_locks = 0; bool slaves_run[num_slaves] = {false}; std::map<int, int> results; bool terminate = false; auto kill_em_all = [&] { LockGuard l(mutex); terminate = true; cond.notify_all(); }; auto master = [&] { try { LockGuard l(mutex); for (int i = 0; i != num_rounds; ++i) { while (num_slaves_ready != num_slaves) { if (terminate) return; cond.wait(l); } num_slaves_ready = 0; ++results[num_good_locks]; num_good_locks = 0; for (int j = 0; j != num_slaves; ++j) slaves_run[j] = true; cond.notify_all(); } } catch (...) { kill_em_all(); throw; } }; auto slave = [&](int ndx, std::string path) { try { File file(path, File::mode_Write); for (int i = 0; i != num_rounds; ++i) { bool good_lock = file.try_lock_exclusive(); if (good_lock) file.unlock(); { LockGuard l(mutex); if (good_lock) ++num_good_locks; ++num_slaves_ready; cond.notify_all(); while (!slaves_run[ndx]) { if (terminate) return; cond.wait(l); } slaves_run[ndx] = false; } } } catch (...) { kill_em_all(); throw; } }; TEST_PATH(path); std::string str_path = path; ThreadWrapper slaves[num_slaves]; for (int i = 0; i != num_slaves; ++i) { slaves[i].start([=] { slave(i, str_path); }); } master(); for (int i = 0; i != num_slaves; ++i) CHECK(!slaves[i].join()); /* typedef std::map<int, int>::const_iterator iter; iter end = results.end(); for (iter i = results.begin(); i != end; ++i) std::cout << i->first << " -> " << i->second << "\n"; */ // Check that there are no cases where no one got the lock CHECK_EQUAL(0, results[0]); } // Same as above, but with busy waiting to increase the chance that try_lock is called simultaneously from // all the threads. Busy waiting is very slow in Valgrind and tsan, so don't run it there. TEST_IF(File_NoSpuriousTryLockFailures2, !(running_with_valgrind || running_with_tsan)) { #if TEST_DURATION < 1 const size_t num_rounds = 20; #elif TEST_DURATION < 2 const int num_rounds = 1000; #elif TEST_DURATION < 3 const int num_rounds = 10000; #else const int num_rounds = 100000; #endif // More threads than cores will give OS time slice yields at random places which is good for randomness size_t num_slaves = 2 * std::thread::hardware_concurrency(); // The number includes HyperThread cores std::atomic<size_t> lock_taken { 0 }; std::atomic<size_t> barrier_1 { 0 }; std::atomic<size_t> barrier_2 { 0 }; std::atomic<size_t> lock_not_taken { 0 }; auto slave = [&](std::string path) { File file(path, File::mode_Write); for(size_t t = 0; t < num_rounds; t++) { lock_taken = 0; lock_not_taken = 0; // Thread barrier barrier_1++; while(barrier_1 < num_slaves) { } // All threads race for the lock bool owns_lock = file.try_lock_exclusive(); barrier_2 = 0; if(owns_lock) { lock_taken++; } else { lock_not_taken++; } // Thread barrier while(lock_taken + lock_not_taken < num_slaves) { } CHECK_EQUAL(lock_taken.load(), 1); if(owns_lock) { file.unlock(); } barrier_1 = 0; // Thread barrier. After this barrier, the file is guaranteed to be unlocked regardless who owned it. barrier_2++; while(barrier_2 < num_slaves) { } } }; TEST_PATH(path); std::string str_path = path; ThreadWrapper slaves[100]; for (size_t i = 0; i != num_slaves; ++i) { slaves[i].start([=] { slave(str_path); }); } for (size_t i = 0; i != num_slaves; ++i) CHECK(!slaves[i].join()); } #endif // TEST_FILE_LOCKS <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <vector> #include <utility> #include <ctime> #include <utils/group_data.h> #include <utils/random.h> #include <utils/omp.h> #include <utils/utils.h> using namespace xgboost::utils; using namespace xgboost; int main(int argc, char *argv[]) { if (argc < 3) { printf("Usage: <nkey> <ndata> pnthread]\n"); return 0; } if (argc > 3) { omp_set_num_threads(atoi(argv[3])); } random::Seed(0); unsigned nkey = static_cast<unsigned>(atoi(argv[1])); size_t ndata = static_cast<size_t>(atol(argv[2])); std::vector<unsigned> keys; std::vector< std::pair<unsigned, unsigned> > raw; raw.reserve(ndata); keys.reserve(ndata); for (size_t i = 0; i < ndata; ++i) { unsigned key = random::NextUInt32(nkey); utils::Check(key < nkey, "key exceed bound\n"); raw.push_back(std::make_pair(key, i)); keys.push_back(key); } printf("loading finish, start working\n"); time_t start_t = time(NULL); int nthread; #pragma omp parallel { nthread = omp_get_num_threads(); } std::vector<size_t> rptr; std::vector<unsigned> data; ParallelGroupBuilder<unsigned> builder(&rptr, &data); builder.InitBudget(0, nthread); bst_omp_uint nlen = raw.size(); #pragma omp parallel for schedule(static) for (bst_omp_uint i = 0; i < nlen; ++i) { builder.AddBudget(raw[i].first, omp_get_thread_num()); } double first_cost = time(NULL) - start_t; builder.InitStorage(); #pragma omp parallel for schedule(static) for (bst_omp_uint i = 0; i < nlen; ++i) { builder.Push(raw[i].first, raw[i].second, omp_get_thread_num()); } double second_cost = time(NULL) - start_t; printf("all finish, phase1=%g sec, phase2=%g sec\n", first_cost, second_cost); Check(rptr.size() <= nkey+1, "nkey exceed bound"); Check(rptr.back() == ndata, "data shape inconsistent"); for (size_t i = 0; i < rptr.size()-1; ++ i) { Check(rptr[i] <= rptr[i+1], "rptr error"); for (size_t j = rptr[i]; j < rptr[i+1]; ++j) { unsigned pos = data[j]; Check(pos < keys.size(), "invalid pos"); Check(keys[pos] == i, "invalid key entry"); } } printf("all check pass\n"); return 0; } <commit_msg>pass group data test<commit_after>#include <cstdio> #include <cstdlib> #include <vector> #include <utility> #include <ctime> #include <utils/group_data.h> #include <utils/random.h> #include <utils/omp.h> #include <utils/utils.h> using namespace xgboost::utils; using namespace xgboost; int main(int argc, char *argv[]) { if (argc < 3) { printf("Usage: <nkey> <ndata> pnthread]\n"); return 0; } if (argc > 3) { omp_set_num_threads(atoi(argv[3])); } random::Seed(0); unsigned nkey = static_cast<unsigned>(atoi(argv[1])); size_t ndata = static_cast<size_t>(atol(argv[2])); std::vector<unsigned> keys; std::vector< std::pair<unsigned, unsigned> > raw; raw.reserve(ndata); keys.reserve(ndata); for (size_t i = 0; i < ndata; ++i) { unsigned key = random::NextUInt32(nkey); utils::Check(key < nkey, "key exceed bound\n"); raw.push_back(std::make_pair(key, i)); keys.push_back(key); } printf("loading finish, start working\n"); time_t start_t = time(NULL); int nthread; #pragma omp parallel { nthread = omp_get_num_threads(); } std::vector<size_t> rptr; std::vector<unsigned> data; ParallelGroupBuilder<unsigned> builder(&rptr, &data); builder.InitBudget(0, nthread); size_t nstep = (raw.size() +nthread-1)/ nthread; #pragma omp parallel { int tid = omp_get_thread_num(); size_t begin = tid * nstep; size_t end = std::min((tid + 1) * nstep, raw.size()); for (size_t i = begin; i < end; ++i) { builder.AddBudget(raw[i].first, tid); } } double first_cost = time(NULL) - start_t; builder.InitStorage(); #pragma omp parallel { int tid = omp_get_thread_num(); size_t begin = tid * nstep; size_t end = std::min((tid + 1)* nstep, raw.size()); for (size_t i = begin; i < end; ++i) { builder.Push(raw[i].first, raw[i].second, tid); } } double second_cost = time(NULL) - start_t; printf("all finish, phase1=%g sec, phase2=%g sec\n", first_cost, second_cost); Check(rptr.size() <= nkey+1, "nkey exceed bound"); Check(rptr.back() == ndata, "data shape inconsistent"); for (size_t i = 0; i < rptr.size()-1; ++ i) { Check(rptr[i] <= rptr[i+1], "rptr error"); for (size_t j = rptr[i]; j < rptr[i+1]; ++j) { unsigned pos = data[j]; Check(pos < keys.size(), "invalid pos"); Check(keys[pos] == i, "invalid key entry"); } } printf("all check pass\n"); return 0; } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org> Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "koeventpopupmenu.h" #include "koglobals.h" #include "kocorehelper.h" #include "korganizer/baseview.h" #include "actionmanager.h" #ifndef KORG_NOPRINTER #include "calprinter.h" #endif #include <kcal/calendar.h> #include <kcal/event.h> #include <kactioncollection.h> #include <klocale.h> #include <kdebug.h> #include <kiconloader.h> #include <kurl.h> #include <QCursor> #include "koeventpopupmenu.moc" KOEventPopupMenu::KOEventPopupMenu() { mCalendar = 0; mCurrentIncidence = 0; mCurrentDate = QDate(); mHasAdditionalItems = false; addAction( i18n( "&Show" ), this, SLOT( popupShow() ) ); mEditOnlyItems.append( addAction( i18n( "&Edit..." ), this, SLOT( popupEdit() ) ) ); #ifndef KORG_NOPRINTER addAction( KOGlobals::self()->smallIcon( "document-print" ), i18n( "&Print..." ), this, SLOT( print() ) ); #endif //------------------------------------------------------------------------ mEditOnlyItems.append( addSeparator() ); mEditOnlyItems.append( addAction( KOGlobals::self()->smallIcon( "edit-cut" ), i18nc( "cut this event", "C&ut" ), this, SLOT(popupCut()) ) ); mEditOnlyItems.append( addAction( KOGlobals::self()->smallIcon( "edit-copy" ), i18nc( "copy this event", "&Copy" ), this, SLOT(popupCopy()) ) ); // paste is always possible mEditOnlyItems.append( addAction( KOGlobals::self()->smallIcon( "edit-paste" ), i18n("&Paste"), this, SLOT(popupPaste()) ) ); mEditOnlyItems.append( addAction( KOGlobals::self()->smallIcon( "edit-delete" ), i18nc( "delete this incidence", "&Delete" ), this, SLOT(popupDelete()) ) ); //------------------------------------------------------------------------ mEditOnlyItems.append( addSeparator() ); mEditOnlyItems.append( addAction( QIcon( KOGlobals::self()->smallIcon( "appointment-reminder" ) ), i18n( "&Toggle Reminder" ), this, SLOT(popupAlarm())) ); //------------------------------------------------------------------------ mRecurrenceItems.append( addSeparator() ); mRecurrenceItems.append( addAction( i18n( "&Dissociate This Occurrence" ), this, SLOT(dissociateOccurrence()) ) ); mRecurrenceItems.append( addAction( i18n( "Dissociate &Future Occurrences" ), this, SLOT(dissociateFutureOccurrence()) ) ); addSeparator(); insertItem( KOGlobals::self()->smallIcon( "mail-forward" ), i18n( "Send as iCalendar..." ), this, SLOT(forward()) ); } void KOEventPopupMenu::showIncidencePopup( Calendar *cal, Incidence *incidence, const QDate &qd ) { mCalendar = cal; mCurrentIncidence = incidence; mCurrentDate = qd; if ( mCurrentIncidence ) { // Enable/Disabled menu items only valid for editable events. QList<QAction *>::Iterator it; for ( it = mEditOnlyItems.begin(); it != mEditOnlyItems.end(); ++it ) { (*it)->setEnabled( !mCurrentIncidence->isReadOnly() ); } for ( it = mRecurrenceItems.begin(); it != mRecurrenceItems.end(); ++it ) { (*it)->setVisible( mCurrentIncidence->recurs() ); } popup( QCursor::pos() ); } else { kDebug() << "No event selected"; } } void KOEventPopupMenu::popupShow() { if ( mCurrentIncidence ) { emit showIncidenceSignal( mCurrentIncidence ); } } void KOEventPopupMenu::popupEdit() { if ( mCurrentIncidence ) { emit editIncidenceSignal( mCurrentIncidence ); } } void KOEventPopupMenu::print() { #ifndef KORG_NOPRINTER KOCoreHelper helper; CalPrinter printer( this, mCalendar, &helper ); connect( this, SIGNAL(configChanged()), &printer, SLOT(updateConfig()) ); Incidence::List selectedIncidences; selectedIncidences.append( mCurrentIncidence ); printer.print( KOrg::CalPrinterBase::Incidence, mCurrentDate, mCurrentDate, selectedIncidences ); #endif } void KOEventPopupMenu::popupDelete() { if ( mCurrentIncidence ) { emit deleteIncidenceSignal( mCurrentIncidence ); } } void KOEventPopupMenu::popupCut() { if ( mCurrentIncidence ) { emit cutIncidenceSignal(mCurrentIncidence); } } void KOEventPopupMenu::popupCopy() { if ( mCurrentIncidence ) { emit copyIncidenceSignal( mCurrentIncidence ); } } void KOEventPopupMenu::popupPaste() { emit pasteIncidenceSignal(); } void KOEventPopupMenu::popupAlarm() { if ( mCurrentIncidence ) { emit toggleAlarmSignal( mCurrentIncidence ); } } void KOEventPopupMenu::dissociateOccurrence() { if ( mCurrentIncidence ) { emit dissociateOccurrenceSignal( mCurrentIncidence, mCurrentDate ); } } void KOEventPopupMenu::dissociateFutureOccurrence() { if ( mCurrentIncidence ) { emit dissociateFutureOccurrenceSignal( mCurrentIncidence, mCurrentDate ); } } void KOEventPopupMenu::forward() { KOrg::MainWindow *w = ActionManager::findInstance( KUrl() ); if ( !w || !mCurrentIncidence ) { return; } KActionCollection *ac = w->getActionCollection(); QAction *action = ac->action( "schedule_forward" ); if ( action ) { action->trigger(); } else { kError() << "What happened to the schedule_forward action?"; } } <commit_msg>Backport r935039 by smartins from trunk to the 4.2 branch:<commit_after>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org> Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "koeventpopupmenu.h" #include "koglobals.h" #include "kocorehelper.h" #include "korganizer/baseview.h" #include "actionmanager.h" #ifndef KORG_NOPRINTER #include "calprinter.h" #endif #include <kcal/calendar.h> #include <kcal/event.h> #include <kactioncollection.h> #include <klocale.h> #include <kdebug.h> #include <kiconloader.h> #include <kurl.h> #include <QCursor> #include "koeventpopupmenu.moc" KOEventPopupMenu::KOEventPopupMenu() { mCalendar = 0; mCurrentIncidence = 0; mCurrentDate = QDate(); mHasAdditionalItems = false; addAction( i18n( "&Show" ), this, SLOT( popupShow() ) ); mEditOnlyItems.append( addAction( i18n( "&Edit..." ), this, SLOT( popupEdit() ) ) ); #ifndef KORG_NOPRINTER addAction( KOGlobals::self()->smallIcon( "document-print" ), i18n( "&Print..." ), this, SLOT( print() ) ); #endif //------------------------------------------------------------------------ mEditOnlyItems.append( addSeparator() ); mEditOnlyItems.append( addAction( KOGlobals::self()->smallIcon( "edit-cut" ), i18nc( "cut this event", "C&ut" ), this, SLOT(popupCut()) ) ); mEditOnlyItems.append( addAction( KOGlobals::self()->smallIcon( "edit-copy" ), i18nc( "copy this event", "&Copy" ), this, SLOT(popupCopy()) ) ); // paste is always possible mEditOnlyItems.append( addAction( KOGlobals::self()->smallIcon( "edit-paste" ), i18n("&Paste"), this, SLOT(popupPaste()) ) ); mEditOnlyItems.append( addAction( KOGlobals::self()->smallIcon( "edit-delete" ), i18nc( "delete this incidence", "&Delete" ), this, SLOT(popupDelete()) ) ); //------------------------------------------------------------------------ mEditOnlyItems.append( addSeparator() ); mEditOnlyItems.append( addAction( QIcon( KOGlobals::self()->smallIcon( "appointment-reminder" ) ), i18n( "&Toggle Reminder" ), this, SLOT(popupAlarm())) ); //------------------------------------------------------------------------ mRecurrenceItems.append( addSeparator() ); mRecurrenceItems.append( addAction( i18n( "&Dissociate This Occurrence" ), this, SLOT(dissociateOccurrence()) ) ); mRecurrenceItems.append( addAction( i18n( "Dissociate &Future Occurrences" ), this, SLOT(dissociateFutureOccurrence()) ) ); addSeparator(); insertItem( KOGlobals::self()->smallIcon( "mail-forward" ), i18n( "Send as iCalendar..." ), this, SLOT(forward()) ); } void KOEventPopupMenu::showIncidencePopup( Calendar *cal, Incidence *incidence, const QDate &qd ) { mCalendar = cal; mCurrentIncidence = incidence; mCurrentDate = qd; if ( mCurrentIncidence ) { // Enable/Disabled menu items only valid for editable events. QList<QAction *>::Iterator it; for ( it = mEditOnlyItems.begin(); it != mEditOnlyItems.end(); ++it ) { (*it)->setEnabled( !mCurrentIncidence->isReadOnly() ); } for ( it = mRecurrenceItems.begin(); it != mRecurrenceItems.end(); ++it ) { (*it)->setVisible( mCurrentIncidence->recurs() ); (*it)->setEnabled( !mCurrentIncidence->isReadOnly() ); } popup( QCursor::pos() ); } else { kDebug() << "No event selected"; } } void KOEventPopupMenu::popupShow() { if ( mCurrentIncidence ) { emit showIncidenceSignal( mCurrentIncidence ); } } void KOEventPopupMenu::popupEdit() { if ( mCurrentIncidence ) { emit editIncidenceSignal( mCurrentIncidence ); } } void KOEventPopupMenu::print() { #ifndef KORG_NOPRINTER KOCoreHelper helper; CalPrinter printer( this, mCalendar, &helper ); connect( this, SIGNAL(configChanged()), &printer, SLOT(updateConfig()) ); Incidence::List selectedIncidences; selectedIncidences.append( mCurrentIncidence ); printer.print( KOrg::CalPrinterBase::Incidence, mCurrentDate, mCurrentDate, selectedIncidences ); #endif } void KOEventPopupMenu::popupDelete() { if ( mCurrentIncidence ) { emit deleteIncidenceSignal( mCurrentIncidence ); } } void KOEventPopupMenu::popupCut() { if ( mCurrentIncidence ) { emit cutIncidenceSignal(mCurrentIncidence); } } void KOEventPopupMenu::popupCopy() { if ( mCurrentIncidence ) { emit copyIncidenceSignal( mCurrentIncidence ); } } void KOEventPopupMenu::popupPaste() { emit pasteIncidenceSignal(); } void KOEventPopupMenu::popupAlarm() { if ( mCurrentIncidence ) { emit toggleAlarmSignal( mCurrentIncidence ); } } void KOEventPopupMenu::dissociateOccurrence() { if ( mCurrentIncidence ) { emit dissociateOccurrenceSignal( mCurrentIncidence, mCurrentDate ); } } void KOEventPopupMenu::dissociateFutureOccurrence() { if ( mCurrentIncidence ) { emit dissociateFutureOccurrenceSignal( mCurrentIncidence, mCurrentDate ); } } void KOEventPopupMenu::forward() { KOrg::MainWindow *w = ActionManager::findInstance( KUrl() ); if ( !w || !mCurrentIncidence ) { return; } KActionCollection *ac = w->getActionCollection(); QAction *action = ac->action( "schedule_forward" ); if ( action ) { action->trigger(); } else { kError() << "What happened to the schedule_forward action?"; } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/String2Int.h" #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Execution/CommandLine.h" #include "Stroika/Foundation/Execution/Module.h" #include "Stroika/Foundation/Execution/SignalHandlers.h" #include "Stroika/Foundation/Execution/TimeOutException.h" #include "Stroika/Foundation/Execution/WaitableEvent.h" #include "Stroika/Foundation/IO/Network/HTTP/Exception.h" #include "Stroika/Foundation/IO/Network/HTTP/Headers.h" #include "Stroika/Foundation/Streams/TextReader.h" #include "Stroika/Frameworks/WebServer/ConnectionManager.h" #include "Stroika/Frameworks/WebServer/FileSystemRouter.h" #include "Stroika/Frameworks/WebServer/Router.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks::WebServer; using Characters::String; using Memory::BLOB; /* * To test this example: (make sure you run with 'current directory == top level directory of this sample else you wont find sample-html-folder) * * o Run the service (under the debugger if you wish) * o curl http://localhost:8080/ OR * o curl http://localhost:8080/FRED OR (to see error handling) * o curl -H "Content-Type: application/json" -X POST -d '{"AppState":"Start"}' http://localhost:8080/SetAppState * o curl http://localhost:8080/Files/foo.html -v */ namespace { /* * It's often helpful to structure together, routes, special interceptors, with your connection manager, to package up * all the logic /options for HTTP interface. * * This particular organization also makes it easy to save instance variables with the webserver (like a pointer to a handler) * and accesss them from the Route handler functions. */ struct MyWebServer_ { const Router fRouter_; ConnectionManager fConnectionMgr_; MyWebServer_ (uint16_t portNumber) : fRouter_{ Sequence<Route>{ Route{RegularExpression (L""), DefaultPage_}, Route{RegularExpression (L"POST"), RegularExpression (L"SetAppState"), SetAppState_}, Route{ RegularExpression (L"Files/.*"), FileSystemRouter{Execution::GetEXEDir () + L"html", String (L"Files"), Sequence<String>{L"index.html"}}, }, }} , fConnectionMgr_{SocketAddresses (InternetAddresses_Any (), portNumber), fRouter_, ConnectionManager::Options{{}, Socket::BindFlags{}, String{L"Stroika-Sample-WebServer/1.0"}}} { } // Can declare arguments as Request*,Response* static void DefaultPage_ (Request*, Response* response) { response->writeln (L"<html><body><p>Hi Mom</p></body></html>"); response->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML); } // Can declare arguments as Message* message static void SetAppState_ (Message* message) { String argsAsString = Streams::TextReader::New (message->PeekRequest ()->GetBody ()).ReadAll (); message->PeekResponse ()->writeln (L"<html><body><p>Hi SetAppState (" + argsAsString.As<wstring> () + L")</p></body></html>"); message->PeekResponse ()->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML); } }; } int main (int argc, const char* argv[]) { Execution::SignalHandlerRegistry::SafeSignalsManager safeSignals; #if qPlatform_POSIX Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED); #endif uint16_t portNumber = 8080; Time::DurationSecondsType quitAfter = numeric_limits<Time::DurationSecondsType>::max (); Sequence<String> args = Execution::ParseCommandLine (argc, argv); for (auto argi = args.begin (); argi != args.end (); ++argi) { if (Execution::MatchesCommandLineArgument (*argi, L"port")) { ++argi; if (argi != args.end ()) { portNumber = Characters::String2Int<uint16_t> (*argi); } else { cerr << "Expected arg to -port" << endl; return EXIT_FAILURE; } } else if (Execution::MatchesCommandLineArgument (*argi, L"quit-after")) { ++argi; if (argi != args.end ()) { quitAfter = Characters::String2Float<Time::DurationSecondsType> (*argi); } else { cerr << "Expected arg to -quit-after" << endl; return EXIT_FAILURE; } } } try { MyWebServer_ myWebServer{portNumber}; // listen and dispatch while this object exists Execution::WaitableEvent{}.Wait (quitAfter); // wait forever - til user hits ctrl-c } catch (const Execution::TimeOutException&) { cerr << "Timed out - so - terminating..." << endl; return EXIT_FAILURE; } catch (...) { cerr << "Error encountered: " << Characters::ToString (current_exception ()).AsNarrowSDKString () << " - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>cosmetic cleanup to WebServer sample<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/String2Int.h" #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Execution/CommandLine.h" #include "Stroika/Foundation/Execution/Module.h" #include "Stroika/Foundation/Execution/SignalHandlers.h" #include "Stroika/Foundation/Execution/TimeOutException.h" #include "Stroika/Foundation/Execution/WaitableEvent.h" #include "Stroika/Foundation/IO/Network/HTTP/Exception.h" #include "Stroika/Foundation/IO/Network/HTTP/Headers.h" #include "Stroika/Foundation/Streams/TextReader.h" #include "Stroika/Frameworks/WebServer/ConnectionManager.h" #include "Stroika/Frameworks/WebServer/FileSystemRouter.h" #include "Stroika/Frameworks/WebServer/Router.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks::WebServer; using Characters::String; using Memory::BLOB; /* * To test this example: (make sure you run with 'current directory == top level directory of this sample else you wont find sample-html-folder) * * o Run the service (under the debugger if you wish) * o curl http://localhost:8080/ OR * o curl http://localhost:8080/FRED OR (to see error handling) * o curl -H "Content-Type: application/json" -X POST -d '{"AppState":"Start"}' http://localhost:8080/SetAppState * o curl http://localhost:8080/Files/foo.html -v */ namespace { /* * It's often helpful to structure together, routes, special interceptors, with your connection manager, to package up * all the logic /options for HTTP interface. * * This particular organization also makes it easy to save instance variables with the webserver (like a pointer to a handler) * and accesss them from the Route handler functions. */ struct MyWebServer_ { const Router kRouter_; ConnectionManager fConnectionMgr_; MyWebServer_ (uint16_t portNumber) : kRouter_{ Sequence<Route>{ Route{RegularExpression (L""), DefaultPage_}, Route{RegularExpression (L"POST"), RegularExpression (L"SetAppState"), SetAppState_}, Route{ RegularExpression (L"Files/.*"), FileSystemRouter{Execution::GetEXEDir () + L"html", String (L"Files"), Sequence<String>{L"index.html"}}, }, }} , fConnectionMgr_{SocketAddresses (InternetAddresses_Any (), portNumber), kRouter_, ConnectionManager::Options{{}, Socket::BindFlags{}, String{L"Stroika-Sample-WebServer/1.0"}}} { } // Can declare arguments as Request*,Response* static void DefaultPage_ (Request*, Response* response) { response->writeln (L"<html><body><p>Hi Mom</p></body></html>"); response->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML); } // Can declare arguments as Message* message static void SetAppState_ (Message* message) { String argsAsString = Streams::TextReader::New (message->PeekRequest ()->GetBody ()).ReadAll (); message->PeekResponse ()->writeln (L"<html><body><p>Hi SetAppState (" + argsAsString.As<wstring> () + L")</p></body></html>"); message->PeekResponse ()->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML); } }; } int main (int argc, const char* argv[]) { Execution::SignalHandlerRegistry::SafeSignalsManager safeSignals; #if qPlatform_POSIX Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED); #endif uint16_t portNumber = 8080; Time::DurationSecondsType quitAfter = numeric_limits<Time::DurationSecondsType>::max (); Sequence<String> args = Execution::ParseCommandLine (argc, argv); for (auto argi = args.begin (); argi != args.end (); ++argi) { if (Execution::MatchesCommandLineArgument (*argi, L"port")) { ++argi; if (argi != args.end ()) { portNumber = Characters::String2Int<uint16_t> (*argi); } else { cerr << "Expected arg to -port" << endl; return EXIT_FAILURE; } } else if (Execution::MatchesCommandLineArgument (*argi, L"quit-after")) { ++argi; if (argi != args.end ()) { quitAfter = Characters::String2Float<Time::DurationSecondsType> (*argi); } else { cerr << "Expected arg to -quit-after" << endl; return EXIT_FAILURE; } } } try { MyWebServer_ myWebServer{portNumber}; // listen and dispatch while this object exists Execution::WaitableEvent{}.Wait (quitAfter); // wait forever - til user hits ctrl-c } catch (const Execution::TimeOutException&) { cerr << "Timed out - so - terminating..." << endl; return EXIT_FAILURE; } catch (...) { cerr << "Error encountered: " << Characters::ToString (current_exception ()).AsNarrowSDKString () << " - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// --- This file is distributed under the MIT Open Source License, as detailed // by the file "LICENSE.TXT" in the root of this repository --- #include "hurchalla/util/sized_uint.h" #include "hurchalla/util/compiler_macros.h" #include "gtest/gtest.h" #include <type_traits> #include <cstdint> namespace { TEST(HurchallaUtil, sized_uint) { namespace hc = ::hurchalla; static_assert(std::is_same<std::uint8_t, hc::sized_uint<8>::type>::value, ""); static_assert(std::is_same<std::uint16_t, hc::sized_uint<16>::type>::value, ""); static_assert(std::is_same<std::uint32_t, hc::sized_uint<32>::type>::value, ""); static_assert(std::is_same<std::uint64_t, hc::sized_uint<64>::type>::value, ""); #if HURCHALLA_COMPILER_HAS_UINT128_T() static_assert(std::is_same<__uint128_t, hc::sized_uint<128>::type>::value, ""); #endif static_assert(hc::sized_uint<8>::is_valid, ""); static_assert(hc::sized_uint<16>::is_valid, ""); static_assert(hc::sized_uint<32>::is_valid, ""); static_assert(hc::sized_uint<64>::is_valid, ""); #if HURCHALLA_COMPILER_HAS_UINT128_T() static_assert(hc::sized_uint<128>::is_valid, ""); #endif EXPECT_TRUE(hc::sized_uint<8>::is_valid); EXPECT_TRUE(hc::sized_uint<16>::is_valid); EXPECT_TRUE(hc::sized_uint<32>::is_valid); EXPECT_TRUE(hc::sized_uint<64>::is_valid); #if HURCHALLA_COMPILER_HAS_UINT128_T() EXPECT_TRUE(hc::sized_uint<128>::is_valid); #endif EXPECT_TRUE(false); // temporary, to check whether github actions sees the failure static_assert(!hc::sized_uint<4>::is_valid, ""); static_assert(!hc::sized_uint<9>::is_valid, ""); EXPECT_FALSE(hc::sized_uint<4>::is_valid); EXPECT_FALSE(hc::sized_uint<9>::is_valid); } } // end namespace <commit_msg>Update test_sized_uint.cpp<commit_after>// --- This file is distributed under the MIT Open Source License, as detailed // by the file "LICENSE.TXT" in the root of this repository --- #include "hurchalla/util/sized_uint.h" #include "hurchalla/util/compiler_macros.h" #include "gtest/gtest.h" #include <type_traits> #include <cstdint> namespace { TEST(HurchallaUtil, sized_uint) { namespace hc = ::hurchalla; static_assert(std::is_same<std::uint8_t, hc::sized_uint<8>::type>::value, ""); static_assert(std::is_same<std::uint16_t, hc::sized_uint<16>::type>::value, ""); static_assert(std::is_same<std::uint32_t, hc::sized_uint<32>::type>::value, ""); static_assert(std::is_same<std::uint64_t, hc::sized_uint<64>::type>::value, ""); #if HURCHALLA_COMPILER_HAS_UINT128_T() static_assert(std::is_same<__uint128_t, hc::sized_uint<128>::type>::value, ""); #endif static_assert(hc::sized_uint<8>::is_valid, ""); static_assert(hc::sized_uint<16>::is_valid, ""); static_assert(hc::sized_uint<32>::is_valid, ""); static_assert(hc::sized_uint<64>::is_valid, ""); #if HURCHALLA_COMPILER_HAS_UINT128_T() static_assert(hc::sized_uint<128>::is_valid, ""); #endif EXPECT_TRUE(hc::sized_uint<8>::is_valid); EXPECT_TRUE(hc::sized_uint<16>::is_valid); EXPECT_TRUE(hc::sized_uint<32>::is_valid); EXPECT_TRUE(hc::sized_uint<64>::is_valid); #if HURCHALLA_COMPILER_HAS_UINT128_T() EXPECT_TRUE(hc::sized_uint<128>::is_valid); #endif static_assert(!hc::sized_uint<4>::is_valid, ""); static_assert(!hc::sized_uint<9>::is_valid, ""); EXPECT_FALSE(hc::sized_uint<4>::is_valid); EXPECT_FALSE(hc::sized_uint<9>::is_valid); } } // end namespace <|endoftext|>
<commit_before>int main(int argc, char *argv[]) { // Reads from the file build/version_number the new version // number and generates the header base/inc/RVersion.h. // To be executed as CINT script by build/unix/makeversion.sh. // // Author: Fons Rademakers 11/10/99 const char *in = "build/version_number"; const char *inr = "etc/svninfo.txt"; FILE *fp = fopen(in, "r"); if (!fp) { printf("%s: can not open input file %s\n", argv[0], in); exit(1); } char vers[32]; fgets(vers, sizeof(vers), fp); if (vers[strlen(vers)-1] == '\n') vers[strlen(vers)-1] = 0; fclose(fp); fp = fopen(inr, "r"); if (!fp) { printf("%s: can not open input file %s\n", argv[0], in); exit(1); } char branch[2048]; fgets(branch, sizeof(branch), fp); if (branch[strlen(branch)-1] == '\n') branch[strlen(branch)-1] = 0; char revs[32]; fgets(revs, sizeof(revs), fp); if (revs[strlen(revs)-1] == '\n') revs[strlen(revs)-1] = 0; fclose(fp); const char *out = "core/base/inc/RVersion.h"; fp = fopen(out, "w"); if (!fp) { printf("%s: can not open output file %s\n", argv[0], out); exit(1); } fprintf(fp, "#ifndef ROOT_RVersion\n"); fprintf(fp, "#define ROOT_RVersion\n\n"); fprintf(fp, "/* Version information automatically generated by installer. */\n\n"); fprintf(fp, "/*\n"); fprintf(fp, " * These macros can be used in the following way:\n"); fprintf(fp, " *\n"); fprintf(fp, " * #if ROOT_VERSION_CODE >= ROOT_VERSION(2,23,4)\n"); fprintf(fp, " * #include <newheader.h>\n"); fprintf(fp, " * #else\n"); fprintf(fp, " * #include <oldheader.h>\n"); fprintf(fp, " * #endif\n"); fprintf(fp, " *\n"); fprintf(fp, "*/\n\n"); int xx, yy, zz, rev; char patch = '\0'; sscanf(vers, "%d.%d/%d%c", &xx, &yy, &zz, &patch); int vers_code = (xx << 16) + (yy << 8) + zz; int full_vers_code = (xx << 24) + (yy << 16) + (zz << 8) + patch; sscanf(revs, "%d", &rev); fprintf(fp, "#define ROOT_RELEASE \"%s\"\n", vers); fprintf(fp, "#define ROOT_RELEASE_DATE \"%s\"\n", __DATE__); fprintf(fp, "#define ROOT_RELEASE_TIME \"%s\"\n", __TIME__); fprintf(fp, "#define ROOT_SVN_REVISION %d\n", rev); fprintf(fp, "#define ROOT_SVN_BRANCH \"%s\"\n", branch); fprintf(fp, "#define ROOT_VERSION_CODE %d\n", vers_code); fprintf(fp, "#define ROOT_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))\n"); fprintf(fp, "#define ROOT_FULL_VERSION_CODE %d\n", full_vers_code); fprintf(fp, "#define ROOT_FULL_VERSION(a,b,c,p) (((a) << 24) + ((b) << 16) + ((c) << 8) + (p))\n"); fprintf(fp, "\n#endif\n"); fclose(fp); exit(0); } <commit_msg>remove ROOT_FULL_VERSION and ROOT_FULL_VERSION_CODE as we will not use the letter extensions anymore for patch releases.<commit_after>int main(int argc, char *argv[]) { // Reads from the file build/version_number the new version // number and generates the header base/inc/RVersion.h. // To be executed as CINT script by build/unix/makeversion.sh. // // Author: Fons Rademakers 11/10/99 const char *in = "build/version_number"; const char *inr = "etc/svninfo.txt"; FILE *fp = fopen(in, "r"); if (!fp) { printf("%s: can not open input file %s\n", argv[0], in); exit(1); } char vers[32]; fgets(vers, sizeof(vers), fp); if (vers[strlen(vers)-1] == '\n') vers[strlen(vers)-1] = 0; fclose(fp); fp = fopen(inr, "r"); if (!fp) { printf("%s: can not open input file %s\n", argv[0], in); exit(1); } char branch[2048]; fgets(branch, sizeof(branch), fp); if (branch[strlen(branch)-1] == '\n') branch[strlen(branch)-1] = 0; char revs[32]; fgets(revs, sizeof(revs), fp); if (revs[strlen(revs)-1] == '\n') revs[strlen(revs)-1] = 0; fclose(fp); const char *out = "core/base/inc/RVersion.h"; fp = fopen(out, "w"); if (!fp) { printf("%s: can not open output file %s\n", argv[0], out); exit(1); } fprintf(fp, "#ifndef ROOT_RVersion\n"); fprintf(fp, "#define ROOT_RVersion\n\n"); fprintf(fp, "/* Version information automatically generated by installer. */\n\n"); fprintf(fp, "/*\n"); fprintf(fp, " * These macros can be used in the following way:\n"); fprintf(fp, " *\n"); fprintf(fp, " * #if ROOT_VERSION_CODE >= ROOT_VERSION(2,23,4)\n"); fprintf(fp, " * #include <newheader.h>\n"); fprintf(fp, " * #else\n"); fprintf(fp, " * #include <oldheader.h>\n"); fprintf(fp, " * #endif\n"); fprintf(fp, " *\n"); fprintf(fp, "*/\n\n"); int xx, yy, zz, rev; sscanf(vers, "%d.%d/%d", &xx, &yy, &zz); int vers_code = (xx << 16) + (yy << 8) + zz; sscanf(revs, "%d", &rev); fprintf(fp, "#define ROOT_RELEASE \"%s\"\n", vers); fprintf(fp, "#define ROOT_RELEASE_DATE \"%s\"\n", __DATE__); fprintf(fp, "#define ROOT_RELEASE_TIME \"%s\"\n", __TIME__); fprintf(fp, "#define ROOT_SVN_REVISION %d\n", rev); fprintf(fp, "#define ROOT_SVN_BRANCH \"%s\"\n", branch); fprintf(fp, "#define ROOT_VERSION_CODE %d\n", vers_code); fprintf(fp, "#define ROOT_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))\n"); fprintf(fp, "\n#endif\n"); fclose(fp); exit(0); } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2014, PAL Robotics S.L. // // 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 PAL Robotics, 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. ////////////////////////////////////////////////////////////////////////////// /// \author Enrique Fernandez #include "test_common.h" // NaN #include <limits> // TEST CASES TEST_F(DiffDriveControllerTest, testNaN) { // wait for ROS waitForController(); // zero everything before test geometry_msgs::Twist cmd_vel; cmd_vel.linear.x = 0.0; cmd_vel.angular.z = 0.0; publish(cmd_vel); ros::Duration(2.0).sleep(); // send a command cmd_vel.linear.x = 0.1; ros::Duration(2.0).sleep(); // stop robot (will generate NaN) stop(); ros::Duration(2.0).sleep(); nav_msgs::Odometry odom = getLastOdom(); EXPECT_FALSE(std::isnan(odom.twist.twist.linear.x)); EXPECT_FALSE(std::isnan(odom.twist.twist.angular.z)); EXPECT_FALSE(std::isnan(odom.pose.pose.position.x)); EXPECT_FALSE(std::isnan(odom.pose.pose.position.y)); EXPECT_FALSE(std::isnan(odom.pose.pose.orientation.z)); EXPECT_FALSE(std::isnan(odom.pose.pose.orientation.w)); // start robot start(); ros::Duration(2.0).sleep(); odom = getLastOdom(); EXPECT_FALSE(std::isnan(odom.twist.twist.linear.x)); EXPECT_FALSE(std::isnan(odom.twist.twist.angular.z)); EXPECT_FALSE(std::isnan(odom.pose.pose.position.x)); EXPECT_FALSE(std::isnan(odom.pose.pose.position.y)); EXPECT_FALSE(std::isnan(odom.pose.pose.orientation.z)); EXPECT_FALSE(std::isnan(odom.pose.pose.orientation.w)); } TEST_F(DiffDriveControllerTest, testNaNCmd) { // wait for ROS while (!isControllerAlive()) { ros::Duration(0.1).sleep(); } // zero everything before test geometry_msgs::Twist cmd_vel; cmd_vel.linear.x = 0.0; cmd_vel.angular.z = 0.0; publish(cmd_vel); ros::Duration(0.1).sleep(); // send NaN for (int i = 0; i < 10; ++i) { geometry_msgs::Twist cmd_vel; cmd_vel.linear.x = NAN; cmd_vel.angular.z = NAN; publish(cmd_vel); geometry_msgs::TwistStamped odom_msg = getLastCmdVelOut(); EXPECT_FALSE(std::isnan(odom_msg.twist.linear.x)); EXPECT_FALSE(std::isnan(odom_msg.twist.angular.z)); ros::Duration(0.1).sleep(); } nav_msgs::Odometry odom = getLastOdom(); EXPECT_DOUBLE_EQ(odom.twist.twist.linear.x, 0.0); EXPECT_DOUBLE_EQ(odom.pose.pose.position.x, 0.0); EXPECT_DOUBLE_EQ(odom.pose.pose.position.y, 0.0); geometry_msgs::TwistStamped odom_msg = getLastCmdVelOut(); EXPECT_DOUBLE_EQ(odom_msg.twist.linear.x, 0.0); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "diff_drive_nan_test"); ros::AsyncSpinner spinner(1); spinner.start(); int ret = RUN_ALL_TESTS(); spinner.stop(); ros::shutdown(); return ret; } <commit_msg>fix test to expose NaN bug<commit_after>/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2014, PAL Robotics S.L. // // 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 PAL Robotics, 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. ////////////////////////////////////////////////////////////////////////////// /// \author Enrique Fernandez #include "test_common.h" // NaN #include <limits> // TEST CASES TEST_F(DiffDriveControllerTest, testNaN) { // wait for ROS waitForController(); // zero everything before test geometry_msgs::Twist cmd_vel; cmd_vel.linear.x = 0.0; cmd_vel.angular.z = 0.0; publish(cmd_vel); ros::Duration(2.0).sleep(); // send a command cmd_vel.linear.x = 0.1; ros::Duration(2.0).sleep(); // stop robot (will generate NaN) stop(); ros::Duration(2.0).sleep(); nav_msgs::Odometry odom = getLastOdom(); EXPECT_FALSE(std::isnan(odom.twist.twist.linear.x)); EXPECT_FALSE(std::isnan(odom.twist.twist.angular.z)); EXPECT_FALSE(std::isnan(odom.pose.pose.position.x)); EXPECT_FALSE(std::isnan(odom.pose.pose.position.y)); EXPECT_FALSE(std::isnan(odom.pose.pose.orientation.z)); EXPECT_FALSE(std::isnan(odom.pose.pose.orientation.w)); // start robot start(); ros::Duration(2.0).sleep(); odom = getLastOdom(); EXPECT_FALSE(std::isnan(odom.twist.twist.linear.x)); EXPECT_FALSE(std::isnan(odom.twist.twist.angular.z)); EXPECT_FALSE(std::isnan(odom.pose.pose.position.x)); EXPECT_FALSE(std::isnan(odom.pose.pose.position.y)); EXPECT_FALSE(std::isnan(odom.pose.pose.orientation.z)); EXPECT_FALSE(std::isnan(odom.pose.pose.orientation.w)); } TEST_F(DiffDriveControllerTest, testNaNCmd) { // wait for ROS while (!isControllerAlive()) { ros::Duration(0.1).sleep(); } // zero everything before test geometry_msgs::Twist cmd_vel; cmd_vel.linear.x = 0.0; cmd_vel.angular.z = 0.0; publish(cmd_vel); ros::Duration(0.1).sleep(); // send NaN for (int i = 0; i < 10; ++i) { geometry_msgs::Twist cmd_vel; cmd_vel.linear.x = NAN; cmd_vel.angular.z = 0.0; publish(cmd_vel); geometry_msgs::TwistStamped odom_msg = getLastCmdVelOut(); EXPECT_FALSE(std::isnan(odom_msg.twist.linear.x)); EXPECT_FALSE(std::isnan(odom_msg.twist.angular.z)); ros::Duration(0.1).sleep(); } for (int i = 0; i < 10; ++i) { geometry_msgs::Twist cmd_vel; cmd_vel.linear.x = 0.0; cmd_vel.angular.z = NAN; publish(cmd_vel); geometry_msgs::TwistStamped odom_msg = getLastCmdVelOut(); EXPECT_FALSE(std::isnan(odom_msg.twist.linear.x)); EXPECT_FALSE(std::isnan(odom_msg.twist.angular.z)); ros::Duration(0.1).sleep(); } nav_msgs::Odometry odom = getLastOdom(); EXPECT_DOUBLE_EQ(odom.twist.twist.linear.x, 0.0); EXPECT_DOUBLE_EQ(odom.pose.pose.position.x, 0.0); EXPECT_DOUBLE_EQ(odom.pose.pose.position.y, 0.0); geometry_msgs::TwistStamped odom_msg = getLastCmdVelOut(); EXPECT_DOUBLE_EQ(odom_msg.twist.linear.x, 0.0); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "diff_drive_nan_test"); ros::AsyncSpinner spinner(1); spinner.start(); int ret = RUN_ALL_TESTS(); spinner.stop(); ros::shutdown(); return ret; } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include <catch.hpp> #include <nitro/jiffy/jiffy.hpp> #include <chrono> TEST_CASE("Print 100 jiffies in iso format", "[jiffy]") { for (int i = 0; i < 100; i++) { nitro::jiffy::Jiffy j; std::cout << j << std::endl; } } TEST_CASE("Jiffy can be taken", "[jiffy]") { SECTION("Default constructed") { nitro::jiffy::Jiffy now; } SECTION("Chrono constructed") { nitro::jiffy::Jiffy now(std::chrono::system_clock::now()); } } TEST_CASE("Jiffy can be printed with a fraction", "[jiffy]") { std::chrono::system_clock::time_point ctp(std::chrono::microseconds(1542297437305463)); nitro::jiffy::Jiffy tp(ctp); REQUIRE(tp.isoformat() == "2018-11-15T16:57:17.305463+0100"); REQUIRE_THROWS(nitro::jiffy::Jiffy("2018-11-15T16:57:17.305463+0100")); } TEST_CASE("Jiffy are comparable", "[jiffy]") { nitro::jiffy::Jiffy now; REQUIRE(now == now); } TEST_CASE("Jiffy can be parsed without a fraction", "[jiffy]") { std::chrono::system_clock::time_point ctp(std::chrono::microseconds(1542297437000000)); nitro::jiffy::Jiffy tp(ctp); REQUIRE(tp.isoformat() == "2018-11-15T16:57:17.000000+0100"); REQUIRE(nitro::jiffy::Jiffy("2018-11-15T16:57:17+0100") == tp); } <commit_msg>Make the jiffy test resilient to time zones<commit_after>#define CATCH_CONFIG_MAIN #include <catch.hpp> #include <nitro/jiffy/jiffy.hpp> #include <chrono> extern "C" { #include <stdlib.h> } TEST_CASE("Print 100 jiffies in iso format", "[jiffy]") { for (int i = 0; i < 100; i++) { nitro::jiffy::Jiffy j; std::cout << j << std::endl; } } TEST_CASE("Jiffy can be taken", "[jiffy]") { SECTION("Default constructed") { nitro::jiffy::Jiffy now; } SECTION("Chrono constructed") { nitro::jiffy::Jiffy now(std::chrono::system_clock::now()); } } TEST_CASE("Jiffy can be printed with a fraction", "[jiffy]") { std::chrono::system_clock::time_point ctp(std::chrono::microseconds(1542297437305463)); nitro::jiffy::Jiffy tp(ctp); REQUIRE(tp.isoformat() == "2018-11-15T16:57:17.305463+0100"); REQUIRE_THROWS(nitro::jiffy::Jiffy("2018-11-15T16:57:17.305463+0100")); } TEST_CASE("Jiffy are comparable", "[jiffy]") { nitro::jiffy::Jiffy now; REQUIRE(now == now); } TEST_CASE("Jiffy can be parsed without a fraction", "[jiffy]") { std::chrono::system_clock::time_point ctp(std::chrono::microseconds(1542297437000000)); nitro::jiffy::Jiffy tp(ctp); // force UTC as timezone setenv("TZ", "", true); REQUIRE(tp.isoformat() == "2018-11-15T15:57:17.000000+0000"); REQUIRE(nitro::jiffy::Jiffy("2018-11-15T16:57:17+0100") == tp); } <|endoftext|>
<commit_before><commit_msg>Add check for `nullptr`.<commit_after><|endoftext|>
<commit_before>/* * Copyright 2015 - 2018 gtalent2@gmail.com * * 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/. */ #pragma once #include <ox/std/assert.hpp> #include <ox/std/byteswap.hpp> namespace ox::mc { template<typename T> static constexpr auto Bits = sizeof(T) << 3; /** * Returns highest bit other than possible signed bit. * Bit numbering starts at 0. */ template<typename I> [[nodiscard]] constexpr std::size_t highestBit(I val) noexcept { auto shiftStart = sizeof(I) * 8 - 1; // find most significant non-sign indicator bit std::size_t highestBit = 0; // start at one bit lower if signed if constexpr(ox::is_signed<I>) { --shiftStart; } for (int i = shiftStart; i > -1; --i) { const auto bitValue = (val >> i) & 1; if (bitValue) { highestBit = i; break; } } return highestBit; } static_assert(highestBit(int8_t(0b10000000)) == 0); static_assert(highestBit(1) == 0); static_assert(highestBit(2) == 1); static_assert(highestBit(4) == 2); static_assert(highestBit(8) == 3); static_assert(highestBit(uint64_t(1) << 31) == 31); static_assert(highestBit(uint64_t(1) << 63) == 63); struct McInt { uint8_t data[9]; // length of integer in bytes std::size_t length = 0; }; template<typename I> [[nodiscard]] McInt encodeInteger(I input) noexcept { McInt out; // move input to uint64_t to allow consistent bit manipulation, and to avoid // overflow concerns uint64_t val = *reinterpret_cast<Uint<Bits<I>>*>(&input); if (val) { // bits needed to represent number factoring in space possibly // needed for signed bit const auto bits = highestBit(val) + 1 + (ox::is_signed<I> ? 1 : 0); // bytes needed to store value std::size_t bytes = bits / 8 + (bits % 8 != 0); const auto bitsAvailable = bytes * 8; // bits available to integer value const auto bitsNeeded = bits + bytes; // factor in bits needed for bytesIndicator (does not affect bytesIndicator) // bits for integer + bits neded to represent bytes > bits available if (bitsNeeded > bitsAvailable && bytes != 9) { ++bytes; } const auto bytesIndicator = onMask<uint8_t>(bytes - 1); // move sign bit if constexpr(ox::is_signed<I>) { if (val < 0) { *reinterpret_cast<uint64_t*>(&val) ^= uint64_t(1) << (sizeof(I) * 8 - 1); *reinterpret_cast<uint64_t*>(&val) |= uint64_t(1) << (bitsAvailable - 1); } } // ensure we are copying from little endian represenstation LittleEndian<I> leVal = val; if (bytes == 9) { out.data[0] = bytesIndicator; *reinterpret_cast<I*>(&out.data[1]) = *reinterpret_cast<I*>(&leVal); } else { *reinterpret_cast<I*>(&out.data[0]) = (leVal << bytes) | bytesIndicator; } out.length = bytes; } return out; } } <commit_msg>[ox/mc] Fix VLI encoding not to chop off ends of >24 bit integers<commit_after>/* * Copyright 2015 - 2018 gtalent2@gmail.com * * 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/. */ #pragma once #include <ox/std/assert.hpp> #include <ox/std/byteswap.hpp> namespace ox::mc { template<typename T> static constexpr auto Bits = sizeof(T) << 3; /** * Returns highest bit other than possible signed bit. * Bit numbering starts at 0. */ template<typename I> [[nodiscard]] constexpr std::size_t highestBit(I val) noexcept { auto shiftStart = sizeof(I) * 8 - 1; // find most significant non-sign indicator bit std::size_t highestBit = 0; // start at one bit lower if signed if constexpr(ox::is_signed<I>) { --shiftStart; } for (int i = shiftStart; i > -1; --i) { const auto bitValue = (val >> i) & 1; if (bitValue) { highestBit = i; break; } } return highestBit; } static_assert(highestBit(int8_t(0b10000000)) == 0); static_assert(highestBit(1) == 0); static_assert(highestBit(2) == 1); static_assert(highestBit(4) == 2); static_assert(highestBit(8) == 3); static_assert(highestBit(uint64_t(1) << 31) == 31); static_assert(highestBit(uint64_t(1) << 63) == 63); struct McInt { uint8_t data[9]; // length of integer in bytes std::size_t length = 0; }; template<typename I> [[nodiscard]] McInt encodeInteger(I input) noexcept { McInt out; // move input to uint64_t to allow consistent bit manipulation, and to avoid // overflow concerns uint64_t val = *reinterpret_cast<Unsigned<I>*>(&input); if (val) { // bits needed to represent number factoring in space possibly // needed for signed bit const auto bits = highestBit(val) + 1 + (ox::is_signed<I> ? 1 : 0); // bytes needed to store value std::size_t bytes = bits / 8 + (bits % 8 != 0); const auto bitsAvailable = bytes * 8; // bits available to integer value const auto bitsNeeded = bits + bytes; // factor in bits needed for bytesIndicator (does not affect bytesIndicator) // bits for integer + bits neded to represent bytes > bits available if (bitsNeeded > bitsAvailable && bytes != 9) { ++bytes; } const auto bytesIndicator = onMask<uint8_t>(bytes - 1); // move sign bit if constexpr(ox::is_signed<I>) { if (val < 0) { *reinterpret_cast<uint64_t*>(&val) ^= uint64_t(1) << (sizeof(I) * 8 - 1); *reinterpret_cast<uint64_t*>(&val) |= uint64_t(1) << (bitsAvailable - 1); } } // ensure we are copying from little endian represenstation LittleEndian<I> leVal = val; if (bytes == 9) { out.data[0] = bytesIndicator; *reinterpret_cast<I*>(&out.data[1]) = leVal.raw(); } else { *reinterpret_cast<uint64_t*>(&out.data[0]) = static_cast<uint64_t>(leVal.raw()) << bytes | static_cast<uint64_t>(bytesIndicator); } out.length = bytes; } return out; } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file camera_trigger.cpp * * External camera-IMU synchronisation and triggering via FMU auxillary pins. * * @author Mohammed Kabir <mhkabir98@gmail.com> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <stdbool.h> #include <nuttx/clock.h> #include <nuttx/arch.h> #include <nuttx/wqueue.h> #include <systemlib/systemlib.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <uORB/uORB.h> #include <uORB/topics/camera_trigger.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/vehicle_command.h> #include <poll.h> #include <drivers/drv_gpio.h> #include <drivers/drv_hrt.h> #include <mavlink/mavlink_log.h> #include <board_config.h> #define TRIGGER_PIN_DEFAULT 1 extern "C" __EXPORT int camera_trigger_main(int argc, char *argv[]); class CameraTrigger { public: /** * Constructor */ CameraTrigger(); /** * Destructor, also kills task. */ ~CameraTrigger(); /** * Set the trigger on / off */ void control(bool on); /** * Start the task. */ void start(); /** * Stop the task. */ void stop(); /** * Display info. */ void info(); int _pins[6]; private: struct hrt_call _engagecall; struct hrt_call _disengagecall; static struct work_s _work; int _gpio_fd; int _polarity; int _mode; float _activation_time; float _interval; uint32_t _trigger_seq; bool _trigger_enabled; int _vcommand_sub; orb_advert_t _trigger_pub; param_t _p_polarity; param_t _p_mode; param_t _p_activation_time; param_t _p_interval; param_t _p_pin; static constexpr uint32_t _gpios[6] = { GPIO_GPIO0_OUTPUT, GPIO_GPIO1_OUTPUT, GPIO_GPIO2_OUTPUT, GPIO_GPIO3_OUTPUT, GPIO_GPIO4_OUTPUT, GPIO_GPIO5_OUTPUT }; /** * Vehicle command handler */ static void cycle_trampoline(void *arg); /** * Fires trigger */ static void engage(void *arg); /** * Resets trigger */ static void disengage(void *arg); }; struct work_s CameraTrigger::_work; constexpr uint32_t CameraTrigger::_gpios[6]; namespace camera_trigger { CameraTrigger *g_camera_trigger; } CameraTrigger::CameraTrigger() : _pins{}, _engagecall {}, _disengagecall {}, _gpio_fd(-1), _polarity(0), _mode(0), _activation_time(0.5f /* ms */), _interval(100.0f /* ms */), _trigger_seq(0), _trigger_enabled(false), _vcommand_sub(-1), _trigger_pub(nullptr) { memset(&_work, 0, sizeof(_work)); // Parameters _p_polarity = param_find("TRIG_POLARITY"); _p_interval = param_find("TRIG_INTERVAL"); _p_activation_time = param_find("TRIG_ACT_TIME"); _p_mode = param_find("TRIG_MODE"); _p_pin = param_find("TRIG_PINS"); param_get(_p_polarity, &_polarity); param_get(_p_activation_time, &_activation_time); param_get(_p_interval, &_interval); param_get(_p_mode, &_mode); int pin_list; param_get(_p_pin, &pin_list); // Set all pins as invalid for (unsigned i = 0; i < sizeof(_pins) / sizeof(_pins[0]); i++) { _pins[i] = -1; } // Convert number to individual channels unsigned i = 0; int single_pin; while ((single_pin = pin_list % 10)) { _pins[i] = single_pin - 1; if (_pins[i] < 0 || _pins[i] >= static_cast<int>(sizeof(_gpios) / sizeof(_gpios[0]))) { _pins[i] = -1; } pin_list /= 10; i++; } struct camera_trigger_s trigger = {}; _trigger_pub = orb_advertise(ORB_ID(camera_trigger), &trigger); } CameraTrigger::~CameraTrigger() { camera_trigger::g_camera_trigger = nullptr; } void CameraTrigger::control(bool on) { // always execute, even if already on // to reset timings if necessary if (on) { // schedule trigger on and off calls hrt_call_every(&_engagecall, 500, (_interval * 1000), (hrt_callout)&CameraTrigger::engage, this); // schedule trigger on and off calls hrt_call_every(&_disengagecall, 500 + (_activation_time * 1000), (_interval * 1000), (hrt_callout)&CameraTrigger::disengage, this); } else { // cancel all calls hrt_cancel(&_engagecall); hrt_cancel(&_disengagecall); // ensure that the pin is off hrt_call_after(&_disengagecall, 500, (hrt_callout)&CameraTrigger::disengage, this); } _trigger_enabled = on; } void CameraTrigger::start() { for (unsigned i = 0; i < sizeof(_pins) / sizeof(_pins[0]); i++) { stm32_configgpio(_gpios[_pins[i]]); stm32_gpiowrite(_gpios[_pins[i]], !_polarity); } // enable immediate if configured that way if (_mode > 1) { control(true); } // start to monitor at high rate for trigger enable command work_queue(LPWORK, &_work, (worker_t)&CameraTrigger::cycle_trampoline, this, USEC2TICK(1)); } void CameraTrigger::stop() { work_cancel(LPWORK, &_work); hrt_cancel(&_engagecall); hrt_cancel(&_disengagecall); if (camera_trigger::g_camera_trigger != nullptr) { delete(camera_trigger::g_camera_trigger); } } void CameraTrigger::cycle_trampoline(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); if (trig->_vcommand_sub < 0) { trig->_vcommand_sub = orb_subscribe(ORB_ID(vehicle_command)); } bool updated; orb_check(trig->_vcommand_sub, &updated); // while the trigger is inactive it has to be ready // to become active instantaneously int poll_interval_usec = 5000; if (updated) { struct vehicle_command_s cmd; orb_copy(ORB_ID(vehicle_command), trig->_vcommand_sub, &cmd); if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_TRIGGER_CONTROL) { // Set trigger rate from command if (cmd.param2 > 0) { trig->_interval = cmd.param2; param_set(trig->_p_interval, &(trig->_interval)); } if (cmd.param1 < 1.0f) { trig->control(false); } else if (cmd.param1 >= 1.0f) { trig->control(true); // while the trigger is active there is no // need to poll at a very high rate poll_interval_usec = 100000; } } } work_queue(LPWORK, &_work, (worker_t)&CameraTrigger::cycle_trampoline, camera_trigger::g_camera_trigger, USEC2TICK(poll_interval_usec)); } void CameraTrigger::engage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); struct camera_trigger_s trigger; /* set timestamp the instant before the trigger goes off */ trigger.timestamp = hrt_absolute_time(); for (unsigned i = 0; i < sizeof(trig->_pins) / sizeof(trig->_pins[0]); i++) { if (trig->_pins[i] >= 0) { // ACTIVE_LOW == 0 stm32_gpiowrite(trig->_gpios[trig->_pins[i]], trig->_polarity); } } trigger.seq = trig->_trigger_seq++; orb_publish(ORB_ID(camera_trigger), trig->_trigger_pub, &trigger); } void CameraTrigger::disengage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); for (unsigned i = 0; i < sizeof(trig->_pins) / sizeof(trig->_pins[0]); i++) { if (trig->_pins[i] >= 0) { // ACTIVE_LOW == 1 stm32_gpiowrite(trig->_gpios[trig->_pins[i]], !(trig->_polarity)); } } } void CameraTrigger::info() { warnx("state : %s", _trigger_enabled ? "enabled" : "disabled"); warnx("pins 1-3 : %d,%d,%d polarity : %s", _pins[0], _pins[1], _pins[2], _polarity ? "ACTIVE_HIGH" : "ACTIVE_LOW"); warnx("interval : %.2f", (double)_interval); } static void usage() { errx(1, "usage: camera_trigger {start|stop|info} [-p <n>]\n"); } int camera_trigger_main(int argc, char *argv[]) { if (argc < 2) { usage(); } if (!strcmp(argv[1], "start")) { if (camera_trigger::g_camera_trigger != nullptr) { errx(0, "already running"); } camera_trigger::g_camera_trigger = new CameraTrigger; if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "alloc failed"); } camera_trigger::g_camera_trigger->start(); return 0; } if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "not running"); } else if (!strcmp(argv[1], "stop")) { camera_trigger::g_camera_trigger->stop(); } else if (!strcmp(argv[1], "info")) { camera_trigger::g_camera_trigger->info(); } else if (!strcmp(argv[1], "enable")) { camera_trigger::g_camera_trigger->control(true); } else if (!strcmp(argv[1], "disable")) { camera_trigger::g_camera_trigger->control(false); } else { usage(); } return 0; } <commit_msg>Update camera_trigger.cpp<commit_after>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file camera_trigger.cpp * * External camera-IMU synchronisation and triggering via FMU auxiliary pins. * * @author Mohammed Kabir <mhkabir98@gmail.com> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <stdbool.h> #include <nuttx/clock.h> #include <nuttx/arch.h> #include <nuttx/wqueue.h> #include <systemlib/systemlib.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <uORB/uORB.h> #include <uORB/topics/camera_trigger.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/vehicle_command.h> #include <poll.h> #include <drivers/drv_gpio.h> #include <drivers/drv_hrt.h> #include <mavlink/mavlink_log.h> #include <board_config.h> #define TRIGGER_PIN_DEFAULT 1 extern "C" __EXPORT int camera_trigger_main(int argc, char *argv[]); class CameraTrigger { public: /** * Constructor */ CameraTrigger(); /** * Destructor, also kills task. */ ~CameraTrigger(); /** * Set the trigger on / off */ void control(bool on); /** * Start the task. */ void start(); /** * Stop the task. */ void stop(); /** * Display info. */ void info(); int _pins[6]; private: struct hrt_call _engagecall; struct hrt_call _disengagecall; static struct work_s _work; int _gpio_fd; int _polarity; int _mode; float _activation_time; float _interval; uint32_t _trigger_seq; bool _trigger_enabled; int _vcommand_sub; orb_advert_t _trigger_pub; param_t _p_polarity; param_t _p_mode; param_t _p_activation_time; param_t _p_interval; param_t _p_pin; static constexpr uint32_t _gpios[6] = { GPIO_GPIO0_OUTPUT, GPIO_GPIO1_OUTPUT, GPIO_GPIO2_OUTPUT, GPIO_GPIO3_OUTPUT, GPIO_GPIO4_OUTPUT, GPIO_GPIO5_OUTPUT }; /** * Vehicle command handler */ static void cycle_trampoline(void *arg); /** * Fires trigger */ static void engage(void *arg); /** * Resets trigger */ static void disengage(void *arg); }; struct work_s CameraTrigger::_work; constexpr uint32_t CameraTrigger::_gpios[6]; namespace camera_trigger { CameraTrigger *g_camera_trigger; } CameraTrigger::CameraTrigger() : _pins{}, _engagecall {}, _disengagecall {}, _gpio_fd(-1), _polarity(0), _mode(0), _activation_time(0.5f /* ms */), _interval(100.0f /* ms */), _trigger_seq(0), _trigger_enabled(false), _vcommand_sub(-1), _trigger_pub(nullptr) { memset(&_work, 0, sizeof(_work)); // Parameters _p_polarity = param_find("TRIG_POLARITY"); _p_interval = param_find("TRIG_INTERVAL"); _p_activation_time = param_find("TRIG_ACT_TIME"); _p_mode = param_find("TRIG_MODE"); _p_pin = param_find("TRIG_PINS"); param_get(_p_polarity, &_polarity); param_get(_p_activation_time, &_activation_time); param_get(_p_interval, &_interval); param_get(_p_mode, &_mode); int pin_list; param_get(_p_pin, &pin_list); // Set all pins as invalid for (unsigned i = 0; i < sizeof(_pins) / sizeof(_pins[0]); i++) { _pins[i] = -1; } // Convert number to individual channels unsigned i = 0; int single_pin; while ((single_pin = pin_list % 10)) { _pins[i] = single_pin - 1; if (_pins[i] < 0 || _pins[i] >= static_cast<int>(sizeof(_gpios) / sizeof(_gpios[0]))) { _pins[i] = -1; } pin_list /= 10; i++; } struct camera_trigger_s trigger = {}; _trigger_pub = orb_advertise(ORB_ID(camera_trigger), &trigger); } CameraTrigger::~CameraTrigger() { camera_trigger::g_camera_trigger = nullptr; } void CameraTrigger::control(bool on) { // always execute, even if already on // to reset timings if necessary if (on) { // schedule trigger on and off calls hrt_call_every(&_engagecall, 500, (_interval * 1000), (hrt_callout)&CameraTrigger::engage, this); // schedule trigger on and off calls hrt_call_every(&_disengagecall, 500 + (_activation_time * 1000), (_interval * 1000), (hrt_callout)&CameraTrigger::disengage, this); } else { // cancel all calls hrt_cancel(&_engagecall); hrt_cancel(&_disengagecall); // ensure that the pin is off hrt_call_after(&_disengagecall, 500, (hrt_callout)&CameraTrigger::disengage, this); } _trigger_enabled = on; } void CameraTrigger::start() { for (unsigned i = 0; i < sizeof(_pins) / sizeof(_pins[0]); i++) { stm32_configgpio(_gpios[_pins[i]]); stm32_gpiowrite(_gpios[_pins[i]], !_polarity); } // enable immediate if configured that way if (_mode > 1) { control(true); } // start to monitor at high rate for trigger enable command work_queue(LPWORK, &_work, (worker_t)&CameraTrigger::cycle_trampoline, this, USEC2TICK(1)); } void CameraTrigger::stop() { work_cancel(LPWORK, &_work); hrt_cancel(&_engagecall); hrt_cancel(&_disengagecall); if (camera_trigger::g_camera_trigger != nullptr) { delete(camera_trigger::g_camera_trigger); } } void CameraTrigger::cycle_trampoline(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); if (trig->_vcommand_sub < 0) { trig->_vcommand_sub = orb_subscribe(ORB_ID(vehicle_command)); } bool updated; orb_check(trig->_vcommand_sub, &updated); // while the trigger is inactive it has to be ready // to become active instantaneously int poll_interval_usec = 5000; if (updated) { struct vehicle_command_s cmd; orb_copy(ORB_ID(vehicle_command), trig->_vcommand_sub, &cmd); if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_TRIGGER_CONTROL) { // Set trigger rate from command if (cmd.param2 > 0) { trig->_interval = cmd.param2; param_set(trig->_p_interval, &(trig->_interval)); } if (cmd.param1 < 1.0f) { trig->control(false); } else if (cmd.param1 >= 1.0f) { trig->control(true); // while the trigger is active there is no // need to poll at a very high rate poll_interval_usec = 100000; } } } work_queue(LPWORK, &_work, (worker_t)&CameraTrigger::cycle_trampoline, camera_trigger::g_camera_trigger, USEC2TICK(poll_interval_usec)); } void CameraTrigger::engage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); struct camera_trigger_s trigger; /* set timestamp the instant before the trigger goes off */ trigger.timestamp = hrt_absolute_time(); for (unsigned i = 0; i < sizeof(trig->_pins) / sizeof(trig->_pins[0]); i++) { if (trig->_pins[i] >= 0) { // ACTIVE_LOW == 0 stm32_gpiowrite(trig->_gpios[trig->_pins[i]], trig->_polarity); } } trigger.seq = trig->_trigger_seq++; orb_publish(ORB_ID(camera_trigger), trig->_trigger_pub, &trigger); } void CameraTrigger::disengage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); for (unsigned i = 0; i < sizeof(trig->_pins) / sizeof(trig->_pins[0]); i++) { if (trig->_pins[i] >= 0) { // ACTIVE_LOW == 1 stm32_gpiowrite(trig->_gpios[trig->_pins[i]], !(trig->_polarity)); } } } void CameraTrigger::info() { warnx("state : %s", _trigger_enabled ? "enabled" : "disabled"); warnx("pins 1-3 : %d,%d,%d polarity : %s", _pins[0], _pins[1], _pins[2], _polarity ? "ACTIVE_HIGH" : "ACTIVE_LOW"); warnx("interval : %.2f", (double)_interval); } static void usage() { errx(1, "usage: camera_trigger {start|stop|info} [-p <n>]\n"); } int camera_trigger_main(int argc, char *argv[]) { if (argc < 2) { usage(); } if (!strcmp(argv[1], "start")) { if (camera_trigger::g_camera_trigger != nullptr) { errx(0, "already running"); } camera_trigger::g_camera_trigger = new CameraTrigger; if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "alloc failed"); } camera_trigger::g_camera_trigger->start(); return 0; } if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "not running"); } else if (!strcmp(argv[1], "stop")) { camera_trigger::g_camera_trigger->stop(); } else if (!strcmp(argv[1], "info")) { camera_trigger::g_camera_trigger->info(); } else if (!strcmp(argv[1], "enable")) { camera_trigger::g_camera_trigger->control(true); } else if (!strcmp(argv[1], "disable")) { camera_trigger::g_camera_trigger->control(false); } else { usage(); } return 0; } <|endoftext|>
<commit_before>/** Implementation of string conversions. * * Copyright (c) 2008-2019, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #include "pqxx/compiler-internal.hxx" #include <cmath> #include <cstring> #include <limits> #include <locale> #include "pqxx/except" #include "pqxx/strconv" using namespace pqxx::internal; namespace { template<typename T> inline void set_to_Inf(T &t, int sign=1) { T value = std::numeric_limits<T>::infinity(); if (sign < 0) value = -value; t = value; } [[noreturn]] void report_overflow() { throw pqxx::failure{ "Could not convert string to integer: value out of range."}; } /** Helper to check for underflow before multiplying a number by 10. * * Needed just so the compiler doesn't get to complain about an "if (n < 0)" * clause that's pointless for unsigned numbers. */ template<typename T, bool is_signed> struct underflow_check; /* Specialization for signed types: check. */ template<typename T> struct underflow_check<T, true> { static void check_before_adding_digit(T n) { constexpr T ten{10}; if (n < 0 and (std::numeric_limits<T>::min() / ten) > n) report_overflow(); } }; /* Specialization for unsigned types: no check needed becaue negative * numbers don't exist. */ template<typename T> struct underflow_check<T, false> { static void check_before_adding_digit(T) {} }; /// Return 10*n, or throw exception if it overflows. template<typename T> T safe_multiply_by_ten(T n) { using limits = std::numeric_limits<T>; constexpr T ten{10}; if (n > 0 and (limits::max() / n) < ten) report_overflow(); underflow_check<T, limits::is_signed>::check_before_adding_digit(n); return T(n * ten); } /// Add a digit d to n, or throw exception if it overflows. template<typename T> T safe_add_digit(T n, T d) { assert((n >= 0 and d >= 0) or (n <=0 and d <= 0)); if ((n > 0) and (n > (std::numeric_limits<T>::max() - d))) report_overflow(); if ((n < 0) and (n < (std::numeric_limits<T>::min() - d))) report_overflow(); return n + d; } /// For use in string parsing: add new numeric digit to intermediate value template<typename L, typename R> inline L absorb_digit(L value, R digit) { return L(safe_multiply_by_ten(value) + L(digit)); } template<typename T> void from_string_signed(const char Str[], T &Obj) { int i = 0; T result = 0; if (not isdigit(Str[i])) { if (Str[i] != '-') throw pqxx::failure{ "Could not convert string to integer: '" + std::string{Str} + "'."}; for (++i; isdigit(Str[i]); ++i) result = absorb_digit(result, -digit_to_number(Str[i])); } else { for (; isdigit(Str[i]); ++i) result = absorb_digit(result, digit_to_number(Str[i])); } if (Str[i]) throw pqxx::failure{ "Unexpected text after integer: '" + std::string{Str} + "'."}; Obj = result; } template<typename T> void from_string_unsigned(const char Str[], T &Obj) { int i = 0; T result = 0; if (not isdigit(Str[i])) throw pqxx::failure{ "Could not convert string to unsigned integer: '" + std::string{Str} + "'."}; for (; isdigit(Str[i]); ++i) result = absorb_digit(result, digit_to_number(Str[i])); if (Str[i]) throw pqxx::failure{ "Unexpected text after integer: '" + std::string{Str} + "'."}; Obj = result; } namespace { /// C string comparison. inline bool equal(const char lhs[], const char rhs[]) { return strcmp(lhs, rhs) == 0; } } // namespace bool valid_infinity_string(const char str[]) noexcept { return equal("infinity", str) or equal("Infinity", str) or equal("INFINITY", str) or equal("inf", str); } /// Wrapper for std::stringstream with C locale. /** Some of our string conversions use the standard library. But, they must * _not_ obey the system's locale settings, or a value like 1000.0 might end * up looking like "1.000,0". * * Initialising the stream (including locale and tweaked precision) seems to * be expensive though. So, create thread-local instances which we re-use. * It's a lockless way of keeping global variables thread-safe, basically. * * The stream initialisation happens once per thread, in the constructor. * And that's why we need to wrap this in a class. We can't just do it at the * call site, or we'd still be doing it for every call. */ template<typename T> class dumb_stringstream : public std::stringstream { public: dumb_stringstream() : std::stringstream{} { this->imbue(std::locale::classic()); // Kirit reports getting two more digits of precision than // numeric_limits::digits10 would give him, so we try not to make him lose // those last few bits. this->precision(std::numeric_limits<T>::digits10 + 2); } }; /* These are hard. Sacrifice performance of specialized, nonflexible, * non-localized code and lean on standard library. Some special-case code * handles NaNs. */ template<typename T> inline void from_string_float(const char Str[], T &Obj) { bool ok = false; T result; switch (Str[0]) { case 'N': case 'n': // Accept "NaN," "nan," etc. ok = ( (Str[1]=='A' or Str[1]=='a') and (Str[2]=='N' or Str[2]=='n') and (Str[3] == '\0')); result = std::numeric_limits<T>::quiet_NaN(); break; case 'I': case 'i': ok = valid_infinity_string(Str); set_to_Inf(result); break; default: if (Str[0] == '-' and valid_infinity_string(&Str[1])) { ok = true; set_to_Inf(result, -1); } else { thread_local dumb_stringstream<T> S; // Visual Studio 2017 seems to fail on repeated conversions if the // clear() is done before the seekg(). Still don't know why! See #124 // and #125. S.seekg(0); S.clear(); S.str(Str); S >> result; ok = S.good() || S.eof(); } break; } if (not ok) throw pqxx::failure{ "Could not convert string to numeric value: '" + std::string{Str} + "'."}; Obj = result; } template<typename T> inline std::string to_string_unsigned(T Obj) { if (not Obj) return "0"; // Every byte of width on T adds somewhere between 3 and 4 digits to the // maximum length of our decimal string. char buf[4*sizeof(T)+1]; char *p = &buf[sizeof(buf)]; *--p = '\0'; while (Obj > 0) { *--p = number_to_digit(int(Obj%10)); Obj /= 10; } return p; } template<typename T> inline std::string to_string_fallback(T Obj) { thread_local dumb_stringstream<T> S; S.str(""); S << Obj; return S.str(); } template<typename T> inline std::string to_string_float(T Obj) { if (std::isnan(Obj)) return "nan"; if (std::isinf(Obj)) return Obj > 0 ? "infinity" : "-infinity"; return to_string_fallback(Obj); } template<typename T> inline std::string to_string_signed(T Obj) { if (Obj < 0) { // Remember--the smallest negative number for a given two's-complement type // cannot be negated. const bool negatable = (Obj != std::numeric_limits<T>::min()); if (negatable) return '-' + to_string_unsigned(-Obj); else return to_string_fallback(Obj); } return to_string_unsigned(Obj); } } // namespace namespace pqxx { namespace internal { void throw_null_conversion(const std::string &type) { throw conversion_error{"Attempt to convert null to " + type + "."}; } } // namespace pqxx::internal void string_traits<bool>::from_string(const char Str[], bool &Obj) { bool OK, result=false; switch (Str[0]) { case 0: result = false; OK = true; break; case 'f': case 'F': result = false; OK = not ( (Str[1] != '\0') and (not equal(Str+1, "alse")) and (not equal(Str+1, "ALSE"))); break; case '0': { int I; string_traits<int>::from_string(Str, I); result = (I != 0); OK = ((I == 0) or (I == 1)); } break; case '1': result = true; OK = (Str[1] != '\0'); break; case 't': case 'T': result = true; OK = not ( (Str[1] != '\0') and (not equal(Str+1, "rue")) and (not equal(Str+1, "RUE"))); break; default: OK = false; } if (not OK) throw argument_error{ "Failed conversion to bool: '" + std::string{Str} + "'."}; Obj = result; } std::string string_traits<bool>::to_string(bool Obj) { return Obj ? "true" : "false"; } void string_traits<short>::from_string(const char Str[], short &Obj) { from_string_signed(Str, Obj); } std::string string_traits<short>::to_string(short Obj) { return to_string_signed(Obj); } void string_traits<unsigned short>::from_string( const char Str[], unsigned short &Obj) { from_string_unsigned(Str, Obj); } std::string string_traits<unsigned short>::to_string(unsigned short Obj) { return to_string_unsigned(Obj); } void string_traits<int>::from_string(const char Str[], int &Obj) { from_string_signed(Str, Obj); } std::string string_traits<int>::to_string(int Obj) { return to_string_signed(Obj); } void string_traits<unsigned int>::from_string( const char Str[], unsigned int &Obj) { from_string_unsigned(Str, Obj); } std::string string_traits<unsigned int>::to_string(unsigned int Obj) { return to_string_unsigned(Obj); } void string_traits<long>::from_string(const char Str[], long &Obj) { from_string_signed(Str, Obj); } std::string string_traits<long>::to_string(long Obj) { return to_string_signed(Obj); } void string_traits<unsigned long>::from_string( const char Str[], unsigned long &Obj) { from_string_unsigned(Str, Obj); } std::string string_traits<unsigned long>::to_string(unsigned long Obj) { return to_string_unsigned(Obj); } void string_traits<long long>::from_string(const char Str[], long long &Obj) { from_string_signed(Str, Obj); } std::string string_traits<long long>::to_string(long long Obj) { return to_string_signed(Obj); } void string_traits<unsigned long long>::from_string( const char Str[], unsigned long long &Obj) { from_string_unsigned(Str, Obj); } std::string string_traits<unsigned long long>::to_string( unsigned long long Obj) { return to_string_unsigned(Obj); } void string_traits<float>::from_string(const char Str[], float &Obj) { from_string_float(Str, Obj); } std::string string_traits<float>::to_string(float Obj) { return to_string_float(Obj); } void string_traits<double>::from_string(const char Str[], double &Obj) { from_string_float(Str, Obj); } std::string string_traits<double>::to_string(double Obj) { return to_string_float(Obj); } void string_traits<long double>::from_string(const char Str[], long double &Obj) { from_string_float(Str, Obj); } std::string string_traits<long double>::to_string(long double Obj) { return to_string_float(Obj); } } // namespace pqxx <commit_msg>dumb_stringstream initialization bugfix. (#150)<commit_after>/** Implementation of string conversions. * * Copyright (c) 2008-2019, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #include "pqxx/compiler-internal.hxx" #include <cmath> #include <cstring> #include <limits> #include <locale> #include "pqxx/except" #include "pqxx/strconv" using namespace pqxx::internal; namespace { template<typename T> inline void set_to_Inf(T &t, int sign=1) { T value = std::numeric_limits<T>::infinity(); if (sign < 0) value = -value; t = value; } [[noreturn]] void report_overflow() { throw pqxx::failure{ "Could not convert string to integer: value out of range."}; } /** Helper to check for underflow before multiplying a number by 10. * * Needed just so the compiler doesn't get to complain about an "if (n < 0)" * clause that's pointless for unsigned numbers. */ template<typename T, bool is_signed> struct underflow_check; /* Specialization for signed types: check. */ template<typename T> struct underflow_check<T, true> { static void check_before_adding_digit(T n) { constexpr T ten{10}; if (n < 0 and (std::numeric_limits<T>::min() / ten) > n) report_overflow(); } }; /* Specialization for unsigned types: no check needed becaue negative * numbers don't exist. */ template<typename T> struct underflow_check<T, false> { static void check_before_adding_digit(T) {} }; /// Return 10*n, or throw exception if it overflows. template<typename T> T safe_multiply_by_ten(T n) { using limits = std::numeric_limits<T>; constexpr T ten{10}; if (n > 0 and (limits::max() / n) < ten) report_overflow(); underflow_check<T, limits::is_signed>::check_before_adding_digit(n); return T(n * ten); } /// Add a digit d to n, or throw exception if it overflows. template<typename T> T safe_add_digit(T n, T d) { assert((n >= 0 and d >= 0) or (n <=0 and d <= 0)); if ((n > 0) and (n > (std::numeric_limits<T>::max() - d))) report_overflow(); if ((n < 0) and (n < (std::numeric_limits<T>::min() - d))) report_overflow(); return n + d; } /// For use in string parsing: add new numeric digit to intermediate value template<typename L, typename R> inline L absorb_digit(L value, R digit) { return L(safe_multiply_by_ten(value) + L(digit)); } template<typename T> void from_string_signed(const char Str[], T &Obj) { int i = 0; T result = 0; if (not isdigit(Str[i])) { if (Str[i] != '-') throw pqxx::failure{ "Could not convert string to integer: '" + std::string{Str} + "'."}; for (++i; isdigit(Str[i]); ++i) result = absorb_digit(result, -digit_to_number(Str[i])); } else { for (; isdigit(Str[i]); ++i) result = absorb_digit(result, digit_to_number(Str[i])); } if (Str[i]) throw pqxx::failure{ "Unexpected text after integer: '" + std::string{Str} + "'."}; Obj = result; } template<typename T> void from_string_unsigned(const char Str[], T &Obj) { int i = 0; T result = 0; if (not isdigit(Str[i])) throw pqxx::failure{ "Could not convert string to unsigned integer: '" + std::string{Str} + "'."}; for (; isdigit(Str[i]); ++i) result = absorb_digit(result, digit_to_number(Str[i])); if (Str[i]) throw pqxx::failure{ "Unexpected text after integer: '" + std::string{Str} + "'."}; Obj = result; } namespace { /// C string comparison. inline bool equal(const char lhs[], const char rhs[]) { return strcmp(lhs, rhs) == 0; } } // namespace bool valid_infinity_string(const char str[]) noexcept { return equal("infinity", str) or equal("Infinity", str) or equal("INFINITY", str) or equal("inf", str); } /// Wrapper for std::stringstream with C locale. /** Some of our string conversions use the standard library. But, they must * _not_ obey the system's locale settings, or a value like 1000.0 might end * up looking like "1.000,0". * * Initialising the stream (including locale and tweaked precision) seems to * be expensive though. So, create thread-local instances which we re-use. * It's a lockless way of keeping global variables thread-safe, basically. * * The stream initialisation happens once per thread, in the constructor. * And that's why we need to wrap this in a class. We can't just do it at the * call site, or we'd still be doing it for every call. */ template<typename T> class dumb_stringstream : public std::stringstream { public: dumb_stringstream() : std::stringstream() { this->imbue(std::locale::classic()); // Kirit reports getting two more digits of precision than // numeric_limits::digits10 would give him, so we try not to make him lose // those last few bits. this->precision(std::numeric_limits<T>::digits10 + 2); } }; /* These are hard. Sacrifice performance of specialized, nonflexible, * non-localized code and lean on standard library. Some special-case code * handles NaNs. */ template<typename T> inline void from_string_float(const char Str[], T &Obj) { bool ok = false; T result; switch (Str[0]) { case 'N': case 'n': // Accept "NaN," "nan," etc. ok = ( (Str[1]=='A' or Str[1]=='a') and (Str[2]=='N' or Str[2]=='n') and (Str[3] == '\0')); result = std::numeric_limits<T>::quiet_NaN(); break; case 'I': case 'i': ok = valid_infinity_string(Str); set_to_Inf(result); break; default: if (Str[0] == '-' and valid_infinity_string(&Str[1])) { ok = true; set_to_Inf(result, -1); } else { thread_local dumb_stringstream<T> S; // Visual Studio 2017 seems to fail on repeated conversions if the // clear() is done before the seekg(). Still don't know why! See #124 // and #125. S.seekg(0); S.clear(); S.str(Str); ok = static_cast<bool>(S >> result); } break; } if (not ok) throw pqxx::failure{ "Could not convert string to numeric value: '" + std::string{Str} + "'."}; Obj = result; } template<typename T> inline std::string to_string_unsigned(T Obj) { if (not Obj) return "0"; // Every byte of width on T adds somewhere between 3 and 4 digits to the // maximum length of our decimal string. char buf[4*sizeof(T)+1]; char *p = &buf[sizeof(buf)]; *--p = '\0'; while (Obj > 0) { *--p = number_to_digit(int(Obj%10)); Obj /= 10; } return p; } template<typename T> inline std::string to_string_fallback(T Obj) { thread_local dumb_stringstream<T> S; S.str(""); S << Obj; return S.str(); } template<typename T> inline std::string to_string_float(T Obj) { if (std::isnan(Obj)) return "nan"; if (std::isinf(Obj)) return Obj > 0 ? "infinity" : "-infinity"; return to_string_fallback(Obj); } template<typename T> inline std::string to_string_signed(T Obj) { if (Obj < 0) { // Remember--the smallest negative number for a given two's-complement type // cannot be negated. const bool negatable = (Obj != std::numeric_limits<T>::min()); if (negatable) return '-' + to_string_unsigned(-Obj); else return to_string_fallback(Obj); } return to_string_unsigned(Obj); } } // namespace namespace pqxx { namespace internal { void throw_null_conversion(const std::string &type) { throw conversion_error{"Attempt to convert null to " + type + "."}; } } // namespace pqxx::internal void string_traits<bool>::from_string(const char Str[], bool &Obj) { bool OK, result=false; switch (Str[0]) { case 0: result = false; OK = true; break; case 'f': case 'F': result = false; OK = not ( (Str[1] != '\0') and (not equal(Str+1, "alse")) and (not equal(Str+1, "ALSE"))); break; case '0': { int I; string_traits<int>::from_string(Str, I); result = (I != 0); OK = ((I == 0) or (I == 1)); } break; case '1': result = true; OK = (Str[1] != '\0'); break; case 't': case 'T': result = true; OK = not ( (Str[1] != '\0') and (not equal(Str+1, "rue")) and (not equal(Str+1, "RUE"))); break; default: OK = false; } if (not OK) throw argument_error{ "Failed conversion to bool: '" + std::string{Str} + "'."}; Obj = result; } std::string string_traits<bool>::to_string(bool Obj) { return Obj ? "true" : "false"; } void string_traits<short>::from_string(const char Str[], short &Obj) { from_string_signed(Str, Obj); } std::string string_traits<short>::to_string(short Obj) { return to_string_signed(Obj); } void string_traits<unsigned short>::from_string( const char Str[], unsigned short &Obj) { from_string_unsigned(Str, Obj); } std::string string_traits<unsigned short>::to_string(unsigned short Obj) { return to_string_unsigned(Obj); } void string_traits<int>::from_string(const char Str[], int &Obj) { from_string_signed(Str, Obj); } std::string string_traits<int>::to_string(int Obj) { return to_string_signed(Obj); } void string_traits<unsigned int>::from_string( const char Str[], unsigned int &Obj) { from_string_unsigned(Str, Obj); } std::string string_traits<unsigned int>::to_string(unsigned int Obj) { return to_string_unsigned(Obj); } void string_traits<long>::from_string(const char Str[], long &Obj) { from_string_signed(Str, Obj); } std::string string_traits<long>::to_string(long Obj) { return to_string_signed(Obj); } void string_traits<unsigned long>::from_string( const char Str[], unsigned long &Obj) { from_string_unsigned(Str, Obj); } std::string string_traits<unsigned long>::to_string(unsigned long Obj) { return to_string_unsigned(Obj); } void string_traits<long long>::from_string(const char Str[], long long &Obj) { from_string_signed(Str, Obj); } std::string string_traits<long long>::to_string(long long Obj) { return to_string_signed(Obj); } void string_traits<unsigned long long>::from_string( const char Str[], unsigned long long &Obj) { from_string_unsigned(Str, Obj); } std::string string_traits<unsigned long long>::to_string( unsigned long long Obj) { return to_string_unsigned(Obj); } void string_traits<float>::from_string(const char Str[], float &Obj) { from_string_float(Str, Obj); } std::string string_traits<float>::to_string(float Obj) { return to_string_float(Obj); } void string_traits<double>::from_string(const char Str[], double &Obj) { from_string_float(Str, Obj); } std::string string_traits<double>::to_string(double Obj) { return to_string_float(Obj); } void string_traits<long double>::from_string(const char Str[], long double &Obj) { from_string_float(Str, Obj); } std::string string_traits<long double>::to_string(long double Obj) { return to_string_float(Obj); } } // namespace pqxx <|endoftext|>
<commit_before>/* This file is part of kdepim. Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org> Copyright (c) 2004 Daniel Molkentin <molkentin@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kolabwizard.h" #include "kolabconfig.h" #include "kolabkmailchanges.h" #include "kresources/kolab/kcal/resourcekolab.h" #include "kresources/kolab/kabc/resourcekolab.h" #include "kresources/kolab/knotes/resourcekolab.h" #include <libkcal/resourcecalendar.h> #include <kabc/resource.h> #include <klineedit.h> #include <klocale.h> #include <qcheckbox.h> #include <qlabel.h> #include <qlayout.h> #include <qradiobutton.h> #include <qwhatsthis.h> #include <QGroupBox> class SetupLDAPSearchAccount : public KConfigPropagator::Change { public: SetupLDAPSearchAccount() : KConfigPropagator::Change( i18n("Setup LDAP Search Account") ) { } void apply() { const QString host = KolabConfig::self()->server(); // Figure out the basedn QString basedn = host; // If the user gave a full email address, the domain name // of that overrides the server name for the ldap dn const QString user = KolabConfig::self()->user(); int pos = user.find( "@" ); if ( pos > 0 ) { const QString h = user.mid( pos+1 ); if ( !h.isEmpty() ) // The user did type in a domain on the email address. Use that basedn = h; } { // while we're here, write default domain KConfig c( "kmailrc" ); c.setGroup( "General" ); c.writeEntry( "Default domain", basedn ); } basedn.replace(".",",dc="); basedn.prepend("dc="); // Set the changes KConfig c( "kabldaprc" ); c.setGroup( "LDAP" ); bool hasMyServer = false; uint selHosts = c.readNumEntry("NumSelectedHosts", 0); for ( uint i = 0 ; i < selHosts && !hasMyServer; ++i ) if ( c.readEntry( QString("SelectedHost%1").arg(i) ) == host ) hasMyServer = true; if ( !hasMyServer ) { c.writeEntry( "NumSelectedHosts", selHosts + 1 ); c.writeEntry( QString("SelectedHost%1").arg(selHosts), host); c.writeEntry( QString("SelectedBase%1").arg(selHosts), basedn); c.writeEntry( QString("SelectedPort%1").arg(selHosts), "389"); } } }; class CreateCalendarImapResource : public KConfigPropagator::Change { public: CreateCalendarImapResource() : KConfigPropagator::Change( i18n("Create Calendar IMAP Resource") ) { } void apply() { KCal::CalendarResourceManager m( "calendar" ); m.readConfig(); KCal::ResourceKolab *r = new KCal::ResourceKolab( 0 ); r->setResourceName( i18n("Kolab Server") ); m.add( r ); m.setStandardResource( r ); m.writeConfig(); } }; class CreateContactImapResource : public KConfigPropagator::Change { public: CreateContactImapResource() : KConfigPropagator::Change( i18n("Create Contact IMAP Resource") ) { } void apply() { KRES::Manager<KABC::Resource> m( "contact" ); m.readConfig(); KABC::ResourceKolab *r = new KABC::ResourceKolab( 0 ); r->setResourceName( i18n("Kolab Server") ); m.add( r ); m.setStandardResource( r ); m.writeConfig(); } }; class CreateNotesImapResource : public KConfigPropagator::Change { public: CreateNotesImapResource() : KConfigPropagator::Change( i18n("Create Notes IMAP Resource") ) { } void apply() { KRES::Manager<ResourceNotes> m( "notes" ); m.readConfig(); Kolab::ResourceKolab *r = new Kolab::ResourceKolab( 0 ); r->setResourceName( i18n("Kolab Server") ); m.add( r ); m.setStandardResource( r ); m.writeConfig(); } }; class KolabPropagator : public KConfigPropagator { public: KolabPropagator() : KConfigPropagator( KolabConfig::self(), "kolab.kcfg" ) { } protected: void addKorganizerChanges( Change::List &changes ) { KURL freeBusyBaseUrl; // usrWriteConfig() is called first, so kolab1Legacy is correct if ( KolabConfig::self()->kolab1Legacy() ) { freeBusyBaseUrl = "webdavs://" + KolabConfig::self()->server() + "/freebusy/"; ChangeConfig *c = new ChangeConfig; c->file = "korganizerrc"; c->group = "FreeBusy"; c->name = "FreeBusyPublishUrl"; QString user = KolabConfig::self()->user(); // We now use the full email address in the freebusy URL //int pos = user.find( "@" ); //if ( pos > 0 ) user = user.left( pos ); KURL publishURL = freeBusyBaseUrl; publishURL.addPath( user + ".ifb" ); // this encodes the '@' in the username c->value = publishURL.url(); changes.append( c ); } else { // Kolab2: only need FreeBusyRetrieveUrl // "Uploading" is done by triggering a server-side script with an HTTP GET // (done by kmail) freeBusyBaseUrl = "https://" + KolabConfig::self()->server() + "/freebusy/"; } ChangeConfig *c = new ChangeConfig; c->file = "korganizerrc"; c->group = "FreeBusy"; c->name = "FreeBusyRetrieveUrl"; c->value = freeBusyBaseUrl.url(); changes.append( c ); // Use full email address for retrieval of free/busy lists c = new ChangeConfig; c->file = "korganizerrc"; c->group = "FreeBusy"; c->name = "FreeBusyFullDomainRetrieval"; c->value = "true"; changes.append( c ); c = new ChangeConfig; c->file = "korganizerrc"; c->group = "Group Scheduling"; c->name = "Use Groupware Communication"; c->value = "true"; changes.append( c ); // Use identity "from control center", i.e. from emaildefaults c = new ChangeConfig; c->file = "korganizerrc"; c->group = "Personal Settings"; c->name = "Use Control Center Email"; c->value = "true"; changes.append( c ); } virtual void addCustomChanges( Change::List &changes ) { addKorganizerChanges( changes ); // KMail cruft has been outsourced to kolabkmailchanges.cpp createKMailChanges( changes ); changes.append( new SetupLDAPSearchAccount ); KCal::CalendarResourceManager m( "calendar" ); m.readConfig(); KCal::CalendarResourceManager::Iterator it; for ( it = m.begin(); it != m.end(); ++it ) { if ( (*it)->type() == "imap" ) break; } if ( it == m.end() ) { changes.append( new CreateCalendarImapResource ); changes.append( new CreateContactImapResource ); changes.append( new CreateNotesImapResource ); } } }; KolabWizard::KolabWizard() : KConfigWizard( new KolabPropagator ) { QFrame *page = createWizardPage( i18n("Kolab Server") ); QGridLayout *topLayout = new QGridLayout( page ); topLayout->setSpacing( spacingHint() ); QLabel *label = new QLabel( i18n("Server name:"), page ); topLayout->addWidget( label, 0, 0 ); mServerEdit = new KLineEdit( page ); topLayout->addWidget( mServerEdit, 0, 1 ); label = new QLabel( i18n("Email address:"), page ); topLayout->addWidget( label, 1, 0 ); mUserEdit = new KLineEdit( page ); topLayout->addWidget( mUserEdit, 1, 1 ); QWhatsThis::add(mUserEdit, i18n("Your email address on the Kolab Server. " "Format: <i>name@example.net</i>")); label = new QLabel( i18n("Real name:"), page ); topLayout->addWidget( label, 2, 0 ); mRealNameEdit = new KLineEdit( page ); topLayout->addWidget( mRealNameEdit, 2, 1 ); label = new QLabel( i18n("Password:"), page ); topLayout->addWidget( label, 3, 0 ); mPasswordEdit = new KLineEdit( page ); mPasswordEdit->setEchoMode( KLineEdit::Password ); topLayout->addWidget( mPasswordEdit, 3, 1 ); mSavePasswordCheck = new QCheckBox( i18n("Save password"), page ); topLayout->addWidget( mSavePasswordCheck, 4, 1 ); topLayout->setRowStretch( 4, 1 ); QGroupBox *bg = new QGroupBox(i18n("Server Version"), page ); QHBoxLayout *hbl = new QHBoxLayout(); bg->setLayout( hbl ); QWhatsThis::add( bg, i18n("Choose the version of the Kolab Server you are using.") ); mKolab1 = new QRadioButton( i18n ( "Kolab 1" ), bg ); hbl->addWidget( mKolab1 ); mKolab2 = new QRadioButton( i18n ( "Kolab 2" ), bg ); hbl->addWidget( mKolab2 ); topLayout->addMultiCellWidget( bg, 5, 5, 0, 1 ); setupRulesPage(); setupChangesPage(); setInitialSize( QSize( 600, 300 ) ); } KolabWizard::~KolabWizard() { } QString KolabWizard::validate() { if( mServerEdit->text().isEmpty() || mUserEdit->text().isEmpty() || mRealNameEdit->text().isEmpty() || mPasswordEdit->text().isEmpty() ) return i18n( "Please fill in all fields." ); return QString::null; } void KolabWizard::usrReadConfig() { mServerEdit->setText( KolabConfig::self()->server() ); mUserEdit->setText( KolabConfig::self()->user() ); mRealNameEdit->setText( KolabConfig::self()->realName() ); mPasswordEdit->setText( KolabConfig::self()->password() ); mSavePasswordCheck->setChecked( KolabConfig::self()->savePassword() ); mKolab1->setChecked( KolabConfig::self()->kolab1Legacy() ); mKolab2->setChecked( !KolabConfig::self()->kolab1Legacy() ); } void KolabWizard::usrWriteConfig() { KolabConfig::self()->setServer( mServerEdit->text() ); KolabConfig::self()->setUser( mUserEdit->text() ); KolabConfig::self()->setRealName( mRealNameEdit->text() ); KolabConfig::self()->setPassword( mPasswordEdit->text() ); KolabConfig::self()->setSavePassword( mSavePasswordCheck->isChecked() ); KolabConfig::self()->setKolab1Legacy( mKolab1->isChecked() ); } <commit_msg>Compile with new kdelibs snapshot.<commit_after>/* This file is part of kdepim. Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org> Copyright (c) 2004 Daniel Molkentin <molkentin@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kolabwizard.h" #include "kolabconfig.h" #include "kolabkmailchanges.h" #include "kresources/kolab/kcal/resourcekolab.h" #include "kresources/kolab/kabc/resourcekolab.h" #include "kresources/kolab/knotes/resourcekolab.h" #include <libkcal/resourcecalendar.h> #include <kabc/resource.h> #include <klineedit.h> #include <klocale.h> #include <qcheckbox.h> #include <qlabel.h> #include <qlayout.h> #include <qradiobutton.h> #include <qwhatsthis.h> #include <QGroupBox> class SetupLDAPSearchAccount : public KConfigPropagator::Change { public: SetupLDAPSearchAccount() : KConfigPropagator::Change( i18n("Setup LDAP Search Account") ) { } void apply() { const QString host = KolabConfig::self()->server(); // Figure out the basedn QString basedn = host; // If the user gave a full email address, the domain name // of that overrides the server name for the ldap dn const QString user = KolabConfig::self()->user(); int pos = user.find( "@" ); if ( pos > 0 ) { const QString h = user.mid( pos+1 ); if ( !h.isEmpty() ) // The user did type in a domain on the email address. Use that basedn = h; } { // while we're here, write default domain KConfig c( "kmailrc" ); c.setGroup( "General" ); c.writeEntry( "Default domain", basedn ); } basedn.replace(".",",dc="); basedn.prepend("dc="); // Set the changes KConfig c( "kabldaprc" ); c.setGroup( "LDAP" ); bool hasMyServer = false; uint selHosts = c.readNumEntry("NumSelectedHosts", 0); for ( uint i = 0 ; i < selHosts && !hasMyServer; ++i ) if ( c.readEntry( QString("SelectedHost%1").arg(i), QString() ) == host ) hasMyServer = true; if ( !hasMyServer ) { c.writeEntry( "NumSelectedHosts", selHosts + 1 ); c.writeEntry( QString("SelectedHost%1").arg(selHosts), host); c.writeEntry( QString("SelectedBase%1").arg(selHosts), basedn); c.writeEntry( QString("SelectedPort%1").arg(selHosts), "389"); } } }; class CreateCalendarImapResource : public KConfigPropagator::Change { public: CreateCalendarImapResource() : KConfigPropagator::Change( i18n("Create Calendar IMAP Resource") ) { } void apply() { KCal::CalendarResourceManager m( "calendar" ); m.readConfig(); KCal::ResourceKolab *r = new KCal::ResourceKolab( 0 ); r->setResourceName( i18n("Kolab Server") ); m.add( r ); m.setStandardResource( r ); m.writeConfig(); } }; class CreateContactImapResource : public KConfigPropagator::Change { public: CreateContactImapResource() : KConfigPropagator::Change( i18n("Create Contact IMAP Resource") ) { } void apply() { KRES::Manager<KABC::Resource> m( "contact" ); m.readConfig(); KABC::ResourceKolab *r = new KABC::ResourceKolab( 0 ); r->setResourceName( i18n("Kolab Server") ); m.add( r ); m.setStandardResource( r ); m.writeConfig(); } }; class CreateNotesImapResource : public KConfigPropagator::Change { public: CreateNotesImapResource() : KConfigPropagator::Change( i18n("Create Notes IMAP Resource") ) { } void apply() { KRES::Manager<ResourceNotes> m( "notes" ); m.readConfig(); Kolab::ResourceKolab *r = new Kolab::ResourceKolab( 0 ); r->setResourceName( i18n("Kolab Server") ); m.add( r ); m.setStandardResource( r ); m.writeConfig(); } }; class KolabPropagator : public KConfigPropagator { public: KolabPropagator() : KConfigPropagator( KolabConfig::self(), "kolab.kcfg" ) { } protected: void addKorganizerChanges( Change::List &changes ) { KURL freeBusyBaseUrl; // usrWriteConfig() is called first, so kolab1Legacy is correct if ( KolabConfig::self()->kolab1Legacy() ) { freeBusyBaseUrl = "webdavs://" + KolabConfig::self()->server() + "/freebusy/"; ChangeConfig *c = new ChangeConfig; c->file = "korganizerrc"; c->group = "FreeBusy"; c->name = "FreeBusyPublishUrl"; QString user = KolabConfig::self()->user(); // We now use the full email address in the freebusy URL //int pos = user.find( "@" ); //if ( pos > 0 ) user = user.left( pos ); KURL publishURL = freeBusyBaseUrl; publishURL.addPath( user + ".ifb" ); // this encodes the '@' in the username c->value = publishURL.url(); changes.append( c ); } else { // Kolab2: only need FreeBusyRetrieveUrl // "Uploading" is done by triggering a server-side script with an HTTP GET // (done by kmail) freeBusyBaseUrl = "https://" + KolabConfig::self()->server() + "/freebusy/"; } ChangeConfig *c = new ChangeConfig; c->file = "korganizerrc"; c->group = "FreeBusy"; c->name = "FreeBusyRetrieveUrl"; c->value = freeBusyBaseUrl.url(); changes.append( c ); // Use full email address for retrieval of free/busy lists c = new ChangeConfig; c->file = "korganizerrc"; c->group = "FreeBusy"; c->name = "FreeBusyFullDomainRetrieval"; c->value = "true"; changes.append( c ); c = new ChangeConfig; c->file = "korganizerrc"; c->group = "Group Scheduling"; c->name = "Use Groupware Communication"; c->value = "true"; changes.append( c ); // Use identity "from control center", i.e. from emaildefaults c = new ChangeConfig; c->file = "korganizerrc"; c->group = "Personal Settings"; c->name = "Use Control Center Email"; c->value = "true"; changes.append( c ); } virtual void addCustomChanges( Change::List &changes ) { addKorganizerChanges( changes ); // KMail cruft has been outsourced to kolabkmailchanges.cpp createKMailChanges( changes ); changes.append( new SetupLDAPSearchAccount ); KCal::CalendarResourceManager m( "calendar" ); m.readConfig(); KCal::CalendarResourceManager::Iterator it; for ( it = m.begin(); it != m.end(); ++it ) { if ( (*it)->type() == "imap" ) break; } if ( it == m.end() ) { changes.append( new CreateCalendarImapResource ); changes.append( new CreateContactImapResource ); changes.append( new CreateNotesImapResource ); } } }; KolabWizard::KolabWizard() : KConfigWizard( new KolabPropagator ) { QFrame *page = createWizardPage( i18n("Kolab Server") ); QGridLayout *topLayout = new QGridLayout( page ); topLayout->setSpacing( spacingHint() ); QLabel *label = new QLabel( i18n("Server name:"), page ); topLayout->addWidget( label, 0, 0 ); mServerEdit = new KLineEdit( page ); topLayout->addWidget( mServerEdit, 0, 1 ); label = new QLabel( i18n("Email address:"), page ); topLayout->addWidget( label, 1, 0 ); mUserEdit = new KLineEdit( page ); topLayout->addWidget( mUserEdit, 1, 1 ); QWhatsThis::add(mUserEdit, i18n("Your email address on the Kolab Server. " "Format: <i>name@example.net</i>")); label = new QLabel( i18n("Real name:"), page ); topLayout->addWidget( label, 2, 0 ); mRealNameEdit = new KLineEdit( page ); topLayout->addWidget( mRealNameEdit, 2, 1 ); label = new QLabel( i18n("Password:"), page ); topLayout->addWidget( label, 3, 0 ); mPasswordEdit = new KLineEdit( page ); mPasswordEdit->setEchoMode( KLineEdit::Password ); topLayout->addWidget( mPasswordEdit, 3, 1 ); mSavePasswordCheck = new QCheckBox( i18n("Save password"), page ); topLayout->addWidget( mSavePasswordCheck, 4, 1 ); topLayout->setRowStretch( 4, 1 ); QGroupBox *bg = new QGroupBox(i18n("Server Version"), page ); QHBoxLayout *hbl = new QHBoxLayout(); bg->setLayout( hbl ); QWhatsThis::add( bg, i18n("Choose the version of the Kolab Server you are using.") ); mKolab1 = new QRadioButton( i18n ( "Kolab 1" ), bg ); hbl->addWidget( mKolab1 ); mKolab2 = new QRadioButton( i18n ( "Kolab 2" ), bg ); hbl->addWidget( mKolab2 ); topLayout->addMultiCellWidget( bg, 5, 5, 0, 1 ); setupRulesPage(); setupChangesPage(); setInitialSize( QSize( 600, 300 ) ); } KolabWizard::~KolabWizard() { } QString KolabWizard::validate() { if( mServerEdit->text().isEmpty() || mUserEdit->text().isEmpty() || mRealNameEdit->text().isEmpty() || mPasswordEdit->text().isEmpty() ) return i18n( "Please fill in all fields." ); return QString::null; } void KolabWizard::usrReadConfig() { mServerEdit->setText( KolabConfig::self()->server() ); mUserEdit->setText( KolabConfig::self()->user() ); mRealNameEdit->setText( KolabConfig::self()->realName() ); mPasswordEdit->setText( KolabConfig::self()->password() ); mSavePasswordCheck->setChecked( KolabConfig::self()->savePassword() ); mKolab1->setChecked( KolabConfig::self()->kolab1Legacy() ); mKolab2->setChecked( !KolabConfig::self()->kolab1Legacy() ); } void KolabWizard::usrWriteConfig() { KolabConfig::self()->setServer( mServerEdit->text() ); KolabConfig::self()->setUser( mUserEdit->text() ); KolabConfig::self()->setRealName( mRealNameEdit->text() ); KolabConfig::self()->setPassword( mPasswordEdit->text() ); KolabConfig::self()->setSavePassword( mSavePasswordCheck->isChecked() ); KolabConfig::self()->setKolab1Legacy( mKolab1->isChecked() ); } <|endoftext|>
<commit_before>//Main graph classes functions #ifndef __FRIGATE_GRAPH_CPP__ #define __FRIGATE_GRAPH_CPP__ #include <string.h> #include "graph.h" namespace frigate{ CharNames Graph::Names; int CodeBlock::setCode(char* _code) { if(code == NULL && file_name == NULL) { code = new char[strlen(_code)+1]; strcpy(code, _code); printf("ohuenchik %s \n", _code); return 0; } return 1; } int CodeBlock::setFileName(char* filename) { if((code == NULL) && (file_name == NULL)) { file_name = new char[strlen(filename)+1]; strcpy(file_name, filename); return 0; } return 1; } int CodeBlock::setIOVolume(char* vol) { io_volume = new char[strlen(vol)+1]; if(io_volume == NULL) return -1; strcpy(io_volume, vol); return 0; } int CodeBlock::setCodeVolume(char* vol) { code_volume = new char[strlen(vol)+1]; if(code_volume == NULL) return -1; strcpy(code_volume, vol); return 0; } int Subgraph::setName(char* name) { std::string str = name; frigate_name_id_type id = Graph::Names.register_name(str); if(id == -1) return -1; else { name_id = id; return 0; } return -1; } int Graph::setMainSubgraph(char* main_subgraph_name) { std::string str = main_subgraph_name; frigate_name_id_type id = Graph::Names.register_name(str); if(id == -1) return -1; else { main_subgraph_id = id; return 0; } return -1; } Subgraph::Subgraph():name_id(-1), predefined_condition_value(){} //Subgraph::~Subgraph() //{ // printf("Hello, i'm your destructor\n"); //} Subgraph* Subgraph::copy() { Subgraph* sbgrph = new Subgraph(); sbgrph->name_id = name_id; sbgrph->condition_code = condition_code; sbgrph->predefined_condition_value = predefined_condition_value; sbgrph->vertices = vertices; sbgrph->internal_edges = internal_edges; sbgrph->control_edges = control_edges; /* for(int i = 0; i<vertices.num_elements(); ++i) { sbgrph->vertices.add_element(vertices.get_elem(i)); } for(int i = 0; i<internal_edges.num_elements(); ++i) { sbgrph->internal_edges.add_element(internal_edges.get_elem(i)); } for(int i = 0; i<control_edges.num_elements(); ++i) { sbgrph->control_edges.add_element(control_edges.get_elem(i)); }*/ return sbgrph; } ExternalEdge::ExternalEdge(): name_id(-1), template_name_id(-1), send_subgraph_id(-1), send_vertex_id(-1), send_exchange_block_id(-1), recv_subgraph_id(-1), recv_vertex_id(-1), recv_exchange_block_id(-1) {} ExternalEdge* ExternalEdge::copy() { ExternalEdge* _ee = new ExternalEdge(); _ee->name_id = name_id; _ee->template_name_id = template_name_id; _ee->send_subgraph_id = send_subgraph_id; _ee->send_vertex_id = send_vertex_id; _ee->send_exchange_block_id = send_exchange_block_id; _ee->recv_subgraph_id = recv_subgraph_id; _ee->recv_vertex_id = recv_vertex_id; _ee->recv_exchange_block_id = recv_exchange_block_id; return _ee; } int ExternalEdge::setSendCoords(char* subgraph, char* vert, char* exchange) { registerName(subgraph, &send_subgraph_id); registerName(vert, &send_vertex_id); registerName(exchange, &send_exchange_block_id); return 0; } int ExternalEdge::setRecvCoords(char* subgraph, char* vert, char* exchange) { registerName(subgraph, &recv_subgraph_id); registerName(vert, &recv_vertex_id); registerName(exchange, &recv_exchange_block_id); return 0; } int VertexTemplate::setName(char* name) { int id = Graph::Names.register_name(name); if(id == -1) return -1; vt_name_id = id; return 0; } Vertex* Vertex::copy() { Vertex* _v = new Vertex(); this->deepCopy(_v); _v->name_id = name_id; _v->template_name_id = template_name_id; return _v; } int Vertex::setTemplateName(char* template_name) { int id = Graph::Names.search_name(template_name); if(id!=-1) { template_name_id = id; return 0; } id = Graph::Names.register_name(template_name); if(id == -1) return -1; template_name_id = id; return 0; } Fragment* Fragment::copy() { Fragment* _f = new Fragment(); _f->variable = variable; _f->type = type; _f->left_border = left_border; _f->right_border = right_border; return _f; } Fragment::Fragment(char* _variable, char* _type, char* _left_border, char* _right_border) { variable.setCode(_variable); type.setCode(_type); left_border.setCode(_left_border); right_border.setCode(_right_border); } ExchangeBlock* ExchangeBlock::copy() { ExchangeBlock* _eb = new ExchangeBlock(); _eb->name_id = name_id; _eb->send = send; _eb->recv = recv; /* for(int i = 0; i<send.num_elements(); ++i) { _eb->send.add_element(send.get_elem(i)); } for(int i = 0; i<recv.num_elements(); ++i) { _eb->recv.add_element(recv.get_elem(i)); }*/ return _eb; } int ExchangeBlock::addSend(char* send_name) { int id = Graph::Names.search_name(send_name); if(id!=-1) { send.add_element(id); return 0; } id = Graph::Names.register_name(send_name); if(id == -1) return -1; send.add_element(id); return 0; } int ExchangeBlock::addRecv(char* recv_name) { int id = Graph::Names.search_name(recv_name); if(id!=-1) { recv.add_element(id); return 0; } id = Graph::Names.register_name(recv_name); if(id == -1) return -1; recv.add_element(id); return 0; } InternalEdge* InternalEdge::copy() { InternalEdge* _ie = new InternalEdge(); _ie->name_id = name_id; _ie->template_name_id = template_name_id; _ie->send_vertex_id = send_vertex_id; _ie->send_vertex_exchange_id = send_vertex_exchange_id; _ie->recv_vertex_id = recv_vertex_id; _ie->recv_vertex_exchange_id = recv_vertex_exchange_id; return _ie; } int InternalEdge::setSendCoords(char* vert, char* exchange) { registerName(vert, &send_vertex_id); registerName(exchange, &send_vertex_exchange_id); return 0; } int InternalEdge::setRecvCoords(char* vert, char* exchange) { registerName(vert, &recv_vertex_id); registerName(exchange, &recv_vertex_exchange_id); return 0; } ControlEdge* ControlEdge::copy() { ControlEdge* _ce = new ControlEdge(); _ce->name_id = name_id; _ce->template_name_id = template_name_id; _ce->send_vertex_id = send_vertex_id; _ce->send_vertex_exchange_id = send_vertex_exchange_id; return _ce; } int ControlEdge::setSendCoords(char* vert, char* exchange) { registerName(vert, &send_vertex_id); registerName(exchange, &send_vertex_exchange_id); return 0; } EdgeTemplate* EdgeTemplate::copy() { EdgeTemplate* _et = new EdgeTemplate(); _et->name_id = name_id; _et->send_fragments = send_fragments; _et->recv_fragments = recv_fragments; return _et; } int EdgeTemplate::setName(char* name) { int id = Graph::Names.register_name(name); if(id == -1) return -1; name_id = id; return 0; } int EdgeTemplate::setTemplateName(char* template_name) { int id = Graph::Names.search_name(template_name); if(id!=-1) { template_name_id = id; return 0; } id = Graph::Names.register_name(template_name); if(id == -1) return -1; template_name_id = id; return 0; } int EdgeTemplate::setSendFragments(Line_dynamic_array<Fragment>& _send_fragments) { send_fragments = _send_fragments; return 0; } int EdgeTemplate::setRecvFragments(Line_dynamic_array<Fragment>& _recv_fragments) { recv_fragments = _recv_fragments; return 0; } int EdgeTemplate::registerName(char* str, int* param_id) { int id = Graph::Names.search_name(str); if(id!=-1) { *param_id = id; return 0; } id = Graph::Names.register_name(str); if(id == -1) return -1; *param_id = id; return 0; } VertexTemplate* VertexTemplate::copy() { VertexTemplate* _vt = new VertexTemplate(); _vt->vt_name_id = vt_name_id; _vt->inside_blocks = inside_blocks; return _vt; } void VertexTemplate::deepCopy(Vertex* child) { child->vt_name_id = vt_name_id; child->inside_blocks = inside_blocks; return; } int VertexTemplate::setVerticeBlocks(Line_dynamic_array<VerticeBlock>& blocks) { inside_blocks = blocks; return 0; } //*******************************************************// CodeBlock::~CodeBlock() { if(code != NULL) { delete [] code; code = NULL; } if(file_name != NULL) { delete [] file_name; file_name = NULL; } if(io_volume != NULL) { delete [] io_volume; io_volume = NULL; } if(code_volume != NULL) { delete [] code_volume; code_volume = NULL; } } CodeBlock::CodeBlock(const CodeBlock& _cb) { if(_cb.code != NULL) { code = new char[strlen(_cb.code)+1]; strcpy(code, _cb.code); } if(file_name != NULL) { file_name = new char[strlen(_cb.file_name)+1]; strcpy(file_name, _cb.file_name); } if(io_volume != NULL) { io_volume = new char[strlen(_cb.io_volume)+1]; strcpy(io_volume, _cb.io_volume); } if(code_volume != NULL) { code_volume = new char[strlen(_cb.code_volume)+1]; strcpy(code_volume, _cb.code_volume); } } CodeBlock& CodeBlock::operator=(const CodeBlock& _cb) { if (this != &_cb) { if (code != NULL) delete [] code; if (_cb.code != NULL) { code = new char[strlen(_cb.code)+1]; strcpy(code, _cb.code); } else code = NULL; if (file_name != NULL) delete [] file_name; if (_cb.file_name != NULL) { file_name = new char[strlen(_cb.file_name)+1]; strcpy(file_name, _cb.file_name); } else file_name = NULL; if (io_volume != NULL) delete [] io_volume; if (_cb.io_volume != NULL) { io_volume = new char[strlen(_cb.io_volume)+1]; strcpy(io_volume, _cb.io_volume); } else io_volume = NULL; if (code_volume != NULL) delete [] code_volume; if (_cb.code_volume != NULL) { code_volume = new char[strlen(_cb.code_volume)+1]; strcpy(code_volume, _cb.code_volume); } else code_volume = NULL; } return *this; } CodeBlock* CodeBlock::copy() { CodeBlock* tmp = new CodeBlock(); *tmp = *this; return tmp; } //*******************************************************// } #endif //__FRIGATE_GRAPH_CPP__ <commit_msg><commit_after>//Main graph classes functions #ifndef __FRIGATE_GRAPH_CPP__ #define __FRIGATE_GRAPH_CPP__ #include <string.h> #include "graph.h" namespace frigate{ CharNames Graph::Names; int CodeBlock::setCode(char* _code) { if(code == NULL && file_name == NULL) { code = new char[strlen(_code)+1]; strcpy(code, _code); printf("ohuenchik %s \n", _code); return 0; } return 1; } int CodeBlock::setFileName(char* filename) { if((code == NULL) && (file_name == NULL)) { file_name = new char[strlen(filename)+1]; strcpy(file_name, filename); return 0; } return 1; } int CodeBlock::setIOVolume(char* vol) { io_volume = new char[strlen(vol)+1]; if(io_volume == NULL) return -1; strcpy(io_volume, vol); return 0; } int CodeBlock::setCodeVolume(char* vol) { code_volume = new char[strlen(vol)+1]; if(code_volume == NULL) return -1; strcpy(code_volume, vol); return 0; } int Subgraph::setName(char* name) { std::string str = name; frigate_name_id_type id = Graph::Names.register_name(str); if(id == -1) return -1; else { name_id = id; return 0; } return -1; } int Graph::setMainSubgraph(char* main_subgraph_name) { std::string str = main_subgraph_name; frigate_name_id_type id = Graph::Names.register_name(str); if(id == -1) return -1; else { main_subgraph_id = id; return 0; } return -1; } Subgraph::Subgraph():name_id(-1), predefined_condition_value(){} //Subgraph::~Subgraph() //{ // printf("Hello, i'm your destructor\n"); //} Subgraph* Subgraph::copy() { Subgraph* sbgrph = new Subgraph(); sbgrph->name_id = name_id; sbgrph->condition_code = condition_code; sbgrph->predefined_condition_value = predefined_condition_value; sbgrph->vertices = vertices; sbgrph->internal_edges = internal_edges; sbgrph->control_edges = control_edges; /* for(int i = 0; i<vertices.num_elements(); ++i) { sbgrph->vertices.add_element(vertices.get_elem(i)); } for(int i = 0; i<internal_edges.num_elements(); ++i) { sbgrph->internal_edges.add_element(internal_edges.get_elem(i)); } for(int i = 0; i<control_edges.num_elements(); ++i) { sbgrph->control_edges.add_element(control_edges.get_elem(i)); }*/ return sbgrph; } ExternalEdge::ExternalEdge(): name_id(-1), template_name_id(-1), send_subgraph_id(-1), send_vertex_id(-1), send_exchange_block_id(-1), recv_subgraph_id(-1), recv_vertex_id(-1), recv_exchange_block_id(-1) {} ExternalEdge* ExternalEdge::copy() { ExternalEdge* _ee = new ExternalEdge(); _ee->name_id = name_id; _ee->template_name_id = template_name_id; _ee->send_subgraph_id = send_subgraph_id; _ee->send_vertex_id = send_vertex_id; _ee->send_exchange_block_id = send_exchange_block_id; _ee->recv_subgraph_id = recv_subgraph_id; _ee->recv_vertex_id = recv_vertex_id; _ee->recv_exchange_block_id = recv_exchange_block_id; return _ee; } int ExternalEdge::setSendCoords(char* subgraph, char* vert, char* exchange) { registerName(subgraph, &send_subgraph_id); registerName(vert, &send_vertex_id); registerName(exchange, &send_exchange_block_id); return 0; } int ExternalEdge::setRecvCoords(char* subgraph, char* vert, char* exchange) { registerName(subgraph, &recv_subgraph_id); registerName(vert, &recv_vertex_id); registerName(exchange, &recv_exchange_block_id); return 0; } int VertexTemplate::setName(char* name) { int id = Graph::Names.register_name(name); if(id == -1) return -1; vt_name_id = id; return 0; } Vertex* Vertex::copy() { Vertex* _v = new Vertex(); this->deepCopy(_v); _v->name_id = name_id; _v->template_name_id = template_name_id; return _v; } int Vertex::setTemplateName(char* template_name) { int id = Graph::Names.search_name(template_name); if(id!=-1) { template_name_id = id; return 0; } id = Graph::Names.register_name(template_name); if(id == -1) return -1; template_name_id = id; return 0; } Fragment* Fragment::copy() { Fragment* _f = new Fragment(); _f->variable = variable; _f->type = type; _f->left_border = left_border; _f->right_border = right_border; return _f; } Fragment::Fragment(char* _variable, char* _type, char* _left_border, char* _right_border) { variable.setCode(_variable); type.setCode(_type); left_border.setCode(_left_border); right_border.setCode(_right_border); } ExchangeBlock* ExchangeBlock::copy() { ExchangeBlock* _eb = new ExchangeBlock(); _eb->name_id = name_id; _eb->send = send; _eb->recv = recv; /* for(int i = 0; i<send.num_elements(); ++i) { _eb->send.add_element(send.get_elem(i)); } for(int i = 0; i<recv.num_elements(); ++i) { _eb->recv.add_element(recv.get_elem(i)); }*/ return _eb; } int ExchangeBlock::addSend(char* send_name) { int id = Graph::Names.search_name(send_name); if(id!=-1) { send.add_element(id); return 0; } id = Graph::Names.register_name(send_name); if(id == -1) return -1; send.add_element(id); return 0; } int ExchangeBlock::addRecv(char* recv_name) { int id = Graph::Names.search_name(recv_name); if(id!=-1) { recv.add_element(id); return 0; } id = Graph::Names.register_name(recv_name); if(id == -1) return -1; recv.add_element(id); return 0; } InternalEdge* InternalEdge::copy() { InternalEdge* _ie = new InternalEdge(); _ie->name_id = name_id; _ie->template_name_id = template_name_id; _ie->send_vertex_id = send_vertex_id; _ie->send_vertex_exchange_id = send_vertex_exchange_id; _ie->recv_vertex_id = recv_vertex_id; _ie->recv_vertex_exchange_id = recv_vertex_exchange_id; return _ie; } int InternalEdge::setSendCoords(char* vert, char* exchange) { registerName(vert, &send_vertex_id); registerName(exchange, &send_vertex_exchange_id); return 0; } int InternalEdge::setRecvCoords(char* vert, char* exchange) { registerName(vert, &recv_vertex_id); registerName(exchange, &recv_vertex_exchange_id); return 0; } ControlEdge* ControlEdge::copy() { ControlEdge* _ce = new ControlEdge(); _ce->name_id = name_id; _ce->template_name_id = template_name_id; _ce->send_vertex_id = send_vertex_id; _ce->send_vertex_exchange_id = send_vertex_exchange_id; return _ce; } int ControlEdge::setSendCoords(char* vert, char* exchange) { registerName(vert, &send_vertex_id); registerName(exchange, &send_vertex_exchange_id); return 0; } EdgeTemplate* EdgeTemplate::copy() { EdgeTemplate* _et = new EdgeTemplate(); _et->name_id = name_id; _et->send_fragments = send_fragments; _et->recv_fragments = recv_fragments; return _et; } int EdgeTemplate::setName(char* name) { int id = Graph::Names.register_name(name); if(id == -1) return -1; name_id = id; return 0; } int EdgeTemplate::setTemplateName(char* template_name) { int id = Graph::Names.search_name(template_name); if(id!=-1) { template_name_id = id; return 0; } id = Graph::Names.register_name(template_name); if(id == -1) return -1; template_name_id = id; return 0; } int EdgeTemplate::setSendFragments(Line_dynamic_array<Fragment>& _send_fragments) { send_fragments = _send_fragments; return 0; } int EdgeTemplate::setRecvFragments(Line_dynamic_array<Fragment>& _recv_fragments) { recv_fragments = _recv_fragments; return 0; } int EdgeTemplate::registerName(char* str, int* param_id) { int id = Graph::Names.search_name(str); if(id!=-1) { *param_id = id; return 0; } id = Graph::Names.register_name(str); if(id == -1) return -1; *param_id = id; return 0; } VertexTemplate* VertexTemplate::copy() { VertexTemplate* _vt = new VertexTemplate(); _vt->vt_name_id = vt_name_id; _vt->inside_blocks = inside_blocks; return _vt; } void VertexTemplate::deepCopy(Vertex* child) { child->vt_name_id = vt_name_id; child->inside_blocks = inside_blocks; return; } int VertexTemplate::setVerticeBlocks(Line_dynamic_array<VerticeBlock>& blocks) { inside_blocks = blocks; return 0; } //*******************************************************// CodeBlock::~CodeBlock() { if(code != NULL) { delete [] code; code = NULL; } if(file_name != NULL) { delete [] file_name; file_name = NULL; } if(io_volume != NULL) { delete [] io_volume; io_volume = NULL; } if(code_volume != NULL) { delete [] code_volume; code_volume = NULL; } } CodeBlock::CodeBlock(const CodeBlock& _cb) { if(_cb.code != NULL) { code = new char[strlen(_cb.code)+1]; strcpy(code, _cb.code); } if(file_name != NULL) { file_name = new char[strlen(_cb.file_name)+1]; strcpy(file_name, _cb.file_name); } if(io_volume != NULL) { io_volume = new char[strlen(_cb.io_volume)+1]; strcpy(io_volume, _cb.io_volume); } if(code_volume != NULL) { code_volume = new char[strlen(_cb.code_volume)+1]; strcpy(code_volume, _cb.code_volume); } } CodeBlock& CodeBlock::operator=(const CodeBlock& _cb) { if (this != &_cb) { if (code != NULL) delete [] code; if (_cb.code != NULL) { code = new char[strlen(_cb.code)+1]; strcpy(code, _cb.code); } else code = NULL; if (file_name != NULL) delete [] file_name; if (_cb.file_name != NULL) { file_name = new char[strlen(_cb.file_name)+1]; strcpy(file_name, _cb.file_name); } else file_name = NULL; if (io_volume != NULL) delete [] io_volume; if (_cb.io_volume != NULL) { io_volume = new char[strlen(_cb.io_volume)+1]; strcpy(io_volume, _cb.io_volume); } else io_volume = NULL; if (code_volume != NULL) delete [] code_volume; if (_cb.code_volume != NULL) { code_volume = new char[strlen(_cb.code_volume)+1]; strcpy(code_volume, _cb.code_volume); } else code_volume = NULL; } return *this; } CodeBlock* CodeBlock::copy() { CodeBlock* tmp = new CodeBlock(); *tmp = *this; return tmp; } //*******************************************************// } #endif //__FRIGATE_GRAPH_CPP__ <|endoftext|>
<commit_before>#include "geocoder.h" #include "address.h" #include <stdlib.h> #include <assert.h> #include <sqlite3.h> #include <math.h> #include <sstream> using namespace std; using namespace std::tr1; static string LATLNG_REGEX = "^(-?[0-9]+(?:\\.[0-9]+)?)\\ *,\\ *(-?[0-9]+(?:\\.[0-9]+)?)$"; static inline double radians(double degrees) { return degrees/180.0f*M_PI; } static inline double degrees(double radians) { return radians*180.0f/M_PI; } static double distance(double src_lat, double src_lng, double dest_lat, double dest_lng) { // returns distance in meters if (src_lat == dest_lat && src_lng == dest_lng) return 0.0f; double theta = src_lng - dest_lng; double src_lat_radians = radians(src_lat); double dest_lat_radians = radians(dest_lat); double dist = sin(src_lat_radians) * sin(dest_lat_radians) + cos(src_lat_radians) * cos(dest_lat_radians) * cos(radians(theta)); dist = acos(dist); dist = degrees(dist); dist *= (60.0f * 1.1515 * 1.609344 * 1000.0f); return dist; } static pair<float, float> interpolated_latlng(float * latlng_array, int num_points, float length, float percent) { float distance_to_travel = percent * length; float distance_travelled = 0.0f; pair<float, float> prevcoord; for (int i=0; i<num_points; i++) { pair<float, float> coord(latlng_array[i*2], latlng_array[(i*2)+1]); if (i > 0) { float seg_travel = distance(prevcoord.first, prevcoord.second, coord.first, coord.second); if (seg_travel > 0.0 && (distance_travelled + seg_travel >= distance_to_travel)) { float seg_percent = ((distance_to_travel - distance_travelled) / seg_travel); return pair<float, float>( prevcoord.first + ((coord.first - prevcoord.first) * seg_percent), prevcoord.second + ((coord.second - prevcoord.second) * seg_percent)); } distance_travelled += seg_travel; } prevcoord = coord; } return prevcoord; } GeoCoder::GeoCoder(const char *dbname) : latlng_re(LATLNG_REGEX, PCRE_CASELESS) { db = NULL; int rc = sqlite3_open(dbname, &db); if (rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); assert(0 && "Couldn't initialize geocoder!!!!"); } parser = shared_ptr<GeoParser>(new GeoParser(db)); } static int sqlite_intersection_cb(void *userdata, int argc, char **argv, char **azColName) { pair<float, float> **latlng = (pair<float, float> **)userdata; (*latlng) = new pair<float, float>(atof(argv[0]), atof(argv[1])); return 0; } static int sqlite_address_cb(void *userdata, int argc, char **argv, char **azColName) { pair<pair<float, float> *, int> * addr_tuple = (pair<pair<float, float> *, int> *)userdata; int first_number = atol(argv[0]); int last_number = atol(argv[1]); float percent = 0.5; if (addr_tuple->second) percent = ((float)(addr_tuple->second - first_number)) / ( (float)(last_number - (float)first_number)); float length = atof(argv[2]); long num_points = *(reinterpret_cast<long *>(&argv[3][0])); float *latlng_array = (reinterpret_cast<float *>(&argv[3][sizeof(long)])); addr_tuple->first = new pair<float,float>(interpolated_latlng(latlng_array, num_points, length, percent)); return 0; } pair<float, float> * GeoCoder::get_latlng(const char *str) { // before anything else, see if we're being passed a latlng pair. if so, // just pass it through string lat, lng; if (latlng_re.FullMatch(str, &lat, &lng)) return new pair<float, float>(atof(lat.c_str()), atof(lng.c_str())); Address *addr = parser->parse_address(str); if (addr && addr->is_intersection()) { pair<float, float> *latlng = NULL; // sql db assumes first road name in intersection is less than // (case insensitive) than the second. we swap them to satisfy this // condition Address *addr1 = addr, *addr2 = addr->cross_street; if (strcasecmp(addr->street.c_str(), addr->cross_street->street.c_str()) > 0) { addr1 = addr->cross_street; addr2 = addr; } stringstream sqlstr; sqlstr << "select lat,lng from intersection where "; sqlstr << "name1 like '" << addr1->street << "' "; sqlstr << " and name2 like '" << addr2->street << "'"; sqlstr << " limit 1"; char *zErrMsg = 0; printf("SQL: %s\n", sqlstr.str().c_str()); int rc = sqlite3_exec(db, sqlstr.str().c_str(), sqlite_intersection_cb, &latlng, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); // we silently fail in this case... maybe it would be better to // just assert? } return latlng; } if (addr && !addr->street.empty()) { pair<pair<float, float> *, int> addr_tuple(NULL, addr->number); stringstream sqlstr; sqlstr << "select firstHouseNumber, lastHouseNumber, length, coords " "from road where "; sqlstr << "name like '" << addr->street << "' "; if (addr->suffix) sqlstr << "and suffixType==" << addr->suffix << " "; if (addr->direction) sqlstr << "and direction==" << addr->direction << " "; if (addr->number) { sqlstr << "and firstHouseNumber <= '" << addr->number << "' "; sqlstr << "and lastHouseNumber >= '" << addr->number << "' "; } if (addr->region.size()) { sqlstr << "and placeName like '" << addr->region << "' "; } sqlstr << "limit 1"; char *zErrMsg = 0; printf("SQL: %s\n", sqlstr.str().c_str()); int rc = sqlite3_exec(db, sqlstr.str().c_str(), sqlite_address_cb, &addr_tuple, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); // we silently fail in this case... maybe it would be better to // just assert? } return addr_tuple.first; } return NULL; } <commit_msg>Display SQL debugging statements only conditionally<commit_after>#include "geocoder.h" #include "address.h" #include <stdlib.h> #include <assert.h> #include <sqlite3.h> #include <math.h> #include <sstream> using namespace std; using namespace std::tr1; static string LATLNG_REGEX = "^(-?[0-9]+(?:\\.[0-9]+)?)\\ *,\\ *(-?[0-9]+(?:\\.[0-9]+)?)$"; // set to 1 to see debugging info (rather verbose) #if 0 # define NEODEBUG(fmt, args...) fprintf(stderr, fmt, ## args) #else # define NEODEBUG #endif static inline double radians(double degrees) { return degrees/180.0f*M_PI; } static inline double degrees(double radians) { return radians*180.0f/M_PI; } static double distance(double src_lat, double src_lng, double dest_lat, double dest_lng) { // returns distance in meters if (src_lat == dest_lat && src_lng == dest_lng) return 0.0f; double theta = src_lng - dest_lng; double src_lat_radians = radians(src_lat); double dest_lat_radians = radians(dest_lat); double dist = sin(src_lat_radians) * sin(dest_lat_radians) + cos(src_lat_radians) * cos(dest_lat_radians) * cos(radians(theta)); dist = acos(dist); dist = degrees(dist); dist *= (60.0f * 1.1515 * 1.609344 * 1000.0f); return dist; } static pair<float, float> interpolated_latlng(float * latlng_array, int num_points, float length, float percent) { float distance_to_travel = percent * length; float distance_travelled = 0.0f; pair<float, float> prevcoord; for (int i=0; i<num_points; i++) { pair<float, float> coord(latlng_array[i*2], latlng_array[(i*2)+1]); if (i > 0) { float seg_travel = distance(prevcoord.first, prevcoord.second, coord.first, coord.second); if (seg_travel > 0.0 && (distance_travelled + seg_travel >= distance_to_travel)) { float seg_percent = ((distance_to_travel - distance_travelled) / seg_travel); return pair<float, float>( prevcoord.first + ((coord.first - prevcoord.first) * seg_percent), prevcoord.second + ((coord.second - prevcoord.second) * seg_percent)); } distance_travelled += seg_travel; } prevcoord = coord; } return prevcoord; } GeoCoder::GeoCoder(const char *dbname) : latlng_re(LATLNG_REGEX, PCRE_CASELESS) { db = NULL; int rc = sqlite3_open(dbname, &db); if (rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); assert(0 && "Couldn't initialize geocoder!!!!"); } parser = shared_ptr<GeoParser>(new GeoParser(db)); } static int sqlite_intersection_cb(void *userdata, int argc, char **argv, char **azColName) { pair<float, float> **latlng = (pair<float, float> **)userdata; (*latlng) = new pair<float, float>(atof(argv[0]), atof(argv[1])); return 0; } static int sqlite_address_cb(void *userdata, int argc, char **argv, char **azColName) { pair<pair<float, float> *, int> * addr_tuple = (pair<pair<float, float> *, int> *)userdata; int first_number = atol(argv[0]); int last_number = atol(argv[1]); float percent = 0.5; if (addr_tuple->second) percent = ((float)(addr_tuple->second - first_number)) / ( (float)(last_number - (float)first_number)); float length = atof(argv[2]); long num_points = *(reinterpret_cast<long *>(&argv[3][0])); float *latlng_array = (reinterpret_cast<float *>(&argv[3][sizeof(long)])); addr_tuple->first = new pair<float,float>(interpolated_latlng(latlng_array, num_points, length, percent)); return 0; } pair<float, float> * GeoCoder::get_latlng(const char *str) { // before anything else, see if we're being passed a latlng pair. if so, // just pass it through string lat, lng; if (latlng_re.FullMatch(str, &lat, &lng)) return new pair<float, float>(atof(lat.c_str()), atof(lng.c_str())); Address *addr = parser->parse_address(str); if (addr && addr->is_intersection()) { pair<float, float> *latlng = NULL; // sql db assumes first road name in intersection is less than // (case insensitive) than the second. we swap them to satisfy this // condition Address *addr1 = addr, *addr2 = addr->cross_street; if (strcasecmp(addr->street.c_str(), addr->cross_street->street.c_str()) > 0) { addr1 = addr->cross_street; addr2 = addr; } stringstream sqlstr; sqlstr << "select lat,lng from intersection where "; sqlstr << "name1 like '" << addr1->street << "' "; sqlstr << " and name2 like '" << addr2->street << "'"; sqlstr << " limit 1"; char *zErrMsg = 0; NEODEBUG("SQL: %s\n", sqlstr.str().c_str()); int rc = sqlite3_exec(db, sqlstr.str().c_str(), sqlite_intersection_cb, &latlng, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); // we silently fail in this case... maybe it would be better to // just assert? } return latlng; } if (addr && !addr->street.empty()) { pair<pair<float, float> *, int> addr_tuple(NULL, addr->number); stringstream sqlstr; sqlstr << "select firstHouseNumber, lastHouseNumber, length, coords " "from road where "; sqlstr << "name like '" << addr->street << "' "; if (addr->suffix) sqlstr << "and suffixType==" << addr->suffix << " "; if (addr->direction) sqlstr << "and direction==" << addr->direction << " "; if (addr->number) { sqlstr << "and firstHouseNumber <= '" << addr->number << "' "; sqlstr << "and lastHouseNumber >= '" << addr->number << "' "; } if (addr->region.size()) { sqlstr << "and placeName like '" << addr->region << "' "; } sqlstr << "limit 1"; char *zErrMsg = 0; NEODEBUG("SQL: %s\n", sqlstr.str().c_str()); int rc = sqlite3_exec(db, sqlstr.str().c_str(), sqlite_address_cb, &addr_tuple, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); // we silently fail in this case... maybe it would be better to // just assert? } return addr_tuple.first; } return NULL; } <|endoftext|>