text
stringlengths
54
60.6k
<commit_before>61ae1464-2e4e-11e5-9284-b827eb9e62be<commit_msg>61b321f2-2e4e-11e5-9284-b827eb9e62be<commit_after>61b321f2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>77f1372a-2e4d-11e5-9284-b827eb9e62be<commit_msg>77f6276c-2e4d-11e5-9284-b827eb9e62be<commit_after>77f6276c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fb40282e-2e4e-11e5-9284-b827eb9e62be<commit_msg>fb453a4e-2e4e-11e5-9284-b827eb9e62be<commit_after>fb453a4e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f1532cd6-2e4d-11e5-9284-b827eb9e62be<commit_msg>f15845f4-2e4d-11e5-9284-b827eb9e62be<commit_after>f15845f4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6a5baf04-2e4e-11e5-9284-b827eb9e62be<commit_msg>6a60a5f4-2e4e-11e5-9284-b827eb9e62be<commit_after>6a60a5f4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cd83fd34-2e4e-11e5-9284-b827eb9e62be<commit_msg>cd8951bc-2e4e-11e5-9284-b827eb9e62be<commit_after>cd8951bc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>09bc57c0-2e4e-11e5-9284-b827eb9e62be<commit_msg>09c17638-2e4e-11e5-9284-b827eb9e62be<commit_after>09c17638-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ddc3d4b4-2e4c-11e5-9284-b827eb9e62be<commit_msg>ddc8c62c-2e4c-11e5-9284-b827eb9e62be<commit_after>ddc8c62c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cae366c4-2e4d-11e5-9284-b827eb9e62be<commit_msg>cae85d6e-2e4d-11e5-9284-b827eb9e62be<commit_after>cae85d6e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>281fc228-2e4f-11e5-9284-b827eb9e62be<commit_msg>2824b7b0-2e4f-11e5-9284-b827eb9e62be<commit_after>2824b7b0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d4e4cb64-2e4c-11e5-9284-b827eb9e62be<commit_msg>d4e9d550-2e4c-11e5-9284-b827eb9e62be<commit_after>d4e9d550-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>85a0355a-2e4e-11e5-9284-b827eb9e62be<commit_msg>85a53a1e-2e4e-11e5-9284-b827eb9e62be<commit_after>85a53a1e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f54f350e-2e4e-11e5-9284-b827eb9e62be<commit_msg>f55436b2-2e4e-11e5-9284-b827eb9e62be<commit_after>f55436b2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before><commit_msg>d6d70a18-2e4c-11e5-9284-b827eb9e62be<commit_after><|endoftext|>
<commit_before>fb16ab2a-2e4e-11e5-9284-b827eb9e62be<commit_msg>fb1ba8e6-2e4e-11e5-9284-b827eb9e62be<commit_after>fb1ba8e6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6d4f8e7a-2e4d-11e5-9284-b827eb9e62be<commit_msg>6d549b18-2e4d-11e5-9284-b827eb9e62be<commit_after>6d549b18-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bfe7d6f2-2e4c-11e5-9284-b827eb9e62be<commit_msg>bfecd8d2-2e4c-11e5-9284-b827eb9e62be<commit_after>bfecd8d2-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>80389f72-2e4d-11e5-9284-b827eb9e62be<commit_msg>803d8f28-2e4d-11e5-9284-b827eb9e62be<commit_after>803d8f28-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>47dee7a8-2e4d-11e5-9284-b827eb9e62be<commit_msg>47e3fa90-2e4d-11e5-9284-b827eb9e62be<commit_after>47e3fa90-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fd10f25c-2e4c-11e5-9284-b827eb9e62be<commit_msg>fd15e5dc-2e4c-11e5-9284-b827eb9e62be<commit_after>fd15e5dc-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2c46a952-2e4f-11e5-9284-b827eb9e62be<commit_msg>2c4baa60-2e4f-11e5-9284-b827eb9e62be<commit_after>2c4baa60-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aeda1b9a-2e4c-11e5-9284-b827eb9e62be<commit_msg>aedf165e-2e4c-11e5-9284-b827eb9e62be<commit_after>aedf165e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7b630734-2e4e-11e5-9284-b827eb9e62be<commit_msg>7b681b5c-2e4e-11e5-9284-b827eb9e62be<commit_after>7b681b5c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include "lua_class.h" #include "../table/table.h" namespace saki { void setupLuaClasses(sol::environment env, LuaUserErrorHandler &error) { setupLuaTile(env, error); setupLuaWho(env); setupLuaMeld(env); setupLuaMount(env); setupLuaTileCount(env); setupLuaHand(env); setupLuaGame(env); } void setupLuaTile(sol::environment env, LuaUserErrorHandler &error) { env.new_enum<Suit>( "Suit", { { "M", Suit::M }, { "P", Suit::P }, { "S", Suit::S }, { "F", Suit::F }, { "Y", Suit::Y } } ); env.new_usertype<T34>( "T34", sol::meta_function::construct, sol::factories( [&error](int ti) { if (ti < 0 || ti >= 34) { error.handleUserError("invalid T34 id"); return T34(); } return T34(ti); }, [&error](Suit s, int v) { if (!(1 <= v && v <= 9)) { error.handleUserError("invalid T34 val"); return T34(); } return T34(s, v); }, [&error](const std::string s) { static const std::array<std::string, 34> dict { "1m", "2m", "3m", "4m", "5m", "6m", "7m", "8m", "9m", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "1s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "1f", "2f", "3f", "4f", "1y", "2y", "3y" }; auto it = std::find(dict.begin(), dict.end(), s); if (it == dict.end()) { error.handleUserError("invalid T34 string"); return T34(); } return T34(it - dict.begin()); } ), "id34", &T34::id34, "isyakuhai", &T34::isYakuhai, sol::meta_function::to_string, &T34::str, "all", sol::var(std::vector<T34>(tiles34::ALL34.begin(), tiles34::ALL34.end())) ); } void setupLuaWho(sol::environment env) { env.new_usertype<Who>( "Who", "right", &Who::right, "cross", &Who::cross, "left", &Who::left, sol::meta_function::to_string, &Who::index, sol::meta_function::equal_to, &Who::operator== ); } void setupLuaMeld(sol::environment env) { env.new_usertype<M37>( "M37", "type", &M37::type, sol::meta_function::index, &M37::operator[] ); sol::table m37 = env["M37"]; m37.new_enum<M37::Type>( "Type", { { "CHII", M37::Type::CHII }, { "PON", M37::Type::PON }, { "DAIMINKAN", M37::Type::DAIMINKAN }, { "ANKAN", M37::Type::ANKAN }, { "KAKAN", M37::Type::KAKAN } } ); } void setupLuaMount(sol::environment env) { env.new_usertype<Mount>( "Mount", "lighta", sol::overload( [](Mount &mount, T34 t, int mk, bool rin) { mount.lightA(t, mk, rin); }, [](Mount &mount, T34 t, int mk) { mount.lightA(t, mk); } ) ); } void setupLuaTileCount(sol::environment env) { env.new_usertype<TileCount>( "Tilecount", "ct", sol::overload( [](const TileCount &tc, T34 t) { return tc.ct(t); }, [](const TileCount &tc, Suit s) { return tc.ct(s); } ) ); } void setupLuaHand(sol::environment env) { env.new_usertype<Hand>( "Hand", "closed", &Hand::closed, "ct", &Hand::ct, "ready", &Hand::ready, "step", &Hand::step, "step4", &Hand::step4, "step7", &Hand::step7, "step13", &Hand::step13, "effa", &Hand::effA, "effa4", &Hand::effA4, "ismenzen", &Hand::isMenzen, "barks", &Hand::barks ); } void setupLuaGame(sol::environment env) { env.new_usertype<Table>( "Game", "gethand", &Table::getHand, "getround", &Table::getRound, "getextraround", &Table::getExtraRound, "getdealer", &Table::getDealer, "getselfwind", &Table::getSelfWind, "getroundwind", &Table::getRoundWind ); } } // namespace saki <commit_msg>add common mount funcs to lua api<commit_after>#include "lua_class.h" #include "../table/table.h" namespace saki { void setupLuaClasses(sol::environment env, LuaUserErrorHandler &error) { setupLuaTile(env, error); setupLuaWho(env); setupLuaMeld(env); setupLuaMount(env); setupLuaTileCount(env); setupLuaHand(env); setupLuaGame(env); } void setupLuaTile(sol::environment env, LuaUserErrorHandler &error) { env.new_enum<Suit>( "Suit", { { "M", Suit::M }, { "P", Suit::P }, { "S", Suit::S }, { "F", Suit::F }, { "Y", Suit::Y } } ); env.new_usertype<T34>( "T34", sol::meta_function::construct, sol::factories( [&error](int ti) { if (ti < 0 || ti >= 34) { error.handleUserError("invalid T34 id"); return T34(); } return T34(ti); }, [&error](Suit s, int v) { if (!(1 <= v && v <= 9)) { error.handleUserError("invalid T34 val"); return T34(); } return T34(s, v); }, [&error](const std::string s) { static const std::array<std::string, 34> dict { "1m", "2m", "3m", "4m", "5m", "6m", "7m", "8m", "9m", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "1s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "1f", "2f", "3f", "4f", "1y", "2y", "3y" }; auto it = std::find(dict.begin(), dict.end(), s); if (it == dict.end()) { error.handleUserError("invalid T34 string"); return T34(); } return T34(it - dict.begin()); } ), "id34", &T34::id34, "isyakuhai", &T34::isYakuhai, sol::meta_function::to_string, &T34::str, "all", sol::var(std::vector<T34>(tiles34::ALL34.begin(), tiles34::ALL34.end())) ); } void setupLuaWho(sol::environment env) { env.new_usertype<Who>( "Who", "right", &Who::right, "cross", &Who::cross, "left", &Who::left, sol::meta_function::to_string, &Who::index, sol::meta_function::equal_to, &Who::operator== ); } void setupLuaMeld(sol::environment env) { env.new_usertype<M37>( "M37", "type", &M37::type, sol::meta_function::index, &M37::operator[] ); sol::table m37 = env["M37"]; m37.new_enum<M37::Type>( "Type", { { "CHII", M37::Type::CHII }, { "PON", M37::Type::PON }, { "DAIMINKAN", M37::Type::DAIMINKAN }, { "ANKAN", M37::Type::ANKAN }, { "KAKAN", M37::Type::KAKAN } } ); } void setupLuaMount(sol::environment env) { env.new_usertype<Mount>( "Mount", "remainpii", &Mount::remainPii, "remainrinshan", &Mount::remainRinshan, "remaina", sol::overload( [](Mount &mount, T34 t) { mount.remainA(t); }, [](Mount &mount, const T37 &t) { mount.remainA(t); } ), "getdrids", &Mount::getDrids, "geturids", &Mount::getUrids, "lighta", sol::overload( [](Mount &mount, T34 t, int mk, bool rin) { mount.lightA(t, mk, rin); }, [](Mount &mount, T34 t, int mk) { mount.lightA(t, mk); } ), "lightb", sol::overload( [](Mount &mount, T34 t, int mk, bool rin) { mount.lightB(t, mk, rin); }, [](Mount &mount, T34 t, int mk) { mount.lightB(t, mk); } ), "incmk", sol::overload( [](Mount &mount, Mount::Exit exit, size_t pos, T34 t, int delta, bool bSpace) { mount.incMk(exit, pos, t, delta, bSpace); }, [](Mount &mount, Mount::Exit exit, size_t pos, const T37 &t, int delta, bool bSpace) { mount.incMk(exit, pos, t, delta, bSpace); } ), "loadB", &Mount::loadB, "dump", [](Mount &mount){ (void) mount; // TODO return a table of mk } ); sol::table m37 = env["Mount"]; m37.new_enum<Mount::Exit>( "Exit", { { "PII", Mount::Exit::PII }, { "RINSHAN", Mount::Exit::RINSHAN }, { "DORAHYOU", Mount::Exit::DORAHYOU }, { "URAHYOU", Mount::Exit::URAHYOU } } ); } void setupLuaTileCount(sol::environment env) { env.new_usertype<TileCount>( "Tilecount", "ct", sol::overload( [](const TileCount &tc, T34 t) { return tc.ct(t); }, [](const TileCount &tc, Suit s) { return tc.ct(s); } ) ); } void setupLuaHand(sol::environment env) { env.new_usertype<Hand>( "Hand", "closed", &Hand::closed, "ct", &Hand::ct, "ready", &Hand::ready, "step", &Hand::step, "step4", &Hand::step4, "step7", &Hand::step7, "step13", &Hand::step13, "effa", &Hand::effA, "effa4", &Hand::effA4, "ismenzen", &Hand::isMenzen, "barks", &Hand::barks ); } void setupLuaGame(sol::environment env) { env.new_usertype<Table>( "Game", "gethand", &Table::getHand, "getround", &Table::getRound, "getextraround", &Table::getExtraRound, "getdealer", &Table::getDealer, "getselfwind", &Table::getSelfWind, "getroundwind", &Table::getRoundWind ); } } // namespace saki <|endoftext|>
<commit_before>#include <iomanip> //std::setw #include <iostream> //std::cout, std::cerr #include <string> //std::string, std::to_string #include <vector> //std::vector #include <dirent.h> //dirent, opendir, readdir #include <errno.h> //errno #include <grp.h> //getgrgid #include <pwd.h> //getpwuid #include <stdio.h> //perror, putchar #include <string.h> //strerror #include <sys/stat.h> //st_mode, st_mtime, S_IFDIR, S_IRUSR, ... #include <time.h> //time_t, tm #include "parse.h" //FLAG_a, FLAG_l, FLAG_R #include "execute.h" void execute(const std::vector<const char*> files, const std::vector<const char*> directories, int flags) { print_files(files); if (files.empty()) { if (directories.empty()) print_directory(".", flags); else if (directories.size() == 1) print_directory(directories[0], flags); else { std::cout << directories[0] << ": " << std::endl; print_directory(directories[0], flags); for (size_t i = 1; i < directories.size(); ++i) print_directory(directories[i], flags, true); } } else { for (size_t i = 0; i < directories.size(); ++i) print_directory(directories[i], flags, true); } } void print_directory(const char *directory, int flags, bool extra) { DIR *dir_ptr = opendir(directory); if (dir_ptr == NULL) { perror("opendir"); return; } if (extra) std::cout << std::endl << directory << ": " << std::endl; std::vector<const char*> files; std::vector<std::string> directory_paths; std::vector<std::string> paths; dirent *entry; while ((entry = readdir(dir_ptr))) { if (entry->d_name[0] != '.' || (flags & FLAG_a)) { std::string path = directory; path += "/" + (std::string)entry->d_name; paths.push_back(path); files.push_back(entry->d_name); struct stat s; if (stat(path.c_str(), &s) == 0) { if (flags & FLAG_R) { //track directories if recursing if (s.st_mode & S_IFDIR) directory_paths.push_back(path); } } else { perror("stat"); return; } } } if (errno) { perror("readdir"); return; } if (closedir(dir_ptr) == -1) { perror("closedir"); return; } if (flags & FLAG_l) print_long(paths, files); else print_files(files); if (flags & FLAG_R) { for (size_t i = 0; i < directory_paths.size(); ++i) { print_directory(directory_paths[i].c_str(), flags, true); } } } void print_files(std::vector<const char*> files) { for (size_t i = 0; i < files.size(); ++i) std::cout << files[i] << std::endl; } void print_long(std::vector<std::string> paths, std::vector<const char*> files) { const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; std::vector<std::string> permissions; std::vector<nlink_t> links; std::vector<const char*> users; std::vector<const char*> groups; std::vector<off_t> sizes; size_t link_max = 0; size_t user_max = 0; size_t group_max = 0; size_t size_max = 0; std::vector<std::string> dates; for (size_t i = 0; i < paths.size(); ++i) { struct stat s; if (stat(paths[i].c_str(), &s) == 0) { std::string permission; permission += (s.st_mode & S_IFDIR ? 'd' : '-'); permission += (s.st_mode & S_IRUSR ? 'r' : '-'); permission += (s.st_mode & S_IWUSR ? 'w' : '-'); permission += (s.st_mode & S_IXUSR ? 'x' : '-'); permission += (s.st_mode & S_IRGRP ? 'r' : '-'); permission += (s.st_mode & S_IWGRP ? 'w' : '-'); permission += (s.st_mode & S_IXGRP ? 'x' : '-'); permission += (s.st_mode & S_IROTH ? 'r' : '-'); permission += (s.st_mode & S_IWOTH ? 'w' : '-'); permission += (s.st_mode & S_IXOTH ? 'x' : '-'); permissions.push_back(permission); std::string slink = std::to_string(s.st_nlink); if (link_max < slink.size()) link_max = slink.size(); links.push_back(s.st_nlink); const char* user = getpwuid(s.st_uid)->pw_name; if (user_max < strlen(user)) user_max = strlen(user); users.push_back(user); const char* group = getgrgid(s.st_gid)->gr_name; if (group_max < strlen(group)) group_max = strlen(group); groups.push_back(group); std::string ssize = std::to_string(s.st_size); if (size_max < ssize.size()) size_max = ssize.size(); sizes.push_back(s.st_size); time_t mtime = s.st_mtime; tm *ltm = localtime(&mtime); std::string date; date += months[ltm->tm_mon]; date += ' '; if (ltm->tm_mday < 10) date += ' '; date += std::to_string(ltm->tm_mday); date += ' '; if (ltm->tm_hour < 10) date += '0'; date += std::to_string(ltm->tm_hour); date += ':'; if (ltm->tm_min < 10) date += '0'; date += std::to_string(ltm->tm_min); dates.push_back(date); } else { perror("stat"); return; } } for (size_t i = 0; i < permissions.size(); ++i) { std::cout << permissions[i] << ' ' << std::setw(link_max) << links[i] << ' ' << std::setw(user_max) << users[i] << ' ' << std::setw(group_max) << groups[i] << ' ' << std::setw(size_max) << sizes[i] << ' ' << dates[i] << ' '; struct stat s; if (stat(paths[i].c_str(), &s) == 0) { if (s.st_mode & S_IFDIR) std::cout << "\x1b[34m"; else if (s.st_mode & S_IXUSR) std::cout << "\x1b[32m"; std::cout << files[i] << "\x1b[0m" << std::endl; } else { perror("stat"); return; } } } <commit_msg>used stringstream instead of to_string<commit_after>#include <iomanip> //std::setw #include <iostream> //std::cout, std::cerr #include <sstream> //std::stringstream #include <string> //std::string #include <vector> //std::vector #include <dirent.h> //dirent, opendir, readdir #include <errno.h> //errno #include <grp.h> //getgrgid #include <pwd.h> //getpwuid #include <stdio.h> //perror, putchar #include <string.h> //strerror #include <sys/stat.h> //st_mode, st_mtime, S_IFDIR, S_IRUSR, ... #include <time.h> //time_t, tm #include "parse.h" //FLAG_a, FLAG_l, FLAG_R #include "execute.h" void execute(const std::vector<const char*> files, const std::vector<const char*> directories, int flags) { print_files(files); if (files.empty()) { if (directories.empty()) print_directory(".", flags); else if (directories.size() == 1) print_directory(directories[0], flags); else { std::cout << directories[0] << ": " << std::endl; print_directory(directories[0], flags); for (size_t i = 1; i < directories.size(); ++i) print_directory(directories[i], flags, true); } } else { for (size_t i = 0; i < directories.size(); ++i) print_directory(directories[i], flags, true); } } void print_directory(const char *directory, int flags, bool extra) { DIR *dir_ptr = opendir(directory); if (dir_ptr == NULL) { perror("opendir"); return; } if (extra) std::cout << std::endl << directory << ": " << std::endl; std::vector<const char*> files; std::vector<std::string> directory_paths; std::vector<std::string> paths; dirent *entry; while ((entry = readdir(dir_ptr))) { if (entry->d_name[0] != '.' || (flags & FLAG_a)) { std::string path = directory; path += "/" + (std::string)entry->d_name; paths.push_back(path); files.push_back(entry->d_name); struct stat s; if (stat(path.c_str(), &s) == 0) { if (flags & FLAG_R) { //track directories if recursing if (s.st_mode & S_IFDIR) directory_paths.push_back(path); } } else { perror("stat"); return; } } } if (errno) { perror("readdir"); return; } if (closedir(dir_ptr) == -1) { perror("closedir"); return; } if (flags & FLAG_l) print_long(paths, files); else print_files(files); if (flags & FLAG_R) { for (size_t i = 0; i < directory_paths.size(); ++i) { print_directory(directory_paths[i].c_str(), flags, true); } } } void print_files(std::vector<const char*> files) { for (size_t i = 0; i < files.size(); ++i) std::cout << files[i] << std::endl; } void print_long(std::vector<std::string> paths, std::vector<const char*> files) { const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; std::vector<std::string> permissions; std::vector<nlink_t> links; std::vector<const char*> users; std::vector<const char*> groups; std::vector<off_t> sizes; size_t link_max = 0; size_t user_max = 0; size_t group_max = 0; size_t size_max = 0; std::vector<std::string> dates; for (size_t i = 0; i < paths.size(); ++i) { struct stat s; if (stat(paths[i].c_str(), &s) == 0) { std::stringstream ss; std::string permission; permission += (s.st_mode & S_IFDIR ? 'd' : '-'); permission += (s.st_mode & S_IRUSR ? 'r' : '-'); permission += (s.st_mode & S_IWUSR ? 'w' : '-'); permission += (s.st_mode & S_IXUSR ? 'x' : '-'); permission += (s.st_mode & S_IRGRP ? 'r' : '-'); permission += (s.st_mode & S_IWGRP ? 'w' : '-'); permission += (s.st_mode & S_IXGRP ? 'x' : '-'); permission += (s.st_mode & S_IROTH ? 'r' : '-'); permission += (s.st_mode & S_IWOTH ? 'w' : '-'); permission += (s.st_mode & S_IXOTH ? 'x' : '-'); permissions.push_back(permission); ss << s.st_nlink; std::string slink = ss.str(); ss.str(""); if (link_max < slink.size()) link_max = slink.size(); links.push_back(s.st_nlink); const char* user = getpwuid(s.st_uid)->pw_name; if (user_max < strlen(user)) user_max = strlen(user); users.push_back(user); const char* group = getgrgid(s.st_gid)->gr_name; if (group_max < strlen(group)) group_max = strlen(group); groups.push_back(group); ss << s.st_size; std::string ssize = ss.str(); ss.str(""); if (size_max < ssize.size()) size_max = ssize.size(); std::cout << "size max: " << size_max << std::endl; sizes.push_back(s.st_size); time_t mtime = s.st_mtime; tm *ltm = localtime(&mtime); std::string date; date += months[ltm->tm_mon]; date += ' '; if (ltm->tm_mday < 10) date += ' '; ss << ltm->tm_mday << ' '; date += ss.str(); ss.str(""); if (ltm->tm_hour < 10) date += '0'; ss << ltm->tm_hour << ':'; date += ss.str(); ss.str(""); if (ltm->tm_min < 10) date += '0'; ss << ltm->tm_min; date += ss.str(); ss.str(""); dates.push_back(date); } else { perror("stat"); return; } } for (size_t i = 0; i < permissions.size(); ++i) { std::cout << permissions[i] << ' ' << std::setw(link_max) << links[i] << ' ' << std::setw(user_max) << users[i] << ' ' << std::setw(group_max) << groups[i] << ' ' << std::setw(size_max) << sizes[i] << ' ' << dates[i] << ' '; struct stat s; if (stat(paths[i].c_str(), &s) == 0) { if (s.st_mode & S_IFDIR) std::cout << "\x1b[34m"; else if (s.st_mode & S_IXUSR) std::cout << "\x1b[32m"; std::cout << files[i] << "\x1b[0m" << std::endl; } else { perror("stat"); return; } } } <|endoftext|>
<commit_before><commit_msg>Add Solution 2<commit_after><|endoftext|>
<commit_before><commit_msg>fix: flushOneDelOrSet race in evaluation of item state<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_accessibility.hxx" #include <accessibility/standard/vclxaccessiblebox.hxx> #include <accessibility/standard/vclxaccessibletextfield.hxx> #include <accessibility/standard/vclxaccessibleedit.hxx> #include <accessibility/standard/vclxaccessiblelist.hxx> #include <accessibility/standard/vclxaccessiblelistboxlist.hxx> #include <accessibility/helper/listboxhelper.hxx> #include <unotools/accessiblestatesethelper.hxx> #include <com/sun/star/accessibility/AccessibleStateType.hpp> #include <com/sun/star/accessibility/AccessibleEventId.hpp> #include <com/sun/star/accessibility/AccessibleRole.hpp> #include <vcl/svapp.hxx> #include <vcl/combobox.hxx> #include <vcl/lstbox.hxx> #include <accessibility/helper/accresmgr.hxx> #include <accessibility/helper/accessiblestrings.hrc> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::accessibility; VCLXAccessibleBox::VCLXAccessibleBox (VCLXWindow* pVCLWindow, BoxType aType, bool bIsDropDownBox) : VCLXAccessibleComponent (pVCLWindow), m_aBoxType (aType), m_bIsDropDownBox (bIsDropDownBox), m_nIndexInParent (DEFAULT_INDEX_IN_PARENT) { // Set up the flags that indicate which children this object has. m_bHasListChild = true; // A text field is not present for non drop down list boxes. if ((m_aBoxType==LISTBOX) && ! m_bIsDropDownBox) m_bHasTextChild = false; else m_bHasTextChild = true; } VCLXAccessibleBox::~VCLXAccessibleBox (void) { } void VCLXAccessibleBox::ProcessWindowChildEvent( const VclWindowEvent& rVclWindowEvent ) { uno::Any aOldValue, aNewValue; uno::Reference<XAccessible> xAcc; switch ( rVclWindowEvent.GetId() ) { case VCLEVENT_WINDOW_SHOW: case VCLEVENT_WINDOW_HIDE: { Window* pChildWindow = (Window *) rVclWindowEvent.GetData(); // Just compare to the combo box text field. All other children // are identical to this object in which case this object will // be removed in a short time. if (m_aBoxType==COMBOBOX) { ComboBox* pComboBox = static_cast<ComboBox*>(GetWindow()); if ( ( pComboBox != NULL ) && ( pChildWindow != NULL ) ) if (pChildWindow == pComboBox->GetSubEdit()) { if (rVclWindowEvent.GetId() == VCLEVENT_WINDOW_SHOW) { // Instantiate text field. getAccessibleChild (0); aNewValue <<= m_xText; } else { // Release text field. aOldValue <<= m_xText; m_xText = NULL; } // Tell the listeners about the new/removed child. NotifyAccessibleEvent ( AccessibleEventId::CHILD, aOldValue, aNewValue); } } } break; default: VCLXAccessibleComponent::ProcessWindowChildEvent (rVclWindowEvent); } } void VCLXAccessibleBox::ProcessWindowEvent (const VclWindowEvent& rVclWindowEvent) { switch ( rVclWindowEvent.GetId() ) { case VCLEVENT_DROPDOWN_OPEN: case VCLEVENT_DROPDOWN_CLOSE: case VCLEVENT_LISTBOX_DOUBLECLICK: case VCLEVENT_LISTBOX_SCROLLED: case VCLEVENT_LISTBOX_SELECT: case VCLEVENT_LISTBOX_ITEMADDED: case VCLEVENT_LISTBOX_ITEMREMOVED: case VCLEVENT_COMBOBOX_ITEMADDED: case VCLEVENT_COMBOBOX_ITEMREMOVED: case VCLEVENT_COMBOBOX_SCROLLED: { // Forward the call to the list child. VCLXAccessibleList* pList = static_cast<VCLXAccessibleList*>(m_xList.get()); if ( pList == NULL ) { getAccessibleChild ( m_bHasTextChild ? 1 : 0 ); pList = static_cast<VCLXAccessibleList*>(m_xList.get()); } if ( pList != NULL ) pList->ProcessWindowEvent (rVclWindowEvent); break; } case VCLEVENT_COMBOBOX_SELECT: case VCLEVENT_COMBOBOX_DESELECT: { // Selection is handled by VCLXAccessibleList which operates on // the same VCL object as this box does. In case of the // combobox, however, we have to help the list with providing // the text of the currently selected item. VCLXAccessibleList* pList = static_cast<VCLXAccessibleList*>(m_xList.get()); if (pList != NULL && m_xText.is()) { Reference<XAccessibleText> xText (m_xText->getAccessibleContext(), UNO_QUERY); if ( xText.is() ) { ::rtl::OUString sText = xText->getSelectedText(); if ( !sText.getLength() ) sText = xText->getText(); pList->UpdateSelection (sText); } } break; } case VCLEVENT_EDIT_MODIFY: case VCLEVENT_EDIT_SELECTIONCHANGED: // Modify/Selection events are handled by the combo box instead of // directly by the edit field (Why?). Therefore, delegate this // call to the edit field. if (m_aBoxType==COMBOBOX) { if (m_xText.is()) { Reference<XAccessibleContext> xContext = m_xText->getAccessibleContext(); VCLXAccessibleEdit* pEdit = static_cast<VCLXAccessibleEdit*>(xContext.get()); if (pEdit != NULL) pEdit->ProcessWindowEvent (rVclWindowEvent); } } break; default: VCLXAccessibleComponent::ProcessWindowEvent( rVclWindowEvent ); } } IMPLEMENT_FORWARD_XINTERFACE2(VCLXAccessibleBox, VCLXAccessibleComponent, VCLXAccessibleBox_BASE) IMPLEMENT_FORWARD_XTYPEPROVIDER2(VCLXAccessibleBox, VCLXAccessibleComponent, VCLXAccessibleBox_BASE) //===== XAccessible ========================================================= Reference< XAccessibleContext > SAL_CALL VCLXAccessibleBox::getAccessibleContext( ) throw (RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); return this; } //===== XAccessibleContext ================================================== sal_Int32 SAL_CALL VCLXAccessibleBox::getAccessibleChildCount (void) throw (RuntimeException) { vos::OGuard aSolarGuard( Application::GetSolarMutex() ); ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); // Usually a box has a text field and a list of items as its children. // Non drop down list boxes have no text field. Additionally check // whether the object is valid. sal_Int32 nCount = 0; if (IsValid()) nCount += (m_bHasTextChild?1:0) + (m_bHasListChild?1:0); else { // Object not valid anymore. Release references to children. m_bHasTextChild = false; m_xText = NULL; m_bHasListChild = false; m_xList = NULL; } return nCount; } Reference<XAccessible> SAL_CALL VCLXAccessibleBox::getAccessibleChild (sal_Int32 i) throw (IndexOutOfBoundsException, RuntimeException) { vos::OGuard aSolarGuard( Application::GetSolarMutex() ); ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); if (i<0 || i>=getAccessibleChildCount()) throw IndexOutOfBoundsException(); Reference< XAccessible > xChild; if (IsValid()) { if (i==1 || ! m_bHasTextChild) { // List. if ( ! m_xList.is()) { VCLXAccessibleList* pList = new VCLXAccessibleList ( GetVCLXWindow(), (m_aBoxType == LISTBOX ? VCLXAccessibleList::LISTBOX : VCLXAccessibleList::COMBOBOX), this); pList->SetIndexInParent (i); m_xList = pList; } xChild = m_xList; } else { // Text Field. if ( ! m_xText.is()) { if (m_aBoxType==COMBOBOX) { ComboBox* pComboBox = static_cast<ComboBox*>(GetWindow()); if (pComboBox!=NULL && pComboBox->GetSubEdit()!=NULL) m_xText = pComboBox->GetSubEdit()->GetAccessible(); } else if (m_bIsDropDownBox) m_xText = new VCLXAccessibleTextField (GetVCLXWindow(),this); } xChild = m_xText; } } return xChild; } sal_Int16 SAL_CALL VCLXAccessibleBox::getAccessibleRole (void) throw (RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); // Return the role <const>COMBO_BOX</const> for both VCL combo boxes and // VCL list boxes in DropDown-Mode else <const>PANEL</const>. // This way the Java bridge has not to handle both independently. return m_bIsDropDownBox ? AccessibleRole::COMBO_BOX : AccessibleRole::PANEL; } sal_Int32 SAL_CALL VCLXAccessibleBox::getAccessibleIndexInParent (void) throw (::com::sun::star::uno::RuntimeException) { if (m_nIndexInParent != DEFAULT_INDEX_IN_PARENT) return m_nIndexInParent; else return VCLXAccessibleComponent::getAccessibleIndexInParent(); } //===== XAccessibleAction =================================================== sal_Int32 SAL_CALL VCLXAccessibleBox::getAccessibleActionCount (void) throw (RuntimeException) { ::osl::Guard< ::osl::Mutex> aGuard (GetMutex()); // There is one action for drop down boxes (toggle popup) and none for // the other boxes. return m_bIsDropDownBox ? 1 : 0; } sal_Bool SAL_CALL VCLXAccessibleBox::doAccessibleAction (sal_Int32 nIndex) throw (IndexOutOfBoundsException, RuntimeException) { sal_Bool bNotify = sal_False; { vos::OGuard aSolarGuard( Application::GetSolarMutex() ); ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); if (nIndex<0 || nIndex>=getAccessibleActionCount()) throw ::com::sun::star::lang::IndexOutOfBoundsException(); if (m_aBoxType == COMBOBOX) { ComboBox* pComboBox = static_cast< ComboBox* >( GetWindow() ); if (pComboBox != NULL) { pComboBox->ToggleDropDown(); bNotify = sal_True; } } else if (m_aBoxType == LISTBOX) { ListBox* pListBox = static_cast< ListBox* >( GetWindow() ); if (pListBox != NULL) { pListBox->ToggleDropDown(); bNotify = sal_True; } } } if (bNotify) NotifyAccessibleEvent (AccessibleEventId::ACTION_CHANGED, Any(), Any()); return bNotify; } ::rtl::OUString SAL_CALL VCLXAccessibleBox::getAccessibleActionDescription (sal_Int32 nIndex) throw (IndexOutOfBoundsException, RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); if (nIndex<0 || nIndex>=getAccessibleActionCount()) throw ::com::sun::star::lang::IndexOutOfBoundsException(); return TK_RES_STRING( RID_STR_ACC_ACTION_TOGGLEPOPUP); } Reference< XAccessibleKeyBinding > VCLXAccessibleBox::getAccessibleActionKeyBinding( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); Reference< XAccessibleKeyBinding > xRet; if (nIndex<0 || nIndex>=getAccessibleActionCount()) throw ::com::sun::star::lang::IndexOutOfBoundsException(); // ... which key? return xRet; } //===== XComponent ========================================================== void SAL_CALL VCLXAccessibleBox::disposing (void) { VCLXAccessibleComponent::disposing(); } <commit_msg>accfixes: removed include of obsolete header file<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_accessibility.hxx" #include <accessibility/standard/vclxaccessiblebox.hxx> #include <accessibility/standard/vclxaccessibletextfield.hxx> #include <accessibility/standard/vclxaccessibleedit.hxx> #include <accessibility/standard/vclxaccessiblelist.hxx> #include <accessibility/helper/listboxhelper.hxx> #include <unotools/accessiblestatesethelper.hxx> #include <com/sun/star/accessibility/AccessibleStateType.hpp> #include <com/sun/star/accessibility/AccessibleEventId.hpp> #include <com/sun/star/accessibility/AccessibleRole.hpp> #include <vcl/svapp.hxx> #include <vcl/combobox.hxx> #include <vcl/lstbox.hxx> #include <accessibility/helper/accresmgr.hxx> #include <accessibility/helper/accessiblestrings.hrc> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::accessibility; VCLXAccessibleBox::VCLXAccessibleBox (VCLXWindow* pVCLWindow, BoxType aType, bool bIsDropDownBox) : VCLXAccessibleComponent (pVCLWindow), m_aBoxType (aType), m_bIsDropDownBox (bIsDropDownBox), m_nIndexInParent (DEFAULT_INDEX_IN_PARENT) { // Set up the flags that indicate which children this object has. m_bHasListChild = true; // A text field is not present for non drop down list boxes. if ((m_aBoxType==LISTBOX) && ! m_bIsDropDownBox) m_bHasTextChild = false; else m_bHasTextChild = true; } VCLXAccessibleBox::~VCLXAccessibleBox (void) { } void VCLXAccessibleBox::ProcessWindowChildEvent( const VclWindowEvent& rVclWindowEvent ) { uno::Any aOldValue, aNewValue; uno::Reference<XAccessible> xAcc; switch ( rVclWindowEvent.GetId() ) { case VCLEVENT_WINDOW_SHOW: case VCLEVENT_WINDOW_HIDE: { Window* pChildWindow = (Window *) rVclWindowEvent.GetData(); // Just compare to the combo box text field. All other children // are identical to this object in which case this object will // be removed in a short time. if (m_aBoxType==COMBOBOX) { ComboBox* pComboBox = static_cast<ComboBox*>(GetWindow()); if ( ( pComboBox != NULL ) && ( pChildWindow != NULL ) ) if (pChildWindow == pComboBox->GetSubEdit()) { if (rVclWindowEvent.GetId() == VCLEVENT_WINDOW_SHOW) { // Instantiate text field. getAccessibleChild (0); aNewValue <<= m_xText; } else { // Release text field. aOldValue <<= m_xText; m_xText = NULL; } // Tell the listeners about the new/removed child. NotifyAccessibleEvent ( AccessibleEventId::CHILD, aOldValue, aNewValue); } } } break; default: VCLXAccessibleComponent::ProcessWindowChildEvent (rVclWindowEvent); } } void VCLXAccessibleBox::ProcessWindowEvent (const VclWindowEvent& rVclWindowEvent) { switch ( rVclWindowEvent.GetId() ) { case VCLEVENT_DROPDOWN_OPEN: case VCLEVENT_DROPDOWN_CLOSE: case VCLEVENT_LISTBOX_DOUBLECLICK: case VCLEVENT_LISTBOX_SCROLLED: case VCLEVENT_LISTBOX_SELECT: case VCLEVENT_LISTBOX_ITEMADDED: case VCLEVENT_LISTBOX_ITEMREMOVED: case VCLEVENT_COMBOBOX_ITEMADDED: case VCLEVENT_COMBOBOX_ITEMREMOVED: case VCLEVENT_COMBOBOX_SCROLLED: { // Forward the call to the list child. VCLXAccessibleList* pList = static_cast<VCLXAccessibleList*>(m_xList.get()); if ( pList == NULL ) { getAccessibleChild ( m_bHasTextChild ? 1 : 0 ); pList = static_cast<VCLXAccessibleList*>(m_xList.get()); } if ( pList != NULL ) pList->ProcessWindowEvent (rVclWindowEvent); break; } case VCLEVENT_COMBOBOX_SELECT: case VCLEVENT_COMBOBOX_DESELECT: { // Selection is handled by VCLXAccessibleList which operates on // the same VCL object as this box does. In case of the // combobox, however, we have to help the list with providing // the text of the currently selected item. VCLXAccessibleList* pList = static_cast<VCLXAccessibleList*>(m_xList.get()); if (pList != NULL && m_xText.is()) { Reference<XAccessibleText> xText (m_xText->getAccessibleContext(), UNO_QUERY); if ( xText.is() ) { ::rtl::OUString sText = xText->getSelectedText(); if ( !sText.getLength() ) sText = xText->getText(); pList->UpdateSelection (sText); } } break; } case VCLEVENT_EDIT_MODIFY: case VCLEVENT_EDIT_SELECTIONCHANGED: // Modify/Selection events are handled by the combo box instead of // directly by the edit field (Why?). Therefore, delegate this // call to the edit field. if (m_aBoxType==COMBOBOX) { if (m_xText.is()) { Reference<XAccessibleContext> xContext = m_xText->getAccessibleContext(); VCLXAccessibleEdit* pEdit = static_cast<VCLXAccessibleEdit*>(xContext.get()); if (pEdit != NULL) pEdit->ProcessWindowEvent (rVclWindowEvent); } } break; default: VCLXAccessibleComponent::ProcessWindowEvent( rVclWindowEvent ); } } IMPLEMENT_FORWARD_XINTERFACE2(VCLXAccessibleBox, VCLXAccessibleComponent, VCLXAccessibleBox_BASE) IMPLEMENT_FORWARD_XTYPEPROVIDER2(VCLXAccessibleBox, VCLXAccessibleComponent, VCLXAccessibleBox_BASE) //===== XAccessible ========================================================= Reference< XAccessibleContext > SAL_CALL VCLXAccessibleBox::getAccessibleContext( ) throw (RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); return this; } //===== XAccessibleContext ================================================== sal_Int32 SAL_CALL VCLXAccessibleBox::getAccessibleChildCount (void) throw (RuntimeException) { vos::OGuard aSolarGuard( Application::GetSolarMutex() ); ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); // Usually a box has a text field and a list of items as its children. // Non drop down list boxes have no text field. Additionally check // whether the object is valid. sal_Int32 nCount = 0; if (IsValid()) nCount += (m_bHasTextChild?1:0) + (m_bHasListChild?1:0); else { // Object not valid anymore. Release references to children. m_bHasTextChild = false; m_xText = NULL; m_bHasListChild = false; m_xList = NULL; } return nCount; } Reference<XAccessible> SAL_CALL VCLXAccessibleBox::getAccessibleChild (sal_Int32 i) throw (IndexOutOfBoundsException, RuntimeException) { vos::OGuard aSolarGuard( Application::GetSolarMutex() ); ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); if (i<0 || i>=getAccessibleChildCount()) throw IndexOutOfBoundsException(); Reference< XAccessible > xChild; if (IsValid()) { if (i==1 || ! m_bHasTextChild) { // List. if ( ! m_xList.is()) { VCLXAccessibleList* pList = new VCLXAccessibleList ( GetVCLXWindow(), (m_aBoxType == LISTBOX ? VCLXAccessibleList::LISTBOX : VCLXAccessibleList::COMBOBOX), this); pList->SetIndexInParent (i); m_xList = pList; } xChild = m_xList; } else { // Text Field. if ( ! m_xText.is()) { if (m_aBoxType==COMBOBOX) { ComboBox* pComboBox = static_cast<ComboBox*>(GetWindow()); if (pComboBox!=NULL && pComboBox->GetSubEdit()!=NULL) m_xText = pComboBox->GetSubEdit()->GetAccessible(); } else if (m_bIsDropDownBox) m_xText = new VCLXAccessibleTextField (GetVCLXWindow(),this); } xChild = m_xText; } } return xChild; } sal_Int16 SAL_CALL VCLXAccessibleBox::getAccessibleRole (void) throw (RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); // Return the role <const>COMBO_BOX</const> for both VCL combo boxes and // VCL list boxes in DropDown-Mode else <const>PANEL</const>. // This way the Java bridge has not to handle both independently. return m_bIsDropDownBox ? AccessibleRole::COMBO_BOX : AccessibleRole::PANEL; } sal_Int32 SAL_CALL VCLXAccessibleBox::getAccessibleIndexInParent (void) throw (::com::sun::star::uno::RuntimeException) { if (m_nIndexInParent != DEFAULT_INDEX_IN_PARENT) return m_nIndexInParent; else return VCLXAccessibleComponent::getAccessibleIndexInParent(); } //===== XAccessibleAction =================================================== sal_Int32 SAL_CALL VCLXAccessibleBox::getAccessibleActionCount (void) throw (RuntimeException) { ::osl::Guard< ::osl::Mutex> aGuard (GetMutex()); // There is one action for drop down boxes (toggle popup) and none for // the other boxes. return m_bIsDropDownBox ? 1 : 0; } sal_Bool SAL_CALL VCLXAccessibleBox::doAccessibleAction (sal_Int32 nIndex) throw (IndexOutOfBoundsException, RuntimeException) { sal_Bool bNotify = sal_False; { vos::OGuard aSolarGuard( Application::GetSolarMutex() ); ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); if (nIndex<0 || nIndex>=getAccessibleActionCount()) throw ::com::sun::star::lang::IndexOutOfBoundsException(); if (m_aBoxType == COMBOBOX) { ComboBox* pComboBox = static_cast< ComboBox* >( GetWindow() ); if (pComboBox != NULL) { pComboBox->ToggleDropDown(); bNotify = sal_True; } } else if (m_aBoxType == LISTBOX) { ListBox* pListBox = static_cast< ListBox* >( GetWindow() ); if (pListBox != NULL) { pListBox->ToggleDropDown(); bNotify = sal_True; } } } if (bNotify) NotifyAccessibleEvent (AccessibleEventId::ACTION_CHANGED, Any(), Any()); return bNotify; } ::rtl::OUString SAL_CALL VCLXAccessibleBox::getAccessibleActionDescription (sal_Int32 nIndex) throw (IndexOutOfBoundsException, RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); if (nIndex<0 || nIndex>=getAccessibleActionCount()) throw ::com::sun::star::lang::IndexOutOfBoundsException(); return TK_RES_STRING( RID_STR_ACC_ACTION_TOGGLEPOPUP); } Reference< XAccessibleKeyBinding > VCLXAccessibleBox::getAccessibleActionKeyBinding( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( GetMutex() ); Reference< XAccessibleKeyBinding > xRet; if (nIndex<0 || nIndex>=getAccessibleActionCount()) throw ::com::sun::star::lang::IndexOutOfBoundsException(); // ... which key? return xRet; } //===== XComponent ========================================================== void SAL_CALL VCLXAccessibleBox::disposing (void) { VCLXAccessibleComponent::disposing(); } <|endoftext|>
<commit_before><commit_msg>tdf#92088 - don't invalidate disposed toolbar items.<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salogl.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: obo $ $Date: 2006-09-17 12:39:27 $ * * 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_vcl.hxx" #include <salunx.h> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALOGL_H #include <salogl.h> #endif #ifndef _SV_SALGDI_H #include <salgdi.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> using namespace rtl; // ------------ // - Lib-Name - // ------------ #ifdef MACOSX #define OGL_LIBNAME "libGL.dylib" #else #define OGL_LIBNAME "libGL.so.1" #endif // ---------- // - Macros - // ---------- // ----------------- // - Statics init. - // ----------------- // Members GLXContext X11SalOpenGL::maGLXContext = 0; Display* X11SalOpenGL::mpDisplay = 0; XVisualInfo* X11SalOpenGL::mpVisualInfo = 0; BOOL X11SalOpenGL::mbHaveGLVisual = FALSE; oslModule X11SalOpenGL::mpGLLib = 0; #ifdef SOLARIS oslModule aMotifLib; #endif ULONG X11SalOpenGL::mnOGLState = OGL_STATE_UNLOADED; GLXContext (*X11SalOpenGL::pCreateContext)( Display *, XVisualInfo *, GLXContext, Bool ) = 0; void (*X11SalOpenGL::pDestroyContext)( Display *, GLXContext ) = 0; GLXContext (*X11SalOpenGL::pGetCurrentContext)( ) = 0; Bool (*X11SalOpenGL::pMakeCurrent)( Display *, GLXDrawable, GLXContext ) = 0; void (*X11SalOpenGL::pSwapBuffers)( Display*, GLXDrawable ) = 0; int (*X11SalOpenGL::pGetConfig)( Display*, XVisualInfo*, int, int* ) = 0; void (*X11SalOpenGL::pFlush)() = 0; // ------------- // - X11SalOpenGL - // ------------- X11SalOpenGL::X11SalOpenGL( SalGraphics* pSGraphics ) { X11SalGraphics* pGraphics = static_cast<X11SalGraphics*>(pSGraphics); mpDisplay = pGraphics->GetXDisplay(); mpVisualInfo = pGraphics->GetDisplay()->GetVisual(); maDrawable = pGraphics->GetDrawable(); } // ------------------------------------------------------------------------ X11SalOpenGL::~X11SalOpenGL() { } // ------------------------------------------------------------------------ bool X11SalOpenGL::IsValid() { if( OGL_STATE_UNLOADED == mnOGLState ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions; if( *DisplayString( mpDisplay ) == ':' || ! strncmp( DisplayString( mpDisplay ), "localhost:", 10 ) ) { // GLX only on local displays due to strange problems // with remote GLX ppExtensions = XListExtensions( mpDisplay, &nExtensions ); for( int i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); #if OSL_DEBUG_LEVEL > 1 if( ! bHasGLX ) fprintf( stderr, "XServer does not support GLX extension\n" ); #endif if( bHasGLX ) { /* * #82406# the XFree4.0 GLX module does not seem * to work that great, at least not the one that comes * with the default installation and Matrox cards. * Since these are common we disable usage of * OpenGL per default. */ static const char* pOverrideGLX = getenv( "SAL_ENABLE_GLX_XFREE4" ); if( ! strncmp( ServerVendor( mpDisplay ), "The XFree86 Project, Inc", 24 ) && VendorRelease( mpDisplay ) >= 4000 && ! pOverrideGLX ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "disabling GLX usage on XFree >= 4.0\n" ); #endif bHasGLX = FALSE; } } } if( bHasGLX && mpVisualInfo->c_class == TrueColor && ImplInit() ) { int nDoubleBuffer = 0; int nHaveGL = 0; pGetConfig( mpDisplay, mpVisualInfo, GLX_USE_GL, &nHaveGL ); pGetConfig( mpDisplay, mpVisualInfo, GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { SalDisplay* pSalDisplay = GetX11SalData()->GetDisplay(); BOOL bPreviousState = pSalDisplay->GetXLib()->GetIgnoreXErrors(); pSalDisplay->GetXLib()->SetIgnoreXErrors( TRUE ); mbHaveGLVisual = TRUE; maGLXContext = pCreateContext( mpDisplay, mpVisualInfo, 0, True ); if( pSalDisplay->GetXLib()->WasXError() ) mbHaveGLVisual = FALSE; else pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); if( pSalDisplay->GetXLib()->WasXError() ) mbHaveGLVisual = FALSE; pSalDisplay->GetXLib()->SetIgnoreXErrors( bPreviousState ); if( mbHaveGLVisual ) mnOGLState = OGL_STATE_VALID; else maGLXContext = None; } } if( mnOGLState != OGL_STATE_VALID ) mnOGLState = OGL_STATE_INVALID; #if OSL_DEBUG_LEVEL > 1 if( mnOGLState == OGL_STATE_VALID ) fprintf( stderr, "Using GLX on visual id %x.\n", mpVisualInfo->visualid ); else fprintf( stderr, "Not using GLX.\n" ); #endif } return mnOGLState == OGL_STATE_VALID ? TRUE : FALSE; } void X11SalOpenGL::Release() { if( maGLXContext && pDestroyContext ) pDestroyContext( mpDisplay, maGLXContext ); } // ------------------------------------------------------------------------ void X11SalOpenGL::ReleaseLib() { if( mpGLLib ) { osl_unloadModule( mpGLLib ); #ifdef SOLARIS if( aMotifLib ) osl_unloadModule( aMotifLib ); #endif mpGLLib = 0; pCreateContext = 0; pDestroyContext = 0; pGetCurrentContext = 0; pMakeCurrent = 0; pSwapBuffers = 0; pGetConfig = 0; mnOGLState = OGL_STATE_UNLOADED; } } // ------------------------------------------------------------------------ oglFunction X11SalOpenGL::GetOGLFnc( const char *pFncName ) { return resolveSymbol( pFncName ); } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLEntry( SalGraphics* pGraphics ) { GLXDrawable aDrawable = static_cast<X11SalGraphics*>(pGraphics)->GetDrawable(); if( aDrawable != maDrawable ) { maDrawable = aDrawable; pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); } } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLExit( SalGraphics* ) { } // ------------------------------------------------------------------------ oglFunction X11SalOpenGL::resolveSymbol( const char* pSymbol ) { oglFunction pSym = NULL; if( mpGLLib ) { OUString aSym = OUString::createFromAscii( pSymbol ); pSym = osl_getFunctionSymbol( mpGLLib, aSym.pData ); } return pSym; } BOOL X11SalOpenGL::ImplInit() { if( ! mpGLLib ) { ByteString sNoGL( getenv( "SAL_NOOPENGL" ) ); if( sNoGL.ToLowerAscii() == "true" ) return FALSE; sal_Int32 nRtldMode = SAL_LOADMODULE_NOW; #ifdef SOLARIS /* #i36866# an obscure interaction with jvm can let java crash * if we do not use SAL_LOADMODULE_GLOBAL here */ nRtldMode |= SAL_LOADMODULE_GLOBAL; /* #i36899# and we need Xm, too, else jvm will not work properly. */ OUString aMotifName( RTL_CONSTASCII_USTRINGPARAM( "libXm.so" ) ); aMotifLib = osl_loadModule( aMotifName.pData, nRtldMode ); #endif OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( OGL_LIBNAME ) ); mpGLLib = osl_loadModule( aLibName.pData, nRtldMode ); } if( ! mpGLLib ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, OGL_LIBNAME "could not be opened\n" ); #endif return FALSE; } // Internal use pCreateContext = (GLXContext(*)(Display*,XVisualInfo*,GLXContext,Bool )) resolveSymbol( "glXCreateContext" ); pDestroyContext = (void(*)(Display*,GLXContext)) resolveSymbol( "glXDestroyContext" ); pGetCurrentContext = (GLXContext(*)()) resolveSymbol( "glXGetCurrentContext" ); pMakeCurrent = (Bool(*)(Display*,GLXDrawable,GLXContext)) resolveSymbol( "glXMakeCurrent" ); pSwapBuffers=(void(*)(Display*, GLXDrawable)) resolveSymbol( "glXSwapBuffers" ); pGetConfig = (int(*)(Display*, XVisualInfo*, int, int* )) resolveSymbol( "glXGetConfig" ); pFlush = (void(*)()) resolveSymbol( "glFlush" ); BOOL bRet = pCreateContext && pDestroyContext && pGetCurrentContext && pMakeCurrent && pSwapBuffers && pGetConfig ? TRUE : FALSE; #if OSL_DEBUG_LEVEL > 1 if( ! bRet ) fprintf( stderr, "could not find all needed symbols in " OGL_LIBNAME "\n" ); #endif return bRet; } void X11SalOpenGL::StartScene( SalGraphics* ) { // flush pending operations which otherwise might be drawn // at the wrong time XSync( mpDisplay, False ); } void X11SalOpenGL::StopScene() { if( maDrawable ) { pSwapBuffers( mpDisplay, maDrawable ); pFlush(); } } void X11SalOpenGL::MakeVisualWeights( Display* pDisplay, XVisualInfo* pInfos, int *pWeights, int nVisuals ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions,i ; // GLX only on local displays due to strange problems // with remote GLX if( ! ( *DisplayString( pDisplay ) == ':' || !strncmp( DisplayString( pDisplay ), "localhost:", 10 ) ) ) return; ppExtensions = XListExtensions( pDisplay, &nExtensions ); for( i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); if( ! bHasGLX ) return; if( ! ImplInit() ) return; for( i = 0; i < nVisuals; i++ ) { int nDoubleBuffer = 0; int nHaveGL = 0; // a weight lesser than zero indicates an invalid visual (wrong screen) if( pInfos[i].c_class == TrueColor && pInfos[i].depth > 14 && pWeights[i] >= 0) { pGetConfig( pDisplay, &pInfos[ i ], GLX_USE_GL, &nHaveGL ); pGetConfig( pDisplay, &pInfos[ i ], GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { mbHaveGLVisual = TRUE; pWeights[ i ] += 65536; } } } } <commit_msg>INTEGRATION: CWS impresshydra (1.16.46); FILE MERGED 2006/09/20 13:52:06 cl 1.16.46.3: RESYNC: (1.17-1.18); FILE MERGED 2006/08/28 13:12:04 cl 1.16.46.2: RESYNC: (1.16-1.17); FILE MERGED 2006/08/09 14:35:09 pl 1.16.46.1: #i67721# on the way to multiscreen support<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salogl.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: kz $ $Date: 2006-10-06 10:06:57 $ * * 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_vcl.hxx" #include <salunx.h> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALOGL_H #include <salogl.h> #endif #ifndef _SV_SALGDI_H #include <salgdi.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> using namespace rtl; // ------------ // - Lib-Name - // ------------ #ifdef MACOSX #define OGL_LIBNAME "libGL.dylib" #else #define OGL_LIBNAME "libGL.so.1" #endif // ---------- // - Macros - // ---------- // ----------------- // - Statics init. - // ----------------- // Members GLXContext X11SalOpenGL::maGLXContext = 0; Display* X11SalOpenGL::mpDisplay = 0; const XVisualInfo* X11SalOpenGL::mpVisualInfo = 0; BOOL X11SalOpenGL::mbHaveGLVisual = FALSE; oslModule X11SalOpenGL::mpGLLib = 0; #ifdef SOLARIS oslModule aMotifLib; #endif ULONG X11SalOpenGL::mnOGLState = OGL_STATE_UNLOADED; GLXContext (*X11SalOpenGL::pCreateContext)( Display *, XVisualInfo *, GLXContext, Bool ) = 0; void (*X11SalOpenGL::pDestroyContext)( Display *, GLXContext ) = 0; GLXContext (*X11SalOpenGL::pGetCurrentContext)( ) = 0; Bool (*X11SalOpenGL::pMakeCurrent)( Display *, GLXDrawable, GLXContext ) = 0; void (*X11SalOpenGL::pSwapBuffers)( Display*, GLXDrawable ) = 0; int (*X11SalOpenGL::pGetConfig)( Display*, XVisualInfo*, int, int* ) = 0; void (*X11SalOpenGL::pFlush)() = 0; // ------------- // - X11SalOpenGL - // ------------- // FIXME: Multiscreen X11SalOpenGL::X11SalOpenGL( SalGraphics* pSGraphics ) { X11SalGraphics* pGraphics = static_cast<X11SalGraphics*>(pSGraphics); mpDisplay = pGraphics->GetXDisplay(); mpVisualInfo = &pGraphics->GetDisplay()->GetVisual(pGraphics->GetScreenNumber()); maDrawable = pGraphics->GetDrawable(); } // ------------------------------------------------------------------------ X11SalOpenGL::~X11SalOpenGL() { } // ------------------------------------------------------------------------ bool X11SalOpenGL::IsValid() { if( OGL_STATE_UNLOADED == mnOGLState ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions; if( *DisplayString( mpDisplay ) == ':' || ! strncmp( DisplayString( mpDisplay ), "localhost:", 10 ) ) { // GLX only on local displays due to strange problems // with remote GLX ppExtensions = XListExtensions( mpDisplay, &nExtensions ); for( int i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); #if OSL_DEBUG_LEVEL > 1 if( ! bHasGLX ) fprintf( stderr, "XServer does not support GLX extension\n" ); #endif if( bHasGLX ) { /* * #82406# the XFree4.0 GLX module does not seem * to work that great, at least not the one that comes * with the default installation and Matrox cards. * Since these are common we disable usage of * OpenGL per default. */ static const char* pOverrideGLX = getenv( "SAL_ENABLE_GLX_XFREE4" ); if( ! strncmp( ServerVendor( mpDisplay ), "The XFree86 Project, Inc", 24 ) && VendorRelease( mpDisplay ) >= 4000 && ! pOverrideGLX ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "disabling GLX usage on XFree >= 4.0\n" ); #endif bHasGLX = FALSE; } } } if( bHasGLX && mpVisualInfo->c_class == TrueColor && ImplInit() ) { int nDoubleBuffer = 0; int nHaveGL = 0; pGetConfig( mpDisplay, const_cast<XVisualInfo*>(mpVisualInfo), GLX_USE_GL, &nHaveGL ); pGetConfig( mpDisplay, const_cast<XVisualInfo*>(mpVisualInfo), GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { SalDisplay* pSalDisplay = GetX11SalData()->GetDisplay(); BOOL bPreviousState = pSalDisplay->GetXLib()->GetIgnoreXErrors(); pSalDisplay->GetXLib()->SetIgnoreXErrors( TRUE ); mbHaveGLVisual = TRUE; maGLXContext = pCreateContext( mpDisplay, const_cast<XVisualInfo*>(mpVisualInfo), 0, True ); if( pSalDisplay->GetXLib()->WasXError() ) mbHaveGLVisual = FALSE; else pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); if( pSalDisplay->GetXLib()->WasXError() ) mbHaveGLVisual = FALSE; pSalDisplay->GetXLib()->SetIgnoreXErrors( bPreviousState ); if( mbHaveGLVisual ) mnOGLState = OGL_STATE_VALID; else maGLXContext = None; } } if( mnOGLState != OGL_STATE_VALID ) mnOGLState = OGL_STATE_INVALID; #if OSL_DEBUG_LEVEL > 1 if( mnOGLState == OGL_STATE_VALID ) fprintf( stderr, "Using GLX on visual id %x.\n", mpVisualInfo->visualid ); else fprintf( stderr, "Not using GLX.\n" ); #endif } return mnOGLState == OGL_STATE_VALID ? TRUE : FALSE; } void X11SalOpenGL::Release() { if( maGLXContext && pDestroyContext ) pDestroyContext( mpDisplay, maGLXContext ); } // ------------------------------------------------------------------------ void X11SalOpenGL::ReleaseLib() { if( mpGLLib ) { osl_unloadModule( mpGLLib ); #ifdef SOLARIS if( aMotifLib ) osl_unloadModule( aMotifLib ); #endif mpGLLib = 0; pCreateContext = 0; pDestroyContext = 0; pGetCurrentContext = 0; pMakeCurrent = 0; pSwapBuffers = 0; pGetConfig = 0; mnOGLState = OGL_STATE_UNLOADED; } } // ------------------------------------------------------------------------ oglFunction X11SalOpenGL::GetOGLFnc( const char *pFncName ) { return resolveSymbol( pFncName ); } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLEntry( SalGraphics* pGraphics ) { GLXDrawable aDrawable = static_cast<X11SalGraphics*>(pGraphics)->GetDrawable(); if( aDrawable != maDrawable ) { maDrawable = aDrawable; pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); } } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLExit( SalGraphics* ) { } // ------------------------------------------------------------------------ oglFunction X11SalOpenGL::resolveSymbol( const char* pSymbol ) { oglFunction pSym = NULL; if( mpGLLib ) { OUString aSym = OUString::createFromAscii( pSymbol ); pSym = osl_getFunctionSymbol( mpGLLib, aSym.pData ); } return pSym; } BOOL X11SalOpenGL::ImplInit() { if( ! mpGLLib ) { ByteString sNoGL( getenv( "SAL_NOOPENGL" ) ); if( sNoGL.ToLowerAscii() == "true" ) return FALSE; sal_Int32 nRtldMode = SAL_LOADMODULE_NOW; #ifdef SOLARIS /* #i36866# an obscure interaction with jvm can let java crash * if we do not use SAL_LOADMODULE_GLOBAL here */ nRtldMode |= SAL_LOADMODULE_GLOBAL; /* #i36899# and we need Xm, too, else jvm will not work properly. */ OUString aMotifName( RTL_CONSTASCII_USTRINGPARAM( "libXm.so" ) ); aMotifLib = osl_loadModule( aMotifName.pData, nRtldMode ); #endif OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( OGL_LIBNAME ) ); mpGLLib = osl_loadModule( aLibName.pData, nRtldMode ); } if( ! mpGLLib ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, OGL_LIBNAME "could not be opened\n" ); #endif return FALSE; } // Internal use pCreateContext = (GLXContext(*)(Display*,XVisualInfo*,GLXContext,Bool )) resolveSymbol( "glXCreateContext" ); pDestroyContext = (void(*)(Display*,GLXContext)) resolveSymbol( "glXDestroyContext" ); pGetCurrentContext = (GLXContext(*)()) resolveSymbol( "glXGetCurrentContext" ); pMakeCurrent = (Bool(*)(Display*,GLXDrawable,GLXContext)) resolveSymbol( "glXMakeCurrent" ); pSwapBuffers=(void(*)(Display*, GLXDrawable)) resolveSymbol( "glXSwapBuffers" ); pGetConfig = (int(*)(Display*, XVisualInfo*, int, int* )) resolveSymbol( "glXGetConfig" ); pFlush = (void(*)()) resolveSymbol( "glFlush" ); BOOL bRet = pCreateContext && pDestroyContext && pGetCurrentContext && pMakeCurrent && pSwapBuffers && pGetConfig ? TRUE : FALSE; #if OSL_DEBUG_LEVEL > 1 if( ! bRet ) fprintf( stderr, "could not find all needed symbols in " OGL_LIBNAME "\n" ); #endif return bRet; } void X11SalOpenGL::StartScene( SalGraphics* ) { // flush pending operations which otherwise might be drawn // at the wrong time XSync( mpDisplay, False ); } void X11SalOpenGL::StopScene() { if( maDrawable ) { pSwapBuffers( mpDisplay, maDrawable ); pFlush(); } } void X11SalOpenGL::MakeVisualWeights( Display* pDisplay, XVisualInfo* pInfos, int *pWeights, int nVisuals ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions,i ; // GLX only on local displays due to strange problems // with remote GLX if( ! ( *DisplayString( pDisplay ) == ':' || !strncmp( DisplayString( pDisplay ), "localhost:", 10 ) ) ) return; ppExtensions = XListExtensions( pDisplay, &nExtensions ); for( i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); if( ! bHasGLX ) return; if( ! ImplInit() ) return; for( i = 0; i < nVisuals; i++ ) { int nDoubleBuffer = 0; int nHaveGL = 0; // a weight lesser than zero indicates an invalid visual (wrong screen) if( pInfos[i].c_class == TrueColor && pInfos[i].depth > 14 && pWeights[i] >= 0) { pGetConfig( pDisplay, &pInfos[ i ], GLX_USE_GL, &nHaveGL ); pGetConfig( pDisplay, &pInfos[ i ], GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { mbHaveGLVisual = TRUE; pWeights[ i ] += 65536; } } } } <|endoftext|>
<commit_before>// @(#)root/hbook:$Id$ // Author: Rene Brun 20/02/2002 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "THbookKey.h" #include "THbookTree.h" #include "TBrowser.h" ClassImp(THbookKey) //______________________________________________________________________________ THbookKey::THbookKey(Int_t id, THbookFile *file) { //constructor fDirectory = file; fID = id; char name[10]; sprintf(name,"h%d",id); SetName(name); } //______________________________________________________________________________ THbookKey::~THbookKey() { } //______________________________________________________________________________ void THbookKey::Browse(TBrowser *b) { // Read object from disk and call its Browse() method. // If object with same name already exist in memory delete it (like // TDirectory::Get() is doing), except when the key references a // folder in which case we don't want to re-read the folder object // since it might contain new objects not yet saved. fDirectory->cd(); TObject *obj = fDirectory->GetList()->FindObject(GetName()); if (obj && !obj->IsFolder()) { if (obj->InheritsFrom(TCollection::Class())) obj->Delete(); // delete also collection elements delete obj; obj = 0; } if (!obj) obj = fDirectory->Get(fID); if (b && obj) { obj->Browse(b); b->SetRefreshFlag(kTRUE); } } //______________________________________________________________________________ Bool_t THbookKey::IsFolder() const { //an hbook key is not a folder Bool_t ret = kFALSE; return( ret ); } <commit_msg>use snprintf<commit_after>// @(#)root/hbook:$Id$ // Author: Rene Brun 20/02/2002 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "THbookKey.h" #include "THbookTree.h" #include "TBrowser.h" ClassImp(THbookKey) //______________________________________________________________________________ THbookKey::THbookKey(Int_t id, THbookFile *file) { //constructor fDirectory = file; fID = id; char name[10]; snprintf(name,10,"h%d",id); SetName(name); } //______________________________________________________________________________ THbookKey::~THbookKey() { } //______________________________________________________________________________ void THbookKey::Browse(TBrowser *b) { // Read object from disk and call its Browse() method. // If object with same name already exist in memory delete it (like // TDirectory::Get() is doing), except when the key references a // folder in which case we don't want to re-read the folder object // since it might contain new objects not yet saved. fDirectory->cd(); TObject *obj = fDirectory->GetList()->FindObject(GetName()); if (obj && !obj->IsFolder()) { if (obj->InheritsFrom(TCollection::Class())) obj->Delete(); // delete also collection elements delete obj; obj = 0; } if (!obj) obj = fDirectory->Get(fID); if (b && obj) { obj->Browse(b); b->SetRefreshFlag(kTRUE); } } //______________________________________________________________________________ Bool_t THbookKey::IsFolder() const { //an hbook key is not a folder Bool_t ret = kFALSE; return( ret ); } <|endoftext|>
<commit_before>#include "stack thread safe.hpp" #include "gtest/gtest.h" #include <thread> #include <algorithm> TEST(Push,HandleBasicOperation){ std::threadsafe::stack<int> stack; int out; for (int i = 1;i <= 10;i++){ stack.push(i); stack.wait_top(out); EXPECT_EQ(i,out); EXPECT_EQ(i,stack.size()); } for (int i = 10;i >= 1;i--){ stack.wait_pop(out); EXPECT_EQ(i,out); EXPECT_EQ(i-1,stack.size()); } } void wait(std::mutex& lock,std::condition_variable& cond,const bool &ready){ std::unique_lock<std::mutex> unique_lock(lock); while (!ready){ cond.wait(unique_lock); } } TEST(Push,ThreadSafety){ std::threadsafe::stack<int> stack; std::threadsafe::stack<int> another_stack; constexpr int ITERATIONS = 10; std::thread producers[ITERATIONS]; std::thread consumers[ITERATIONS]; std::mutex lock; std::condition_variable cond; bool ready = false; for (int i = 0;i < ITERATIONS;i++){ producers[i] = std::thread([&](int id){ wait(lock,cond,ready); for (int j = 0;j < ITERATIONS;j++){ stack.push(id); } },i); } for (int i = 0;i < ITERATIONS;i++){ consumers[i] = std::thread([&]{ wait(lock,cond,ready); int out; for (int j = 0;j < ITERATIONS;j++){ stack.wait_pop(out); ASSERT_LT(out,ITERATIONS); ASSERT_GE(out,0); another_stack.push(out); } }); } ready = true; cond.notify_all(); for (int i = 0;i < ITERATIONS;i++){ producers[i].join(); consumers[i].join(); } ASSERT_EQ(ITERATIONS*ITERATIONS,another_stack.size()); int freq_table[ITERATIONS]; std::fill(freq_table,freq_table+ITERATIONS,0); while (!another_stack.empty()){ int out; another_stack.wait_pop(out); freq_table[out]++; } for (int i = 0;i < ITERATIONS;i++) { ASSERT_EQ(ITERATIONS,freq_table[i]); } } TEST(Push,UpperBound){ std::threadsafe::stack<int> stack; constexpr int ITERATIONS = 10; stack.setLimit(ITERATIONS/2); std::thread producers[ITERATIONS]; std::thread consumer; std::mutex lock; std::condition_variable cond; bool ready = false; for (int i = 0;i < ITERATIONS;i++){ producers[i] = std::thread([&](int id){ wait(lock,cond,ready); for (int j = 0;j < ITERATIONS;j++){ stack.push(id); ASSERT_LE(stack.size(),ITERATIONS/2); } },i); } consumer = std::thread([&]{ wait(lock,cond,ready); int out; for (int j = 0;j < ITERATIONS*ITERATIONS;j++){ ASSERT_LE(stack.size(),ITERATIONS/2); stack.wait_pop(out); } }); ready = true; cond.notify_all(); for (int i = 0;i < ITERATIONS;i++){ producers[i].join(); } consumer.join(); } TEST(Try_pop,HandleBasicOperation){ std::threadsafe::stack<int> stack; for (int i = 1;i <= 10;i++){ stack.push(i); } int out; for (int i = 10;i >= 1;i--){ ASSERT_EQ(i,stack.size()); ASSERT_EQ(true,stack.try_pop(out)); ASSERT_EQ(i,out); } ASSERT_EQ(0,stack.size()); } <commit_msg>Added test TryPop stack, thread safety<commit_after>#include "stack thread safe.hpp" #include "gtest/gtest.h" #include <thread> #include <algorithm> TEST(Push,HandleBasicOperation){ std::threadsafe::stack<int> stack; int out; for (int i = 1;i <= 10;i++){ stack.push(i); stack.wait_top(out); EXPECT_EQ(i,out); EXPECT_EQ(i,stack.size()); } for (int i = 10;i >= 1;i--){ stack.wait_pop(out); EXPECT_EQ(i,out); EXPECT_EQ(i-1,stack.size()); } } void wait(std::mutex& lock,std::condition_variable& cond,const bool &ready){ std::unique_lock<std::mutex> unique_lock(lock); while (!ready){ cond.wait(unique_lock); } } TEST(Push,ThreadSafety){ std::threadsafe::stack<int> stack; std::threadsafe::stack<int> another_stack; constexpr int ITERATIONS = 10; std::thread producers[ITERATIONS]; std::thread consumers[ITERATIONS]; std::mutex lock; std::condition_variable cond; bool ready = false; for (int i = 0;i < ITERATIONS;i++){ producers[i] = std::thread([&](int id){ wait(lock,cond,ready); for (int j = 0;j < ITERATIONS;j++){ stack.push(id); } },i); } for (int i = 0;i < ITERATIONS;i++){ consumers[i] = std::thread([&]{ wait(lock,cond,ready); int out; for (int j = 0;j < ITERATIONS;j++){ stack.wait_pop(out); ASSERT_LT(out,ITERATIONS); ASSERT_GE(out,0); another_stack.push(out); } }); } ready = true; cond.notify_all(); for (int i = 0;i < ITERATIONS;i++){ producers[i].join(); consumers[i].join(); } ASSERT_EQ(ITERATIONS*ITERATIONS,another_stack.size()); int freq_table[ITERATIONS]; std::fill(freq_table,freq_table+ITERATIONS,0); while (!another_stack.empty()){ int out; another_stack.wait_pop(out); freq_table[out]++; } for (int i = 0;i < ITERATIONS;i++) { ASSERT_EQ(ITERATIONS,freq_table[i]); } } TEST(Push,UpperBound){ std::threadsafe::stack<int> stack; constexpr int ITERATIONS = 10; stack.setLimit(ITERATIONS/2); std::thread producers[ITERATIONS]; std::thread consumer; std::mutex lock; std::condition_variable cond; bool ready = false; for (int i = 0;i < ITERATIONS;i++){ producers[i] = std::thread([&](int id){ wait(lock,cond,ready); for (int j = 0;j < ITERATIONS;j++){ stack.push(id); ASSERT_LE(stack.size(),ITERATIONS/2); } },i); } consumer = std::thread([&]{ wait(lock,cond,ready); int out; for (int j = 0;j < ITERATIONS*ITERATIONS;j++){ ASSERT_LE(stack.size(),ITERATIONS/2); stack.wait_pop(out); } }); ready = true; cond.notify_all(); for (int i = 0;i < ITERATIONS;i++){ producers[i].join(); } consumer.join(); } TEST(Try_pop,HandleBasicOperation){ std::threadsafe::stack<int> stack; for (int i = 1;i <= 10;i++){ stack.push(i); } int out; for (int i = 10;i >= 1;i--){ ASSERT_EQ(i,stack.size()); ASSERT_EQ(true,stack.try_pop(out)); ASSERT_EQ(i,out); } ASSERT_EQ(0,stack.size()); } TEST(Try_pop,ThreadSafety){ std::threadsafe::stack<int> stack; std::threadsafe::stack<int> another_stack; constexpr int ITERATIONS = 10; std::thread producers[ITERATIONS]; std::thread consumers[ITERATIONS]; std::mutex lock; std::condition_variable cond; bool ready = false; for (int i = 0;i < ITERATIONS;i++){ producers[i] = std::thread([&](int id){ wait(lock,cond,ready); for (int j = 0;j < ITERATIONS;j++){ stack.push(id); } },i); } for (int i = 0;i < ITERATIONS;i++){ consumers[i] = std::thread([&]{ wait(lock,cond,ready); int out; for (int j = 0;j < ITERATIONS;j++){ while (!stack.try_pop(out)); another_stack.push(out); } }); } ready = true; cond.notify_all(); for (int i = 0;i < ITERATIONS;i++){ producers[i].join(); consumers[i].join(); } ASSERT_EQ(ITERATIONS*ITERATIONS,another_stack.size()); int freq_table[ITERATIONS]; std::fill(freq_table,freq_table+ITERATIONS,0); while (!another_stack.empty()){ int out; another_stack.wait_pop(out); freq_table[out]++; } for (int i = 0;i < ITERATIONS;i++) { ASSERT_EQ(ITERATIONS,freq_table[i]); } } <|endoftext|>
<commit_before>#ifndef ARABICA_UTILS_GET_PARAM_HPP #define ARABICA_UTILS_GET_PARAM_HPP #ifdef HAVE_BOOST #include <boost/mpl/if.hpp> #include <boost/type_traits/is_base_and_derived.hpp> #endif namespace Arabica { struct nil_t { }; #ifdef HAVE_BOOST template <typename BaseT, typename DefaultT, typename T0, typename T1> struct get_param { typedef typename boost::mpl::if_< boost::is_base_and_derived<BaseT, T0> , T0 , typename boost::mpl::if_< boost::is_base_and_derived<BaseT, T1> , T1 , DefaultT >::type >::type type; }; // get_param #else template <typename T0, typename DefaultT> struct chosen_type { typedef T0 type; }; template <typename DefaultT> struct chosen_type<Arabica::nil_t, DefaultT> { typedef DefaultT type; }; template <typename BaseT, typename DefaultT, typename T0, typename T1> struct get_param { typedef typename chosen_type<T0, DefaultT>::type type; }; #endif } // namespace Arabica #endif <commit_msg>added get_string_adaptor as a slightly less typing version of using get_param to pull it<commit_after>#ifndef ARABICA_UTILS_GET_PARAM_HPP #define ARABICA_UTILS_GET_PARAM_HPP #ifdef HAVE_BOOST #include <boost/mpl/if.hpp> #include <boost/type_traits/is_base_and_derived.hpp> #endif namespace Arabica { struct nil_t { }; #ifdef HAVE_BOOST template <typename BaseT, typename DefaultT, typename T0, typename T1> struct get_param { typedef typename boost::mpl::if_< boost::is_base_and_derived<BaseT, T0> , T0 , typename boost::mpl::if_< boost::is_base_and_derived<BaseT, T1> , T1 , DefaultT >::type >::type type; }; // get_param #else template <typename T0, typename DefaultT> struct chosen_type { typedef T0 type; }; template <typename DefaultT> struct chosen_type<Arabica::nil_t, DefaultT> { typedef DefaultT type; }; template <typename BaseT, typename DefaultT, typename T0, typename T1> struct get_param { typedef typename chosen_type<T0, DefaultT>::type type; }; #endif template <typename string_type, typename T0, typename T1> struct get_string_adaptor { typedef typename get_param<Arabica::string_adaptor_tag, Arabica::default_string_adaptor<string_type>, T0, T1>::type type; }; } // namespace Arabica #endif <|endoftext|>
<commit_before>#pragma once #include <string> #include "common.hpp" #include "x11/color.hpp" #include "x11/randr.hpp" POLYBAR_NS struct enum_hash { template <typename T> inline typename std::enable_if<std::is_enum<T>::value, size_t>::type operator()(T const value) const { return static_cast<size_t>(value); } }; enum class edge : uint8_t { NONE = 0U, TOP, BOTTOM, LEFT, RIGHT, ALL }; enum class alignment : uint8_t { NONE = 0U, LEFT, CENTER, RIGHT }; enum class attribute : uint8_t { NONE = 0U, UNDERLINE, OVERLINE }; enum class syntaxtag : uint8_t { NONE = 0U, A, // mouse action B, // background color F, // foreground color T, // font index O, // pixel offset R, // flip colors o, // overline color u, // underline color }; enum class mousebtn : uint8_t { NONE = 0U, LEFT, MIDDLE, RIGHT, SCROLL_UP, SCROLL_DOWN }; enum class strut : uint16_t { LEFT = 0U, RIGHT, TOP, BOTTOM, LEFT_START_Y, LEFT_END_Y, RIGHT_START_Y, RIGHT_END_Y, TOP_START_X, TOP_END_X, BOTTOM_START_X, BOTTOM_END_X, }; struct position { int16_t x{0}; int16_t y{0}; }; struct size { uint16_t w{1U}; uint16_t h{1U}; }; struct side_values { uint16_t left{0U}; uint16_t right{0U}; }; struct edge_values { uint16_t left{0U}; uint16_t right{0U}; uint16_t top{0U}; uint16_t bottom{0U}; }; struct border_settings { uint32_t color{0xFF000000}; uint16_t size{0U}; }; struct line_settings { uint32_t color{0xFF000000}; uint16_t size{0U}; }; struct action { mousebtn button{mousebtn::NONE}; string command{}; }; struct action_block : public action { alignment align{alignment::NONE}; volatile double start_x{0.0}; volatile double end_x{0.0}; bool active{true}; uint16_t width() const { return static_cast<uint16_t>(end_x - start_x + 0.5); } bool test(int16_t point) const { return static_cast<int16_t>(start_x) < point && static_cast<int16_t>(end_x) >= point; } }; struct bar_settings { explicit bar_settings() = default; bar_settings(const bar_settings& other) = default; xcb_window_t window{XCB_NONE}; monitor_t monitor{}; edge origin{edge::TOP}; struct size size { 1U, 1U }; position pos{0, 0}; position offset{0, 0}; position center{0, 0}; side_values padding{0U, 0U}; side_values margin{0U, 0U}; side_values module_margin{0U, 2U}; edge_values strut{0U, 0U, 0U, 0U}; uint32_t background{0xFFFFFFFF}; uint32_t foreground{0xFF000000}; line_settings underline{}; line_settings overline{}; std::unordered_map<edge, border_settings, enum_hash> borders{}; uint8_t spacing{1U}; string separator{}; string wmname{}; string locale{}; bool override_redirect{false}; vector<action> actions{}; bool dimmed{false}; double dimvalue{1.0}; const xcb_rectangle_t inner_area(bool abspos = false) const { xcb_rectangle_t rect{0, 0, size.w, size.h}; if (abspos) { rect.x = pos.x; rect.y = pos.y; } if (borders.find(edge::TOP) != borders.end()) { rect.y += borders.at(edge::TOP).size; rect.height -= borders.at(edge::TOP).size; } if (borders.find(edge::BOTTOM) != borders.end()) { rect.height -= borders.at(edge::BOTTOM).size; } if (borders.find(edge::LEFT) != borders.end()) { rect.x += borders.at(edge::LEFT).size; rect.width -= borders.at(edge::LEFT).size; } if (borders.find(edge::RIGHT) != borders.end()) { rect.width -= borders.at(edge::RIGHT).size; } return rect; } }; struct event_timer { xcb_timestamp_t event{0L}; xcb_timestamp_t offset{1L}; bool allow(xcb_timestamp_t time) { bool pass = time >= event + offset; event = time; return pass; }; bool deny(xcb_timestamp_t time) { return !allow(time); }; }; POLYBAR_NS_END <commit_msg>fix(bar): Action x values should not be volatile<commit_after>#pragma once #include <string> #include "common.hpp" #include "x11/color.hpp" #include "x11/randr.hpp" POLYBAR_NS struct enum_hash { template <typename T> inline typename std::enable_if<std::is_enum<T>::value, size_t>::type operator()(T const value) const { return static_cast<size_t>(value); } }; enum class edge : uint8_t { NONE = 0U, TOP, BOTTOM, LEFT, RIGHT, ALL }; enum class alignment : uint8_t { NONE = 0U, LEFT, CENTER, RIGHT }; enum class attribute : uint8_t { NONE = 0U, UNDERLINE, OVERLINE }; enum class syntaxtag : uint8_t { NONE = 0U, A, // mouse action B, // background color F, // foreground color T, // font index O, // pixel offset R, // flip colors o, // overline color u, // underline color }; enum class mousebtn : uint8_t { NONE = 0U, LEFT, MIDDLE, RIGHT, SCROLL_UP, SCROLL_DOWN }; enum class strut : uint16_t { LEFT = 0U, RIGHT, TOP, BOTTOM, LEFT_START_Y, LEFT_END_Y, RIGHT_START_Y, RIGHT_END_Y, TOP_START_X, TOP_END_X, BOTTOM_START_X, BOTTOM_END_X, }; struct position { int16_t x{0}; int16_t y{0}; }; struct size { uint16_t w{1U}; uint16_t h{1U}; }; struct side_values { uint16_t left{0U}; uint16_t right{0U}; }; struct edge_values { uint16_t left{0U}; uint16_t right{0U}; uint16_t top{0U}; uint16_t bottom{0U}; }; struct border_settings { uint32_t color{0xFF000000}; uint16_t size{0U}; }; struct line_settings { uint32_t color{0xFF000000}; uint16_t size{0U}; }; struct action { mousebtn button{mousebtn::NONE}; string command{}; }; struct action_block : public action { alignment align{alignment::NONE}; double start_x{0.0}; double end_x{0.0}; bool active{true}; uint16_t width() const { return static_cast<uint16_t>(end_x - start_x + 0.5); } bool test(int16_t point) const { return static_cast<int16_t>(start_x) < point && static_cast<int16_t>(end_x) >= point; } }; struct bar_settings { explicit bar_settings() = default; bar_settings(const bar_settings& other) = default; xcb_window_t window{XCB_NONE}; monitor_t monitor{}; edge origin{edge::TOP}; struct size size { 1U, 1U }; position pos{0, 0}; position offset{0, 0}; position center{0, 0}; side_values padding{0U, 0U}; side_values margin{0U, 0U}; side_values module_margin{0U, 2U}; edge_values strut{0U, 0U, 0U, 0U}; uint32_t background{0xFFFFFFFF}; uint32_t foreground{0xFF000000}; line_settings underline{}; line_settings overline{}; std::unordered_map<edge, border_settings, enum_hash> borders{}; uint8_t spacing{1U}; string separator{}; string wmname{}; string locale{}; bool override_redirect{false}; vector<action> actions{}; bool dimmed{false}; double dimvalue{1.0}; const xcb_rectangle_t inner_area(bool abspos = false) const { xcb_rectangle_t rect{0, 0, size.w, size.h}; if (abspos) { rect.x = pos.x; rect.y = pos.y; } if (borders.find(edge::TOP) != borders.end()) { rect.y += borders.at(edge::TOP).size; rect.height -= borders.at(edge::TOP).size; } if (borders.find(edge::BOTTOM) != borders.end()) { rect.height -= borders.at(edge::BOTTOM).size; } if (borders.find(edge::LEFT) != borders.end()) { rect.x += borders.at(edge::LEFT).size; rect.width -= borders.at(edge::LEFT).size; } if (borders.find(edge::RIGHT) != borders.end()) { rect.width -= borders.at(edge::RIGHT).size; } return rect; } }; struct event_timer { xcb_timestamp_t event{0L}; xcb_timestamp_t offset{1L}; bool allow(xcb_timestamp_t time) { bool pass = time >= event + offset; event = time; return pass; }; bool deny(xcb_timestamp_t time) { return !allow(time); }; }; POLYBAR_NS_END <|endoftext|>
<commit_before>#pragma once /** @file @brief succinct vector @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause @note use -msse4.2 option for popcnt */ #include <assert.h> #include <vector> #include <cybozu/exception.hpp> #include <cybozu/bit_operation.hpp> #include <cybozu/select8.hpp> #include <cybozu/serializer.hpp> #include <iosfwd> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace cybozu { const uint64_t NotFound = ~uint64_t(0); namespace sucvector_util { inline uint32_t rank64(uint64_t v, size_t i) { return cybozu::popcnt<uint64_t>(v & cybozu::makeBitMask64(i)); } template<class T> T getBlockNum(T x, T block) { return (x + block - 1) / block; } inline uint32_t select64(uint64_t v, size_t r) { assert(r <= 64); if (r > popcnt(v)) return 64; uint32_t pos = 0; uint32_t c = popcnt(uint32_t(v)); if (r > c) { r -= c; pos = 32; v >>= 32; } c = popcnt<uint32_t>(uint16_t(v)); if (r > c) { r -= c; pos += 16; v >>= 16; } c = popcnt<uint32_t>(uint8_t(v)); if (r > c) { r -= c; pos += 8; v >>= 8; } if (r == 8 && uint8_t(v) == 0xff) return pos + 7; assert(r <= 8); c = cybozu::select8_util::select8(uint8_t(v), r); return pos + c; } } // cybozu::sucvector_util /* extra memory (32 + 8 * 4) / 256 = 1/4 bit per bit for rank */ template<class type, bool withSelect = true> class SucVectorT { typedef type size_type; static const bool support1TiB = sizeof(size_type) == 8; static const int maxBitLen = support1TiB ? 32 + 8 : 32; // don't increase this value static const uint64_t maxBitSize = uint64_t(1) << maxBitLen; struct Block { uint64_t org[4]; union { uint64_t a64; struct { uint32_t a; uint8_t b[4]; // b[0] is used for (b[0] << 32) | a } ab; }; void clear() { memset(this, 0, sizeof(Block)); } }; uint64_t bitSize_; uint64_t numTbl_[2]; bool freezed_; std::vector<Block> blk_; typedef std::vector<uint32_t> Uint32Vec; static const uint64_t posUnit = 1024; Uint32Vec selTbl_[2]; template<int b> uint64_t rank_a(size_t i) const { assert(i < blk_.size()); uint64_t ret; if (support1TiB) { ret = blk_[i].a64 & makeBitMask64(maxBitLen); } else { ret = blk_[i].ab.a; } if (!b) ret = i * uint64_t(256) - ret; return ret; } template<bool b> size_t get_b(size_t L, size_t i) const { assert(L < blk_.size()); assert(0 < i && i < 4); size_t r = blk_[L].ab.b[i]; if (!b) r = 64 * i - r; return r; } // call after blk_, numTbl_ are initialized void initSelTbl() { if (!withSelect) return; initSelTblSub<false>(selTbl_[0]); initSelTblSub<true>(selTbl_[1]); } template<bool b> void initSelTblSub(Uint32Vec& tbl) { const int tablePos = b ? 1 : 0; assert(numTbl_[tablePos] / posUnit < 0x7fffffff - 1); const size_t size = size_t(sucvector_util::getBlockNum(numTbl_[tablePos], posUnit)); tbl.resize(size); uint32_t pos = 0; for (size_t i = 0; i < size; i++) { uint64_t r = i * posUnit; while (rank_a<b>(pos) < r) { pos++; if (pos == blk_.size()) break; } tbl[i] = pos; } } void initBlock(const uint64_t *buf, size_t blkNum) { uint64_t num1 = 0; size_t pos = 0; for (size_t i = 0, n = blk_.size(); i < n; i++) { Block& blk = blk_[i]; if (support1TiB) { blk.a64 = num1 % maxBitSize; } else { if (num1 > 0xffffffff) throw cybozu::Exception("SucVectorT:too large num1") << num1; blk.ab.a = (uint32_t)num1; } uint32_t subNum1 = 0; for (size_t j = 0; j < 4; j++) { uint64_t v; if (buf) { v = pos < blkNum ? buf[pos++] : 0; blk.org[j] = v; } else { v = blk.org[j]; } uint32_t c = cybozu::popcnt(v); num1 += c; if (j > 0) { blk.ab.b[j] = (uint8_t)subNum1; } subNum1 += c; } } numTbl_[0] = blkNum * 64 - num1; numTbl_[1] = num1; initSelTbl(); freezed_ = true; } public: /* data format(endian is depend on CPU:eg. little endian for x86/x64) bitSize : 8 numTbl_[0] : 8 numTbl_[1] : 8 blkSize : 8 blk data : blkSize * sizeof(Block) */ template<class OutputStream> void save(OutputStream& os) const { cybozu::save(os, bitSize_); cybozu::save(os, numTbl_[0]); cybozu::save(os, numTbl_[1]); cybozu::savePodVec(os, blk_); } template<class InputStream> void load(InputStream& is) { cybozu::load(bitSize_, is); cybozu::load(numTbl_[0], is); cybozu::load(numTbl_[1], is); cybozu::loadPodVec(blk_, is); } SucVectorT() : bitSize_(0), freezed_(false) { numTbl_[0] = numTbl_[1] = 0; } SucVectorT(const uint64_t *buf, uint64_t bitSize) { init(buf, bitSize); } /* initialize SucVector @param buf [in] bit pattern buffer @param bitSize [in] bitSize ; buf size = (bitSize + 63) / 64 */ void init(const uint64_t *buf, uint64_t bitSize) { const size_t blkNum = resize(bitSize, false); initBlock(buf, blkNum); } /* initialize SucVector after calling set without BitVector 1. resize(bitSize) 2. construct bit vector with set(pos) 3. ready() */ size_t resize(size_t bitSize, bool doClear = true) { if (bitSize > maxBitSize) throw cybozu::Exception("SucVectorT:resize:too large bitSize") << bitSize; assert((bitSize + 63) / 64 <= ~size_t(0)); bitSize_ = bitSize; const size_t blkNum = size_t((bitSize + 63) / 64); const size_t tblNum = (blkNum + 3) / 4; // tblNum <= 2^32 blk_.resize(tblNum); if (doClear) { for (size_t i = 0; i < tblNum; i++) { blk_[i].clear(); } } freezed_ = false; return blkNum; } void set(size_t idx) { if (freezed_) throw cybozu::Exception("SucVector:set:freezed"); if (idx >= bitSize_) throw cybozu::Exception("SucVector:set:bad idx") << idx; const size_t q = idx / 256; const size_t r = idx % 256; uint64_t& b = blk_[q].org[r / 64]; b |= uint64_t(1) << (r % 64); } void ready() { initBlock(0, blk_.size() * 4); } uint64_t rank1(uint64_t pos) const { if (pos >= bitSize_) return numTbl_[1]; assert(pos / 256 <= ~size_t(0)); size_t q = size_t(pos / 256); size_t r = size_t((pos / 64) & 3); assert(q < blk_.size()); const Block& blk = blk_[q]; uint64_t ret; if (support1TiB) { ret = blk.a64 % maxBitSize; } else { ret = blk.ab.a; } if (r > 0) { ret += blk.ab.b[r]; // faster on sandy-bridge // ret += uint8_t(blk.a64 >> (32 + r * 8)); } ret += cybozu::popcnt<uint64_t>(blk.org[r] & cybozu::makeBitMask64(pos & 63)); return ret; } uint64_t size() const { return bitSize_; } uint64_t size(bool b) const { return numTbl_[b ? 1 : 0]; } uint64_t rank0(uint64_t pos) const { return pos - rank1(pos); } uint64_t rank(bool b, uint64_t pos) const { if (b) return rank1(pos); return rank0(pos); } bool get(uint64_t pos) const { if (pos >= bitSize_) throw cybozu::Exception("SucVector:get") << pos << bitSize_; size_t q = size_t(pos / 256); size_t r = size_t((pos / 64) & 3); assert(q < blk_.size()); const Block& blk = blk_[q]; return (blk.org[r] & (1ULL << (pos & 63))) != 0; } uint64_t select0(uint64_t rank) const { return selectSub<false>(rank); } uint64_t select1(uint64_t rank) const { return selectSub<true>(rank); } uint64_t select(bool b, uint64_t rank) const { if (b) return select1(rank); return select0(rank); } /* 0123456789 0100101101 ^ ^ ^^ 0 1 23 select(v, r) = min { i - 1 | rank(v, i) = r + 1 } select(3) = 7 */ template<bool b> uint64_t selectSub(uint64_t rank) const { if (!withSelect) throw cybozu::Exception("SucVector:selectSub is not supported"); const int tablePos = b ? 1 : 0; if (rank >= numTbl_[tablePos]) return NotFound; const Uint32Vec& tbl = selTbl_[tablePos]; assert(rank / posUnit < tbl.size()); const size_t pos = size_t(rank / posUnit); size_t L = tbl[pos]; size_t R = pos >= tbl.size() - 1 ? blk_.size() : tbl[pos + 1]; rank++; while (L < R) { size_t M = (L + R) / 2; // (R - L) / 2 + L; if (rank_a<b>(M) < rank) { L = M + 1; } else { R = M; } } if (L > 0) L--; rank -= rank_a<b>(L); size_t i = 0; while (i < 3) { size_t r = get_b<b>(L, i + 1); if (r >= rank) { break; } i++; } if (i > 0) { size_t r = get_b<b>(L, i); rank -= r; } uint64_t v = blk_[L].org[i]; if (!b) v = ~v; assert(rank <= 64); uint64_t ret = cybozu::sucvector_util::select64(v, size_t(rank)); ret += L * 256 + i * 64; return ret; } }; typedef cybozu::SucVectorT<uint32_t> SucVectorLt4G; typedef cybozu::SucVectorT<uint64_t> SucVector; } // cybozu #ifdef _WIN32 #pragma warning(pop) #endif <commit_msg>Support withSelect=true in SucVectorT::save/load<commit_after>#pragma once /** @file @brief succinct vector @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause @note use -msse4.2 option for popcnt */ #include <assert.h> #include <vector> #include <cybozu/exception.hpp> #include <cybozu/bit_operation.hpp> #include <cybozu/select8.hpp> #include <cybozu/serializer.hpp> #include <iosfwd> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace cybozu { const uint64_t NotFound = ~uint64_t(0); namespace sucvector_util { inline uint32_t rank64(uint64_t v, size_t i) { return cybozu::popcnt<uint64_t>(v & cybozu::makeBitMask64(i)); } template<class T> T getBlockNum(T x, T block) { return (x + block - 1) / block; } inline uint32_t select64(uint64_t v, size_t r) { assert(r <= 64); if (r > popcnt(v)) return 64; uint32_t pos = 0; uint32_t c = popcnt(uint32_t(v)); if (r > c) { r -= c; pos = 32; v >>= 32; } c = popcnt<uint32_t>(uint16_t(v)); if (r > c) { r -= c; pos += 16; v >>= 16; } c = popcnt<uint32_t>(uint8_t(v)); if (r > c) { r -= c; pos += 8; v >>= 8; } if (r == 8 && uint8_t(v) == 0xff) return pos + 7; assert(r <= 8); c = cybozu::select8_util::select8(uint8_t(v), r); return pos + c; } } // cybozu::sucvector_util /* extra memory (32 + 8 * 4) / 256 = 1/4 bit per bit for rank */ template<class type, bool withSelect = true> class SucVectorT { typedef type size_type; static const bool support1TiB = sizeof(size_type) == 8; static const int maxBitLen = support1TiB ? 32 + 8 : 32; // don't increase this value static const uint64_t maxBitSize = uint64_t(1) << maxBitLen; struct Block { uint64_t org[4]; union { uint64_t a64; struct { uint32_t a; uint8_t b[4]; // b[0] is used for (b[0] << 32) | a } ab; }; void clear() { memset(this, 0, sizeof(Block)); } }; uint64_t bitSize_; uint64_t numTbl_[2]; bool freezed_; std::vector<Block> blk_; typedef std::vector<uint32_t> Uint32Vec; static const uint64_t posUnit = 1024; Uint32Vec selTbl_[2]; template<int b> uint64_t rank_a(size_t i) const { assert(i < blk_.size()); uint64_t ret; if (support1TiB) { ret = blk_[i].a64 & makeBitMask64(maxBitLen); } else { ret = blk_[i].ab.a; } if (!b) ret = i * uint64_t(256) - ret; return ret; } template<bool b> size_t get_b(size_t L, size_t i) const { assert(L < blk_.size()); assert(0 < i && i < 4); size_t r = blk_[L].ab.b[i]; if (!b) r = 64 * i - r; return r; } // call after blk_, numTbl_ are initialized void initSelTbl() { if (!withSelect) return; initSelTblSub<false>(selTbl_[0]); initSelTblSub<true>(selTbl_[1]); } template<bool b> void initSelTblSub(Uint32Vec& tbl) { const int tablePos = b ? 1 : 0; assert(numTbl_[tablePos] / posUnit < 0x7fffffff - 1); const size_t size = size_t(sucvector_util::getBlockNum(numTbl_[tablePos], posUnit)); tbl.resize(size); uint32_t pos = 0; for (size_t i = 0; i < size; i++) { uint64_t r = i * posUnit; while (rank_a<b>(pos) < r) { pos++; if (pos == blk_.size()) break; } tbl[i] = pos; } } void initBlock(const uint64_t *buf, size_t blkNum) { uint64_t num1 = 0; size_t pos = 0; for (size_t i = 0, n = blk_.size(); i < n; i++) { Block& blk = blk_[i]; if (support1TiB) { blk.a64 = num1 % maxBitSize; } else { if (num1 > 0xffffffff) throw cybozu::Exception("SucVectorT:too large num1") << num1; blk.ab.a = (uint32_t)num1; } uint32_t subNum1 = 0; for (size_t j = 0; j < 4; j++) { uint64_t v; if (buf) { v = pos < blkNum ? buf[pos++] : 0; blk.org[j] = v; } else { v = blk.org[j]; } uint32_t c = cybozu::popcnt(v); num1 += c; if (j > 0) { blk.ab.b[j] = (uint8_t)subNum1; } subNum1 += c; } } numTbl_[0] = blkNum * 64 - num1; numTbl_[1] = num1; initSelTbl(); freezed_ = true; } public: /* data format(endian is depend on CPU:eg. little endian for x86/x64) bitSize : 8 numTbl_[0] : 8 numTbl_[1] : 8 blkSize : 8 blk data : blkSize * sizeof(Block) */ template<class OutputStream> void save(OutputStream& os) const { cybozu::save(os, bitSize_); cybozu::save(os, numTbl_[0]); cybozu::save(os, numTbl_[1]); cybozu::savePodVec(os, blk_); if (withSelect) { cybozu::savePodVec(os, selTbl_[0]); cybozu::savePodVec(os, selTbl_[1]); } } template<class InputStream> void load(InputStream& is) { cybozu::load(bitSize_, is); cybozu::load(numTbl_[0], is); cybozu::load(numTbl_[1], is); cybozu::loadPodVec(blk_, is); if (withSelect) { cybozu::loadPodVec(selTbl_[0], is); cybozu::loadPodVec(selTbl_[1], is); } else { initSelTbl(); } } SucVectorT() : bitSize_(0), freezed_(false) { numTbl_[0] = numTbl_[1] = 0; } SucVectorT(const uint64_t *buf, uint64_t bitSize) { init(buf, bitSize); } /* initialize SucVector @param buf [in] bit pattern buffer @param bitSize [in] bitSize ; buf size = (bitSize + 63) / 64 */ void init(const uint64_t *buf, uint64_t bitSize) { const size_t blkNum = resize(bitSize, false); initBlock(buf, blkNum); } /* initialize SucVector after calling set without BitVector 1. resize(bitSize) 2. construct bit vector with set(pos) 3. ready() */ size_t resize(size_t bitSize, bool doClear = true) { if (bitSize > maxBitSize) throw cybozu::Exception("SucVectorT:resize:too large bitSize") << bitSize; assert((bitSize + 63) / 64 <= ~size_t(0)); bitSize_ = bitSize; const size_t blkNum = size_t((bitSize + 63) / 64); const size_t tblNum = (blkNum + 3) / 4; // tblNum <= 2^32 blk_.resize(tblNum); if (doClear) { for (size_t i = 0; i < tblNum; i++) { blk_[i].clear(); } } freezed_ = false; return blkNum; } void set(size_t idx) { if (freezed_) throw cybozu::Exception("SucVector:set:freezed"); if (idx >= bitSize_) throw cybozu::Exception("SucVector:set:bad idx") << idx; const size_t q = idx / 256; const size_t r = idx % 256; uint64_t& b = blk_[q].org[r / 64]; b |= uint64_t(1) << (r % 64); } void ready() { initBlock(0, blk_.size() * 4); } uint64_t rank1(uint64_t pos) const { if (pos >= bitSize_) return numTbl_[1]; assert(pos / 256 <= ~size_t(0)); size_t q = size_t(pos / 256); size_t r = size_t((pos / 64) & 3); assert(q < blk_.size()); const Block& blk = blk_[q]; uint64_t ret; if (support1TiB) { ret = blk.a64 % maxBitSize; } else { ret = blk.ab.a; } if (r > 0) { ret += blk.ab.b[r]; // faster on sandy-bridge // ret += uint8_t(blk.a64 >> (32 + r * 8)); } ret += cybozu::popcnt<uint64_t>(blk.org[r] & cybozu::makeBitMask64(pos & 63)); return ret; } uint64_t size() const { return bitSize_; } uint64_t size(bool b) const { return numTbl_[b ? 1 : 0]; } uint64_t rank0(uint64_t pos) const { return pos - rank1(pos); } uint64_t rank(bool b, uint64_t pos) const { if (b) return rank1(pos); return rank0(pos); } bool get(uint64_t pos) const { if (pos >= bitSize_) throw cybozu::Exception("SucVector:get") << pos << bitSize_; size_t q = size_t(pos / 256); size_t r = size_t((pos / 64) & 3); assert(q < blk_.size()); const Block& blk = blk_[q]; return (blk.org[r] & (1ULL << (pos & 63))) != 0; } uint64_t select0(uint64_t rank) const { return selectSub<false>(rank); } uint64_t select1(uint64_t rank) const { return selectSub<true>(rank); } uint64_t select(bool b, uint64_t rank) const { if (b) return select1(rank); return select0(rank); } /* 0123456789 0100101101 ^ ^ ^^ 0 1 23 select(v, r) = min { i - 1 | rank(v, i) = r + 1 } select(3) = 7 */ template<bool b> uint64_t selectSub(uint64_t rank) const { if (!withSelect) throw cybozu::Exception("SucVector:selectSub is not supported"); const int tablePos = b ? 1 : 0; if (rank >= numTbl_[tablePos]) return NotFound; const Uint32Vec& tbl = selTbl_[tablePos]; assert(rank / posUnit < tbl.size()); const size_t pos = size_t(rank / posUnit); size_t L = tbl[pos]; size_t R = pos >= tbl.size() - 1 ? blk_.size() : tbl[pos + 1]; rank++; while (L < R) { size_t M = (L + R) / 2; // (R - L) / 2 + L; if (rank_a<b>(M) < rank) { L = M + 1; } else { R = M; } } if (L > 0) L--; rank -= rank_a<b>(L); size_t i = 0; while (i < 3) { size_t r = get_b<b>(L, i + 1); if (r >= rank) { break; } i++; } if (i > 0) { size_t r = get_b<b>(L, i); rank -= r; } uint64_t v = blk_[L].org[i]; if (!b) v = ~v; assert(rank <= 64); uint64_t ret = cybozu::sucvector_util::select64(v, size_t(rank)); ret += L * 256 + i * 64; return ret; } }; typedef cybozu::SucVectorT<uint32_t> SucVectorLt4G; typedef cybozu::SucVectorT<uint64_t> SucVector; } // cybozu #ifdef _WIN32 #pragma warning(pop) #endif <|endoftext|>
<commit_before>/** * This file contains configuration options and macros to stay portable. * * If we have access to boost, use their macros to achieve maximum * portability. Otherwise, roll our own macros and support some common cases. * * To signal that boost is available, define the `D2_HAS_BOOST` macro before * including this header. * * @internal This header is included in the public API, hence the care to keep * it compatible with C (no C++ comments!) and not to take for * granted the availability of boost. */ #ifndef D2_DETAIL_CONFIG_HPP #define D2_DETAIL_CONFIG_HPP #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) # define D2_WIN32 #endif #if defined(D2_HAS_BOOST) # include <boost/config.hpp> # define D2_SYMBOL_IMPORT BOOST_SYMBOL_IMPORT # define D2_SYMBOL_EXPORT BOOST_SYMBOL_EXPORT #else # if defined(D2_WIN32) # define D2_SYMBOL_IMPORT __declspec(dllimport) # define D2_SYMBOL_EXPORT __declspec(dllexport) # else # define D2_SYMBOL_IMPORT /* nothing */ # define D2_SYMBOL_EXPORT /* nothing */ # endif #endif /* defined(D2_HAS_BOOST) */ #if defined(D2_DYN_LINK) # if defined(D2_SOURCE) # define D2_API BOOST_SYMBOL_EXPORT # else # define D2_API BOOST_SYMBOL_IMPORT # endif #else # define D2_API /* nothing */ #endif #endif /* !D2_DETAIL_CONFIG_HPP */ <commit_msg>Fix D2_SYMBOL_IMPORT/EXPORT definition.<commit_after>/** * This file contains configuration options and macros to stay portable. * * If we have access to boost, use their macros to achieve maximum * portability. Otherwise, roll our own macros and support some common cases. * * To signal that boost is available, define the `D2_HAS_BOOST` macro before * including this header. * * @internal This header is included in the public API, hence the care to keep * it compatible with C (no C++ comments!) and not to take for * granted the availability of boost. */ #ifndef D2_DETAIL_CONFIG_HPP #define D2_DETAIL_CONFIG_HPP #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) # define D2_WIN32 #endif #if defined(D2_HAS_BOOST) # include <boost/config.hpp> # define D2_SYMBOL_IMPORT BOOST_SYMBOL_IMPORT # define D2_SYMBOL_EXPORT BOOST_SYMBOL_EXPORT #else # if defined(D2_WIN32) # define D2_SYMBOL_IMPORT __declspec(dllimport) # define D2_SYMBOL_EXPORT __declspec(dllexport) # else # define D2_SYMBOL_IMPORT /* nothing */ # define D2_SYMBOL_EXPORT /* nothing */ # endif #endif /* defined(D2_HAS_BOOST) */ #if defined(D2_DYN_LINK) # if defined(D2_SOURCE) # define D2_API D2_SYMBOL_EXPORT # else # define D2_API D2_SYMBOL_IMPORT # endif #else # define D2_API /* nothing */ #endif #endif /* !D2_DETAIL_CONFIG_HPP */ <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #ifndef INCLUDED_POINTBUFFER_HPP #define INCLUDED_POINTBUFFER_HPP #include <boost/scoped_array.hpp> #include <boost/lexical_cast.hpp> #include <pdal/pdal_internal.hpp> #include <pdal/Bounds.hpp> #include <pdal/Schema.hpp> namespace pdal { // a PointBuffer object is just an untyped array of N bytes, // where N is (the size of the given Schema * the number of points) // // That is, a PointBuffer represents the underlying data for one or more points. // // A PointBuffer object has an associated Schema object. // // Many of the methods take a first parameter "index", to specify which point in the // collection is to be operated upon. The point index is a uint32; you can't read // more than 4 billion points at a time. class PDAL_DLL PointBuffer { public: // note that when we make a PointBuffer object all the fields are initialized to inactive, // regardless of what the passed-in schema says -- this is because the field object // represents the state within the owning object, which in this case is a completely // empty buffer (similarly, all the points in the buffer are marked "invalid") PointBuffer(const Schema&, boost::uint32_t capacity); PointBuffer(const PointBuffer&); PointBuffer& operator=(const PointBuffer&); ~PointBuffer(); const Bounds<double>& getSpatialBounds() const; void setSpatialBounds(const Bounds<double>& bounds); // This is the number of points in this buffer that actually have valid data. This number // will be less than or equal to the getCapacity() value. boost::uint32_t getNumPoints() const; inline void setNumPoints(boost::uint32_t v) { assert(v <= m_capacity);m_numPoints = v; } // This is the number of points that this buffer is allocated to be able to store. // This is a fixed constant, set at ctor time by the person constructing the buffer. inline boost::uint32_t getCapacity() const { return m_capacity; } const Schema& getSchema() const { return m_schema; } // accessors to a particular field of a particular point in this buffer template<class T> T getField(std::size_t pointIndex, boost::int32_t fieldIndex) const; template<class T> T getField(Dimension const& dim, std::size_t pointIndex) const; template<class T> T getRawField(std::size_t pointIndex, std::size_t pointBytePosition) const; template<class T> void setField(std::size_t pointIndex, boost::int32_t fieldIndex, T value); template<class T> void setField(Dimension const& dim, std::size_t pointIndex, T value); void setFieldData(std::size_t pointIndex, boost::int32_t fieldIndex, const boost::uint8_t* data); // bulk copy all the fields from the given point into this object // NOTE: this is only legal if the src and dest schemas are exactly the same // (later, this will be implemented properly, to handle the general cases slowly and the best case quickly) inline void copyPointFast(std::size_t destPointIndex, std::size_t srcPointIndex, const PointBuffer& srcPointBuffer) { const boost::uint8_t* src = srcPointBuffer.getData(srcPointIndex); boost::uint8_t* dest = getData(destPointIndex); memcpy(dest, src, m_byteSize); assert(m_numPoints <= m_capacity); return; } // same as above, but copies N points inline void copyPointsFast(std::size_t destPointIndex, std::size_t srcPointIndex, const PointBuffer& srcPointBuffer, std::size_t numPoints) { const boost::uint8_t* src = srcPointBuffer.getData(srcPointIndex); boost::uint8_t* dest = getData(destPointIndex); memcpy(dest, src, m_byteSize * numPoints); assert(m_numPoints <= m_capacity); return; } inline boost::uint64_t getBufferByteLength() const { return m_byteSize * m_numPoints; } inline boost::uint64_t getBufferByteCapacity() const { return m_schema.getByteSize() * m_capacity; } // access to the raw memory inline boost::uint8_t* getData(std::size_t pointIndex) const { return m_data.get() + m_schema.getByteSize() * pointIndex; } inline boost::uint8_t* getData(std::size_t pointIndex) { return m_data.get() + m_schema.getByteSize() * pointIndex; } // copy in raw data void setData(boost::uint8_t* data, std::size_t pointIndex); void setAllData(boost::uint8_t* data, boost::uint32_t byteCount); void setDataStride(boost::uint8_t* data, std::size_t index, boost::uint32_t byteCount); // access to the raw memory void getData(boost::uint8_t** data, std::size_t* array_size) const; // returns a ptree containing the point records, useful for dumping // and such // // The tree will look like this: // // 0: // X: 1.00 // Y: 2.00 // Z: 3.00 // 1: // X: 1.00 // Y: 2.00 // Z: 3.00 // // If you want to print out details about the fields, e.g. the byte // offset or the datatype, use the Schema's ptree dumper. // boost::property_tree::ptree toPTree() const; private: Schema m_schema; boost::scoped_array<boost::uint8_t> m_data; boost::uint32_t m_numPoints; boost::uint32_t m_capacity; Bounds<double> m_bounds; schema::size_type m_byteSize; }; template <class T> inline void PointBuffer::setField(std::size_t pointIndex, boost::int32_t fieldIndex, T value) { if (fieldIndex == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw pdal_error("filedIndex is not valid at this point of access"); } const Dimension& dim = m_schema.getDimension(fieldIndex); std::size_t offset = (pointIndex * m_byteSize ) + dim.getByteOffset(); assert(offset + sizeof(T) <= m_byteSize * m_capacity); boost::uint8_t* p = m_data.get() + offset; *(T*)(void*)p = value; } template <class T> inline void PointBuffer::setField(pdal::Dimension const& dim, std::size_t pointIndex, T value) { if (dim.getPosition() == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw buffer_error("This dimension has no identified position in a schema. Use the setRawField method to access an arbitrary byte position."); } std::size_t offset = (pointIndex * m_byteSize ) + dim.getByteOffset(); assert(offset + sizeof(T) <= m_byteSize * m_capacity); boost::uint8_t* p = m_data.get() + offset; if (sizeof(T) == dim.getByteSize()) { // Winner, winner, chicken dinner. We're not going to try to // do anything magical. It's up to you to get the interpretation right. *(T*)(void*)p = value; } T output(0); output = boost::lexical_cast<T>(value); *(T*)(void*)p = output; } inline void PointBuffer::setFieldData(std::size_t pointIndex, boost::int32_t fieldIndex, const boost::uint8_t* data) { if (fieldIndex == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw pdal_error("filedIndex is not valid at this point of access"); } const Dimension& dim = m_schema.getDimension(fieldIndex); std::size_t offset = (pointIndex * m_byteSize) + dim.getByteOffset(); std::size_t size = dim.getDataTypeSize(dim.getDataType()); // std::cout << "copying field " << d.getFieldName() << " with index" << fieldIndex << " of size " << size << " at offset " << offset << std::endl; // assert(offset + sizeof(T) <= m_schema.getByteSize() * m_capacity); boost::uint8_t* p = m_data.get() + offset; memcpy(p, data, size); } template <class T> inline T PointBuffer::getField(std::size_t pointIndex, boost::int32_t fieldIndex) const { if (fieldIndex == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw pdal_error("filedIndex is not valid at this point of access"); } const Dimension& dim = m_schema.getDimension(fieldIndex); std::size_t offset = (pointIndex * m_byteSize) + dim.getByteOffset(); assert(offset + sizeof(T) <= m_byteSize * m_capacity); boost::uint8_t* p = m_data.get() + offset; return *(T*)(void*)p; } template <class T> inline T PointBuffer::getField(pdal::Dimension const& dim, std::size_t pointIndex) const { if (dim.getPosition() == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw buffer_error("This dimension has no identified position in a schema. Use the getRawField method to access an arbitrary byte position."); } std::size_t offset = (pointIndex * m_schema.getByteSize()) + dim.getByteOffset(); if (offset + sizeof(T) > m_byteSize * m_capacity) { std::ostringstream oss; oss << "Offset for given dimension is off the end of the buffer!"; throw buffer_error(oss.str()); } assert(offset + sizeof(T) <= m_byteSize * m_capacity); boost::uint8_t* p = m_data.get() + offset; // If the byte size of what was requested is the same as our dimension's // We're just going to give it back to you. If not, we're going to try to do // some magic below to try to give you what you asked for. if (sizeof(T) == dim.getByteSize()) { // Winner, winner, chicken dinner. We're not going to try to // do anything magical. It's up to you to get the interpretation right. return *(T*)(void*)p; } T output(0); float flt(0.0); double dbl(0.0); boost::int8_t i8(0); boost::uint8_t u8(0); boost::int16_t i16(0); boost::uint16_t u16(0); boost::int32_t i32(0); boost::uint32_t u32(0); boost::int64_t i64(0); boost::uint64_t u64(0); switch (dim.getInterpretation()) { case dimension::SignedByte: i8 = *(boost::int8_t*)(void*)p; output = boost::lexical_cast<T>(i8); break; case dimension::UnsignedByte: u8 = *(boost::uint8_t*)(void*)p; output = boost::lexical_cast<T>(u8); break; case dimension::SignedInteger: if (dim.getByteSize() == 1 ) { i8 = *(boost::int8_t*)(void*)p; output = boost::lexical_cast<T>(i8); } else if (dim.getByteSize() == 2) { i16 = *(boost::int16_t*)(void*)p; output = boost::lexical_cast<T>(i16); } else if (dim.getByteSize() == 4) { i32 = *(boost::int32_t*)(void*)p; output = boost::lexical_cast<T>(i32); } else if (dim.getByteSize() == 8) { i64 = *(boost::int64_t*)(void*)p; output = boost::lexical_cast<T>(i64); } else { throw buffer_error("getField::Unhandled datatype size for SignedInteger"); } break; case dimension::UnsignedInteger: if (dim.getByteSize() == 1 ) { u8 = *(boost::uint8_t*)(void*)p; output = boost::lexical_cast<T>(u8); } else if (dim.getByteSize() == 2) { u16 = *(boost::uint16_t*)(void*)p; output = boost::lexical_cast<T>(u16); } else if (dim.getByteSize() == 4) { u32 = *(boost::uint32_t*)(void*)p; output = boost::lexical_cast<T>(u32); } else if (dim.getByteSize() == 8) { u64 = *(boost::uint64_t*)(void*)p; output = boost::lexical_cast<T>(u64); } else { throw buffer_error("getField::Unhandled datatype size for UnsignedInteger"); } break; case dimension::Float: if (dim.getByteSize() == 4) { flt = *(float*)(void*)p; output = boost::lexical_cast<T>(flt); } else if (dim.getByteSize() == 8) { dbl = *(double*)(void*)p; output = boost::lexical_cast<T>(dbl); } else { throw buffer_error("getField::Unhandled datatype size for Float"); } break; case dimension::Pointer: break; default: throw buffer_error("Undefined interpretation for getField"); } return output; } template <class T> inline T PointBuffer::getRawField(std::size_t pointIndex, std::size_t pointBytePosition) const { std::size_t offset = (pointIndex * m_byteSize ) + pointBytePosition; boost::uint8_t* p = m_data.get() + offset; return *(T*)(void*)p; } PDAL_DLL std::ostream& operator<<(std::ostream& ostr, const PointBuffer&); } // namespace pdal #endif <commit_msg>whitespace normalization<commit_after>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #ifndef INCLUDED_POINTBUFFER_HPP #define INCLUDED_POINTBUFFER_HPP #include <boost/scoped_array.hpp> #include <boost/lexical_cast.hpp> #include <pdal/pdal_internal.hpp> #include <pdal/Bounds.hpp> #include <pdal/Schema.hpp> namespace pdal { // a PointBuffer object is just an untyped array of N bytes, // where N is (the size of the given Schema * the number of points) // // That is, a PointBuffer represents the underlying data for one or more points. // // A PointBuffer object has an associated Schema object. // // Many of the methods take a first parameter "index", to specify which point in the // collection is to be operated upon. The point index is a uint32; you can't read // more than 4 billion points at a time. class PDAL_DLL PointBuffer { public: // note that when we make a PointBuffer object all the fields are initialized to inactive, // regardless of what the passed-in schema says -- this is because the field object // represents the state within the owning object, which in this case is a completely // empty buffer (similarly, all the points in the buffer are marked "invalid") PointBuffer(const Schema&, boost::uint32_t capacity); PointBuffer(const PointBuffer&); PointBuffer& operator=(const PointBuffer&); ~PointBuffer(); const Bounds<double>& getSpatialBounds() const; void setSpatialBounds(const Bounds<double>& bounds); // This is the number of points in this buffer that actually have valid data. This number // will be less than or equal to the getCapacity() value. boost::uint32_t getNumPoints() const; inline void setNumPoints(boost::uint32_t v) { assert(v <= m_capacity);m_numPoints = v; } // This is the number of points that this buffer is allocated to be able to store. // This is a fixed constant, set at ctor time by the person constructing the buffer. inline boost::uint32_t getCapacity() const { return m_capacity; } const Schema& getSchema() const { return m_schema; } // accessors to a particular field of a particular point in this buffer template<class T> T getField(std::size_t pointIndex, boost::int32_t fieldIndex) const; template<class T> T getField(Dimension const& dim, std::size_t pointIndex) const; template<class T> T getRawField(std::size_t pointIndex, std::size_t pointBytePosition) const; template<class T> void setField(std::size_t pointIndex, boost::int32_t fieldIndex, T value); template<class T> void setField(Dimension const& dim, std::size_t pointIndex, T value); void setFieldData(std::size_t pointIndex, boost::int32_t fieldIndex, const boost::uint8_t* data); // bulk copy all the fields from the given point into this object // NOTE: this is only legal if the src and dest schemas are exactly the same // (later, this will be implemented properly, to handle the general cases slowly and the best case quickly) inline void copyPointFast(std::size_t destPointIndex, std::size_t srcPointIndex, const PointBuffer& srcPointBuffer) { const boost::uint8_t* src = srcPointBuffer.getData(srcPointIndex); boost::uint8_t* dest = getData(destPointIndex); memcpy(dest, src, m_byteSize); assert(m_numPoints <= m_capacity); return; } // same as above, but copies N points inline void copyPointsFast(std::size_t destPointIndex, std::size_t srcPointIndex, const PointBuffer& srcPointBuffer, std::size_t numPoints) { const boost::uint8_t* src = srcPointBuffer.getData(srcPointIndex); boost::uint8_t* dest = getData(destPointIndex); memcpy(dest, src, m_byteSize * numPoints); assert(m_numPoints <= m_capacity); return; } inline boost::uint64_t getBufferByteLength() const { return m_byteSize * m_numPoints; } inline boost::uint64_t getBufferByteCapacity() const { return m_schema.getByteSize() * m_capacity; } // access to the raw memory inline boost::uint8_t* getData(std::size_t pointIndex) const { return m_data.get() + m_schema.getByteSize() * pointIndex; } inline boost::uint8_t* getData(std::size_t pointIndex) { return m_data.get() + m_schema.getByteSize() * pointIndex; } // copy in raw data void setData(boost::uint8_t* data, std::size_t pointIndex); void setAllData(boost::uint8_t* data, boost::uint32_t byteCount); void setDataStride(boost::uint8_t* data, std::size_t index, boost::uint32_t byteCount); // access to the raw memory void getData(boost::uint8_t** data, std::size_t* array_size) const; // returns a ptree containing the point records, useful for dumping // and such // // The tree will look like this: // // 0: // X: 1.00 // Y: 2.00 // Z: 3.00 // 1: // X: 1.00 // Y: 2.00 // Z: 3.00 // // If you want to print out details about the fields, e.g. the byte // offset or the datatype, use the Schema's ptree dumper. // boost::property_tree::ptree toPTree() const; private: Schema m_schema; boost::scoped_array<boost::uint8_t> m_data; boost::uint32_t m_numPoints; boost::uint32_t m_capacity; Bounds<double> m_bounds; schema::size_type m_byteSize; }; template <class T> inline void PointBuffer::setField(std::size_t pointIndex, boost::int32_t fieldIndex, T value) { if (fieldIndex == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw pdal_error("filedIndex is not valid at this point of access"); } const Dimension& dim = m_schema.getDimension(fieldIndex); std::size_t offset = (pointIndex * m_byteSize ) + dim.getByteOffset(); assert(offset + sizeof(T) <= m_byteSize * m_capacity); boost::uint8_t* p = m_data.get() + offset; *(T*)(void*)p = value; } template <class T> inline void PointBuffer::setField(pdal::Dimension const& dim, std::size_t pointIndex, T value) { if (dim.getPosition() == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw buffer_error("This dimension has no identified position in a schema. Use the setRawField method to access an arbitrary byte position."); } std::size_t offset = (pointIndex * m_byteSize ) + dim.getByteOffset(); assert(offset + sizeof(T) <= m_byteSize * m_capacity); boost::uint8_t* p = m_data.get() + offset; if (sizeof(T) == dim.getByteSize()) { // Winner, winner, chicken dinner. We're not going to try to // do anything magical. It's up to you to get the interpretation right. *(T*)(void*)p = value; } T output(0); output = boost::lexical_cast<T>(value); *(T*)(void*)p = output; } inline void PointBuffer::setFieldData(std::size_t pointIndex, boost::int32_t fieldIndex, const boost::uint8_t* data) { if (fieldIndex == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw pdal_error("filedIndex is not valid at this point of access"); } const Dimension& dim = m_schema.getDimension(fieldIndex); std::size_t offset = (pointIndex * m_byteSize) + dim.getByteOffset(); std::size_t size = dim.getDataTypeSize(dim.getDataType()); // std::cout << "copying field " << d.getFieldName() << " with index" << fieldIndex << " of size " << size << " at offset " << offset << std::endl; // assert(offset + sizeof(T) <= m_schema.getByteSize() * m_capacity); boost::uint8_t* p = m_data.get() + offset; memcpy(p, data, size); } template <class T> inline T PointBuffer::getField(std::size_t pointIndex, boost::int32_t fieldIndex) const { if (fieldIndex == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw pdal_error("filedIndex is not valid at this point of access"); } const Dimension& dim = m_schema.getDimension(fieldIndex); std::size_t offset = (pointIndex * m_byteSize) + dim.getByteOffset(); assert(offset + sizeof(T) <= m_byteSize * m_capacity); boost::uint8_t* p = m_data.get() + offset; return *(T*)(void*)p; } template <class T> inline T PointBuffer::getField(pdal::Dimension const& dim, std::size_t pointIndex) const { if (dim.getPosition() == -1) { // this is a little harsh, but we'll keep it for now as we shake things out throw buffer_error("This dimension has no identified position in a schema. Use the getRawField method to access an arbitrary byte position."); } std::size_t offset = (pointIndex * m_schema.getByteSize()) + dim.getByteOffset(); if (offset + sizeof(T) > m_byteSize * m_capacity) { std::ostringstream oss; oss << "Offset for given dimension is off the end of the buffer!"; throw buffer_error(oss.str()); } assert(offset + sizeof(T) <= m_byteSize * m_capacity); boost::uint8_t* p = m_data.get() + offset; // If the byte size of what was requested is the same as our dimension's // We're just going to give it back to you. If not, we're going to try to do // some magic below to try to give you what you asked for. if (sizeof(T) == dim.getByteSize()) { // Winner, winner, chicken dinner. We're not going to try to // do anything magical. It's up to you to get the interpretation right. return *(T*)(void*)p; } T output(0); float flt(0.0); double dbl(0.0); boost::int8_t i8(0); boost::uint8_t u8(0); boost::int16_t i16(0); boost::uint16_t u16(0); boost::int32_t i32(0); boost::uint32_t u32(0); boost::int64_t i64(0); boost::uint64_t u64(0); switch (dim.getInterpretation()) { case dimension::SignedByte: i8 = *(boost::int8_t*)(void*)p; output = boost::lexical_cast<T>(i8); break; case dimension::UnsignedByte: u8 = *(boost::uint8_t*)(void*)p; output = boost::lexical_cast<T>(u8); break; case dimension::SignedInteger: if (dim.getByteSize() == 1 ) { i8 = *(boost::int8_t*)(void*)p; output = boost::lexical_cast<T>(i8); } else if (dim.getByteSize() == 2) { i16 = *(boost::int16_t*)(void*)p; output = boost::lexical_cast<T>(i16); } else if (dim.getByteSize() == 4) { i32 = *(boost::int32_t*)(void*)p; output = boost::lexical_cast<T>(i32); } else if (dim.getByteSize() == 8) { i64 = *(boost::int64_t*)(void*)p; output = boost::lexical_cast<T>(i64); } else { throw buffer_error("getField::Unhandled datatype size for SignedInteger"); } break; case dimension::UnsignedInteger: if (dim.getByteSize() == 1 ) { u8 = *(boost::uint8_t*)(void*)p; output = boost::lexical_cast<T>(u8); } else if (dim.getByteSize() == 2) { u16 = *(boost::uint16_t*)(void*)p; output = boost::lexical_cast<T>(u16); } else if (dim.getByteSize() == 4) { u32 = *(boost::uint32_t*)(void*)p; output = boost::lexical_cast<T>(u32); } else if (dim.getByteSize() == 8) { u64 = *(boost::uint64_t*)(void*)p; output = boost::lexical_cast<T>(u64); } else { throw buffer_error("getField::Unhandled datatype size for UnsignedInteger"); } break; case dimension::Float: if (dim.getByteSize() == 4) { flt = *(float*)(void*)p; output = boost::lexical_cast<T>(flt); } else if (dim.getByteSize() == 8) { dbl = *(double*)(void*)p; output = boost::lexical_cast<T>(dbl); } else { throw buffer_error("getField::Unhandled datatype size for Float"); } break; case dimension::Pointer: break; default: throw buffer_error("Undefined interpretation for getField"); } return output; } template <class T> inline T PointBuffer::getRawField(std::size_t pointIndex, std::size_t pointBytePosition) const { std::size_t offset = (pointIndex * m_byteSize ) + pointBytePosition; boost::uint8_t* p = m_data.get() + offset; return *(T*)(void*)p; } PDAL_DLL std::ostream& operator<<(std::ostream& ostr, const PointBuffer&); } // namespace pdal #endif <|endoftext|>
<commit_before>/// /// @file Wheel.hpp /// @brief Wheel factorization is used to skip multiles of /// small primes in the sieve of Eratosthenes. /// /// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef WHEEL_HPP #define WHEEL_HPP #include "pmath.hpp" #include <stdint.h> #include <algorithm> #include <cassert> namespace primesieve { /// The WheelInit data structure is used to calculate the /// first multiple >= start of each sieving prime /// struct WheelInit { uint8_t nextMultipleFactor; uint8_t wheelIndex; }; extern const WheelInit wheel30Init[30]; extern const WheelInit wheel210Init[210]; /// The WheelElement data structure is used to skip multiples /// of small primes using wheel factorization /// struct WheelElement { /// Bitmask used to unset the bit corresponding to the current /// multiple of a SievingPrime object uint8_t unsetBit; /// Factor used to calculate the next multiple of a sieving prime /// that is not divisible by any of the wheel factors uint8_t nextMultipleFactor; /// Overflow needed to correct the next multiple index /// (due to sievingPrime = prime / 30) uint8_t correct; /// Used to get the next wheel index: /// wheelIndex = next; uint32_t next; }; /// The compiler should add 1 byte of padding to WheelElement static_assert(isPow2(sizeof(WheelElement)), "For best performance sizeof(WheelElement) must be a power of 2!"); extern const WheelElement wheel30[8*8]; extern const WheelElement wheel210[8*48]; /// The abstract Wheel class is used skip multiples of small /// primes in the sieve of Eratosthenes. The EratSmall, /// EratMedium and EratBig classes are derived from Wheel. /// template <int MODULO, int SIZE, int MAXMULTIPLEFACTOR, const WheelInit* INIT> class Wheel { public: /// Add a new sieving prime to the sieving algorithm. /// Calculate the first multiple > segmentLow of prime and /// the position within the sieve array of that multiple /// and its wheel index. When done store the sieving prime. /// void addSievingPrime(uint64_t prime, uint64_t segmentLow) { assert(segmentLow % 30 == 0); // This hack is required because in primesieve the 8 // bits of each byte (of the sieve array) correspond to // the offsets { 7, 11, 13, 17, 19, 23, 29, 31 }. // So we are looking for: multiples > segmentLow + 6. segmentLow += 6; // calculate the first multiple (of prime) > segmentLow uint64_t quotient = (segmentLow / prime) + 1; quotient = std::max(prime, quotient); uint64_t multiple = prime * quotient; // prime not needed for sieving if (multiple > stop_ || multiple < segmentLow) return; // calculate the next multiple of prime that is not // divisible by any of the wheel's factors uint64_t nextMultipleFactor = INIT[quotient % MODULO].nextMultipleFactor; uint64_t nextMultiple = prime * nextMultipleFactor; if (nextMultiple > stop_ - multiple) return; nextMultiple += multiple - segmentLow; uint64_t multipleIndex = nextMultiple / 30; uint64_t wheelIndex = wheelOffsets_[prime % 30] + INIT[quotient % MODULO].wheelIndex; storeSievingPrime(prime, multipleIndex, wheelIndex); } protected: uint64_t stop_ = 0; virtual ~Wheel() = default; virtual void storeSievingPrime(uint64_t, uint64_t, uint64_t) = 0; static uint64_t getMaxFactor() { return MAXMULTIPLEFACTOR; } private: static const uint64_t wheelOffsets_[30]; }; template <int MODULO, int SIZE, int MAXMULTIPLEFACTOR, const WheelInit* INIT> const uint64_t Wheel<MODULO, SIZE, MAXMULTIPLEFACTOR, INIT>::wheelOffsets_[30] = { 0, SIZE * 7, 0, 0, 0, 0, 0, SIZE * 0, 0, 0, 0, SIZE * 1, 0, SIZE * 2, 0, 0, 0, SIZE * 3, 0, SIZE * 4, 0, 0, 0, SIZE * 5, 0, 0, 0, 0, 0, SIZE * 6 }; /// 3rd wheel, skips multiples of 2, 3 and 5 using Wheel30_t = Wheel<30, 8, 6, wheel30Init>; /// 4th wheel, skips multiples of 2, 3, 5 and 7 using Wheel210_t = Wheel<210, 48, 10, wheel210Init>; } // namespace #endif <commit_msg>Update comment<commit_after>/// /// @file Wheel.hpp /// @brief Wheel factorization is used to skip multiles of /// small primes in the sieve of Eratosthenes. /// /// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef WHEEL_HPP #define WHEEL_HPP #include "pmath.hpp" #include <stdint.h> #include <algorithm> #include <cassert> namespace primesieve { /// The WheelInit data structure is used to calculate the /// first multiple >= start of each sieving prime. /// struct WheelInit { uint8_t nextMultipleFactor; uint8_t wheelIndex; }; extern const WheelInit wheel30Init[30]; extern const WheelInit wheel210Init[210]; /// The WheelElement data structure is used to skip multiples /// of small primes using wheel factorization. /// struct WheelElement { /// Bitmask used to unset the bit corresponding to the /// current multiple of a SievingPrime object. uint8_t unsetBit; /// Factor used to calculate the next multiple of a sieving /// prime that is not divisible by any of the wheel factors. uint8_t nextMultipleFactor; /// Overflow needed to correct the next multiple index /// (due to sievingPrime = prime / 30) uint8_t correct; /// Used to get the next wheel index: /// wheelIndex = next; uint32_t next; }; /// The compiler must insert 1 byte of padding to WheelElement /// before the uint32_t WheelElement::next variable so that /// this variable is properly aligned to a 4-byte boundary. static_assert(isPow2(sizeof(WheelElement)), "For best performance sizeof(WheelElement) must be a power of 2!"); extern const WheelElement wheel30[8*8]; extern const WheelElement wheel210[8*48]; /// The abstract Wheel class is used skip multiples of small /// primes in the sieve of Eratosthenes. The EratSmall, /// EratMedium and EratBig classes are derived from Wheel. /// template <int MODULO, int SIZE, int MAXMULTIPLEFACTOR, const WheelInit* INIT> class Wheel { public: /// Add a new sieving prime to the sieving algorithm. /// Calculate the first multiple > segmentLow of prime and /// the position within the sieve array of that multiple /// and its wheel index. When done store the sieving prime. /// void addSievingPrime(uint64_t prime, uint64_t segmentLow) { assert(segmentLow % 30 == 0); // This hack is required because in primesieve the 8 // bits of each byte (of the sieve array) correspond to // the offsets { 7, 11, 13, 17, 19, 23, 29, 31 }. // So we are looking for: multiples > segmentLow + 6. segmentLow += 6; // calculate the first multiple (of prime) > segmentLow uint64_t quotient = (segmentLow / prime) + 1; quotient = std::max(prime, quotient); uint64_t multiple = prime * quotient; // prime not needed for sieving if (multiple > stop_ || multiple < segmentLow) return; // calculate the next multiple of prime that is not // divisible by any of the wheel's factors uint64_t nextMultipleFactor = INIT[quotient % MODULO].nextMultipleFactor; uint64_t nextMultiple = prime * nextMultipleFactor; if (nextMultiple > stop_ - multiple) return; nextMultiple += multiple - segmentLow; uint64_t multipleIndex = nextMultiple / 30; uint64_t wheelIndex = wheelOffsets_[prime % 30] + INIT[quotient % MODULO].wheelIndex; storeSievingPrime(prime, multipleIndex, wheelIndex); } protected: uint64_t stop_ = 0; virtual ~Wheel() = default; virtual void storeSievingPrime(uint64_t, uint64_t, uint64_t) = 0; static uint64_t getMaxFactor() { return MAXMULTIPLEFACTOR; } private: static const uint64_t wheelOffsets_[30]; }; template <int MODULO, int SIZE, int MAXMULTIPLEFACTOR, const WheelInit* INIT> const uint64_t Wheel<MODULO, SIZE, MAXMULTIPLEFACTOR, INIT>::wheelOffsets_[30] = { 0, SIZE * 7, 0, 0, 0, 0, 0, SIZE * 0, 0, 0, 0, SIZE * 1, 0, SIZE * 2, 0, 0, 0, SIZE * 3, 0, SIZE * 4, 0, 0, 0, SIZE * 5, 0, 0, 0, 0, 0, SIZE * 6 }; /// 3rd wheel, skips multiples of 2, 3 and 5 using Wheel30_t = Wheel<30, 8, 6, wheel30Init>; /// 4th wheel, skips multiples of 2, 3, 5 and 7 using Wheel210_t = Wheel<210, 48, 10, wheel210Init>; } // namespace #endif <|endoftext|>
<commit_before>#ifndef __RANK_FILTER_BASE__ #define __RANK_FILTER_BASE__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Rank must be in the range 0 to 1 assert((0 <= rank) && (rank <= 1)); const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); // The position of the window. I_diff_t window_begin = 0; // Lengths. const I_diff_t src_size = std::distance(src_begin, src_end); const I_diff_t dest_size = std::distance(dest_begin, dest_end); typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; multiset sorted_window; deque window_iters; // Get the initial sorted window. // Include the reflection. for (I_diff_t j = half_length; j > 0; j--) { window_iters.push_back(sorted_window.insert(src_begin[window_begin + j])); } for (I_diff_t j = 0; j <= half_length; j++) { window_iters.push_back(sorted_window.insert(src_begin[window_begin + j])); } typename multiset::iterator rank_point = sorted_window.begin(); for (I_diff_t i = 0; i < rank_pos; i++) { rank_point++; } typename multiset::iterator prev_iter; T prev_value; T next_value; while ( window_begin < src_size ) { dest_begin[window_begin] = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); window_begin++; if ( window_begin < (src_size - half_length) ) { next_value = src_begin[window_begin + half_length]; } else { next_value = *(window_iters[window_iters.size() + 2*src_size - 2*(window_begin + half_length) - 2]); } if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER_BASE__ <commit_msg>Preallocate deque used for the filter window<commit_after>#ifndef __RANK_FILTER_BASE__ #define __RANK_FILTER_BASE__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Rank must be in the range 0 to 1 assert((0 <= rank) && (rank <= 1)); const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); // The position of the window. I_diff_t window_begin = 0; // Lengths. const I_diff_t src_size = std::distance(src_begin, src_end); const I_diff_t dest_size = std::distance(dest_begin, dest_end); typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; multiset sorted_window; deque window_iters(2 * half_length + 1); // Get the initial sorted window. // Include the reflection. for (I_diff_t j = 0; j < half_length; j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]); } for (I_diff_t j = half_length; j < (2 * half_length + 1); j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]); } typename multiset::iterator rank_point = sorted_window.begin(); for (I_diff_t i = 0; i < rank_pos; i++) { rank_point++; } typename multiset::iterator prev_iter; T prev_value; T next_value; while ( window_begin < src_size ) { dest_begin[window_begin] = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); window_begin++; if ( window_begin < (src_size - half_length) ) { next_value = src_begin[window_begin + half_length]; } else { next_value = *(window_iters[window_iters.size() + 2*src_size - 2*(window_begin + half_length) - 2]); } if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER_BASE__ <|endoftext|>
<commit_before>#ifndef GP_UTILITY_VARIABLE #define GP_UTILITY_VARIABLE #include <any> #include <type_traits> #include <cassert> #include <exception> namespace gp::utility { class Variable { private: const bool hasPointer; std::any variable; const std::type_info* type; public: bool hasValue()const noexcept {return *type != typeid(void);} template <typename T> T get() { if constexpr (std::is_pointer_v<T>) { assert(typeid(std::remove_pointer_t<std::remove_cv_t <T>>) == *type); if (typeid(std::remove_pointer_t<std::remove_cv_t <T>>) != *type) return nullptr; if (hasPointer) { return std::any_cast<T>(variable); }else { return &std::any_cast<std::add_lvalue_reference_t<std::remove_pointer_t<T>>>(variable); } } else if constexpr (std::is_reference_v<T>) { assert(typeid(std::remove_reference_t<std::remove_cv_t<T>>) == *type); if (hasPointer) { return *std::any_cast<std::add_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>>(variable); } else { return std::any_cast<T>(variable); } } else { assert(typeid(std::remove_cv_t<T>) == *type); if (hasPointer) { return *std::any_cast<std::add_pointer_t<T>>(variable); } else { return std::any_cast<T>(variable); } } } template <typename T> void set(T&& val) { variable = std::forward<T>(val); hasPointer = std::is_pointer_v<T>; type = &typeid(std::remove_pointer_t<std::remove_cv_t<T>>); } const std::type_info& getType()const noexcept{return *type;} public: template <typename T> Variable(T&& val): variable(std::forward<T>(val)), hasPointer(std::is_pointer_v<T>), type(&typeid(std::remove_pointer_t<std::remove_cv_t<T>>)){} Variable(): hasPointer(false), variable(), type(&typeid(void)){}; ~Variable() = default; Variable(const Variable&) = default; Variable(Variable&&) = default; Variable& operator=(const Variable&) = default; Variable& operator=(Variable&&) = default; }; } #endif<commit_msg>remove const<commit_after>#ifndef GP_UTILITY_VARIABLE #define GP_UTILITY_VARIABLE #include <any> #include <type_traits> #include <cassert> #include <exception> namespace gp::utility { class Variable { private: bool hasPointer; std::any variable; const std::type_info* type; public: bool hasValue()const noexcept {return *type != typeid(void);} template <typename T> T get() { if constexpr (std::is_pointer_v<T>) { assert(typeid(std::remove_pointer_t<std::remove_cv_t <T>>) == *type); if (typeid(std::remove_pointer_t<std::remove_cv_t <T>>) != *type) return nullptr; if (hasPointer) { return std::any_cast<T>(variable); }else { return &std::any_cast<std::add_lvalue_reference_t<std::remove_pointer_t<T>>>(variable); } } else if constexpr (std::is_reference_v<T>) { assert(typeid(std::remove_reference_t<std::remove_cv_t<T>>) == *type); if (hasPointer) { return *std::any_cast<std::add_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>>(variable); } else { return std::any_cast<T>(variable); } } else { assert(typeid(std::remove_cv_t<T>) == *type); if (hasPointer) { return *std::any_cast<std::add_pointer_t<T>>(variable); } else { return std::any_cast<T>(variable); } } } template <typename T> void set(T&& val) { variable = std::forward<T>(val); hasPointer = std::is_pointer_v<T>; type = &typeid(std::remove_pointer_t<std::remove_cv_t<T>>); } const std::type_info& getType()const noexcept{return *type;} public: template <typename T> Variable(T&& val): variable(std::forward<T>(val)), hasPointer(std::is_pointer_v<T>), type(&typeid(std::remove_pointer_t<std::remove_cv_t<T>>)){} Variable(): hasPointer(false), variable(), type(&typeid(void)){}; ~Variable() = default; Variable(const Variable&) = default; Variable(Variable&&) = default; Variable& operator=(const Variable&) = default; Variable& operator=(Variable&&) = default; }; } #endif<|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile: mitkPropertyManager.cpp,v $ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkSliceBasedSegmentation.h" // includes mitkConfig, where BUILD_TESTING is defined #ifdef BUILD_TESTING // only if we build a test driver #include "QmitkSliceBasedSegmentationControls.h" #include "QmitkToolReferenceDataSelectionBox.h" #include "QmitkToolSelectionBox.h" #include "QmitkNewSegmentationDialog.h" #include "QmitkStdMultiWidget.h" #include "QmitkSelectableGLWidget.h" #include "QmitkUserInputSimulation.h" #include "QmitkMessageBoxHelper.h" #include "QmitkSlicesInterpolator.h" // bad, bad - but I cannot figure out where to click for the checkbox on the interpolation group box #include "mitkMemoryUtilities.h" #include "mitkOrganTypeProperty.h" #include <qwidgetlist.h> #include <qobjectlist.h> #include <qtoolbutton.h> #include <qlineedit.h> #include <ctime> /** * \brief Test entry point */ bool QmitkSliceBasedSegmentation::TestYourself() { std::cout << std::endl; time_t randomInit = std::time(0); //time_t randomInit = 1187613660; // some errors on muhu (fixed) std::cout << "Initializing random number generator with " << randomInit << std::endl; std::srand(randomInit); // a helper object to close popping up message boxes QmitkMessageBoxHelper messageBoxHelper(this); // check if there is a tool manager and if we have some data // - having no tool manager is not ok // - having no data is ok, then we just have no work to do mitk::ToolManager* toolManager = m_Controls->m_ToolReferenceDataSelectionBox->GetToolManager(); if (!toolManager) { std::cerr << "Couldn't get a ToolManager object (l. " << __LINE__ << ")" << std::endl; return false; } if ( toolManager->GetReferenceData(0) == NULL ) { std::cerr << "No possible reference image in scene. Won't apply test (l. " << __LINE__ << ")" << std::endl; return true; } // Test: click the "New segmentation" button, expect: new segmentation is selected afterwards std::cout << "Creating a new segmentation: " << std::flush; // we expect a new window of type "QmitkNewSegmentationDialog" to pop up // here we ask messageBoxHelper to wait for that window in a separate thread and tell us when the window shows up connect( &messageBoxHelper, SIGNAL(DialogFound(QWidget*)), this, SLOT(TestOnNewSegmentationDialogFound(QWidget*)) ); messageBoxHelper.WaitForDialogAndCallback( "QmitkNewSegmentationDialog" ); QmitkUserInputSimulation::MouseClick( m_Controls->btnNewSegmentation, Qt::LeftButton ); // check if a new segmentation was created. After clicking "New" the new segmentation should be selected automatically if ( !toolManager->GetWorkingData(0) ) { std::cerr << "Segmentation was perhaps generated after clicking on 'New', but no segmentation was selected as active (l. " << __LINE__ << ")" << std::endl; return false; } else { // checking some things about the new segmentation mitk::DataTreeNode* segmentationNode = toolManager->GetWorkingData(0); std::string name; segmentationNode->GetName( name ); if ( name.find( "testname" ) == std::string::npos ) { std::cerr << "New segmentation name is wrong (expected '...testname')." << std::endl; return false; } mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( segmentationNode->GetData() ); if ( image.IsNull() ) { std::cerr << "New segmentation is no image!" << std::endl; return false; } mitk::OrganTypeProperty::Pointer organTypeProperty = dynamic_cast<mitk::OrganTypeProperty*>( image->GetProperty("organ type").GetPointer() ); if ( organTypeProperty.IsNull() ) { std::cerr << "New segmentation has no organ type associated." << std::endl; return false; } if ( ! (*(image->GetPixelType().GetTypeId()) == typeid(unsigned char)) ) { std::cerr << "New segmentation data type is wrong (should be unsigned char)." << std::endl; return false; } } std::cout << "[PASSED]" << std::endl; // Test: tools should be enabled when a segmentation is active if ( !m_Controls->m_ToolSelectionBox->isEnabled() ) { std::cerr << "Tools should be enabled after creating a new segmentation (l. " << __LINE__ << ")" << std::endl; return false; } std::cout << "[PASSED]" << std::endl; // test if interpolation does not crash // THIS FIRST, because the drawing area is still clear here if (!TestInterpolation()) return false; // Test: test all the tools if (!TestAllTools()) return false; std::cout << "Cropping active segmentation: " << std::flush; QmitkUserInputSimulation::MouseClick( m_Controls->btnAutoCropSegmentation, Qt::LeftButton ); // Test: click the "Delete segmentation" button, expect: no segmentations selected afterwards std::cout << "Deleting active segmentation: " << std::flush; // again use a helper to close a standard dialog after some time. messageBoxHelper.CloseMessageBoxes(1, 1000); // click first button (yes) in messagebox after 1000 msec QmitkUserInputSimulation::MouseClick( m_Controls->btnDeleteSegmentation, Qt::LeftButton ); // nothing should be selected as active segmenation anymore if ( toolManager->GetWorkingData(0) ) { std::cerr << "Segmentation was perhaps deleted, but something is still selected as active segmentation (l. " << __LINE__ << ")" << std::endl; return false; } std::cout << "[PASSED]" << std::endl; // done std::cout << "Whole functionality testing [PASSED]" << std::endl; return true; } bool QmitkSliceBasedSegmentation::TestAllTools() { QWidget* widget = m_Controls->m_ToolSelectionBox; QObjectList* childList = widget->queryList( "QToolButton" ); QObjectListIt childIter( *childList ); QObject* child; while ( (child = childIter.current()) ) { QToolButton* button = static_cast<QToolButton*>(child); std::cout << "Using '" << button->textLabel().ascii() << "' tool..." << std::flush; if (!button->isOn()) // if not yet pressed, then press it now (otherwise, DONT press because that would deactivate the tool) { QmitkUserInputSimulation::MouseClick( button, Qt::LeftButton ); } mitk::Tool* tool = m_Controls->m_ToolSelectionBox->GetToolManager()->GetActiveTool(); if (!tool) { std::cerr << "Clicked a button, but no tool was activated! (l. " << __LINE__ << ")" << std::endl; return false; } QWidget* sliceWidget; for (unsigned int window = 1; window < 4; ++window) { switch (window) { case 1: sliceWidget = m_MultiWidget->mitkWidget1->GetRenderWindow(); // IMPORTANT to send the events to the renderwindow and not to the multiwidget or one selectableglwidget break; case 2: sliceWidget = m_MultiWidget->mitkWidget2->GetRenderWindow(); break; case 3: default: sliceWidget = m_MultiWidget->mitkWidget3->GetRenderWindow(); break; } std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.25, 0.25, 0.2 ); std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.75, 0.75, 0.2 ); std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.75, 0.25, 0.2 ); std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.25, 0.75, 0.2 ); std::cout << " chaos " << std::flush; QmitkUserInputSimulation::MouseDrawRandom( sliceWidget, Qt::LeftButton, 100 ); // random points if ( std::string("Region growing") == tool->GetName() // little more stress for problematic tools || std::string("Correction") == tool->GetName()) { for (unsigned int j = 0; j < 20; ++j) { QmitkUserInputSimulation::MouseDrawRandom( sliceWidget, Qt::LeftButton, 5 ); // random points } } } std::cout << "[PASSED]" << std::endl; ++childIter; } delete childList; return true; } bool QmitkSliceBasedSegmentation::TestInterpolation() { std::cout << "Testing interpolation" << std::endl; QWidget* widget = m_Controls->m_ToolSelectionBox; QObjectList* childList = widget->queryList( "QToolButton" ); QObjectListIt childIter( *childList ); // look for the "add" tool QToolButton* button = NULL; QObject* child; while ( (child = childIter.current()) ) { button = static_cast<QToolButton*>(child); if ( button->textLabel() == "&Add" ) break; else button = NULL; ++childIter; } delete childList; if (!button) { std::cerr << "Could not find 'Add' tool" << std::endl; return false; } // activate the "add" tool if (!button->isOn()) // if not yet pressed, then press it now (otherwise, DONT press because that would deactivate the tool) { QmitkUserInputSimulation::MouseClick( button, Qt::LeftButton ); } QWidget* sliceWidget; for (unsigned int window = 1; window < 4; ++window) { switch (window) { case 1: sliceWidget = m_MultiWidget->mitkWidget1->GetRenderWindow(); // IMPORTANT to send the events to the renderwindow and not to the multiwidget or one selectableglwidget break; case 2: sliceWidget = m_MultiWidget->mitkWidget2->GetRenderWindow(); break; case 3: default: sliceWidget = m_MultiWidget->mitkWidget3->GetRenderWindow(); break; } // activate interpolation m_Controls->grpInterpolation->setChecked( true ); m_Controls->m_SlicesInterpolator->EnableInterpolation( true ); // draw a full circle std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.5, 0.5, 0.1 ); // scroll a bit QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); // draw another circle std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.5, 0.5, 0.2 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); // one behind everything now QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); // on first slice now QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); // somewhere inbetween QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); // on last slice now QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); // before everything now // deactivate interpolation m_Controls->grpInterpolation->setChecked( false ); m_Controls->m_SlicesInterpolator->EnableInterpolation( false ); } std::cout << "[PASSED]" << std::endl; return true; } void QmitkSliceBasedSegmentation::TestOnNewSegmentationDialogFound( QWidget* widget ) { // method is called after the "new segmentation dialog" shows up. the dialog is found in "widget" if (!widget) return; QmitkNewSegmentationDialog* newDialog =dynamic_cast<QmitkNewSegmentationDialog*>( widget ); if (!newDialog) return; QmitkMessageBoxHelper messageBoxHelper(this); // we simulate that some other organ is selected (click center of list), something is entered for the name, and then OK is clicked QmitkUserInputSimulation::MouseClick( messageBoxHelper.FindDialogItem("lstOrgans", newDialog), Qt::LeftButton ); // somewhere - should always be ok QLineEdit* edtName = dynamic_cast<QLineEdit*>( messageBoxHelper.FindDialogItem("edtName", newDialog) ); if (edtName) { QmitkUserInputSimulation::MouseClick( edtName, Qt::LeftButton ); QmitkUserInputSimulation::MouseClick( edtName, Qt::LeftButton ); QmitkUserInputSimulation::SimulateKeyboardTyping( edtName, "testname" ); } QmitkUserInputSimulation::MouseClick( messageBoxHelper.FindDialogItem("btnOk", newDialog), Qt::LeftButton ); } #endif <commit_msg>CHG reduce number of tests to avoid time limit<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile: mitkPropertyManager.cpp,v $ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkSliceBasedSegmentation.h" // includes mitkConfig, where BUILD_TESTING is defined #ifdef BUILD_TESTING // only if we build a test driver #include "QmitkSliceBasedSegmentationControls.h" #include "QmitkToolReferenceDataSelectionBox.h" #include "QmitkToolSelectionBox.h" #include "QmitkNewSegmentationDialog.h" #include "QmitkStdMultiWidget.h" #include "QmitkSelectableGLWidget.h" #include "QmitkUserInputSimulation.h" #include "QmitkMessageBoxHelper.h" #include "QmitkSlicesInterpolator.h" // bad, bad - but I cannot figure out where to click for the checkbox on the interpolation group box #include "mitkMemoryUtilities.h" #include "mitkOrganTypeProperty.h" #include <qwidgetlist.h> #include <qobjectlist.h> #include <qtoolbutton.h> #include <qlineedit.h> #include <ctime> /** * \brief Test entry point */ bool QmitkSliceBasedSegmentation::TestYourself() { std::cout << std::endl; time_t randomInit = std::time(0); //time_t randomInit = 1187613660; // some errors on muhu (fixed) std::cout << "Initializing random number generator with " << randomInit << std::endl; std::srand(randomInit); // a helper object to close popping up message boxes QmitkMessageBoxHelper messageBoxHelper(this); // check if there is a tool manager and if we have some data // - having no tool manager is not ok // - having no data is ok, then we just have no work to do mitk::ToolManager* toolManager = m_Controls->m_ToolReferenceDataSelectionBox->GetToolManager(); if (!toolManager) { std::cerr << "Couldn't get a ToolManager object (l. " << __LINE__ << ")" << std::endl; return false; } if ( toolManager->GetReferenceData(0) == NULL ) { std::cerr << "No possible reference image in scene. Won't apply test (l. " << __LINE__ << ")" << std::endl; return true; } // Test: click the "New segmentation" button, expect: new segmentation is selected afterwards std::cout << "Creating a new segmentation: " << std::flush; // we expect a new window of type "QmitkNewSegmentationDialog" to pop up // here we ask messageBoxHelper to wait for that window in a separate thread and tell us when the window shows up connect( &messageBoxHelper, SIGNAL(DialogFound(QWidget*)), this, SLOT(TestOnNewSegmentationDialogFound(QWidget*)) ); messageBoxHelper.WaitForDialogAndCallback( "QmitkNewSegmentationDialog" ); QmitkUserInputSimulation::MouseClick( m_Controls->btnNewSegmentation, Qt::LeftButton ); // check if a new segmentation was created. After clicking "New" the new segmentation should be selected automatically if ( !toolManager->GetWorkingData(0) ) { std::cerr << "Segmentation was perhaps generated after clicking on 'New', but no segmentation was selected as active (l. " << __LINE__ << ")" << std::endl; return false; } else { // checking some things about the new segmentation mitk::DataTreeNode* segmentationNode = toolManager->GetWorkingData(0); std::string name; segmentationNode->GetName( name ); if ( name.find( "testname" ) == std::string::npos ) { std::cerr << "New segmentation name is wrong (expected '...testname')." << std::endl; return false; } mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( segmentationNode->GetData() ); if ( image.IsNull() ) { std::cerr << "New segmentation is no image!" << std::endl; return false; } mitk::OrganTypeProperty::Pointer organTypeProperty = dynamic_cast<mitk::OrganTypeProperty*>( image->GetProperty("organ type").GetPointer() ); if ( organTypeProperty.IsNull() ) { std::cerr << "New segmentation has no organ type associated." << std::endl; return false; } if ( ! (*(image->GetPixelType().GetTypeId()) == typeid(unsigned char)) ) { std::cerr << "New segmentation data type is wrong (should be unsigned char)." << std::endl; return false; } } std::cout << "[PASSED]" << std::endl; // Test: tools should be enabled when a segmentation is active if ( !m_Controls->m_ToolSelectionBox->isEnabled() ) { std::cerr << "Tools should be enabled after creating a new segmentation (l. " << __LINE__ << ")" << std::endl; return false; } std::cout << "[PASSED]" << std::endl; // test if interpolation does not crash // THIS FIRST, because the drawing area is still clear here if (!TestInterpolation()) return false; // Test: test all the tools if (!TestAllTools()) return false; std::cout << "Cropping active segmentation: " << std::flush; QmitkUserInputSimulation::MouseClick( m_Controls->btnAutoCropSegmentation, Qt::LeftButton ); // Test: click the "Delete segmentation" button, expect: no segmentations selected afterwards std::cout << "Deleting active segmentation: " << std::flush; // again use a helper to close a standard dialog after some time. messageBoxHelper.CloseMessageBoxes(1, 1000); // click first button (yes) in messagebox after 1000 msec QmitkUserInputSimulation::MouseClick( m_Controls->btnDeleteSegmentation, Qt::LeftButton ); // nothing should be selected as active segmenation anymore if ( toolManager->GetWorkingData(0) ) { std::cerr << "Segmentation was perhaps deleted, but something is still selected as active segmentation (l. " << __LINE__ << ")" << std::endl; return false; } std::cout << "[PASSED]" << std::endl; // done std::cout << "Whole functionality testing [PASSED]" << std::endl; return true; } bool QmitkSliceBasedSegmentation::TestAllTools() { QWidget* widget = m_Controls->m_ToolSelectionBox; QObjectList* childList = widget->queryList( "QToolButton" ); QObjectListIt childIter( *childList ); QObject* child; while ( (child = childIter.current()) ) { QToolButton* button = static_cast<QToolButton*>(child); std::cout << "Using '" << button->textLabel().ascii() << "' tool..." << std::flush; if (!button->isOn()) // if not yet pressed, then press it now (otherwise, DONT press because that would deactivate the tool) { QmitkUserInputSimulation::MouseClick( button, Qt::LeftButton ); } mitk::Tool* tool = m_Controls->m_ToolSelectionBox->GetToolManager()->GetActiveTool(); if (!tool) { std::cerr << "Clicked a button, but no tool was activated! (l. " << __LINE__ << ")" << std::endl; return false; } QWidget* sliceWidget; for (unsigned int window = 1; window < 4; ++window) { switch (window) { case 1: sliceWidget = m_MultiWidget->mitkWidget1->GetRenderWindow(); // IMPORTANT to send the events to the renderwindow and not to the multiwidget or one selectableglwidget break; case 2: sliceWidget = m_MultiWidget->mitkWidget2->GetRenderWindow(); break; case 3: default: sliceWidget = m_MultiWidget->mitkWidget3->GetRenderWindow(); break; } /* std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.25, 0.25, 0.2 ); std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.75, 0.75, 0.2 ); */ std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.75, 0.25, 0.2 ); std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.25, 0.75, 0.2 ); std::cout << " chaos " << std::flush; QmitkUserInputSimulation::MouseDrawRandom( sliceWidget, Qt::LeftButton, 50 ); // random points if ( std::string("Region growing") == tool->GetName() // little more stress for problematic tools || std::string("Correction") == tool->GetName()) { for (unsigned int j = 0; j < 20; ++j) { QmitkUserInputSimulation::MouseDrawRandom( sliceWidget, Qt::LeftButton, 5 ); // random points } } } std::cout << "[PASSED]" << std::endl; ++childIter; } delete childList; return true; } bool QmitkSliceBasedSegmentation::TestInterpolation() { std::cout << "Testing interpolation" << std::endl; QWidget* widget = m_Controls->m_ToolSelectionBox; QObjectList* childList = widget->queryList( "QToolButton" ); QObjectListIt childIter( *childList ); // look for the "add" tool QToolButton* button = NULL; QObject* child; while ( (child = childIter.current()) ) { button = static_cast<QToolButton*>(child); if ( button->textLabel() == "&Add" ) break; else button = NULL; ++childIter; } delete childList; if (!button) { std::cerr << "Could not find 'Add' tool" << std::endl; return false; } // activate the "add" tool if (!button->isOn()) // if not yet pressed, then press it now (otherwise, DONT press because that would deactivate the tool) { QmitkUserInputSimulation::MouseClick( button, Qt::LeftButton ); } QWidget* sliceWidget; for (unsigned int window = 1; window < 4; ++window) { switch (window) { case 1: sliceWidget = m_MultiWidget->mitkWidget1->GetRenderWindow(); // IMPORTANT to send the events to the renderwindow and not to the multiwidget or one selectableglwidget break; case 2: sliceWidget = m_MultiWidget->mitkWidget2->GetRenderWindow(); break; case 3: default: sliceWidget = m_MultiWidget->mitkWidget3->GetRenderWindow(); break; } // activate interpolation m_Controls->grpInterpolation->setChecked( true ); m_Controls->m_SlicesInterpolator->EnableInterpolation( true ); // draw a full circle std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.5, 0.5, 0.1 ); // scroll a bit QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); // draw another circle std::cout << " circle " << std::flush; QmitkUserInputSimulation::MouseDrawCircle( sliceWidget, Qt::LeftButton, 0.5, 0.5, 0.2 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, +1 ); // one behind everything now QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); // on first slice now QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); // somewhere inbetween QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); // on last slice now QmitkUserInputSimulation::MouseMoveScrollWheel( sliceWidget, -1 ); // before everything now // deactivate interpolation m_Controls->grpInterpolation->setChecked( false ); m_Controls->m_SlicesInterpolator->EnableInterpolation( false ); } std::cout << "[PASSED]" << std::endl; return true; } void QmitkSliceBasedSegmentation::TestOnNewSegmentationDialogFound( QWidget* widget ) { // method is called after the "new segmentation dialog" shows up. the dialog is found in "widget" if (!widget) return; QmitkNewSegmentationDialog* newDialog =dynamic_cast<QmitkNewSegmentationDialog*>( widget ); if (!newDialog) return; QmitkMessageBoxHelper messageBoxHelper(this); // we simulate that some other organ is selected (click center of list), something is entered for the name, and then OK is clicked QmitkUserInputSimulation::MouseClick( messageBoxHelper.FindDialogItem("lstOrgans", newDialog), Qt::LeftButton ); // somewhere - should always be ok QLineEdit* edtName = dynamic_cast<QLineEdit*>( messageBoxHelper.FindDialogItem("edtName", newDialog) ); if (edtName) { QmitkUserInputSimulation::MouseClick( edtName, Qt::LeftButton ); QmitkUserInputSimulation::MouseClick( edtName, Qt::LeftButton ); QmitkUserInputSimulation::SimulateKeyboardTyping( edtName, "testname" ); } QmitkUserInputSimulation::MouseClick( messageBoxHelper.FindDialogItem("btnOk", newDialog), Qt::LeftButton ); } #endif <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "CoreComponentsRegistry.h" #include <android/log.h> #include <fbjni/fbjni.h> #include <react/renderer/componentregistry/ComponentDescriptorRegistry.h> #include <react/renderer/components/androidtextinput/AndroidTextInputComponentDescriptor.h> #include <react/renderer/components/image/ImageComponentDescriptor.h> #include <react/renderer/components/modal/ModalHostViewComponentDescriptor.h> #include <react/renderer/components/rncore/ComponentDescriptors.h> #include <react/renderer/components/scrollview/ScrollViewComponentDescriptor.h> #include <react/renderer/components/text/ParagraphComponentDescriptor.h> #include <react/renderer/components/text/RawTextComponentDescriptor.h> #include <react/renderer/components/text/TextComponentDescriptor.h> #include <react/renderer/components/view/ViewComponentDescriptor.h> namespace facebook { namespace react { CoreComponentsRegistry::CoreComponentsRegistry(ComponentFactory *delegate) : delegate_(delegate) {} std::shared_ptr<ComponentDescriptorProviderRegistry const> CoreComponentsRegistry::sharedProviderRegistry() { static auto providerRegistry = []() -> std::shared_ptr<ComponentDescriptorProviderRegistry> { auto providerRegistry = std::make_shared<ComponentDescriptorProviderRegistry>(); providerRegistry->add(concreteComponentDescriptorProvider< AndroidTextInputComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<ViewComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<ImageComponentDescriptor>()); providerRegistry->add(concreteComponentDescriptorProvider< ModalHostViewComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<TextComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<RawTextComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<ScrollViewComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<ParagraphComponentDescriptor>()); providerRegistry->add(concreteComponentDescriptorProvider< AndroidDrawerLayoutComponentDescriptor>()); return providerRegistry; }(); return providerRegistry; } jni::local_ref<CoreComponentsRegistry::jhybriddata> CoreComponentsRegistry::initHybrid( jni::alias_ref<jclass>, ComponentFactory *delegate) { auto instance = makeCxxInstance(delegate); // TODO T69453179: Codegen this file auto buildRegistryFunction = [](EventDispatcher::Weak const &eventDispatcher, ContextContainer::Shared const &contextContainer) -> ComponentDescriptorRegistry::Shared { auto registry = CoreComponentsRegistry::sharedProviderRegistry() ->createComponentDescriptorRegistry( {eventDispatcher, contextContainer}); auto mutableRegistry = std::const_pointer_cast<ComponentDescriptorRegistry>(registry); mutableRegistry->setFallbackComponentDescriptor( std::make_shared<UnimplementedNativeViewComponentDescriptor>( ComponentDescriptorParameters{ eventDispatcher, contextContainer, nullptr})); return registry; }; delegate->buildRegistryFunction = buildRegistryFunction; return instance; } void CoreComponentsRegistry::registerNatives() { registerHybrid({ makeNativeMethod("initHybrid", CoreComponentsRegistry::initHybrid), }); } } // namespace react } // namespace facebook <commit_msg>Integrate Activity Indicator into RN Tester Android OSS app<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "CoreComponentsRegistry.h" #include <android/log.h> #include <fbjni/fbjni.h> #include <react/renderer/componentregistry/ComponentDescriptorRegistry.h> #include <react/renderer/components/androidtextinput/AndroidTextInputComponentDescriptor.h> #include <react/renderer/components/image/ImageComponentDescriptor.h> #include <react/renderer/components/modal/ModalHostViewComponentDescriptor.h> #include <react/renderer/components/rncore/ComponentDescriptors.h> #include <react/renderer/components/scrollview/ScrollViewComponentDescriptor.h> #include <react/renderer/components/text/ParagraphComponentDescriptor.h> #include <react/renderer/components/text/RawTextComponentDescriptor.h> #include <react/renderer/components/text/TextComponentDescriptor.h> #include <react/renderer/components/view/ViewComponentDescriptor.h> namespace facebook { namespace react { CoreComponentsRegistry::CoreComponentsRegistry(ComponentFactory *delegate) : delegate_(delegate) {} std::shared_ptr<ComponentDescriptorProviderRegistry const> CoreComponentsRegistry::sharedProviderRegistry() { static auto providerRegistry = []() -> std::shared_ptr<ComponentDescriptorProviderRegistry> { auto providerRegistry = std::make_shared<ComponentDescriptorProviderRegistry>(); providerRegistry->add(concreteComponentDescriptorProvider< ActivityIndicatorViewComponentDescriptor>()); providerRegistry->add(concreteComponentDescriptorProvider< AndroidTextInputComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<ViewComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<ImageComponentDescriptor>()); providerRegistry->add(concreteComponentDescriptorProvider< ModalHostViewComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<TextComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<RawTextComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<ScrollViewComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider<ParagraphComponentDescriptor>()); providerRegistry->add(concreteComponentDescriptorProvider< AndroidDrawerLayoutComponentDescriptor>()); return providerRegistry; }(); return providerRegistry; } jni::local_ref<CoreComponentsRegistry::jhybriddata> CoreComponentsRegistry::initHybrid( jni::alias_ref<jclass>, ComponentFactory *delegate) { auto instance = makeCxxInstance(delegate); // TODO T69453179: Codegen this file auto buildRegistryFunction = [](EventDispatcher::Weak const &eventDispatcher, ContextContainer::Shared const &contextContainer) -> ComponentDescriptorRegistry::Shared { auto registry = CoreComponentsRegistry::sharedProviderRegistry() ->createComponentDescriptorRegistry( {eventDispatcher, contextContainer}); auto mutableRegistry = std::const_pointer_cast<ComponentDescriptorRegistry>(registry); mutableRegistry->setFallbackComponentDescriptor( std::make_shared<UnimplementedNativeViewComponentDescriptor>( ComponentDescriptorParameters{ eventDispatcher, contextContainer, nullptr})); return registry; }; delegate->buildRegistryFunction = buildRegistryFunction; return instance; } void CoreComponentsRegistry::registerNatives() { registerHybrid({ makeNativeMethod("initHybrid", CoreComponentsRegistry::initHybrid), }); } } // namespace react } // namespace facebook <|endoftext|>
<commit_before>/* * This program is just for personal experiments here on AVR features and C++ stuff * This one is a proof of concept on adapting new I2C asynchronous handling (ATmega) * to also fit ATtiny architecture in a degraded (synchronous) way while keeping * original API. * As a matter of fact, ATtiny USI feature is not very well suited for asynchronous * I2C handling as I2C master (this is easier for slaves). */ #include <util/delay_basic.h> #include <fastarduino/boards/board.h> #include <fastarduino/i2c.h> #include <fastarduino/queue.h> #include <fastarduino/time.h> #include <fastarduino/interrupts.h> #include <fastarduino/bits.h> #include <fastarduino/utilities.h> #include <fastarduino/iomanip.h> #ifdef ARDUINO_UNO #define HARD_UART #include <fastarduino/uart.h> static constexpr const board::USART UART = board::USART::USART0; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128; static constexpr uint8_t I2C_BUFFER_SIZE = 32; static constexpr uint8_t MAX_FUTURES = 128; static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE]; // Define vectors we need in the example REGISTER_UATX_ISR(0) #elif defined (BREADBOARD_ATTINYX4) #include <fastarduino/soft_uart.h> static constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; static constexpr uint8_t MAX_FUTURES = 8; #else #error "Current target is not yet supported!" #endif #include "i2c_handler.h" #include "ds1307.h" // Uncomment when device does nto work properly and we want to trace in "real time" // every I2C step // #define TRACE_PROTOCOL // This is used when nothing works at all and this reduces the tests to only one get_ram() call // #define BASIC_DEBUG #ifdef TWCR REGISTER_I2C_ISR(i2c::I2CMode::STANDARD) #endif // Add utility ostream manipulator for FutureStatus static const flash::FlashStorage* convert(future::FutureStatus s) { switch (s) { case future::FutureStatus::INVALID: return F("INVALID"); case future::FutureStatus::NOT_READY: return F("NOT_READY"); case future::FutureStatus::READY: return F("READY"); case future::FutureStatus::ERROR: return F("ERROR"); } } streams::ostream& operator<<(streams::ostream& out, future::FutureStatus s) { return out << convert(s); } static char output_buffer[OUTPUT_BUFFER_SIZE]; using I2CHANDLER = i2c::I2CHandler<i2c::I2CMode::STANDARD>; using namespace streams; ostream* pout = nullptr; #define OUT (*pout) #ifdef TRACE_PROTOCOL static void i2c_hook(i2c::DebugStatus status, uint8_t data) { switch (status) { case i2c::DebugStatus::START: OUT << F("St ") << flush; break; case i2c::DebugStatus::REPEAT_START: OUT << F("RS ") << flush; break; case i2c::DebugStatus::STOP: OUT << F("Sp ") << flush; break; case i2c::DebugStatus::SLAW: OUT << F("AW ") << hex << data << ' ' << flush; break; case i2c::DebugStatus::SLAR: OUT << F("AR ") << hex << data << ' ' << flush; break; case i2c::DebugStatus::SEND: OUT << F("S ") << hex << data << ' ' << flush; break; case i2c::DebugStatus::SEND_OK: OUT << F("So ") << flush; break; case i2c::DebugStatus::SEND_ERROR: OUT << F("Se ") << flush; break; case i2c::DebugStatus::RECV: OUT << F("R ") << flush; break; case i2c::DebugStatus::RECV_LAST: OUT << F("RL ") << flush; break; case i2c::DebugStatus::RECV_OK: OUT << F("Ro ") << flush; break; case i2c::DebugStatus::RECV_ERROR: OUT << F("Re ") << flush; break; } } #else i2c::I2C_DEBUG_HOOK i2c_hook = nullptr; #endif int main() __attribute__((OS_main)); int main() { board::init(); // Enable interrupts at startup time sei(); // Initialize debugging output #ifdef HARD_UART serial::hard::UATX<UART> uatx{output_buffer}; #else serial::soft::UATX<TX> uatx{output_buffer}; #endif // Start UART uatx.begin(115200); ostream out = uatx.out(); pout = &out; out << F("Starting...") << endl; // Initialize FutureManager future::FutureManager<MAX_FUTURES> future_manager; // Initialize I2C async handler #ifdef TWCR I2CHANDLER handler{i2c_buffer, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, i2c_hook}; #else I2CHANDLER handler{i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, i2c_hook}; #endif RTC rtc{handler}; out << F("Before handler.begin()") << endl; out << boolalpha << showbase; handler.begin(); constexpr uint8_t RAM_SIZE = rtc.ram_size(); constexpr uint8_t MAX_READ = (RAM_SIZE < MAX_FUTURES ? RAM_SIZE : MAX_FUTURES); #ifdef BASIC_DEBUG // INITIAL debug test with only one call, normally not part of complete unit tests { out << F("\nTEST #0 read one RAM byte") << endl; RTC::GET_RAM1 data{0}; int ok = rtc.get_ram(data); out << F("get_ram()=") << dec << ok << endl; out << F("handler.status()=") << hex << handler.status() << endl; uint8_t id = data.id(); future::FutureStatus status = data.status(); out << F("id=") << dec << id << F(" status=") << status << endl; // out << F("id=") << dec << data.id() << F(" status=") << data.status() << endl; // time::delay_ms(1000); out << F("data await()=") << data.await() << endl; out << F("error()=") << dec << data.error() << endl; uint8_t result = 0; data.get(result); out << F("get()=") << hex << result << endl; } #else { out << F("\nTEST #0 read all RAM bytes, one by one") << endl; RTC::GET_RAM1 data[MAX_READ]; for (uint8_t i = 0; i < MAX_READ; ++i) { data[i] = RTC::GET_RAM1{i}; int error = rtc.get_ram(data[i]); if (error) out << F("F") << dec << i << F(" ") << flush; // This delay is needed to give time to I2C transactions to finish // and free I2C commands in buffer (only 32) time::delay_us(200); } out << endl; for (uint8_t i = 0 ; i < MAX_READ; ++i) { out << F("data[") << dec << i << F("] await()=") << data[i].await() << endl; out << F("error()=") << dec << data[i].error() << endl; uint8_t result = 0; data[i].get(result); out << F("get()=") << hex << result << endl; } } #endif handler.end(); } <commit_msg>Add further checks for DS1307 with ATtiny<commit_after>/* * This program is just for personal experiments here on AVR features and C++ stuff * This one is a proof of concept on adapting new I2C asynchronous handling (ATmega) * to also fit ATtiny architecture in a degraded (synchronous) way while keeping * original API. * As a matter of fact, ATtiny USI feature is not very well suited for asynchronous * I2C handling as I2C master (this is easier for slaves). */ #include <util/delay_basic.h> #include <fastarduino/boards/board.h> #include <fastarduino/i2c.h> #include <fastarduino/queue.h> #include <fastarduino/time.h> #include <fastarduino/interrupts.h> #include <fastarduino/bits.h> #include <fastarduino/utilities.h> #include <fastarduino/iomanip.h> #ifdef ARDUINO_UNO #define HARD_UART #include <fastarduino/uart.h> static constexpr const board::USART UART = board::USART::USART0; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128; static constexpr uint8_t I2C_BUFFER_SIZE = 32; static constexpr uint8_t MAX_FUTURES = 128; static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE]; // Define vectors we need in the example REGISTER_UATX_ISR(0) #elif defined (BREADBOARD_ATTINYX4) #include <fastarduino/soft_uart.h> static constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; static constexpr uint8_t MAX_FUTURES = 8; #else #error "Current target is not yet supported!" #endif #include "i2c_handler.h" #include "ds1307.h" // Uncomment when device does nto work properly and we want to trace in "real time" // every I2C step // #define TRACE_PROTOCOL // This is used when nothing works at all and this reduces the tests to only one get_ram() call // #define BASIC_DEBUG #ifdef TWCR REGISTER_I2C_ISR(i2c::I2CMode::STANDARD) #endif // Add utility ostream manipulator for FutureStatus static const flash::FlashStorage* convert(future::FutureStatus s) { switch (s) { case future::FutureStatus::INVALID: return F("INVALID"); case future::FutureStatus::NOT_READY: return F("NOT_READY"); case future::FutureStatus::READY: return F("READY"); case future::FutureStatus::ERROR: return F("ERROR"); } } streams::ostream& operator<<(streams::ostream& out, future::FutureStatus s) { return out << convert(s); } static char output_buffer[OUTPUT_BUFFER_SIZE]; using I2CHANDLER = i2c::I2CHandler<i2c::I2CMode::STANDARD>; using namespace streams; void display_time(streams::ostream& out, const tm& time) { out << streams::dec << F("RTC: [") << uint8_t(time.tm_wday) << ']' << time.tm_mday << '.' << time.tm_mon << '.' << time.tm_year << ' ' << time.tm_hour << ':' << time.tm_min << ':' << time.tm_sec << streams::endl; } ostream* pout = nullptr; #define COUT (*pout) #ifdef TRACE_PROTOCOL static void i2c_hook(i2c::DebugStatus status, uint8_t data) { switch (status) { case i2c::DebugStatus::START: COUT << F("St ") << flush; break; case i2c::DebugStatus::REPEAT_START: COUT << F("RS ") << flush; break; case i2c::DebugStatus::STOP: COUT << F("Sp ") << flush; break; case i2c::DebugStatus::SLAW: COUT << F("AW ") << hex << data << ' ' << flush; break; case i2c::DebugStatus::SLAR: COUT << F("AR ") << hex << data << ' ' << flush; break; case i2c::DebugStatus::SEND: COUT << F("S ") << hex << data << ' ' << flush; break; case i2c::DebugStatus::SEND_OK: COUT << F("So ") << flush; break; case i2c::DebugStatus::SEND_ERROR: COUT << F("Se ") << flush; break; case i2c::DebugStatus::RECV: COUT << F("R ") << flush; break; case i2c::DebugStatus::RECV_LAST: COUT << F("RL ") << flush; break; case i2c::DebugStatus::RECV_OK: COUT << F("Ro ") << flush; break; case i2c::DebugStatus::RECV_ERROR: COUT << F("Re ") << flush; break; } } #else i2c::I2C_DEBUG_HOOK i2c_hook = nullptr; #endif int main() __attribute__((OS_main)); int main() { board::init(); // Enable interrupts at startup time sei(); // Initialize debugging output #ifdef HARD_UART serial::hard::UATX<UART> uatx{output_buffer}; #else serial::soft::UATX<TX> uatx{output_buffer}; #endif // Start UART uatx.begin(115200); ostream out = uatx.out(); pout = &out; out << F("Starting...") << endl; // Initialize FutureManager future::FutureManager<MAX_FUTURES> future_manager; // Initialize I2C async handler #ifdef TWCR I2CHANDLER handler{i2c_buffer, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, i2c_hook}; #else I2CHANDLER handler{i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, i2c_hook}; #endif RTC rtc{handler}; out << F("Before handler.begin()") << endl; out << boolalpha << showbase; handler.begin(); constexpr uint8_t RAM_SIZE = rtc.ram_size(); constexpr uint8_t MAX_READ = (RAM_SIZE < MAX_FUTURES ? RAM_SIZE : MAX_FUTURES); #ifdef BASIC_DEBUG // INITIAL debug test with only one call, normally not part of complete unit tests { out << F("\nTEST #0 read one RAM byte") << endl; RTC::GET_RAM1 data{0}; int ok = rtc.get_ram(data); out << F("get_ram()=") << dec << ok << endl; out << F("handler.status()=") << hex << handler.status() << endl; uint8_t id = data.id(); future::FutureStatus status = data.status(); out << F("id=") << dec << id << F(" status=") << status << endl; // out << F("id=") << dec << data.id() << F(" status=") << data.status() << endl; // time::delay_ms(1000); out << F("data await()=") << data.await() << endl; out << F("error()=") << dec << data.error() << endl; uint8_t result = 0; data.get(result); out << F("get()=") << hex << result << endl; } #else { out << F("\nTEST #0 read all RAM bytes, one by one") << endl; RTC::GET_RAM1 data[MAX_READ]; for (uint8_t i = 0; i < MAX_READ; ++i) { data[i] = RTC::GET_RAM1{i}; int error = rtc.get_ram(data[i]); if (error) out << F("F") << dec << i << F(" ") << flush; // This delay is needed to give time to I2C transactions to finish // and free I2C commands in buffer (only 32) time::delay_us(200); } out << endl; for (uint8_t i = 0 ; i < MAX_READ; ++i) { out << F("data[") << dec << i << F("] await()=") << data[i].await() << endl; out << F("error()=") << dec << data[i].error() << endl; uint8_t result = 0; data[i].get(result); out << F("get()=") << hex << result << endl; } } { out << F("\nTEST #1 read all RAM bytes, all at once") << endl; RTC::GET_RAM<RAM_SIZE> data{0}; int error = rtc.get_ram(data); if (error) out << F("F") << flush; out << endl; out << F("data await()=") << data.await() << endl; out << F("error()=") << dec << data.error() << endl; RTC::GET_RAM<RAM_SIZE>::OUT result; data.get(result); out << F("result") << endl; for (uint8_t i = 0; i < RAM_SIZE; ++i) { out << dec << i << '=' << hex << result[i] << endl; } } { out << F("\nTEST #2 set datetime (Wed 06.05.2020 20:00:00)") << endl; tm datetime; datetime.tm_year = 20; datetime.tm_mon = 5; datetime.tm_mday = 6; datetime.tm_wday = WeekDay::WEDNESDAY; datetime.tm_hour = 20; datetime.tm_min = 0; datetime.tm_sec = 0; RTC::SET_DATETIME set{datetime}; int error = rtc.set_datetime(set); if (error) out << F("S") << endl; out << F("set await()=") << set.await() << endl; out << F("error()=") << dec << set.error() << endl; } time::delay_ms(13000); { out << F("\nTEST #3 get datetime (should be: Wed 06.05.2020 20:00:13") << endl; RTC::GET_DATETIME get; int error = rtc.get_datetime(get); if (error) out << F("G") << endl; out << F("get await()=") << get.await() << endl; out << F("error()=") << dec << get.error() << endl; tm datetime; out << F("get()=") << dec << get.get(datetime) << endl; display_time(out, datetime); } #endif handler.end(); } <|endoftext|>
<commit_before>// Copyright 2014 Hazy Research (http://i.stanford.edu/hazy) // // 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. #ifndef _GLM_SPARSE_SGD_H #define _GLM_SPARSE_SGD_H #include "dimmwitted.h" /** * \brief This file shows how to specify the same * synthetic model as in app/glm_dense_sgd.h * but store the data as sparse matrix instead * of dense matrix. * * See app/glm_dense_sgd.h for more detailed * comments. */ class GLMModelExample_Sparse{ public: double * const p; int n; GLMModelExample_Sparse(int _n): n(_n), p(new double[_n]){} GLMModelExample_Sparse( const GLMModelExample_Sparse& other ) : n(other.n), p(new double[other.n]){ for(int i=0;i<n;i++){ p[i] = other.p[i]; } } }; void f_lr_modelavg(GLMModelExample_Sparse** const p_models, int nreplicas, int ireplica){ GLMModelExample_Sparse * p_model = p_models[ireplica]; double sum = 0.0; for(int i=0;i<p_model->n;i++){ sum = 0.0; for(int j=0;j<nreplicas;j++){ sum += p_models[j]->p[i]; } (p_model->p)[i] = sum/nreplicas; } } double f_lr_loss_sparse(const SparseVector<double>* const ex, GLMModelExample_Sparse* const p_model){ double * model = p_model->p; double label = ex->p[ex->n-1]; double dot = 0.0; for(int i=0;i<ex->n-1;i++){ dot += ex->p[i] * model[ex->idxs[i]]; } return - label * dot + log(exp(dot) + 1.0); } double f_lr_grad_sparse(const SparseVector<double>* const ex, GLMModelExample_Sparse* const p_model){ double * model = p_model->p; double label = ex->p[ex->n-1]; double dot = 0.0; for(int i=0;i<ex->n-1;i++){ dot += ex->p[i] * model[ex->idxs[i]]; } const double d = exp(-dot); const double Z = 0.0001 * (-label + 1.0/(1.0+d)); for(int i=0;i<ex->n-1;i++){ model[ex->idxs[i]] -= ex->p[i] * Z; } return 1.0; } template<ModelReplType MODELREPL, DataReplType DATAREPL> double test_glm_sparse_sgd(){ long nexp = 100000; long nfeat = 1024; double * examples = new double[nexp*(nfeat+1)]; long * cols = new long[nexp*(nfeat+1)]; long * rows = new long[nexp]; long ct = 0; for(long i=0;i<nexp;i++){ rows[i] = ct; for(int j=0;j<nfeat;j++){ examples[ct] = 1; cols[ct] = j; ct ++; } examples[ct] = drand48() > 0.8 ? 0 : 1.0; cols[ct] = nfeat; ct ++; } GLMModelExample_Sparse model(nfeat); for(int i=0;i<model.n;i++){ model.p[i] = 0.0; } SparseDimmWitted<double, GLMModelExample_Sparse, MODELREPL, DATAREPL, DW_ACCESS_C2R> dw(examples, rows, cols, nexp, nfeat+1, nexp*(nfeat+1), &model); unsigned int f_handle_grad = dw.register_row(f_lr_grad_sparse); unsigned int f_handle_loss = dw.register_row(f_lr_loss_sparse); dw.register_model_avg(f_handle_grad, f_lr_modelavg); dw.register_model_avg(f_handle_loss, f_lr_modelavg); double sum = 0.0; for(int i_epoch=0;i_epoch<10;i_epoch++){ double loss = dw.exec(f_handle_loss)/nexp; sum = 0.0; for(int i=0;i<nfeat;i++){ sum += model.p[i]; } std::cout.precision(8); std::cout << sum << " loss=" << loss << std::endl; dw.exec(f_handle_grad); } return sum; } #endif <commit_msg>silly bug<commit_after>// Copyright 2014 Hazy Research (http://i.stanford.edu/hazy) // // 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. #ifndef _GLM_SPARSE_SGD_H #define _GLM_SPARSE_SGD_H #include "dimmwitted.h" /** * \brief This file shows how to specify the same * synthetic model as in app/glm_dense_sgd.h * but store the data as sparse matrix instead * of dense matrix. * * See app/glm_dense_sgd.h for more detailed * comments. */ class GLMModelExample_Sparse{ public: double * const p; int n; GLMModelExample_Sparse(int _n): n(_n), p(new double[_n]){} GLMModelExample_Sparse( const GLMModelExample_Sparse& other ) : n(other.n), p(new double[other.n]){ for(int i=0;i<n;i++){ p[i] = other.p[i]; } } }; void f_lr_modelavg(GLMModelExample_Sparse** const p_models, int nreplicas, int ireplica){ GLMModelExample_Sparse * p_model = p_models[ireplica]; double sum = 0.0; for(int i=0;i<p_model->n;i++){ sum = 0.0; for(int j=0;j<nreplicas;j++){ sum += p_models[j]->p[i]; } (p_model->p)[i] = sum/nreplicas; } } double f_lr_loss_sparse(const SparseVector<double>* const ex, GLMModelExample_Sparse* const p_model){ double * model = p_model->p; double label = ex->p[ex->n-1]; double dot = 0.0; for(int i=0;i<ex->n-1;i++){ dot += ex->p[i] * model[ex->idxs[i]]; } return - label * dot + log(exp(dot) + 1.0); } double f_lr_grad_sparse(const SparseVector<double>* const ex, GLMModelExample_Sparse* const p_model){ double * model = p_model->p; double label = ex->p[ex->n-1]; double dot = 0.0; for(int i=0;i<ex->n-1;i++){ dot += ex->p[i] * model[ex->idxs[i]]; } const double d = exp(-dot); const double Z = 0.0001 * (-label + 1.0/(1.0+d)); for(int i=0;i<ex->n-1;i++){ model[ex->idxs[i]] -= ex->p[i] * Z; } return 1.0; } template<ModelReplType MODELREPL, DataReplType DATAREPL> double test_glm_sparse_sgd(){ long nexp = 100000; long nfeat = 1024; double * examples = new double[nexp*(nfeat+1)]; long * cols = new long[nexp*(nfeat+1)]; long * rows = new long[nexp]; long ct = 0; for(long i=0;i<nexp;i++){ rows[i] = ct; for(int j=0;j<nfeat;j++){ examples[ct] = 1; cols[ct] = j; ct ++; } examples[ct] = drand48() > 0.8 ? 0 : 1.0; cols[ct] = nfeat; ct ++; } GLMModelExample_Sparse model(nfeat); for(int i=0;i<model.n;i++){ model.p[i] = 0.0; } SparseDimmWitted<double, GLMModelExample_Sparse, MODELREPL, DATAREPL, DW_ACCESS_ROW> dw(examples, rows, cols, nexp, nfeat+1, nexp*(nfeat+1), &model); unsigned int f_handle_grad = dw.register_row(f_lr_grad_sparse); unsigned int f_handle_loss = dw.register_row(f_lr_loss_sparse); dw.register_model_avg(f_handle_grad, f_lr_modelavg); dw.register_model_avg(f_handle_loss, f_lr_modelavg); double sum = 0.0; for(int i_epoch=0;i_epoch<10;i_epoch++){ double loss = dw.exec(f_handle_loss)/nexp; sum = 0.0; for(int i=0;i<nfeat;i++){ sum += model.p[i]; } std::cout.precision(8); std::cout << sum << " loss=" << loss << std::endl; dw.exec(f_handle_grad); } return sum; } /** * \brief This is one example of running SGD for logistic regression * in DimmWitted. You can find more examples in test/glm_dense.cc * and test/glm_sparse.cc, and the documented code in * app/glm_dense_sgd.h */ int main(int argc, char** argv){ double rs = test_glm_sparse_sgd<DW_MODELREPL_PERMACHINE, DW_DATAREPL_SHARDING>(); std::cout << "SUM OF MODEL (Should be ~1.3-1.4): " << rs << std::endl; return 0; } #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Author: Miroslav Safr <miroslav.safr@gmail.com> ** Web: http://semaphored.safrm.net/ ** Source: https://github.com/safrm/semaphored ** ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ****************************************************************************/ #include <QMenuBar> #include <QFileDialog> #include <QImageWriter> #include <QDebug> #include <QMessageBox> #include <QPrinter> #include <QPrintDialog> #include <QPainter> #include "mainwindow.h" #include "draglabel.h" #include "dragwidget.h" #include "aboutdialog.h" #include "version.h" MainWindow * g_pMainGuiWindow =NULL; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), loadProjectAct(NULL), saveProjectAct(NULL), exportAsPictureAct(NULL), loadTextFileAct(NULL), printAct(NULL), exportAsPdf(NULL), quitAct(NULL), aboutAct(NULL), deleteAllAct(NULL), m_canvasWidget(new DragWidget()), //TODO use size hint in canvas m_aboutDialog(NULL) { g_pMainGuiWindow = this; //createDockWindows(); createActions(); createMenus(); //createToolBars(); //createStatusBar(); setCentralWidget(m_canvasWidget); setWindowTitle(QString(APPLICATION_NAME) + "-" + QString(APP_FULL_VERSION_TAG) + " (" + QString(APP_DATE) +")"); setWindowIcon(QIcon(":/icons/semaphored.svg")); } MainWindow* MainWindow::instance() { return g_pMainGuiWindow; } void MainWindow::createActions() { loadProjectAct = new QAction(QIcon(":/icons/load_project.svg"), tr("&Load project"), this); loadProjectAct->setStatusTip(tr("Load project")); connect(loadProjectAct, SIGNAL(triggered()), this, SLOT(loadProjectSlot())); saveProjectAct = new QAction(QIcon(":/icons/save_project.svg"), tr("&Save project"), this); saveProjectAct->setStatusTip(tr("Save project")); connect(saveProjectAct, SIGNAL(triggered()), this, SLOT(saveProjectSlot())); exportAsPictureAct = new QAction(QIcon(":/icons/export_as_picture.png"), tr("&Export as a picture"), this); exportAsPictureAct->setStatusTip(tr("Export as a picture")); connect(exportAsPictureAct, SIGNAL(triggered()), this, SLOT(exportAsPictureSlot())); loadTextFileAct = new QAction(QIcon(":/icons/load_text_file.svg"), tr("&Load text file"), this); loadTextFileAct->setStatusTip(tr("Load text file")); connect(loadTextFileAct, SIGNAL(triggered()), this, SLOT(loadTextFileSlot())); exportAsPdf = new QAction(QIcon(":/icons/export_as_pdf.svg"), tr("&Export To PDF"), this); exportAsPdf->setStatusTip(tr("Export To PDF")); connect(exportAsPdf, SIGNAL(triggered()), this, SLOT(exportCanvasToPdfSlot())); printAct = new QAction(QIcon(":/icons/print.svg"), tr("&Print..."), this); printAct->setShortcuts(QKeySequence::Print); printAct->setStatusTip(tr("Print the current canvas")); connect(printAct, SIGNAL(triggered()), this, SLOT(printCurrentCanvasSlot())); quitAct = new QAction(QIcon(":/icons/quit.svg"), tr("&Quit"), this); quitAct->setStatusTip(tr("Quit")); connect(quitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(QIcon(":/icons/about.svg"), tr("&About"), this); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(showAboutDialogSlot())); deleteAllAct = new QAction(QIcon(":/icons/delete_all.svg"), tr("&Delete All"), this); deleteAllAct->setStatusTip(tr("Delete all")); connect(deleteAllAct, SIGNAL(triggered()), m_canvasWidget, SLOT(deleteAllItemsSlot())); QActionGroup* backgroundColorGroup = new QActionGroup(this); m_BgColorWhiteAction = new QAction(QIcon(":/icons/white-bg.svg"), tr("&White"), this); m_BgColorWhiteAction->setCheckable(true); m_BgColorGrayAction = new QAction(QIcon(":/icons/gray-bg.svg"), tr("&Gray"), this); m_BgColorGrayAction->setCheckable(true); m_BgColorCyanAction = new QAction(QIcon(":/icons/cyan-bg.svg"), tr("&Cyan"), this); m_BgColorCyanAction->setCheckable(true); m_BgDefaultImage1Action = new QAction(QIcon(":/icons/default_image1.png"), tr("&Default background image titles"), this); m_BgDefaultImage1Action->setCheckable(true); m_BgDefaultImage1Action->setChecked(true); m_BgDefaultImage2Action = new QAction(QIcon(":/icons/default_image2.png"), tr("&Default background image painting"), this); m_BgDefaultImage2Action->setCheckable(true); m_BgImageKanban1Action = new QAction(QIcon(":/icons/bg-kanban1-a5.svg"), tr("&Background image Kanban 4 cols"), this); m_BgImageKanban1Action->setCheckable(true); m_BgImageKanban1HAction = new QAction(QIcon(":/icons/bg-kanban1-a5h.svg"), tr("&Background image Kanban 4 rows"), this); m_BgImageKanban1HAction->setCheckable(true); m_BgImageKanban2Action = new QAction(QIcon(":/icons/bg-kanban2-a5.svg"), tr("&Background image Kanban 3 cols"), this); m_BgImageKanban2Action->setCheckable(true); m_BgImageKanban2HAction = new QAction(QIcon(":/icons/bg-kanban2-a5h.svg"), tr("&Background image Kanban 3 rows"), this); m_BgImageKanban2HAction->setCheckable(true); m_BgUserImageAction = new QAction(QIcon(":/icons/load_background_image.png"), tr("&User background image"), this); m_BgUserImageAction->setStatusTip(tr("User background image")); m_BgUserImageAction->setCheckable(true); //connect(m_BgUserImageAction, SIGNAL(triggered()), m_canvasWidget, SLOT(loadBackgroundImageSlot())); backgroundColorGroup->addAction(m_BgColorWhiteAction); backgroundColorGroup->addAction(m_BgColorGrayAction); backgroundColorGroup->addAction(m_BgColorCyanAction); backgroundColorGroup->addAction(m_BgDefaultImage1Action); backgroundColorGroup->addAction(m_BgDefaultImage2Action); backgroundColorGroup->addAction(m_BgImageKanban1Action); backgroundColorGroup->addAction(m_BgImageKanban1HAction); backgroundColorGroup->addAction(m_BgImageKanban2Action); backgroundColorGroup->addAction(m_BgImageKanban2HAction); backgroundColorGroup->addAction(m_BgUserImageAction); backgroundColorGroup->setExclusive(true); connect(backgroundColorGroup, SIGNAL(triggered(QAction *)), this, SLOT(changeBackgroundColorSlot(QAction*))); } void MainWindow::createMenus() { QMenu* fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(loadProjectAct); fileMenu->addAction(saveProjectAct); fileMenu->addSeparator(); fileMenu->addAction(loadTextFileAct); fileMenu->addSeparator(); fileMenu->addAction(exportAsPictureAct); fileMenu->addAction(exportAsPdf); fileMenu->addAction(printAct); fileMenu->addSeparator(); fileMenu->addAction(quitAct); QMenu* editMenu = menuBar()->addMenu(tr("&Edit")); editMenu->addAction(deleteAllAct); //menuBar()->addMenu(tr("&View")); QMenu* backgroundMenu = menuBar()->addMenu(tr("&Background")); backgroundMenu->addAction(m_BgColorWhiteAction); backgroundMenu->addAction(m_BgColorGrayAction); backgroundMenu->addAction(m_BgColorCyanAction); backgroundMenu->addSeparator(); backgroundMenu->addAction(m_BgDefaultImage1Action); backgroundMenu->addAction(m_BgDefaultImage2Action); backgroundMenu->addSeparator(); backgroundMenu->addAction(m_BgImageKanban1Action); backgroundMenu->addAction(m_BgImageKanban1HAction); backgroundMenu->addAction(m_BgImageKanban2Action); backgroundMenu->addAction(m_BgImageKanban2HAction); backgroundMenu->addSeparator(); backgroundMenu->addAction(m_BgUserImageAction); menuBar()->addSeparator(); QMenu* helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); } void MainWindow::loadProjectSlot() { QString sFilename = QFileDialog::getOpenFileName(this, "Load project from file ", QString(), tr("Semaphored project files (*.sem)")); if(sFilename.size()) if(QMessageBox::question(this, tr("Load project"), tr("Do you want to <b>load project</b> %1 ? \nUnsaved changes in current project will be lost.").arg(sFilename), QMessageBox::Yes | QMessageBox::No |QMessageBox::Cancel) == QMessageBox::Yes) m_canvasWidget->loadProject(sFilename); } void MainWindow::saveProjectSlot() { QString sFilename = QFileDialog::getSaveFileName(this, "Save project as: ", "untitled.sem", tr("Semaphored project files (*.sem)")); if(sFilename.size()) { QByteArray ext = QFileInfo(sFilename).suffix().toLower().toLatin1(); if(ext != "sem") sFilename += ".sem"; m_canvasWidget->saveProject(sFilename); } } void MainWindow::exportAsPictureSlot() { QString supportedFormats(""); foreach(QByteArray name,QImageWriter::supportedImageFormats()) supportedFormats += name + " "; QString sFilename = QFileDialog::getSaveFileName(this, "Save as picture as: " + supportedFormats,"untitled.png", tr("Images (*.png *.xpm *.jpg)")); if(sFilename.size()) { QByteArray ext = QFileInfo(sFilename).suffix().toLower().toLatin1(); //suffix = suffix.mid(suffix.lastIndexOf('.')); - grabs the last period in addition to the suffix if(QImageWriter::supportedImageFormats().contains(ext)) { QPixmap pix = QPixmap::grabWidget(centralWidget()); pix.save(sFilename, ext); } else { QMessageBox::warning(this,"Picture was not exported", "Your system supports only following formats: " +supportedFormats); } } } void MainWindow::changeBackgroundColorSlot(QAction * action) { //TPDP this could be unified by m_BackgroundPicture, "" - default, filename = picture, QColor::isValidColor - color QColor newColor(Qt::white); if (action == m_BgColorWhiteAction ) m_canvasWidget->changeBackgroundColor(Qt::white); else if (action == m_BgColorGrayAction) m_canvasWidget->changeBackgroundColor(Qt::gray); else if (action == m_BgColorCyanAction) m_canvasWidget->changeBackgroundColor(newColor = Qt::cyan); else if (action == m_BgDefaultImage1Action) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_DEFAULT_1); else if (action == m_BgDefaultImage2Action) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_DEFAULT_2); else if (action == m_BgImageKanban1Action) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_KANBAN_1); else if (action == m_BgImageKanban1HAction) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_KANBAN_1H); else if (action == m_BgImageKanban2Action) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_KANBAN_2); else if (action == m_BgImageKanban2HAction) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_KANBAN_2H); else if (action == m_BgUserImageAction) { m_canvasWidget->loadUserBackgroundImage(); } } void MainWindow::loadTextFileSlot() { QString sFilename = QFileDialog::getOpenFileName(this, "Load source test file: ",QString(), tr("Text files (*.txt *.*)")); if(sFilename.size()) m_canvasWidget->loadTextFile(sFilename); } DragWidget* MainWindow::canvasWidget() { return m_canvasWidget; } void MainWindow::printCurrentCanvasSlot() { QPrinter printer(QPrinter::HighResolution); QPrintDialog dlg(&printer, this); if (dlg.exec() != QDialog::Accepted) return; QPixmap qpm = QPixmap::grabWidget(centralWidget()); QPainter painter; qpm = qpm.scaled(printer.pageRect().width(), printer.pageRect().height(), Qt::KeepAspectRatio); painter.begin (&printer); painter.drawPixmap (0, 0, qpm); painter.end(); } void MainWindow::exportCanvasToPdfSlot() { QString fileName = QFileDialog::getSaveFileName(this, "Export to PDF", QString(), "*.pdf"); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) fileName.append(".pdf"); QPrinter printer(QPrinter::HighResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); QPixmap qpm = QPixmap::grabWidget(centralWidget()); QPainter painter; qpm = qpm.scaled(printer.pageRect().width(), printer.pageRect().height(), Qt::KeepAspectRatio); painter.begin (&printer); painter.drawPixmap (0, 0, qpm); painter.end(); } } void MainWindow::showAboutDialogSlot() { if (!m_aboutDialog) { m_aboutDialog = new AboutDialog(this); } m_aboutDialog->show(); } <commit_msg>New: main window title with short version in release<commit_after>/**************************************************************************** ** ** Author: Miroslav Safr <miroslav.safr@gmail.com> ** Web: http://semaphored.safrm.net/ ** Source: https://github.com/safrm/semaphored ** ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ****************************************************************************/ #include <QMenuBar> #include <QFileDialog> #include <QImageWriter> #include <QDebug> #include <QMessageBox> #include <QPrinter> #include <QPrintDialog> #include <QPainter> #include "mainwindow.h" #include "draglabel.h" #include "dragwidget.h" #include "aboutdialog.h" #include "version.h" MainWindow * g_pMainGuiWindow =NULL; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), loadProjectAct(NULL), saveProjectAct(NULL), exportAsPictureAct(NULL), loadTextFileAct(NULL), printAct(NULL), exportAsPdf(NULL), quitAct(NULL), aboutAct(NULL), deleteAllAct(NULL), m_canvasWidget(new DragWidget()), //TODO use size hint in canvas m_aboutDialog(NULL) { g_pMainGuiWindow = this; //createDockWindows(); createActions(); createMenus(); //createToolBars(); //createStatusBar(); setCentralWidget(m_canvasWidget); #ifdef DEBUG setWindowTitle(QString(APPLICATION_NAME) + "-" + QString(APP_FULL_VERSION_TAG) + " (" + QString(APP_DATE) +")"); #else setWindowTitle(QString(APPLICATION_NAME) + "-" + QString(APP_SHORT_VERSION_TAG)); #endif //DEBUG setWindowIcon(QIcon(":/icons/semaphored.svg")); } MainWindow* MainWindow::instance() { return g_pMainGuiWindow; } void MainWindow::createActions() { loadProjectAct = new QAction(QIcon(":/icons/load_project.svg"), tr("&Load project"), this); loadProjectAct->setStatusTip(tr("Load project")); connect(loadProjectAct, SIGNAL(triggered()), this, SLOT(loadProjectSlot())); saveProjectAct = new QAction(QIcon(":/icons/save_project.svg"), tr("&Save project"), this); saveProjectAct->setStatusTip(tr("Save project")); connect(saveProjectAct, SIGNAL(triggered()), this, SLOT(saveProjectSlot())); exportAsPictureAct = new QAction(QIcon(":/icons/export_as_picture.png"), tr("&Export as a picture"), this); exportAsPictureAct->setStatusTip(tr("Export as a picture")); connect(exportAsPictureAct, SIGNAL(triggered()), this, SLOT(exportAsPictureSlot())); loadTextFileAct = new QAction(QIcon(":/icons/load_text_file.svg"), tr("&Load text file"), this); loadTextFileAct->setStatusTip(tr("Load text file")); connect(loadTextFileAct, SIGNAL(triggered()), this, SLOT(loadTextFileSlot())); exportAsPdf = new QAction(QIcon(":/icons/export_as_pdf.svg"), tr("&Export To PDF"), this); exportAsPdf->setStatusTip(tr("Export To PDF")); connect(exportAsPdf, SIGNAL(triggered()), this, SLOT(exportCanvasToPdfSlot())); printAct = new QAction(QIcon(":/icons/print.svg"), tr("&Print..."), this); printAct->setShortcuts(QKeySequence::Print); printAct->setStatusTip(tr("Print the current canvas")); connect(printAct, SIGNAL(triggered()), this, SLOT(printCurrentCanvasSlot())); quitAct = new QAction(QIcon(":/icons/quit.svg"), tr("&Quit"), this); quitAct->setStatusTip(tr("Quit")); connect(quitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(QIcon(":/icons/about.svg"), tr("&About"), this); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(showAboutDialogSlot())); deleteAllAct = new QAction(QIcon(":/icons/delete_all.svg"), tr("&Delete All"), this); deleteAllAct->setStatusTip(tr("Delete all")); connect(deleteAllAct, SIGNAL(triggered()), m_canvasWidget, SLOT(deleteAllItemsSlot())); QActionGroup* backgroundColorGroup = new QActionGroup(this); m_BgColorWhiteAction = new QAction(QIcon(":/icons/white-bg.svg"), tr("&White"), this); m_BgColorWhiteAction->setCheckable(true); m_BgColorGrayAction = new QAction(QIcon(":/icons/gray-bg.svg"), tr("&Gray"), this); m_BgColorGrayAction->setCheckable(true); m_BgColorCyanAction = new QAction(QIcon(":/icons/cyan-bg.svg"), tr("&Cyan"), this); m_BgColorCyanAction->setCheckable(true); m_BgDefaultImage1Action = new QAction(QIcon(":/icons/default_image1.png"), tr("&Default background image titles"), this); m_BgDefaultImage1Action->setCheckable(true); m_BgDefaultImage1Action->setChecked(true); m_BgDefaultImage2Action = new QAction(QIcon(":/icons/default_image2.png"), tr("&Default background image painting"), this); m_BgDefaultImage2Action->setCheckable(true); m_BgImageKanban1Action = new QAction(QIcon(":/icons/bg-kanban1-a5.svg"), tr("&Background image Kanban 4 cols"), this); m_BgImageKanban1Action->setCheckable(true); m_BgImageKanban1HAction = new QAction(QIcon(":/icons/bg-kanban1-a5h.svg"), tr("&Background image Kanban 4 rows"), this); m_BgImageKanban1HAction->setCheckable(true); m_BgImageKanban2Action = new QAction(QIcon(":/icons/bg-kanban2-a5.svg"), tr("&Background image Kanban 3 cols"), this); m_BgImageKanban2Action->setCheckable(true); m_BgImageKanban2HAction = new QAction(QIcon(":/icons/bg-kanban2-a5h.svg"), tr("&Background image Kanban 3 rows"), this); m_BgImageKanban2HAction->setCheckable(true); m_BgUserImageAction = new QAction(QIcon(":/icons/load_background_image.png"), tr("&User background image"), this); m_BgUserImageAction->setStatusTip(tr("User background image")); m_BgUserImageAction->setCheckable(true); //connect(m_BgUserImageAction, SIGNAL(triggered()), m_canvasWidget, SLOT(loadBackgroundImageSlot())); backgroundColorGroup->addAction(m_BgColorWhiteAction); backgroundColorGroup->addAction(m_BgColorGrayAction); backgroundColorGroup->addAction(m_BgColorCyanAction); backgroundColorGroup->addAction(m_BgDefaultImage1Action); backgroundColorGroup->addAction(m_BgDefaultImage2Action); backgroundColorGroup->addAction(m_BgImageKanban1Action); backgroundColorGroup->addAction(m_BgImageKanban1HAction); backgroundColorGroup->addAction(m_BgImageKanban2Action); backgroundColorGroup->addAction(m_BgImageKanban2HAction); backgroundColorGroup->addAction(m_BgUserImageAction); backgroundColorGroup->setExclusive(true); connect(backgroundColorGroup, SIGNAL(triggered(QAction *)), this, SLOT(changeBackgroundColorSlot(QAction*))); } void MainWindow::createMenus() { QMenu* fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(loadProjectAct); fileMenu->addAction(saveProjectAct); fileMenu->addSeparator(); fileMenu->addAction(loadTextFileAct); fileMenu->addSeparator(); fileMenu->addAction(exportAsPictureAct); fileMenu->addAction(exportAsPdf); fileMenu->addAction(printAct); fileMenu->addSeparator(); fileMenu->addAction(quitAct); QMenu* editMenu = menuBar()->addMenu(tr("&Edit")); editMenu->addAction(deleteAllAct); //menuBar()->addMenu(tr("&View")); QMenu* backgroundMenu = menuBar()->addMenu(tr("&Background")); backgroundMenu->addAction(m_BgColorWhiteAction); backgroundMenu->addAction(m_BgColorGrayAction); backgroundMenu->addAction(m_BgColorCyanAction); backgroundMenu->addSeparator(); backgroundMenu->addAction(m_BgDefaultImage1Action); backgroundMenu->addAction(m_BgDefaultImage2Action); backgroundMenu->addSeparator(); backgroundMenu->addAction(m_BgImageKanban1Action); backgroundMenu->addAction(m_BgImageKanban1HAction); backgroundMenu->addAction(m_BgImageKanban2Action); backgroundMenu->addAction(m_BgImageKanban2HAction); backgroundMenu->addSeparator(); backgroundMenu->addAction(m_BgUserImageAction); menuBar()->addSeparator(); QMenu* helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); } void MainWindow::loadProjectSlot() { QString sFilename = QFileDialog::getOpenFileName(this, "Load project from file ", QString(), tr("Semaphored project files (*.sem)")); if(sFilename.size()) if(QMessageBox::question(this, tr("Load project"), tr("Do you want to <b>load project</b> %1 ? \nUnsaved changes in current project will be lost.").arg(sFilename), QMessageBox::Yes | QMessageBox::No |QMessageBox::Cancel) == QMessageBox::Yes) m_canvasWidget->loadProject(sFilename); } void MainWindow::saveProjectSlot() { QString sFilename = QFileDialog::getSaveFileName(this, "Save project as: ", "untitled.sem", tr("Semaphored project files (*.sem)")); if(sFilename.size()) { QByteArray ext = QFileInfo(sFilename).suffix().toLower().toLatin1(); if(ext != "sem") sFilename += ".sem"; m_canvasWidget->saveProject(sFilename); } } void MainWindow::exportAsPictureSlot() { QString supportedFormats(""); foreach(QByteArray name,QImageWriter::supportedImageFormats()) supportedFormats += name + " "; QString sFilename = QFileDialog::getSaveFileName(this, "Save as picture as: " + supportedFormats,"untitled.png", tr("Images (*.png *.xpm *.jpg)")); if(sFilename.size()) { QByteArray ext = QFileInfo(sFilename).suffix().toLower().toLatin1(); //suffix = suffix.mid(suffix.lastIndexOf('.')); - grabs the last period in addition to the suffix if(QImageWriter::supportedImageFormats().contains(ext)) { QPixmap pix = QPixmap::grabWidget(centralWidget()); pix.save(sFilename, ext); } else { QMessageBox::warning(this,"Picture was not exported", "Your system supports only following formats: " +supportedFormats); } } } void MainWindow::changeBackgroundColorSlot(QAction * action) { //TPDP this could be unified by m_BackgroundPicture, "" - default, filename = picture, QColor::isValidColor - color QColor newColor(Qt::white); if (action == m_BgColorWhiteAction ) m_canvasWidget->changeBackgroundColor(Qt::white); else if (action == m_BgColorGrayAction) m_canvasWidget->changeBackgroundColor(Qt::gray); else if (action == m_BgColorCyanAction) m_canvasWidget->changeBackgroundColor(newColor = Qt::cyan); else if (action == m_BgDefaultImage1Action) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_DEFAULT_1); else if (action == m_BgDefaultImage2Action) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_DEFAULT_2); else if (action == m_BgImageKanban1Action) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_KANBAN_1); else if (action == m_BgImageKanban1HAction) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_KANBAN_1H); else if (action == m_BgImageKanban2Action) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_KANBAN_2); else if (action == m_BgImageKanban2HAction) m_canvasWidget->changeBackgroundImage(DragWidget::BG_IMAGE_KANBAN_2H); else if (action == m_BgUserImageAction) { m_canvasWidget->loadUserBackgroundImage(); } } void MainWindow::loadTextFileSlot() { QString sFilename = QFileDialog::getOpenFileName(this, "Load source test file: ",QString(), tr("Text files (*.txt *.*)")); if(sFilename.size()) m_canvasWidget->loadTextFile(sFilename); } DragWidget* MainWindow::canvasWidget() { return m_canvasWidget; } void MainWindow::printCurrentCanvasSlot() { QPrinter printer(QPrinter::HighResolution); QPrintDialog dlg(&printer, this); if (dlg.exec() != QDialog::Accepted) return; QPixmap qpm = QPixmap::grabWidget(centralWidget()); QPainter painter; qpm = qpm.scaled(printer.pageRect().width(), printer.pageRect().height(), Qt::KeepAspectRatio); painter.begin (&printer); painter.drawPixmap (0, 0, qpm); painter.end(); } void MainWindow::exportCanvasToPdfSlot() { QString fileName = QFileDialog::getSaveFileName(this, "Export to PDF", QString(), "*.pdf"); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) fileName.append(".pdf"); QPrinter printer(QPrinter::HighResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); QPixmap qpm = QPixmap::grabWidget(centralWidget()); QPainter painter; qpm = qpm.scaled(printer.pageRect().width(), printer.pageRect().height(), Qt::KeepAspectRatio); painter.begin (&printer); painter.drawPixmap (0, 0, qpm); painter.end(); } } void MainWindow::showAboutDialogSlot() { if (!m_aboutDialog) { m_aboutDialog = new AboutDialog(this); } m_aboutDialog->show(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: flags.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 03:47:52 $ * * 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 INCLUDED_DATA_FLAGS_HXX #define INCLUDED_DATA_FLAGS_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif namespace configmgr { //----------------------------------------------------------------------------- namespace data { //----------------------------------------------------------------------------- // node type + value type selector - fits into a byte (bit 5 currently unassigned) namespace Type { enum Type { // Primitive Data Type is stored in bits 0-4 (bit 3 currently unused) // base data types value_any, // = 0 value_string, // = 1 value_boolean, // = 2 value_short, // = 3 value_int, // = 4 value_long, // = 5 value_double, // = 6 value_binary, // = 7 mask_basetype = 0x0F, // sequence data types flag_sequence = 0x10, value_invalid = value_any | flag_sequence, value_string_list = value_string | flag_sequence, value_boolean_list = value_boolean | flag_sequence, value_short_list = value_short | flag_sequence, value_int_list = value_int | flag_sequence, value_long_list = value_long | flag_sequence, value_double_list = value_double | flag_sequence, value_binary_list = value_binary | flag_sequence, mask_valuetype = mask_basetype | flag_sequence, // 0x1F // Node Type is stored in bits 6+7 nodetype_shift_ = 6, mask_nodetype = 0x03 << nodetype_shift_, // 0xC0 // maybe we should use 0 for node type 'value' // to make the complete type be the valuetype ? nodetype_invalid= 0x00, nodetype_value = 0x01 << nodetype_shift_, // 0x40 nodetype_group = 0x02 << nodetype_shift_, // 0x80 nodetype_set = 0x03 << nodetype_shift_, // 0xC0 flag_innernode = 0x02 << nodetype_shift_, // 0x80 flag_setnode = 0x01 << nodetype_shift_ // 0x40 }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- // node attributes namespace Flags { enum Type { readonly = 0x01, finalized = 0x02, nullable = 0x04, localized = 0x08, valueAvailable = 0x10, // only used for value nodes defaultAvailable = 0x20, // only used for value nodes defaulted = 0x40, // somewhat redundant with State defaultable = 0x80 // redundant with State (merged || defaulted) }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- // set element or tree state namespace State { enum Type { merged, // = 0, - result of merging defaults + changes defaulted, // = 1, - result of copying defaults unchanged replaced, // = 2, - result of copying new layer unchanged added, // = 3, - same as 'replaced', but it is known, // that there is no corresponding default mask_state = 0x0F, // leaves bits 3+4 reserved for states flag_mandatory = 0x10, // marks this element as non-removable/replacable flag_readonly = 0x20, // marks this element as read-only flag_default_avail = 0x40, // marks this element as containing default values flag_removable = 0x80 // marks this element as removable }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- } //----------------------------------------------------------------------------- } #endif // INCLUDED_DATA_FLAGS_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.4.130); FILE MERGED 2008/04/01 15:06:43 thb 1.4.130.2: #i85898# Stripping all external header guards 2008/03/31 12:22:44 rt 1.4.130.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: flags.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_DATA_FLAGS_HXX #define INCLUDED_DATA_FLAGS_HXX #include <sal/types.h> namespace configmgr { //----------------------------------------------------------------------------- namespace data { //----------------------------------------------------------------------------- // node type + value type selector - fits into a byte (bit 5 currently unassigned) namespace Type { enum Type { // Primitive Data Type is stored in bits 0-4 (bit 3 currently unused) // base data types value_any, // = 0 value_string, // = 1 value_boolean, // = 2 value_short, // = 3 value_int, // = 4 value_long, // = 5 value_double, // = 6 value_binary, // = 7 mask_basetype = 0x0F, // sequence data types flag_sequence = 0x10, value_invalid = value_any | flag_sequence, value_string_list = value_string | flag_sequence, value_boolean_list = value_boolean | flag_sequence, value_short_list = value_short | flag_sequence, value_int_list = value_int | flag_sequence, value_long_list = value_long | flag_sequence, value_double_list = value_double | flag_sequence, value_binary_list = value_binary | flag_sequence, mask_valuetype = mask_basetype | flag_sequence, // 0x1F // Node Type is stored in bits 6+7 nodetype_shift_ = 6, mask_nodetype = 0x03 << nodetype_shift_, // 0xC0 // maybe we should use 0 for node type 'value' // to make the complete type be the valuetype ? nodetype_invalid= 0x00, nodetype_value = 0x01 << nodetype_shift_, // 0x40 nodetype_group = 0x02 << nodetype_shift_, // 0x80 nodetype_set = 0x03 << nodetype_shift_, // 0xC0 flag_innernode = 0x02 << nodetype_shift_, // 0x80 flag_setnode = 0x01 << nodetype_shift_ // 0x40 }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- // node attributes namespace Flags { enum Type { readonly = 0x01, finalized = 0x02, nullable = 0x04, localized = 0x08, valueAvailable = 0x10, // only used for value nodes defaultAvailable = 0x20, // only used for value nodes defaulted = 0x40, // somewhat redundant with State defaultable = 0x80 // redundant with State (merged || defaulted) }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- // set element or tree state namespace State { enum Type { merged, // = 0, - result of merging defaults + changes defaulted, // = 1, - result of copying defaults unchanged replaced, // = 2, - result of copying new layer unchanged added, // = 3, - same as 'replaced', but it is known, // that there is no corresponding default mask_state = 0x0F, // leaves bits 3+4 reserved for states flag_mandatory = 0x10, // marks this element as non-removable/replacable flag_readonly = 0x20, // marks this element as read-only flag_default_avail = 0x40, // marks this element as containing default values flag_removable = 0x80 // marks this element as removable }; typedef sal_uInt8 Field; } //----------------------------------------------------------------------------- } //----------------------------------------------------------------------------- } #endif // INCLUDED_DATA_FLAGS_HXX <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <algorithm> #include "matrix/Room.hpp" #include "LabeledProgressBar.hpp" namespace { QString room_sort_key(const matrix::Room &r) { const auto &n = r.display_name(); auto i = std::find_if(n.begin(), n.end(), [](QChar c) { return c != '#'; }); if(i != n.end()) return n; return QString(n.data() + (i - n.begin()), n.end() - i).toLower(); } } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), progress_(new LabeledProgressBar) { ui->setupUi(this); ui->status_bar->addPermanentWidget(progress_); connect(ui->action_log_out, &QAction::triggered, [this]() { log_out(); }); ui->action_quit->setShortcuts(QKeySequence::Quit); connect(ui->action_quit, &QAction::triggered, [this]() { quit(); }); } MainWindow::~MainWindow() { delete ui; } void MainWindow::set_rooms(gsl::span<matrix::Room *const> rooms_in) { std::vector<matrix::Room *> rooms(rooms_in.begin(), rooms_in.end()); std::sort(rooms.begin(), rooms.end(), [](const matrix::Room *a, const matrix::Room *b) { return room_sort_key(*a) < room_sort_key(*b); }); ui->room_list->clear(); for(auto room : rooms) { auto item = new QListWidgetItem; item->setText(room->display_name()); item->setData(Qt::UserRole, QVariant::fromValue(reinterpret_cast<void*>(room))); ui->room_list->addItem(item); } } void MainWindow::set_initial_sync(bool underway) { if(underway) { progress_->show(); progress_->set_text(tr("Downloading state...")); } else { progress_->hide(); } } <commit_msg>Cleanup<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <algorithm> #include "matrix/Room.hpp" #include "LabeledProgressBar.hpp" namespace { QString room_sort_key(const matrix::Room &r) { const auto &n = r.display_name(); auto i = std::find_if(n.begin(), n.end(), [](QChar c) { return c != '#'; }); if(i != n.end()) return n; return QString(n.data() + (i - n.begin()), n.end() - i).toLower(); } } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), progress_(new LabeledProgressBar) { ui->setupUi(this); ui->status_bar->addPermanentWidget(progress_); connect(ui->action_log_out, &QAction::triggered, this, &MainWindow::log_out); ui->action_quit->setShortcuts(QKeySequence::Quit); connect(ui->action_quit, &QAction::triggered, this, &MainWindow::quit); } MainWindow::~MainWindow() { delete ui; } void MainWindow::set_rooms(gsl::span<matrix::Room *const> rooms_in) { std::vector<matrix::Room *> rooms(rooms_in.begin(), rooms_in.end()); std::sort(rooms.begin(), rooms.end(), [](const matrix::Room *a, const matrix::Room *b) { return room_sort_key(*a) < room_sort_key(*b); }); ui->room_list->clear(); for(auto room : rooms) { auto item = new QListWidgetItem; item->setText(room->display_name()); item->setData(Qt::UserRole, QVariant::fromValue(reinterpret_cast<void*>(room))); ui->room_list->addItem(item); } } void MainWindow::set_initial_sync(bool underway) { if(underway) { progress_->show(); progress_->set_text(tr("Downloading state...")); } else { progress_->hide(); } } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "db.h" #include "commands.h" #include "iomidi.h" #include "midiconnectionsmodel.h" #include "midivaluedelegate.h" #include "programsmodel.h" #include "sysexhandler.h" #include "utils.h" #include <QApplication> #include <QComboBox> #include <QDataWidgetMapper> #include <QFileDialog> #include <QPushButton> #include <QMessageBox> #include <QSettings> #include <QStandardPaths> #include <QStandardItemModel> #include <QUndoStack> static const QString SETTINGS_KEY_DEFAULT_NAME = "default/name"; static const QString SETTINGS_KEY_DEFAULT_SYSEX = "default/sysex"; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), programsModel(nullptr) { // Database if (!initFilesystem()) { throw std::runtime_error("Failed filesystem initialization"); } QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(defaultDbPath()); if (!db.open()) { throw std::runtime_error(QString("Failed to open db %1").arg(defaultDbPath()).toStdString()); } if (initDb(db).isValid()) { throw std::runtime_error("Failed database initialization"); } programsModel = new ProgramsModel(this, db); ui->setupUi(this); setStatusBar(nullptr); // Undo QUndoStack* stack = undoStack(); Q_CHECK_PTR(stack); QAction* undoAction = stack->createUndoAction(this, tr("Undo")); undoAction->setShortcuts(QKeySequence::Undo); QAction* redoAction = stack->createRedoAction(this, tr("Redo")); redoAction->setShortcuts(QKeySequence::Redo); ui->menuEdit->insertAction(ui->actionNewProgram, redoAction); ui->menuEdit->insertAction(redoAction, undoAction); ui->menuEdit->insertSeparator(ui->actionNewProgram); // Client selection combo box QComboBox* clientComboBox = new QComboBox(this); clientComboBox->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); ui->toolBar->addWidget(clientComboBox); ui->newProgramButton->setDefaultAction(ui->actionNewProgram); ui->deleteProgramButton->setDefaultAction(ui->actionDeleteProgram); ui->programsView->setModel(programsModel); ui->programsView->setModelColumn(programModelColumn()); QDataWidgetMapper *mapper = new QDataWidgetMapper(this); mapper->setModel(programsModel); mapper->setItemDelegate(new MidiValueDelegate(this)); mapper->addMapping(ui->channelSpinBox, 2); // XXX ui->padsView->setItemDelegate(new MidiValueDelegate(this)); ui->padsView->setModel(programsModel); ui->padsView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); QHeaderView* headerView = new QHeaderView(Qt::Horizontal, this); headerView->setModel(programsModel->padsHeaderModel()); ui->padsView->setHorizontalHeader(headerView); ui->padsView->hideColumn(0); ui->padsView->hideColumn(1); ui->knobsView->setItemDelegate(new MidiValueDelegate(this)); ui->knobsView->setModel(programsModel); ui->knobsView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); headerView = new QHeaderView(Qt::Horizontal, this); headerView->setModel(programsModel->knobsHeaderModel()); ui->knobsView->setHorizontalHeader(headerView); ui->knobsView->hideColumn(0); ui->knobsView->hideColumn(1); // Refresh action delete program QItemSelectionModel *sel = ui->programsView->selectionModel(); Q_CHECK_PTR(sel); connect(sel, &QItemSelectionModel::selectionChanged, this, &MainWindow::refreshUiAccordingToSelection ); connect(sel, &QItemSelectionModel::currentRowChanged, mapper, &QDataWidgetMapper::setCurrentModelIndex); connect(sel, &QItemSelectionModel::currentRowChanged, [=](const QModelIndex &current) { Q_CHECK_PTR(programsModel); ui->padsView->setRootIndex(programsModel->padsParentIndex(current)); ui->knobsView->setRootIndex(programsModel->knobsParentIndex(current)); } ); connect(programsModel, &QAbstractItemModel::modelReset, this, &MainWindow::refreshUiAccordingToSelection ); ProgramIdSelectionRestorer *restorer = new ProgramIdSelectionRestorer(ui->programsView->selectionModel(), this); connect(programsModel, &ProgramsModel::modelAboutToBeReset, restorer, &ProgramIdSelectionRestorer::store); connect(programsModel, &ProgramsModel::modelReset, restorer, &ProgramIdSelectionRestorer::restore); // Enable MIDI send / receive action when connected auto io = new IOMidi(this); // MIDI connections auto connectionsModel = new MidiConnectionsModel(io); clientComboBox->setModel(connectionsModel); Q_ASSERT(clientComboBox->count() > 0); clientComboBox->setEnabled(connectionsModel->connectedPort().isValid()); connect(connectionsModel, &MidiConnectionsModel::connectedPortChanged, [=](const QModelIndex &index) { clientComboBox->setEnabled(index.isValid()); if (index.isValid()) { clientComboBox->setCurrentIndex(index.row()); } }); // Do not use QOverload for compatibility with older Qt, // as in Linux Mint 18.3 connect( clientComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), [=](int row) { connectionsModel->connectPort(connectionsModel->index(row)); } ); // MIDI actions QList<QAction *> midiSendActions = { ui->actionGetProgram1, ui->actionGetProgram2, ui->actionGetProgram3, ui->actionGetProgram4 }; QList<QAction *> midiReceiveActions { ui->actionSendToProgram1, ui->actionSendToProgram2, ui->actionSendToProgram3, ui->actionSendToProgram4, }; QList<QAction *> midiActions = midiSendActions + midiReceiveActions; auto midiActionsSetEnabled = [=](){ for (auto it = midiActions.begin() ; it != midiActions.end() ; ++it) { QAction* a = *it; Q_CHECK_PTR(a); a->setEnabled(connectionsModel->connected() && ui->programsView->selectionModel()->currentIndex().row() != -1); } }; midiActionsSetEnabled(); connect( connectionsModel, &MidiConnectionsModel::connectedChanged, midiActionsSetEnabled ); connect( ui->programsView->selectionModel(), &QItemSelectionModel::currentChanged, midiActionsSetEnabled ); connect( programsModel, &ProgramsModel::modelReset, midiActionsSetEnabled ); // Sysex auto sysexHandler = new SysexHandler(io); connect(sysexHandler, &SysexHandler::programReceived, [=](const QByteArray& sysex) { Q_CHECK_PTR(ui->programsView->selectionModel()); Q_CHECK_PTR(programsModel); Q_CHECK_PTR(undoStack()); const int programId = currentSelectedProjectId(); if (programId == -1) { Q_UNIMPLEMENTED(); } else { UpdateProgramFromSysexCommand* cmd = new UpdateProgramFromSysexCommand( programsModel, programId, sysex ); undoStack()->push(cmd); } }); for (int i = 0 ; i < midiSendActions.count() ; ++i) { connect( midiSendActions[i], &QAction::triggered, [=]() { Q_CHECK_PTR(sysexHandler); sysexHandler->getProgram(i+1); } ); } for (int i = 0 ; i < midiReceiveActions.count() ; ++i) { connect( midiReceiveActions[i], &QAction::triggered, [=]() { const QByteArray sysex = programsModel->programSysex(currentSelectedProjectId()); sysexHandler->sendProgram(sysex, i+1); } ); } } MainWindow::~MainWindow() { delete ui; } int MainWindow::programModelColumn() const { return 1; } QString defaultSysex() { return readTextFile(":/default-sysex.sql"); } void MainWindow::on_actionNewProgram_triggered() { Q_CHECK_PTR(programsModel); Q_CHECK_PTR(undoStack()); QUndoCommand* cmd = new CreateProgramCommand( programsModel, QSettings().value(SETTINGS_KEY_DEFAULT_NAME).toString(), QSettings().value(SETTINGS_KEY_DEFAULT_SYSEX).toByteArray() ); undoStack()->push(cmd); } void MainWindow::on_actionDeleteProgram_triggered() { Q_CHECK_PTR(programsModel); Q_CHECK_PTR(undoStack()); QItemSelectionModel* selection_model = ui->programsView->selectionModel(); Q_CHECK_PTR(selection_model); Q_ASSERT(selection_model->currentIndex().row() > -1); QUndoCommand *cmd = new DeleteProgramCommand( programsModel, selectedProgramId(selection_model) ); undoStack()->push(cmd); } void MainWindow::on_actionQuit_triggered() { qApp->quit(); } void MainWindow::refreshUiAccordingToSelection() { QItemSelectionModel *sel = ui->programsView->selectionModel(); Q_CHECK_PTR(sel); ui->actionDeleteProgram->setEnabled(sel->hasSelection()); QWidget* w = sel->currentIndex().row() != -1 ? ui->pageEditor : ui->pageDefault; ui->stackedWidget->setCurrentWidget(w); } void MainWindow::on_actionImportProgram_triggered() { Q_CHECK_PTR(programsModel); Q_CHECK_PTR(undoStack()); const QString path( QFileDialog::getOpenFileName( this, "Import LPD8 program", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation))); if (path.isEmpty()) { return; } const QByteArray sysex = fromSysexTextFile(path); if (sysex.isNull()) { return; } const QString name = QDir(path).dirName(); QUndoCommand* cmd = new CreateProgramCommand( programsModel, name, sysex ); undoStack()->push(cmd); } void MainWindow::on_actionExportProgram_triggered() { QItemSelectionModel *m = ui->programsView->selectionModel(); Q_CHECK_PTR(m); const int programId = selectedProgramId(m); const QString name = programName(programId); const QByteArray sysex = programSysex(programId); const QDir defaultDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)); const QString defaultPath = defaultDir.absoluteFilePath(name); const QString path( QFileDialog::getSaveFileName( this, "Export LPD8 program", defaultPath)); if (path.isEmpty()) { return; } writeProgramFile(sysex, path); } int MainWindow::currentSelectedProjectId() const { Q_CHECK_PTR(ui->programsView->selectionModel()); return selectedProgramId(ui->programsView->selectionModel()); } void MainWindow::on_actionAbout_triggered() { QMessageBox::about( this, QString("About %1").arg(qApp->applicationName()), QString("<h1>%1 v%2</h1><a href=\"%3\">%4</a><p>%5</p><p>%6</p>") .arg(qApp->applicationName()) .arg(qApp->applicationVersion()) .arg(qApp->property("applicationLink").toString()) .arg(qApp->property("applicationLink").toString()) .arg(qApp->property("applicationLicense").toString()) .arg(qApp->property("applicationCopyright").toString()) ); } void MainWindow::on_actionAboutQt_triggered() { qApp->aboutQt(); } <commit_msg>Disable MIDI operations when sequencer can not be opened<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "db.h" #include "commands.h" #include "iomidi.h" #include "midiconnectionsmodel.h" #include "midivaluedelegate.h" #include "programsmodel.h" #include "sysexhandler.h" #include "utils.h" #include <QApplication> #include <QComboBox> #include <QDataWidgetMapper> #include <QFileDialog> #include <QPushButton> #include <QMessageBox> #include <QSettings> #include <QStandardPaths> #include <QStandardItemModel> #include <QUndoStack> #include <QtDebug> static const QString SETTINGS_KEY_DEFAULT_NAME = "default/name"; static const QString SETTINGS_KEY_DEFAULT_SYSEX = "default/sysex"; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), programsModel(nullptr) { // Database if (!initFilesystem()) { throw std::runtime_error("Failed filesystem initialization"); } QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(defaultDbPath()); if (!db.open()) { throw std::runtime_error(QString("Failed to open db %1").arg(defaultDbPath()).toStdString()); } if (initDb(db).isValid()) { throw std::runtime_error("Failed database initialization"); } programsModel = new ProgramsModel(this, db); ui->setupUi(this); setStatusBar(nullptr); // Undo QUndoStack* stack = undoStack(); Q_CHECK_PTR(stack); QAction* undoAction = stack->createUndoAction(this, tr("Undo")); undoAction->setShortcuts(QKeySequence::Undo); QAction* redoAction = stack->createRedoAction(this, tr("Redo")); redoAction->setShortcuts(QKeySequence::Redo); ui->menuEdit->insertAction(ui->actionNewProgram, redoAction); ui->menuEdit->insertAction(redoAction, undoAction); ui->menuEdit->insertSeparator(ui->actionNewProgram); // Client selection combo box QComboBox* clientComboBox = new QComboBox(this); clientComboBox->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); ui->toolBar->addWidget(clientComboBox); ui->newProgramButton->setDefaultAction(ui->actionNewProgram); ui->deleteProgramButton->setDefaultAction(ui->actionDeleteProgram); ui->programsView->setModel(programsModel); ui->programsView->setModelColumn(programModelColumn()); QDataWidgetMapper *mapper = new QDataWidgetMapper(this); mapper->setModel(programsModel); mapper->setItemDelegate(new MidiValueDelegate(this)); mapper->addMapping(ui->channelSpinBox, 2); // XXX ui->padsView->setItemDelegate(new MidiValueDelegate(this)); ui->padsView->setModel(programsModel); ui->padsView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); QHeaderView* headerView = new QHeaderView(Qt::Horizontal, this); headerView->setModel(programsModel->padsHeaderModel()); ui->padsView->setHorizontalHeader(headerView); ui->padsView->hideColumn(0); ui->padsView->hideColumn(1); ui->knobsView->setItemDelegate(new MidiValueDelegate(this)); ui->knobsView->setModel(programsModel); ui->knobsView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); headerView = new QHeaderView(Qt::Horizontal, this); headerView->setModel(programsModel->knobsHeaderModel()); ui->knobsView->setHorizontalHeader(headerView); ui->knobsView->hideColumn(0); ui->knobsView->hideColumn(1); // Refresh action delete program QItemSelectionModel *sel = ui->programsView->selectionModel(); Q_CHECK_PTR(sel); connect(sel, &QItemSelectionModel::selectionChanged, this, &MainWindow::refreshUiAccordingToSelection ); connect(sel, &QItemSelectionModel::currentRowChanged, mapper, &QDataWidgetMapper::setCurrentModelIndex); connect(sel, &QItemSelectionModel::currentRowChanged, [=](const QModelIndex &current) { Q_CHECK_PTR(programsModel); ui->padsView->setRootIndex(programsModel->padsParentIndex(current)); ui->knobsView->setRootIndex(programsModel->knobsParentIndex(current)); } ); connect(programsModel, &QAbstractItemModel::modelReset, this, &MainWindow::refreshUiAccordingToSelection ); ProgramIdSelectionRestorer *restorer = new ProgramIdSelectionRestorer(ui->programsView->selectionModel(), this); connect(programsModel, &ProgramsModel::modelAboutToBeReset, restorer, &ProgramIdSelectionRestorer::store); connect(programsModel, &ProgramsModel::modelReset, restorer, &ProgramIdSelectionRestorer::restore); // Enable MIDI send / receive action when connected IOMidi* io = nullptr; try { io = new IOMidi(this); } catch (const std::runtime_error& e) { qWarning() << "Disabling MIDI: " << e.what(); return; } // MIDI connections auto connectionsModel = new MidiConnectionsModel(io); clientComboBox->setModel(connectionsModel); Q_ASSERT(clientComboBox->count() > 0); clientComboBox->setEnabled(connectionsModel->connectedPort().isValid()); connect(connectionsModel, &MidiConnectionsModel::connectedPortChanged, [=](const QModelIndex &index) { clientComboBox->setEnabled(index.isValid()); if (index.isValid()) { clientComboBox->setCurrentIndex(index.row()); } }); // Do not use QOverload for compatibility with older Qt, // as in Linux Mint 18.3 connect( clientComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), [=](int row) { connectionsModel->connectPort(connectionsModel->index(row)); } ); // MIDI actions QList<QAction *> midiSendActions = { ui->actionGetProgram1, ui->actionGetProgram2, ui->actionGetProgram3, ui->actionGetProgram4 }; QList<QAction *> midiReceiveActions { ui->actionSendToProgram1, ui->actionSendToProgram2, ui->actionSendToProgram3, ui->actionSendToProgram4, }; QList<QAction *> midiActions = midiSendActions + midiReceiveActions; auto midiActionsSetEnabled = [=](){ for (auto it = midiActions.begin() ; it != midiActions.end() ; ++it) { QAction* a = *it; Q_CHECK_PTR(a); a->setEnabled(connectionsModel->connected() && ui->programsView->selectionModel()->currentIndex().row() != -1); } }; midiActionsSetEnabled(); connect( connectionsModel, &MidiConnectionsModel::connectedChanged, midiActionsSetEnabled ); connect( ui->programsView->selectionModel(), &QItemSelectionModel::currentChanged, midiActionsSetEnabled ); connect( programsModel, &ProgramsModel::modelReset, midiActionsSetEnabled ); // Sysex auto sysexHandler = new SysexHandler(io); connect(sysexHandler, &SysexHandler::programReceived, [=](const QByteArray& sysex) { Q_CHECK_PTR(ui->programsView->selectionModel()); Q_CHECK_PTR(programsModel); Q_CHECK_PTR(undoStack()); const int programId = currentSelectedProjectId(); if (programId == -1) { Q_UNIMPLEMENTED(); } else { UpdateProgramFromSysexCommand* cmd = new UpdateProgramFromSysexCommand( programsModel, programId, sysex ); undoStack()->push(cmd); } }); for (int i = 0 ; i < midiSendActions.count() ; ++i) { connect( midiSendActions[i], &QAction::triggered, [=]() { Q_CHECK_PTR(sysexHandler); sysexHandler->getProgram(i+1); } ); } for (int i = 0 ; i < midiReceiveActions.count() ; ++i) { connect( midiReceiveActions[i], &QAction::triggered, [=]() { const QByteArray sysex = programsModel->programSysex(currentSelectedProjectId()); sysexHandler->sendProgram(sysex, i+1); } ); } } MainWindow::~MainWindow() { delete ui; } int MainWindow::programModelColumn() const { return 1; } QString defaultSysex() { return readTextFile(":/default-sysex.sql"); } void MainWindow::on_actionNewProgram_triggered() { Q_CHECK_PTR(programsModel); Q_CHECK_PTR(undoStack()); QUndoCommand* cmd = new CreateProgramCommand( programsModel, QSettings().value(SETTINGS_KEY_DEFAULT_NAME).toString(), QSettings().value(SETTINGS_KEY_DEFAULT_SYSEX).toByteArray() ); undoStack()->push(cmd); } void MainWindow::on_actionDeleteProgram_triggered() { Q_CHECK_PTR(programsModel); Q_CHECK_PTR(undoStack()); QItemSelectionModel* selection_model = ui->programsView->selectionModel(); Q_CHECK_PTR(selection_model); Q_ASSERT(selection_model->currentIndex().row() > -1); QUndoCommand *cmd = new DeleteProgramCommand( programsModel, selectedProgramId(selection_model) ); undoStack()->push(cmd); } void MainWindow::on_actionQuit_triggered() { qApp->quit(); } void MainWindow::refreshUiAccordingToSelection() { QItemSelectionModel *sel = ui->programsView->selectionModel(); Q_CHECK_PTR(sel); ui->actionDeleteProgram->setEnabled(sel->hasSelection()); QWidget* w = sel->currentIndex().row() != -1 ? ui->pageEditor : ui->pageDefault; ui->stackedWidget->setCurrentWidget(w); } void MainWindow::on_actionImportProgram_triggered() { Q_CHECK_PTR(programsModel); Q_CHECK_PTR(undoStack()); const QString path( QFileDialog::getOpenFileName( this, "Import LPD8 program", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation))); if (path.isEmpty()) { return; } const QByteArray sysex = fromSysexTextFile(path); if (sysex.isNull()) { return; } const QString name = QDir(path).dirName(); QUndoCommand* cmd = new CreateProgramCommand( programsModel, name, sysex ); undoStack()->push(cmd); } void MainWindow::on_actionExportProgram_triggered() { QItemSelectionModel *m = ui->programsView->selectionModel(); Q_CHECK_PTR(m); const int programId = selectedProgramId(m); const QString name = programName(programId); const QByteArray sysex = programSysex(programId); const QDir defaultDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)); const QString defaultPath = defaultDir.absoluteFilePath(name); const QString path( QFileDialog::getSaveFileName( this, "Export LPD8 program", defaultPath)); if (path.isEmpty()) { return; } writeProgramFile(sysex, path); } int MainWindow::currentSelectedProjectId() const { Q_CHECK_PTR(ui->programsView->selectionModel()); return selectedProgramId(ui->programsView->selectionModel()); } void MainWindow::on_actionAbout_triggered() { QMessageBox::about( this, QString("About %1").arg(qApp->applicationName()), QString("<h1>%1 v%2</h1><a href=\"%3\">%4</a><p>%5</p><p>%6</p>") .arg(qApp->applicationName()) .arg(qApp->applicationVersion()) .arg(qApp->property("applicationLink").toString()) .arg(qApp->property("applicationLink").toString()) .arg(qApp->property("applicationLicense").toString()) .arg(qApp->property("applicationCopyright").toString()) ); } void MainWindow::on_actionAboutQt_triggered() { qApp->aboutQt(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/video_engine/vie_base_impl.h" #include <sstream> #include <string> #include "webrtc/engine_configurations.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h" #include "webrtc/modules/video_coding/main/interface/video_coding.h" #include "webrtc/modules/video_processing/main/interface/video_processing.h" #include "webrtc/modules/video_render/include/video_render.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/video_engine/include/vie_errors.h" #include "webrtc/video_engine/vie_channel.h" #include "webrtc/video_engine/vie_channel_manager.h" #include "webrtc/video_engine/vie_defines.h" #include "webrtc/video_engine/vie_encoder.h" #include "webrtc/video_engine/vie_impl.h" #include "webrtc/video_engine/vie_input_manager.h" #include "webrtc/video_engine/vie_shared_data.h" namespace webrtc { ViEBase* ViEBase::GetInterface(VideoEngine* video_engine) { if (!video_engine) { return NULL; } VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine); ViEBaseImpl* vie_base_impl = vie_impl; (*vie_base_impl)++; // Increase ref count. return vie_base_impl; } int ViEBaseImpl::Release() { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(), "ViEBase::Release()"); (*this)--; // Decrease ref count. int32_t ref_count = GetCount(); if (ref_count < 0) { WEBRTC_TRACE(kTraceWarning, kTraceVideo, shared_data_.instance_id(), "ViEBase release too many times"); shared_data_.SetLastError(kViEAPIDoesNotExist); return -1; } WEBRTC_TRACE(kTraceInfo, kTraceVideo, shared_data_.instance_id(), "ViEBase reference count: %d", ref_count); return ref_count; } ViEBaseImpl::ViEBaseImpl(const Config& config) : shared_data_(config) { WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(), "ViEBaseImpl::ViEBaseImpl() Ctor"); } ViEBaseImpl::~ViEBaseImpl() { WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(), "ViEBaseImpl::ViEBaseImpl() Dtor"); } int ViEBaseImpl::Init() { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(), "Init"); return 0; } int ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s", __FUNCTION__); if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::CreateChannel(int& video_channel) { // NOLINT WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s", __FUNCTION__); if (shared_data_.channel_manager()->CreateChannel(&video_channel) == -1) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: Could not create channel", __FUNCTION__); video_channel = -1; shared_data_.SetLastError(kViEBaseChannelCreationFailed); return -1; } WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel created: %d", __FUNCTION__, video_channel); return 0; } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT int original_channel) { return CreateChannel(video_channel, original_channel, true); } int ViEBaseImpl::CreateReceiveChannel(int& video_channel, // NOLINT int original_channel) { return CreateChannel(video_channel, original_channel, false); } int ViEBaseImpl::DeleteChannel(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s(%d)", __FUNCTION__, video_channel); { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel %d doesn't exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } // Deregister the ViEEncoder if no other channel is using it. ViEEncoder* vie_encoder = cs.Encoder(video_channel); if (cs.ChannelUsingViEEncoder(video_channel) == false) { ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { provider->DeregisterFrameCallback(vie_encoder); } } } if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: Could not delete channel %d", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseUnknownError); return -1; } WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel deleted: %d", __FUNCTION__, video_channel); return 0; } int ViEBaseImpl::ConnectAudioChannel(const int video_channel, const int audio_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s(%d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(video_channel)) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel %d doesn't exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel, audio_channel) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::DisconnectAudioChannel(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s(%d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(video_channel)) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel %d doesn't exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->DisconnectVoiceChannel( video_channel) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::StartSend(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s(channel: %d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Channel %d does not exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder != NULL); if (vie_encoder->Owner() != video_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "Can't start ssend on a receive only channel."); shared_data_.SetLastError(kViEBaseReceiveOnlyChannel); return -1; } // Pause and trigger a key frame. vie_encoder->Pause(); int32_t error = vie_channel->StartSend(); if (error != 0) { vie_encoder->Restart(); WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Could not start sending on channel %d", __FUNCTION__, video_channel); if (error == kViEBaseAlreadySending) { shared_data_.SetLastError(kViEBaseAlreadySending); } shared_data_.SetLastError(kViEBaseUnknownError); return -1; } vie_encoder->SendKeyFrame(); vie_encoder->Restart(); return 0; } int ViEBaseImpl::StopSend(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s(channel: %d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Channel %d does not exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } int32_t error = vie_channel->StopSend(); if (error != 0) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Could not stop sending on channel %d", __FUNCTION__, video_channel); if (error == kViEBaseNotSending) { shared_data_.SetLastError(kViEBaseNotSending); } else { shared_data_.SetLastError(kViEBaseUnknownError); } return -1; } return 0; } int ViEBaseImpl::StartReceive(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s(channel: %d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Channel %d does not exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (vie_channel->StartReceive() != 0) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } return 0; } int ViEBaseImpl::StopReceive(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s(channel: %d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Channel %d does not exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (vie_channel->StopReceive() != 0) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } return 0; } int ViEBaseImpl::GetVersion(char version[1024]) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "GetVersion(version=?)"); assert(kViEVersionMaxMessageSize == 1024); if (!version) { shared_data_.SetLastError(kViEBaseInvalidArgument); return -1; } // Add WebRTC Version. std::stringstream version_stream; version_stream << "VideoEngine 3.31.0" << std::endl; // Add build info. version_stream << "Build: svn:" << WEBRTC_SVNREVISION << " " << BUILDINFO << std::endl; #ifdef WEBRTC_EXTERNAL_TRANSPORT version_stream << "External transport build" << std::endl; #endif int version_length = version_stream.tellp(); assert(version_length < 1024); memcpy(version, version_stream.str().c_str(), version_length); version[version_length] = '\0'; WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, ViEId(shared_data_.instance_id()), "GetVersion() => %s", version); return 0; } int ViEBaseImpl::LastError() { return shared_data_.LastErrorInternal(); } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT int original_channel, bool sender) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(original_channel)) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s - original_channel does not exist.", __FUNCTION__, shared_data_.instance_id()); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->CreateChannel(&video_channel, original_channel, sender) == -1) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: Could not create channel", __FUNCTION__); video_channel = -1; shared_data_.SetLastError(kViEBaseChannelCreationFailed); return -1; } WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel created: %d", __FUNCTION__, video_channel); return 0; } } // namespace webrtc <commit_msg>Updated WebRTC version to 3.32 TBR=wu@webrtc.org<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/video_engine/vie_base_impl.h" #include <sstream> #include <string> #include "webrtc/engine_configurations.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h" #include "webrtc/modules/video_coding/main/interface/video_coding.h" #include "webrtc/modules/video_processing/main/interface/video_processing.h" #include "webrtc/modules/video_render/include/video_render.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/video_engine/include/vie_errors.h" #include "webrtc/video_engine/vie_channel.h" #include "webrtc/video_engine/vie_channel_manager.h" #include "webrtc/video_engine/vie_defines.h" #include "webrtc/video_engine/vie_encoder.h" #include "webrtc/video_engine/vie_impl.h" #include "webrtc/video_engine/vie_input_manager.h" #include "webrtc/video_engine/vie_shared_data.h" namespace webrtc { ViEBase* ViEBase::GetInterface(VideoEngine* video_engine) { if (!video_engine) { return NULL; } VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine); ViEBaseImpl* vie_base_impl = vie_impl; (*vie_base_impl)++; // Increase ref count. return vie_base_impl; } int ViEBaseImpl::Release() { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(), "ViEBase::Release()"); (*this)--; // Decrease ref count. int32_t ref_count = GetCount(); if (ref_count < 0) { WEBRTC_TRACE(kTraceWarning, kTraceVideo, shared_data_.instance_id(), "ViEBase release too many times"); shared_data_.SetLastError(kViEAPIDoesNotExist); return -1; } WEBRTC_TRACE(kTraceInfo, kTraceVideo, shared_data_.instance_id(), "ViEBase reference count: %d", ref_count); return ref_count; } ViEBaseImpl::ViEBaseImpl(const Config& config) : shared_data_(config) { WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(), "ViEBaseImpl::ViEBaseImpl() Ctor"); } ViEBaseImpl::~ViEBaseImpl() { WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(), "ViEBaseImpl::ViEBaseImpl() Dtor"); } int ViEBaseImpl::Init() { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(), "Init"); return 0; } int ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s", __FUNCTION__); if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::CreateChannel(int& video_channel) { // NOLINT WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s", __FUNCTION__); if (shared_data_.channel_manager()->CreateChannel(&video_channel) == -1) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: Could not create channel", __FUNCTION__); video_channel = -1; shared_data_.SetLastError(kViEBaseChannelCreationFailed); return -1; } WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel created: %d", __FUNCTION__, video_channel); return 0; } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT int original_channel) { return CreateChannel(video_channel, original_channel, true); } int ViEBaseImpl::CreateReceiveChannel(int& video_channel, // NOLINT int original_channel) { return CreateChannel(video_channel, original_channel, false); } int ViEBaseImpl::DeleteChannel(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s(%d)", __FUNCTION__, video_channel); { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel %d doesn't exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } // Deregister the ViEEncoder if no other channel is using it. ViEEncoder* vie_encoder = cs.Encoder(video_channel); if (cs.ChannelUsingViEEncoder(video_channel) == false) { ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { provider->DeregisterFrameCallback(vie_encoder); } } } if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: Could not delete channel %d", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseUnknownError); return -1; } WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel deleted: %d", __FUNCTION__, video_channel); return 0; } int ViEBaseImpl::ConnectAudioChannel(const int video_channel, const int audio_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s(%d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(video_channel)) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel %d doesn't exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel, audio_channel) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::DisconnectAudioChannel(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "%s(%d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(video_channel)) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel %d doesn't exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->DisconnectVoiceChannel( video_channel) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::StartSend(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s(channel: %d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Channel %d does not exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder != NULL); if (vie_encoder->Owner() != video_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "Can't start ssend on a receive only channel."); shared_data_.SetLastError(kViEBaseReceiveOnlyChannel); return -1; } // Pause and trigger a key frame. vie_encoder->Pause(); int32_t error = vie_channel->StartSend(); if (error != 0) { vie_encoder->Restart(); WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Could not start sending on channel %d", __FUNCTION__, video_channel); if (error == kViEBaseAlreadySending) { shared_data_.SetLastError(kViEBaseAlreadySending); } shared_data_.SetLastError(kViEBaseUnknownError); return -1; } vie_encoder->SendKeyFrame(); vie_encoder->Restart(); return 0; } int ViEBaseImpl::StopSend(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s(channel: %d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Channel %d does not exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } int32_t error = vie_channel->StopSend(); if (error != 0) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Could not stop sending on channel %d", __FUNCTION__, video_channel); if (error == kViEBaseNotSending) { shared_data_.SetLastError(kViEBaseNotSending); } else { shared_data_.SetLastError(kViEBaseUnknownError); } return -1; } return 0; } int ViEBaseImpl::StartReceive(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s(channel: %d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Channel %d does not exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (vie_channel->StartReceive() != 0) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } return 0; } int ViEBaseImpl::StopReceive(const int video_channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s(channel: %d)", __FUNCTION__, video_channel); ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id(), video_channel), "%s: Channel %d does not exist", __FUNCTION__, video_channel); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (vie_channel->StopReceive() != 0) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } return 0; } int ViEBaseImpl::GetVersion(char version[1024]) { WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()), "GetVersion(version=?)"); assert(kViEVersionMaxMessageSize == 1024); if (!version) { shared_data_.SetLastError(kViEBaseInvalidArgument); return -1; } // Add WebRTC Version. std::stringstream version_stream; version_stream << "VideoEngine 3.32.0" << std::endl; // Add build info. version_stream << "Build: svn:" << WEBRTC_SVNREVISION << " " << BUILDINFO << std::endl; #ifdef WEBRTC_EXTERNAL_TRANSPORT version_stream << "External transport build" << std::endl; #endif int version_length = version_stream.tellp(); assert(version_length < 1024); memcpy(version, version_stream.str().c_str(), version_length); version[version_length] = '\0'; WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, ViEId(shared_data_.instance_id()), "GetVersion() => %s", version); return 0; } int ViEBaseImpl::LastError() { return shared_data_.LastErrorInternal(); } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT int original_channel, bool sender) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(original_channel)) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s - original_channel does not exist.", __FUNCTION__, shared_data_.instance_id()); shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->CreateChannel(&video_channel, original_channel, sender) == -1) { WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: Could not create channel", __FUNCTION__); video_channel = -1; shared_data_.SetLastError(kViEBaseChannelCreationFailed); return -1; } WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()), "%s: channel created: %d", __FUNCTION__, video_channel); return 0; } } // namespace webrtc <|endoftext|>
<commit_before>/* * Copyright (c) 2000 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) && !defined(macintosh) #ident "$Id: net_link.cc,v 1.8 2002/06/30 02:21:31 steve Exp $" #endif # include "config.h" # include <iostream> # include "netlist.h" # include <strstream> # include <string> # include <typeinfo> #ifdef HAVE_MALLOC_H # include <malloc.h> #endif void connect(Nexus*l, Link&r) { assert(l); assert(r.nexus_); if (l == r.nexus_) return; Nexus*tmp = r.nexus_; while (Link*cur = tmp->list_) { tmp->list_ = cur->next_; cur->nexus_ = 0; cur->next_ = 0; l->relink(cur); } l->driven_ = Nexus::NO_GUESS; assert(tmp->list_ == 0); delete tmp; } void connect(Link&l, Link&r) { assert(&l != &r); connect(l.nexus_, r); } Link::Link() : dir_(PASSIVE), drive0_(STRONG), drive1_(STRONG), init_(verinum::Vx), inst_(0), next_(0), nexus_(0) { (new Nexus()) -> relink(this); } Link::~Link() { assert(nexus_); Nexus*tmp = nexus_; nexus_->unlink(this); if (tmp->list_ == 0) delete tmp; } Nexus* Link::nexus() { return nexus_; } const Nexus* Link::nexus() const { return nexus_; } void Link::set_dir(DIR d) { dir_ = d; } Link::DIR Link::get_dir() const { return dir_; } void Link::drive0(Link::strength_t str) { drive0_ = str; } void Link::drive1(Link::strength_t str) { drive1_ = str; } Link::strength_t Link::drive0() const { return drive0_; } Link::strength_t Link::drive1() const { return drive1_; } void Link::set_init(verinum::V val) { init_ = val; } verinum::V Link::get_init() const { return init_; } void Link::cur_link(NetObj*&net, unsigned &pin) { net = node_; pin = pin_; } void Link::cur_link(const NetObj*&net, unsigned &pin) const { net = node_; pin = pin_; } void Link::unlink() { assert(nexus_); if (! is_linked()) return; nexus_->unlink(this); (new Nexus()) -> relink(this); } bool Link::is_equal(const Link&that) const { return (node_ == that.node_) && (pin_ == that.pin_); } bool Link::is_linked() const { if (next_) return true; if (nexus_->first_nlink() != this) return true; return false; } bool Link::is_linked(const Link&that) const { return nexus_ == that.nexus_; } Link* Link::next_nlink() { return next_; } const Link* Link::next_nlink() const { return next_; } const NetObj*Link::get_obj() const { return node_; } NetObj*Link::get_obj() { return node_; } unsigned Link::get_pin() const { return pin_; } void Link::set_name(const string&n, unsigned i) { name_ = n; inst_ = i; } const string& Link::get_name() const { return name_; } unsigned Link::get_inst() const { return inst_; } Nexus::Nexus() { name_ = 0; list_ = 0; driven_ = NO_GUESS; t_cookie_ = 0; } Nexus::~Nexus() { assert(list_ == 0); if (name_) delete[]name_; } verinum::V Nexus::get_init() const { assert(list_); for (Link*cur = list_ ; cur ; cur = cur->next_) { if (cur->get_dir() == Link::OUTPUT) return verinum::Vx; if ((cur->get_dir() == Link::PASSIVE) && (cur->get_init() != verinum::Vz)) return cur->get_init(); } return verinum::Vz; } void Nexus::unlink(Link*that) { if (name_) { delete[] name_; name_ = 0; } assert(that); if (list_ == that) { list_ = that->next_; that->next_ = 0; that->nexus_ = 0; return; } Link*cur = list_; while (cur->next_ != that) { assert(cur->next_); cur = cur->next_; } cur->next_ = that->next_; that->nexus_ = 0; that->next_ = 0; } void Nexus::relink(Link*that) { if (name_) { delete[] name_; name_ = 0; } assert(that->nexus_ == 0); assert(that->next_ == 0); that->next_ = list_; that->nexus_ = this; list_ = that; } Link* Nexus::first_nlink() { return list_; } const Link* Nexus::first_nlink() const { return list_; } void* Nexus::t_cookie() const { return t_cookie_; } void* Nexus::t_cookie(void*val)const { void*tmp = t_cookie_; t_cookie_ = val; return tmp; } const char* Nexus::name() const { if (name_) return name_; const NetNet*sig = 0; unsigned pin = 0; for (const Link*cur = first_nlink() ; cur ; cur = cur->next_nlink()) { const NetNet*cursig = dynamic_cast<const NetNet*>(cur->get_obj()); if (cursig == 0) continue; if (sig == 0) { sig = cursig; pin = cur->get_pin(); continue; } if ((cursig->pin_count() == 1) && (sig->pin_count() > 1)) continue; if ((cursig->pin_count() > 1) && (sig->pin_count() == 1)) { sig = cursig; pin = cur->get_pin(); continue; } if (cursig->local_flag() && !sig->local_flag()) continue; if (cursig->name() < sig->name()) continue; sig = cursig; pin = cur->get_pin(); } if (sig == 0) { const Link*lnk = first_nlink(); const NetObj*obj = lnk->get_obj(); pin = lnk->get_pin(); cerr << "internal error: No signal for nexus of " << obj->name() << " pin " << pin << "(" << lnk->get_name() << "<" << lnk->get_inst() << ">)" " type=" << typeid(*obj).name() << "?" << endl; } assert(sig); ostrstream tmp; tmp << sig->name(); if (sig->pin_count() > 1) tmp << "<" << pin << ">"; tmp << ends; name_ = new char[strlen(tmp.str()) + 1]; strcpy(name_, tmp.str()); return name_; } NexusSet::NexusSet() { items_ = 0; nitems_ = 0; } NexusSet::~NexusSet() { if (nitems_ > 0) { assert(items_ != 0); delete[] items_; } else { assert(items_ == 0); } } unsigned NexusSet::count() const { return nitems_; } void NexusSet::add(Nexus*that) { if (nitems_ == 0) { assert(items_ == 0); items_ = (Nexus**)malloc(sizeof(Nexus*)); items_[0] = that; nitems_ = 1; return; } unsigned ptr = bsearch_(that); if ((ptr < nitems_) && (items_[ptr] == that)) return; items_ = (Nexus**)realloc(items_, (nitems_+1) * sizeof(Nexus*)); for (unsigned idx = nitems_ ; idx > ptr ; idx -= 1) items_[idx] = items_[idx-1]; items_[ptr] = that; nitems_ += 1; } void NexusSet::add(const NexusSet&that) { for (unsigned idx = 0 ; idx < that.nitems_ ; idx += 1) add(that.items_[idx]); } Nexus* NexusSet::operator[] (unsigned idx) const { assert(idx < nitems_); return items_[idx]; } unsigned NexusSet::bsearch_(Nexus*that) const { for (unsigned idx = 0 ; idx < nitems_ ; idx += 1) { if (items_[idx] < that) continue; return idx; } return nitems_; } bool NexusSet::contains(const NexusSet&that) const { for (unsigned idx = 0 ; idx < that.nitems_ ; idx += 1) { unsigned where = bsearch_(that[idx]); if (where == nitems_) return false; if (items_[where] != that[idx]) return false; } return true; } /* * $Log: net_link.cc,v $ * Revision 1.8 2002/06/30 02:21:31 steve * Add structure for asynchronous logic synthesis. * * Revision 1.7 2002/06/24 01:49:39 steve * Make link_drive_constant cache its results in * the Nexus, to improve cprop performance. * * Revision 1.6 2002/04/21 04:59:08 steve * Add support for conbinational events by finding * the inputs to expressions and some statements. * Get case and assignment statements working. * * Revision 1.5 2001/07/25 03:10:49 steve * Create a config.h.in file to hold all the config * junk, and support gcc 3.0. (Stephan Boettcher) * * Revision 1.4 2000/10/06 23:46:50 steve * ivl_target updates, including more complete * handling of ivl_nexus_t objects. Much reduced * dependencies on pointers to netlist objects. * * Revision 1.3 2000/08/26 00:54:03 steve * Get at gate information for ivl_target interface. * * Revision 1.2 2000/07/14 06:12:57 steve * Move inital value handling from NetNet to Nexus * objects. This allows better propogation of inital * values. * * Clean up constant propagation a bit to account * for regs that are not really values. * * Revision 1.1 2000/06/25 19:59:42 steve * Redesign Links to include the Nexus class that * carries properties of the connected set of links. * */ <commit_msg> Clear drive cache on link or unlink.<commit_after>/* * Copyright (c) 2000 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) && !defined(macintosh) #ident "$Id: net_link.cc,v 1.9 2002/07/03 03:08:47 steve Exp $" #endif # include "config.h" # include <iostream> # include "netlist.h" # include <strstream> # include <string> # include <typeinfo> #ifdef HAVE_MALLOC_H # include <malloc.h> #endif void connect(Nexus*l, Link&r) { assert(l); assert(r.nexus_); if (l == r.nexus_) return; Nexus*tmp = r.nexus_; while (Link*cur = tmp->list_) { tmp->list_ = cur->next_; cur->nexus_ = 0; cur->next_ = 0; l->relink(cur); } l->driven_ = Nexus::NO_GUESS; assert(tmp->list_ == 0); delete tmp; } void connect(Link&l, Link&r) { assert(&l != &r); connect(l.nexus_, r); } Link::Link() : dir_(PASSIVE), drive0_(STRONG), drive1_(STRONG), init_(verinum::Vx), inst_(0), next_(0), nexus_(0) { (new Nexus()) -> relink(this); } Link::~Link() { assert(nexus_); Nexus*tmp = nexus_; nexus_->unlink(this); if (tmp->list_ == 0) delete tmp; } Nexus* Link::nexus() { return nexus_; } const Nexus* Link::nexus() const { return nexus_; } void Link::set_dir(DIR d) { dir_ = d; } Link::DIR Link::get_dir() const { return dir_; } void Link::drive0(Link::strength_t str) { drive0_ = str; } void Link::drive1(Link::strength_t str) { drive1_ = str; } Link::strength_t Link::drive0() const { return drive0_; } Link::strength_t Link::drive1() const { return drive1_; } void Link::set_init(verinum::V val) { init_ = val; } verinum::V Link::get_init() const { return init_; } void Link::cur_link(NetObj*&net, unsigned &pin) { net = node_; pin = pin_; } void Link::cur_link(const NetObj*&net, unsigned &pin) const { net = node_; pin = pin_; } void Link::unlink() { assert(nexus_); if (! is_linked()) return; nexus_->unlink(this); (new Nexus()) -> relink(this); } bool Link::is_equal(const Link&that) const { return (node_ == that.node_) && (pin_ == that.pin_); } bool Link::is_linked() const { if (next_) return true; if (nexus_->first_nlink() != this) return true; return false; } bool Link::is_linked(const Link&that) const { return nexus_ == that.nexus_; } Link* Link::next_nlink() { return next_; } const Link* Link::next_nlink() const { return next_; } const NetObj*Link::get_obj() const { return node_; } NetObj*Link::get_obj() { return node_; } unsigned Link::get_pin() const { return pin_; } void Link::set_name(const string&n, unsigned i) { name_ = n; inst_ = i; } const string& Link::get_name() const { return name_; } unsigned Link::get_inst() const { return inst_; } Nexus::Nexus() { name_ = 0; list_ = 0; driven_ = NO_GUESS; t_cookie_ = 0; } Nexus::~Nexus() { assert(list_ == 0); if (name_) delete[]name_; } verinum::V Nexus::get_init() const { assert(list_); for (Link*cur = list_ ; cur ; cur = cur->next_) { if (cur->get_dir() == Link::OUTPUT) return verinum::Vx; if ((cur->get_dir() == Link::PASSIVE) && (cur->get_init() != verinum::Vz)) return cur->get_init(); } return verinum::Vz; } void Nexus::unlink(Link*that) { if (name_) { delete[] name_; name_ = 0; } /* If the link I'm removing was a driver for this nexus, then cancel my guess of the driven value. */ if (that->get_dir() != Link::INPUT) driven_ = NO_GUESS; assert(that); if (list_ == that) { list_ = that->next_; that->next_ = 0; that->nexus_ = 0; return; } Link*cur = list_; while (cur->next_ != that) { assert(cur->next_); cur = cur->next_; } cur->next_ = that->next_; that->nexus_ = 0; that->next_ = 0; } void Nexus::relink(Link*that) { if (name_) { delete[] name_; name_ = 0; } /* If the link I'm adding is a driver for this nexus, then cancel my guess of the driven value. */ if (that->get_dir() != Link::INPUT) driven_ = NO_GUESS; assert(that->nexus_ == 0); assert(that->next_ == 0); that->next_ = list_; that->nexus_ = this; list_ = that; } Link* Nexus::first_nlink() { return list_; } const Link* Nexus::first_nlink() const { return list_; } void* Nexus::t_cookie() const { return t_cookie_; } void* Nexus::t_cookie(void*val)const { void*tmp = t_cookie_; t_cookie_ = val; return tmp; } const char* Nexus::name() const { if (name_) return name_; const NetNet*sig = 0; unsigned pin = 0; for (const Link*cur = first_nlink() ; cur ; cur = cur->next_nlink()) { const NetNet*cursig = dynamic_cast<const NetNet*>(cur->get_obj()); if (cursig == 0) continue; if (sig == 0) { sig = cursig; pin = cur->get_pin(); continue; } if ((cursig->pin_count() == 1) && (sig->pin_count() > 1)) continue; if ((cursig->pin_count() > 1) && (sig->pin_count() == 1)) { sig = cursig; pin = cur->get_pin(); continue; } if (cursig->local_flag() && !sig->local_flag()) continue; if (cursig->name() < sig->name()) continue; sig = cursig; pin = cur->get_pin(); } if (sig == 0) { const Link*lnk = first_nlink(); const NetObj*obj = lnk->get_obj(); pin = lnk->get_pin(); cerr << "internal error: No signal for nexus of " << obj->name() << " pin " << pin << "(" << lnk->get_name() << "<" << lnk->get_inst() << ">)" " type=" << typeid(*obj).name() << "?" << endl; } assert(sig); ostrstream tmp; tmp << sig->name(); if (sig->pin_count() > 1) tmp << "<" << pin << ">"; tmp << ends; name_ = new char[strlen(tmp.str()) + 1]; strcpy(name_, tmp.str()); return name_; } NexusSet::NexusSet() { items_ = 0; nitems_ = 0; } NexusSet::~NexusSet() { if (nitems_ > 0) { assert(items_ != 0); delete[] items_; } else { assert(items_ == 0); } } unsigned NexusSet::count() const { return nitems_; } void NexusSet::add(Nexus*that) { if (nitems_ == 0) { assert(items_ == 0); items_ = (Nexus**)malloc(sizeof(Nexus*)); items_[0] = that; nitems_ = 1; return; } unsigned ptr = bsearch_(that); if ((ptr < nitems_) && (items_[ptr] == that)) return; items_ = (Nexus**)realloc(items_, (nitems_+1) * sizeof(Nexus*)); for (unsigned idx = nitems_ ; idx > ptr ; idx -= 1) items_[idx] = items_[idx-1]; items_[ptr] = that; nitems_ += 1; } void NexusSet::add(const NexusSet&that) { for (unsigned idx = 0 ; idx < that.nitems_ ; idx += 1) add(that.items_[idx]); } Nexus* NexusSet::operator[] (unsigned idx) const { assert(idx < nitems_); return items_[idx]; } unsigned NexusSet::bsearch_(Nexus*that) const { for (unsigned idx = 0 ; idx < nitems_ ; idx += 1) { if (items_[idx] < that) continue; return idx; } return nitems_; } bool NexusSet::contains(const NexusSet&that) const { for (unsigned idx = 0 ; idx < that.nitems_ ; idx += 1) { unsigned where = bsearch_(that[idx]); if (where == nitems_) return false; if (items_[where] != that[idx]) return false; } return true; } /* * $Log: net_link.cc,v $ * Revision 1.9 2002/07/03 03:08:47 steve * Clear drive cache on link or unlink. * * Revision 1.8 2002/06/30 02:21:31 steve * Add structure for asynchronous logic synthesis. * * Revision 1.7 2002/06/24 01:49:39 steve * Make link_drive_constant cache its results in * the Nexus, to improve cprop performance. * * Revision 1.6 2002/04/21 04:59:08 steve * Add support for conbinational events by finding * the inputs to expressions and some statements. * Get case and assignment statements working. * * Revision 1.5 2001/07/25 03:10:49 steve * Create a config.h.in file to hold all the config * junk, and support gcc 3.0. (Stephan Boettcher) * * Revision 1.4 2000/10/06 23:46:50 steve * ivl_target updates, including more complete * handling of ivl_nexus_t objects. Much reduced * dependencies on pointers to netlist objects. * * Revision 1.3 2000/08/26 00:54:03 steve * Get at gate information for ivl_target interface. * * Revision 1.2 2000/07/14 06:12:57 steve * Move inital value handling from NetNet to Nexus * objects. This allows better propogation of inital * values. * * Clean up constant propagation a bit to account * for regs that are not really values. * * Revision 1.1 2000/06/25 19:59:42 steve * Redesign Links to include the Nexus class that * carries properties of the connected set of links. * */ <|endoftext|>
<commit_before>/*========================================================================= File: vtkReplayImageVideoSource.cxx Author: Chris Wedlake <cwedlake@robarts.ca> Language: C++ Description: ========================================================================= Copyright (c) Chris Wedlake, cwedlake@robarts.ca Use, modification and redistribution of the software, in source or binary forms, are permitted provided that the following terms and conditions are met: 1) Redistribution of the source code, in verbatim or modified form, must retain the above copyright notice, this license, the following disclaimer, and any notices that refer to this license and/or the following disclaimer. 2) Redistribution in binary form must include the above copyright notice, a copy of this license and the following disclaimer in the documentation or with other materials provided with the distribution. 3) Modified copies of the source code must be clearly marked as such, and must not be misrepresented as verbatim copies of the source code. THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT EXPRESSED OR IMPLIED WARRANTY INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE UNDER THE TERMS OF THIS LICENSE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BECOMING INACCURATE OR LOSS OF PROFIT OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. =========================================================================*/ #include "vtkReplayImageVideoSource.h" #include "vtkTimerLog.h" #include "vtkObjectFactory.h" #include "vtkCriticalSection.h" #include "vtkUnsignedCharArray.h" #include "vtkMutexLock.h" #include "vtkSmartPointer.h" #include "vtkJPEGReader.h" #include "vtkJPEGWriter.h" #include "vtkPNGReader.h" #include "vtkBMPReader.h" #include "vtkTIFFReader.h" #include "vtkImageData.h" #include "vtkPointData.h" #include <vtkstd/string> #include <string> #include <algorithm> // #include <windows.h> // #include <tchar.h> #include <stdio.h> //#include <strsafe.h> #include <vtkDirectory.h> #include <vtkSortFileNames.h> #include <vtkStringArray.h> //#pragma comment(lib, "User32.lib") vtkReplayImageVideoSource* vtkReplayImageVideoSource::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkReplayImageVideoSource"); if(ret) { return (vtkReplayImageVideoSource*)ret; } // If the factory was unable to create the object, then create it here. return new vtkReplayImageVideoSource; } //---------------------------------------------------------------------------- vtkReplayImageVideoSource::vtkReplayImageVideoSource() { this->Initialized = 0; this->pauseFeed = 0; this->currentLength = 0; this->vtkVideoSource::SetOutputFormat(VTK_RGB); this->vtkVideoSource::SetFrameBufferSize( 54 ); this->vtkVideoSource::SetFrameRate( 15.0f ); this->SetFrameSize(720,480,1); this->SetFrameSizeAutomatically = true; this->imageIndex=-1; } //---------------------------------------------------------------------------- vtkReplayImageVideoSource::~vtkReplayImageVideoSource() { this->vtkReplayImageVideoSource::ReleaseSystemResources(); for (unsigned int i = 0; i < this->loadedData.size(); i++) { this->loadedData[i]->Delete(); } this->loadedData.clear(); } //---------------------------------------------------------------------------- void vtkReplayImageVideoSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- void vtkReplayImageVideoSource::Initialize() { if (this->Initialized) { return; } // Initialization worked this->Initialized = 1; // Update frame buffer to reflect any changes this->UpdateFrameBuffer(); } //---------------------------------------------------------------------------- void vtkReplayImageVideoSource::ReleaseSystemResources() { this->Initialized = 0; } void vtkReplayImageVideoSource::InternalGrab() { if (this->loadedData.size() == 0) { return; } // get a thread lock on the frame buffer this->FrameBufferMutex->Lock(); if (this->AutoAdvance) { this->AdvanceFrameBuffer(1); if (this->FrameIndex + 1 < this->FrameBufferSize) { this->FrameIndex++; } } int index = this->FrameBufferIndex % this->FrameBufferSize; while (index < 0) { index += this->FrameBufferSize; } this->imageIndex = ++this->imageIndex % this->loadedData.size(); void *buffer = this->loadedData[this->imageIndex]->GetScalarPointer(); unsigned char *ptr = reinterpret_cast<vtkUnsignedCharArray *>(this->FrameBuffer[index])->GetPointer(0); //int ImageSize = (this->FrameBufferExtent[1]-this->FrameBufferExtent[0])*(this->FrameBufferExtent[3]-this->FrameBufferExtent[2]); memcpy(ptr, buffer, this->NumberOfScalarComponents*(this->FrameSize[0]-1)*(this->FrameSize[1]-1)); this->FrameBufferTimeStamps[index] = vtkTimerLog::GetUniversalTime(); if (this->FrameCount++ == 0) { this->StartTimeStamp = this->FrameBufferTimeStamps[index]; } this->Modified(); this->FrameBufferMutex->Unlock(); } //---------------------------------------------------------------------------- // platform-independent sleep function static inline void vtkSleep(double duration) { duration = duration; // avoid warnings // sleep according to OS preference #ifdef _WIN32 Sleep((int)(1000*duration)); #elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi) struct timespec sleep_time, dummy; sleep_time.tv_sec = (int)duration; sleep_time.tv_nsec = (int)(1000000000*(duration-sleep_time.tv_sec)); nanosleep(&sleep_time,&dummy); #endif } //---------------------------------------------------------------------------- // Sleep until the specified absolute time has arrived. // You must pass a handle to the current thread. // If '0' is returned, then the thread was aborted before or during the wait. static int vtkThreadSleep(vtkMultiThreader::ThreadInfo *data, double time) { // loop either until the time has arrived or until the thread is ended for (int i = 0;; i++) { double remaining = time - vtkTimerLog::GetUniversalTime(); // check to see if we have reached the specified time if (remaining <= 0) { if (i == 0) { vtkGenericWarningMacro("Dropped a video frame."); } return 1; } // check the ActiveFlag at least every 0.1 seconds if (remaining > 0.1) { remaining = 0.1; } // check to see if we are being told to quit data->ActiveFlagLock->Lock(); int activeFlag = *(data->ActiveFlag); data->ActiveFlagLock->Unlock(); if (activeFlag == 0) { break; } vtkSleep(remaining); } return 0; } //---------------------------------------------------------------------------- // this function runs in an alternate thread to asyncronously grab frames static void *vtkReplayImageVideoSourceRecordThread(vtkMultiThreader::ThreadInfo *data) { vtkReplayImageVideoSource *self = (vtkReplayImageVideoSource *)(data->UserData); double startTime = vtkTimerLog::GetUniversalTime(); double rate = self->GetFrameRate(); int frame = 0; do { self->InternalGrab(); frame++; } while (vtkThreadSleep(data, startTime + frame/rate)); return NULL; } //---------------------------------------------------------------------------- // Set the source to grab frames continuously. // You should override this as appropriate for your device. void vtkReplayImageVideoSource::Record() { // We don't actually record data. return; } //---------------------------------------------------------------------------- // this function runs in an alternate thread to 'play the tape' at the // specified frame rate. static void *vtkReplayImageVideoSourcePlayThread(vtkMultiThreader::ThreadInfo *data) { vtkVideoSource *self = (vtkVideoSource *)(data->UserData); double startTime = vtkTimerLog::GetUniversalTime(); double rate = self->GetFrameRate(); int frame = 0; do { self->Seek(1); frame++; } while (vtkThreadSleep(data, startTime + frame/rate)); return NULL; } //---------------------------------------------------------------------------- // Set the source to play back recorded frames. // You should override this as appropriate for your device. void vtkReplayImageVideoSource::Play() { if (this->Recording) { this->Stop(); } if (!this->Playing) { this->Initialize(); this->Playing = 1; this->Modified(); this->PlayerThreadId = this->PlayerThreader->SpawnThread((vtkThreadFunctionType)\ &vtkReplayImageVideoSourcePlayThread,this); } } //---------------------------------------------------------------------------- // Stop continuous grabbing or playback. You will have to override this // if your class overrides Play() and Record() void vtkReplayImageVideoSource::Stop() { if (this->Playing || this->Recording) { this->PlayerThreader->TerminateThread(this->PlayerThreadId); this->PlayerThreadId = -1; this->Playing = 0; this->Recording = 0; this->Modified(); } } void vtkReplayImageVideoSource::Pause() { this->pauseFeed = 1; } void vtkReplayImageVideoSource::UnPause() { this->pauseFeed = 0; } void vtkReplayImageVideoSource::LoadFile(char * filename) { std::string str(filename); std::string ext = ""; for(unsigned int i=0; i<str.length(); i++) { if(str[i] == '.') { for(unsigned int j = i; j<str.length(); j++) { ext += str[j]; } break; } } std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); vtkImageData * data = vtkImageData::New(); vtkSmartPointer<vtkImageReader2> reader; if (ext == ".jpg") { reader = vtkSmartPointer<vtkJPEGReader>::New(); } else if (ext == ".png") { reader = vtkSmartPointer<vtkPNGReader>::New(); } else if (ext == ".bmp") { reader = vtkSmartPointer<vtkBMPReader>::New(); } else if (ext == ".tiff") { reader = vtkSmartPointer<vtkTIFFReader>::New(); } else { return; } if (reader->CanReadFile(filename)) { reader->SetFileName(filename); reader->Update(); reader->Modified(); reader->GetOutput()->Update(); } else { cerr << "Unable To Read File:" << filename << endl; return; } int extents[6]; reader->GetOutput()->GetExtent(extents); if (extents[1]-extents[0]+1 != this->FrameSize[0] || extents[3]-extents[2]+1 != this->FrameSize[1] || extents[5]-extents[4]+1 != this->FrameSize[2] ) { if (this->SetFrameSizeAutomatically) { this->SetFrameSize(extents[1]-extents[0]+1, extents[3]-extents[2]+1,extents[5]-extents[4]+1); this->SetFrameSizeAutomatically = false; } else { vtkErrorMacro("Unable to open file as size doesn't match video source"); return; } } data->DeepCopy(reader->GetOutput()); this->loadedData.push_back(data); } int vtkReplayImageVideoSource::LoadFolder(char * folder, char * filetype) { char* fullPath = new char[1024]; vtkSmartPointer<vtkDirectory> dir = vtkSmartPointer<vtkDirectory>::New(); fullPath = strncpy( fullPath, folder,1024); fullPath = strncat( fullPath, "/",1024); int hFind = dir->Open(fullPath); if(hFind != 1){ return -1; } vtkSmartPointer<vtkSortFileNames> sort = vtkSmartPointer<vtkSortFileNames>::New(); sort->SetInputFileNames(dir->GetFiles()); sort->SkipDirectoriesOn(); sort->NumericSortOn(); for(int i = 0; i < sort->GetFileNames()->GetNumberOfValues(); i++){ char *file = new char[1024]; file = strncpy(file, fullPath,1024); file = strncat(file, sort->GetFileNames()->GetValue(i),1024); //std::cout << file << std::endl; this->LoadFile(file); } return 0; } void vtkReplayImageVideoSource::Clear() { } void vtkReplayImageVideoSource::SetClipRegion(int x0, int x1, int y0, int y1, int z0, int z1) { return; } <commit_msg>- fixes for tiff reading. - changing of defaults. - allowed clip region or things get odd.<commit_after>/*========================================================================= File: vtkReplayImageVideoSource.cxx Author: Chris Wedlake <cwedlake@robarts.ca> Language: C++ Description: ========================================================================= Copyright (c) Chris Wedlake, cwedlake@robarts.ca Use, modification and redistribution of the software, in source or binary forms, are permitted provided that the following terms and conditions are met: 1) Redistribution of the source code, in verbatim or modified form, must retain the above copyright notice, this license, the following disclaimer, and any notices that refer to this license and/or the following disclaimer. 2) Redistribution in binary form must include the above copyright notice, a copy of this license and the following disclaimer in the documentation or with other materials provided with the distribution. 3) Modified copies of the source code must be clearly marked as such, and must not be misrepresented as verbatim copies of the source code. THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT EXPRESSED OR IMPLIED WARRANTY INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE UNDER THE TERMS OF THIS LICENSE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BECOMING INACCURATE OR LOSS OF PROFIT OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. =========================================================================*/ #include "vtkReplayImageVideoSource.h" #include "vtkTimerLog.h" #include "vtkObjectFactory.h" #include "vtkCriticalSection.h" #include "vtkUnsignedCharArray.h" #include "vtkMutexLock.h" #include "vtkSmartPointer.h" #include "vtkJPEGReader.h" #include "vtkJPEGWriter.h" #include "vtkPNGReader.h" #include "vtkBMPReader.h" #include "vtkTIFFReader.h" #include "vtkImageData.h" #include "vtkPointData.h" #include "vtkImageFlip.h" #include <vtkstd/string> #include <string> #include <algorithm> // #include <windows.h> // #include <tchar.h> #include <stdio.h> //#include <strsafe.h> #include <vtkDirectory.h> #include <vtkSortFileNames.h> #include <vtkStringArray.h> //#pragma comment(lib, "User32.lib") vtkReplayImageVideoSource* vtkReplayImageVideoSource::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkReplayImageVideoSource"); if(ret) { return (vtkReplayImageVideoSource*)ret; } // If the factory was unable to create the object, then create it here. return new vtkReplayImageVideoSource; } //---------------------------------------------------------------------------- vtkReplayImageVideoSource::vtkReplayImageVideoSource() { this->Initialized = 0; this->pauseFeed = 0; this->currentLength = 0; this->vtkVideoSource::SetOutputFormat(VTK_RGB); this->vtkVideoSource::SetFrameBufferSize( 54 ); this->vtkVideoSource::SetFrameRate( 15.0f ); this->SetFrameSize(1680,1048,1); this->SetFrameSizeAutomatically = true; this->imageIndex=-1; } //---------------------------------------------------------------------------- vtkReplayImageVideoSource::~vtkReplayImageVideoSource() { this->vtkReplayImageVideoSource::ReleaseSystemResources(); for (unsigned int i = 0; i < this->loadedData.size(); i++) { this->loadedData[i]->Delete(); } this->loadedData.clear(); } //---------------------------------------------------------------------------- void vtkReplayImageVideoSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- void vtkReplayImageVideoSource::Initialize() { if (this->Initialized) { return; } // Initialization worked this->Initialized = 1; // Update frame buffer to reflect any changes this->UpdateFrameBuffer(); } //---------------------------------------------------------------------------- void vtkReplayImageVideoSource::ReleaseSystemResources() { this->Initialized = 0; } void vtkReplayImageVideoSource::InternalGrab() { if (this->loadedData.size() == 0) { return; } // get a thread lock on the frame buffer this->FrameBufferMutex->Lock(); if (this->AutoAdvance) { this->AdvanceFrameBuffer(1); if (this->FrameIndex + 1 < this->FrameBufferSize) { this->FrameIndex++; } } int index = this->FrameBufferIndex % this->FrameBufferSize; while (index < 0) { index += this->FrameBufferSize; } this->imageIndex = ++this->imageIndex % this->loadedData.size(); void *buffer = this->loadedData[this->imageIndex]->GetScalarPointer(); unsigned char *ptr = reinterpret_cast<vtkUnsignedCharArray *>(this->FrameBuffer[index])->GetPointer(0); //int ImageSize = (this->FrameBufferExtent[1]-this->FrameBufferExtent[0])*(this->FrameBufferExtent[3]-this->FrameBufferExtent[2]); memcpy(ptr, buffer, this->NumberOfScalarComponents*(this->FrameSize[0]-1)*(this->FrameSize[1]-1)); this->FrameBufferTimeStamps[index] = vtkTimerLog::GetUniversalTime(); if (this->FrameCount++ == 0) { this->StartTimeStamp = this->FrameBufferTimeStamps[index]; } this->Modified(); this->FrameBufferMutex->Unlock(); } //---------------------------------------------------------------------------- // platform-independent sleep function static inline void vtkSleep(double duration) { duration = duration; // avoid warnings // sleep according to OS preference #ifdef _WIN32 Sleep((int)(1000*duration)); #elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi) struct timespec sleep_time, dummy; sleep_time.tv_sec = (int)duration; sleep_time.tv_nsec = (int)(1000000000*(duration-sleep_time.tv_sec)); nanosleep(&sleep_time,&dummy); #endif } //---------------------------------------------------------------------------- // Sleep until the specified absolute time has arrived. // You must pass a handle to the current thread. // If '0' is returned, then the thread was aborted before or during the wait. static int vtkThreadSleep(vtkMultiThreader::ThreadInfo *data, double time) { // loop either until the time has arrived or until the thread is ended for (int i = 0;; i++) { double remaining = time - vtkTimerLog::GetUniversalTime(); // check to see if we have reached the specified time if (remaining <= 0) { if (i == 0) { vtkGenericWarningMacro("Dropped a video frame."); } return 1; } // check the ActiveFlag at least every 0.1 seconds if (remaining > 0.1) { remaining = 0.1; } // check to see if we are being told to quit data->ActiveFlagLock->Lock(); int activeFlag = *(data->ActiveFlag); data->ActiveFlagLock->Unlock(); if (activeFlag == 0) { break; } vtkSleep(remaining); } return 0; } //---------------------------------------------------------------------------- // this function runs in an alternate thread to asyncronously grab frames static void *vtkReplayImageVideoSourceRecordThread(vtkMultiThreader::ThreadInfo *data) { vtkReplayImageVideoSource *self = (vtkReplayImageVideoSource *)(data->UserData); double startTime = vtkTimerLog::GetUniversalTime(); double rate = self->GetFrameRate(); int frame = 0; do { self->InternalGrab(); frame++; } while (vtkThreadSleep(data, startTime + frame/rate)); return NULL; } //---------------------------------------------------------------------------- // Set the source to grab frames continuously. // You should override this as appropriate for your device. void vtkReplayImageVideoSource::Record() { // We don't actually record data. return; } //---------------------------------------------------------------------------- // this function runs in an alternate thread to 'play the tape' at the // specified frame rate. static void *vtkReplayImageVideoSourcePlayThread(vtkMultiThreader::ThreadInfo *data) { vtkVideoSource *self = (vtkVideoSource *)(data->UserData); double startTime = vtkTimerLog::GetUniversalTime(); double rate = self->GetFrameRate(); int frame = 0; do { self->Seek(1); frame++; } while (vtkThreadSleep(data, startTime + frame/rate)); return NULL; } //---------------------------------------------------------------------------- // Set the source to play back recorded frames. // You should override this as appropriate for your device. void vtkReplayImageVideoSource::Play() { if (this->Recording) { this->Stop(); } if (!this->Playing) { this->Initialize(); this->Playing = 1; this->Modified(); this->PlayerThreadId = this->PlayerThreader->SpawnThread((vtkThreadFunctionType)\ &vtkReplayImageVideoSourcePlayThread,this); } } //---------------------------------------------------------------------------- // Stop continuous grabbing or playback. You will have to override this // if your class overrides Play() and Record() void vtkReplayImageVideoSource::Stop() { if (this->Playing || this->Recording) { this->PlayerThreader->TerminateThread(this->PlayerThreadId); this->PlayerThreadId = -1; this->Playing = 0; this->Recording = 0; this->Modified(); } } void vtkReplayImageVideoSource::Pause() { this->pauseFeed = 1; } void vtkReplayImageVideoSource::UnPause() { this->pauseFeed = 0; } void vtkReplayImageVideoSource::LoadFile(char * filename) { bool applyFlip = false; std::string str(filename); std::string ext = ""; for(unsigned int i=0; i<str.length(); i++) { if(str[i] == '.') { for(unsigned int j = i; j<str.length(); j++) { ext += str[j]; } break; } } std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); vtkImageData * data = vtkImageData::New(); vtkSmartPointer<vtkImageReader2> reader; if (ext == ".jpg") { reader = vtkSmartPointer<vtkJPEGReader>::New(); } else if (ext == ".png") { reader = vtkSmartPointer<vtkPNGReader>::New(); } else if (ext == ".bmp") { reader = vtkSmartPointer<vtkBMPReader>::New(); } else if (ext == ".tif") { reader = vtkSmartPointer<vtkTIFFReader>::New(); applyFlip = true; } else { return; } if (reader->CanReadFile(filename)) { reader->SetFileName(filename); reader->Update(); reader->Modified(); reader->GetOutput()->Update(); } else { cerr << "Unable To Read File:" << filename << endl; return; } int extents[6]; reader->GetOutput()->GetExtent(extents); if (extents[1]-extents[0]+1 != this->FrameSize[0] || extents[3]-extents[2]+1 != this->FrameSize[1] || extents[5]-extents[4]+1 != this->FrameSize[2] ) { if (this->SetFrameSizeAutomatically) { this->SetFrameSize(extents[1]-extents[0]+1, extents[3]-extents[2]+1,extents[5]-extents[4]+1); this->SetFrameSizeAutomatically = false; } else { vtkErrorMacro("Unable to open file as size doesn't match video source"); return; } } if (applyFlip == true) { vtkSmartPointer<vtkImageFlip> flip = vtkSmartPointer<vtkImageFlip>::New(); flip->SetInput(reader->GetOutput()); flip->SetFilteredAxis(1); flip->Modified(); flip->Update(); data->DeepCopy(flip->GetOutput()); } else { data->DeepCopy(reader->GetOutput()); } this->loadedData.push_back(data); } int vtkReplayImageVideoSource::LoadFolder(char * folder, char * filetype) { char* fullPath = new char[1024]; vtkSmartPointer<vtkDirectory> dir = vtkSmartPointer<vtkDirectory>::New(); fullPath = strncpy( fullPath, folder,1024); fullPath = strncat( fullPath, "/",1024); int hFind = dir->Open(fullPath); if(hFind != 1){ return -1; } vtkSmartPointer<vtkSortFileNames> sort = vtkSmartPointer<vtkSortFileNames>::New(); sort->SetInputFileNames(dir->GetFiles()); sort->SkipDirectoriesOn(); sort->NumericSortOn(); for(int i = 0; i < sort->GetFileNames()->GetNumberOfValues(); i++){ char *file = new char[1024]; file = strncpy(file, fullPath,1024); file = strncat(file, sort->GetFileNames()->GetValue(i),1024); //std::cout << file << std::endl; this->LoadFile(file); } return 0; } void vtkReplayImageVideoSource::Clear() { } void vtkReplayImageVideoSource::SetClipRegion(int x0, int x1, int y0, int y1, int z0, int z1) { vtkVideoSource::SetClipRegion(x0,x1,y0,y1,z0,z1); //return; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "text.h" //Dring #include <media_const.h> #include "dbus/callmanager.h" #include "dbus/configurationmanager.h" //Ring #include <call.h> #include <callmodel.h> #include <account.h> #include <person.h> #include <contactmethod.h> #include <mime.h> #include <media/textrecording.h> #include <media/recordingmodel.h> #include <phonedirectorymodel.h> #include <private/call_p.h> #include <private/vcardutils.h> #include <private/textrecording_p.h> #include <private/imconversationmanagerprivate.h> /* * Instant message have 3 major modes, "past", "in call" and "offline" * * Offline messages are currently implemented over the DHT and may eventually * be implemented over account registration (publish--subscribe) * * In call messages are the fastest as they have a communication channels of their * own. * * Past messages are local copy of past communication stored somewhere. * * All 3 sources have to be combined dynamically into a single stream per person. * * So chunks can come from all 3 sources for the same stream, including part that * are shared in a conference with multiple peers. */ class MediaTextPrivate { public: MediaTextPrivate(Media::Text* parent); //Attributes Media::TextRecording* m_pRecording; bool m_HasChecked; private: Media::Text* q_ptr; }; class ProfileChunk { public: //Helper static Person* addChunk( const QMap<QString,QString>& args, const QString& payload); private: //Attributes QHash<int, QString> m_hParts { }; int m_PartsCount { 0 }; static QHash<QString, ProfileChunk*> m_hRequest; }; QHash<QString, ProfileChunk*> ProfileChunk::m_hRequest; IMConversationManagerPrivate::IMConversationManagerPrivate(QObject* parent) : QObject(parent) { CallManagerInterface& callManager = DBus::CallManager::instance(); ConfigurationManagerInterface& configurationManager = DBus::ConfigurationManager::instance(); connect(&configurationManager, &ConfigurationManagerInterface::incomingAccountMessage, this, &IMConversationManagerPrivate::newAccountMessage); connect(&callManager , &CallManagerInterface::incomingMessage , this, &IMConversationManagerPrivate::newMessage ); } IMConversationManagerPrivate* IMConversationManagerPrivate::instance() { static IMConversationManagerPrivate* ins = new IMConversationManagerPrivate(nullptr); return ins; } Person* ProfileChunk::addChunk(const QMap<QString, QString>& args, const QString& payload) { const int total = args[ "of" ].toInt(); const int part = args[ "part" ].toInt(); const QString id = args[ "id" ]; auto c = m_hRequest[id]; if (!c) { c = new ProfileChunk(); c->m_PartsCount = total; m_hRequest[id] = c; } if (part < 1 and part > total) return nullptr; c->m_hParts[part] = payload; if (c->m_hParts.size() != c->m_PartsCount) return nullptr; QByteArray cv; for (int i=0; i < c->m_PartsCount; ++i) { cv += c->m_hParts[i+1]; } m_hRequest[id] = nullptr; delete c; return new Person(cv); } ///Called when a new message is incoming void IMConversationManagerPrivate::newMessage(const QString& callId, const QString& from, const QMap<QString,QString>& message) { Q_UNUSED(from) Call* call = CallModel::instance()->getCall(callId); Q_ASSERT(call); qDebug() << "Creating messaging model for call" << callId; Media::Text* media = call->firstMedia<Media::Text>(Media::Media::Direction::IN); if (!media) { media = call->d_ptr->mediaFactory<Media::Text>(Media::Media::Direction::IN); } static const int profileSize = QString(RingMimes::PROFILE_VCF).size(); //Intercept some messages early, those are intended for internal Ring usage QMapIterator<QString, QString> iter(message); while (iter.hasNext()) { iter.next(); if (iter.key().left(profileSize) == RingMimes::PROFILE_VCF) { //For now only add the profile for the CM without person. //Eventually this should be upgraded to save the vCards in the folder and //update them. if (!call->peerContactMethod()->contact()) { const auto& args = VCardUtils::parseMimeAttributes(iter.key()); if (auto person = ProfileChunk::addChunk(args, iter.value())) call->peerContactMethod()->setPerson(person); } return; } } media->recording()->setCall(call); media->recording()->d_ptr->insertNewMessage(message,call->peerContactMethod(),Media::Media::Direction::IN); emit media->messageReceived(message); } void IMConversationManagerPrivate::newAccountMessage(const QString& accountId, const QString& from, const QString& message) { qDebug() << "GOT MESSAGE" << accountId << from << message; } MediaTextPrivate::MediaTextPrivate(Media::Text* parent) : q_ptr(parent),m_pRecording(nullptr),m_HasChecked(false) { } Media::Text::Text(Call* parent, const Media::Direction direction) : Media::Media(parent, direction), d_ptr(new MediaTextPrivate(this)) { Q_ASSERT(parent); } Media::Media::Type Media::Text::type() { return Media::Media::Type::TEXT; } Media::Text::~Text() { delete d_ptr; } Media::TextRecording* Media::Text::recording() const { const bool wasChecked = d_ptr->m_HasChecked; d_ptr->m_HasChecked = true; if ((!wasChecked) && !d_ptr->m_pRecording) { Text* other = call()->firstMedia<Text>(direction() == Media::Direction::OUT ? Media::Direction::IN : Media::Direction::OUT ); if (other && other->recording()) d_ptr->m_pRecording = other->recording(); } if ((!wasChecked) && !d_ptr->m_pRecording) { d_ptr->m_pRecording = RecordingModel::instance()->createTextRecording(call()->peerContactMethod()); } return d_ptr->m_pRecording; } /** * Send a message to the peer. * * @param message A messages encoded in various alternate payloads * * The send a single messages. Just as e-mails, the message can be * encoded differently. The peer client will interpret the richest * payload it support and then fallback to lesser ones. * * Suggested payloads include: * * "text/plain" : The most common plain UTF-8 text * "text/enriched" : (RTF) The rich text format used by older applications (like WordPad and OS X TextEdit) * "text/html" : The format used by web browsers */ void Media::Text::send(const QMap<QString,QString>& message, const bool isMixed) { CallManagerInterface& callManager = DBus::CallManager::instance(); Q_NOREPLY callManager.sendTextMessage(call()->dringId(), message, isMixed); //Make sure the recording exist recording(); d_ptr->m_pRecording->setCall(call()); d_ptr->m_pRecording->d_ptr->insertNewMessage(message,call()->account()->contactMethod(),Media::Direction::OUT); emit messageSent(message); } #include <text.moc> <commit_msg>profiles: interpret profile byte array as vcard<commit_after>/**************************************************************************** * Copyright (C) 2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "text.h" //Dring #include <media_const.h> #include "dbus/callmanager.h" #include "dbus/configurationmanager.h" //Ring #include <call.h> #include <callmodel.h> #include <account.h> #include <person.h> #include <contactmethod.h> #include <mime.h> #include <media/textrecording.h> #include <media/recordingmodel.h> #include <phonedirectorymodel.h> #include <private/call_p.h> #include <private/vcardutils.h> #include <private/textrecording_p.h> #include <private/imconversationmanagerprivate.h> /* * Instant message have 3 major modes, "past", "in call" and "offline" * * Offline messages are currently implemented over the DHT and may eventually * be implemented over account registration (publish--subscribe) * * In call messages are the fastest as they have a communication channels of their * own. * * Past messages are local copy of past communication stored somewhere. * * All 3 sources have to be combined dynamically into a single stream per person. * * So chunks can come from all 3 sources for the same stream, including part that * are shared in a conference with multiple peers. */ class MediaTextPrivate { public: MediaTextPrivate(Media::Text* parent); //Attributes Media::TextRecording* m_pRecording; bool m_HasChecked; private: Media::Text* q_ptr; }; class ProfileChunk { public: //Helper static Person* addChunk( const QMap<QString,QString>& args, const QString& payload); private: //Attributes QHash<int, QString> m_hParts { }; int m_PartsCount { 0 }; static QHash<QString, ProfileChunk*> m_hRequest; }; QHash<QString, ProfileChunk*> ProfileChunk::m_hRequest; IMConversationManagerPrivate::IMConversationManagerPrivate(QObject* parent) : QObject(parent) { CallManagerInterface& callManager = DBus::CallManager::instance(); ConfigurationManagerInterface& configurationManager = DBus::ConfigurationManager::instance(); connect(&configurationManager, &ConfigurationManagerInterface::incomingAccountMessage, this, &IMConversationManagerPrivate::newAccountMessage); connect(&callManager , &CallManagerInterface::incomingMessage , this, &IMConversationManagerPrivate::newMessage ); } IMConversationManagerPrivate* IMConversationManagerPrivate::instance() { static IMConversationManagerPrivate* ins = new IMConversationManagerPrivate(nullptr); return ins; } Person* ProfileChunk::addChunk(const QMap<QString, QString>& args, const QString& payload) { const int total = args[ "of" ].toInt(); const int part = args[ "part" ].toInt(); const QString id = args[ "id" ]; auto c = m_hRequest[id]; if (!c) { c = new ProfileChunk(); c->m_PartsCount = total; m_hRequest[id] = c; } if (part < 1 and part > total) return nullptr; c->m_hParts[part] = payload; if (c->m_hParts.size() != c->m_PartsCount) return nullptr; QByteArray cv; for (int i=0; i < c->m_PartsCount; ++i) { cv += c->m_hParts[i+1]; } m_hRequest[id] = nullptr; delete c; return new Person(cv, Person::Encoding::vCard); } ///Called when a new message is incoming void IMConversationManagerPrivate::newMessage(const QString& callId, const QString& from, const QMap<QString,QString>& message) { Q_UNUSED(from) Call* call = CallModel::instance()->getCall(callId); Q_ASSERT(call); qDebug() << "Creating messaging model for call" << callId; Media::Text* media = call->firstMedia<Media::Text>(Media::Media::Direction::IN); if (!media) { media = call->d_ptr->mediaFactory<Media::Text>(Media::Media::Direction::IN); } static const int profileSize = QString(RingMimes::PROFILE_VCF).size(); //Intercept some messages early, those are intended for internal Ring usage QMapIterator<QString, QString> iter(message); while (iter.hasNext()) { iter.next(); if (iter.key().left(profileSize) == RingMimes::PROFILE_VCF) { //For now only add the profile for the CM without person. //Eventually this should be upgraded to save the vCards in the folder and //update them. if (!call->peerContactMethod()->contact()) { const auto& args = VCardUtils::parseMimeAttributes(iter.key()); if (auto person = ProfileChunk::addChunk(args, iter.value())) call->peerContactMethod()->setPerson(person); } return; } } media->recording()->setCall(call); media->recording()->d_ptr->insertNewMessage(message,call->peerContactMethod(),Media::Media::Direction::IN); emit media->messageReceived(message); } void IMConversationManagerPrivate::newAccountMessage(const QString& accountId, const QString& from, const QString& message) { qDebug() << "GOT MESSAGE" << accountId << from << message; } MediaTextPrivate::MediaTextPrivate(Media::Text* parent) : q_ptr(parent),m_pRecording(nullptr),m_HasChecked(false) { } Media::Text::Text(Call* parent, const Media::Direction direction) : Media::Media(parent, direction), d_ptr(new MediaTextPrivate(this)) { Q_ASSERT(parent); } Media::Media::Type Media::Text::type() { return Media::Media::Type::TEXT; } Media::Text::~Text() { delete d_ptr; } Media::TextRecording* Media::Text::recording() const { const bool wasChecked = d_ptr->m_HasChecked; d_ptr->m_HasChecked = true; if ((!wasChecked) && !d_ptr->m_pRecording) { Text* other = call()->firstMedia<Text>(direction() == Media::Direction::OUT ? Media::Direction::IN : Media::Direction::OUT ); if (other && other->recording()) d_ptr->m_pRecording = other->recording(); } if ((!wasChecked) && !d_ptr->m_pRecording) { d_ptr->m_pRecording = RecordingModel::instance()->createTextRecording(call()->peerContactMethod()); } return d_ptr->m_pRecording; } /** * Send a message to the peer. * * @param message A messages encoded in various alternate payloads * * The send a single messages. Just as e-mails, the message can be * encoded differently. The peer client will interpret the richest * payload it support and then fallback to lesser ones. * * Suggested payloads include: * * "text/plain" : The most common plain UTF-8 text * "text/enriched" : (RTF) The rich text format used by older applications (like WordPad and OS X TextEdit) * "text/html" : The format used by web browsers */ void Media::Text::send(const QMap<QString,QString>& message, const bool isMixed) { CallManagerInterface& callManager = DBus::CallManager::instance(); Q_NOREPLY callManager.sendTextMessage(call()->dringId(), message, isMixed); //Make sure the recording exist recording(); d_ptr->m_pRecording->setCall(call()); d_ptr->m_pRecording->d_ptr->insertNewMessage(message,call()->account()->contactMethod(),Media::Direction::OUT); emit messageSent(message); } #include <text.moc> <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ron Dreslinski * Steve Reinhardt * Ali Saidi */ /** * @file * Declaration of a request, the overall memory request consisting of the parts of the request that are persistent throughout the transaction. */ #ifndef __MEM_REQUEST_HH__ #define __MEM_REQUEST_HH__ #include <cassert> #include "base/fast_alloc.hh" #include "base/flags.hh" #include "base/misc.hh" #include "sim/host.hh" #include "sim/core.hh" class Request; typedef Request* RequestPtr; class Request : public FastAlloc { friend class Packet; public: typedef uint32_t FlagsType; typedef ::Flags<FlagsType> Flags; /** ASI information for this request if it exists. */ static const FlagsType ASI_BITS = 0x000000FF; /** The request is a Load locked/store conditional. */ static const FlagsType LLSC = 0x00000100; /** The virtual address is also the physical address. */ static const FlagsType PHYSICAL = 0x00000200; /** The request is an ALPHA VPTE pal access (hw_ld). */ static const FlagsType VPTE = 0x00000400; /** Use the alternate mode bits in ALPHA. */ static const FlagsType ALTMODE = 0x00000800; /** The request is to an uncacheable address. */ static const FlagsType UNCACHEABLE = 0x00001000; /** The request should not cause a page fault. */ static const FlagsType NO_FAULT = 0x00002000; /** The request should not cause a memory access. */ static const FlagsType NO_ACCESS = 0x00004000; /** The request should be prefetched into the exclusive state. */ static const FlagsType PF_EXCLUSIVE = 0x00010000; /** The request should be marked as LRU. */ static const FlagsType EVICT_NEXT = 0x00020000; /** The request should ignore unaligned access faults */ static const FlagsType NO_ALIGN_FAULT = 0x00040000; /** The request was an instruction read. */ static const FlagsType INST_READ = 0x00080000; /** This request is for a memory swap. */ static const FlagsType MEM_SWAP = 0x00100000; static const FlagsType MEM_SWAP_COND = 0x00200000; /** The request should ignore unaligned access faults */ static const FlagsType NO_HALF_WORD_ALIGN_FAULT = 0x00400000; /** This request is to a memory mapped register. */ static const FlagsType MMAPED_IPR = 0x00800000; private: static const FlagsType PUBLIC_FLAGS = 0x00FF3FFF; static const FlagsType PRIVATE_FLAGS = 0xFF000000; /** Whether or not the size is valid. */ static const FlagsType VALID_SIZE = 0x01000000; /** Whether or not paddr is valid (has been written yet). */ static const FlagsType VALID_PADDR = 0x02000000; /** Whether or not the vaddr & asid are valid. */ static const FlagsType VALID_VADDR = 0x04000000; /** Whether or not the pc is valid. */ static const FlagsType VALID_PC = 0x10000000; /** Whether or not the context ID is valid. */ static const FlagsType VALID_CONTEXT_ID = 0x20000000; static const FlagsType VALID_THREAD_ID = 0x40000000; /** Whether or not the sc result is valid. */ static const FlagsType VALID_EXTRA_DATA = 0x80000000; private: /** * The physical address of the request. Valid only if validPaddr * is set. */ Addr paddr; /** * The size of the request. This field must be set when vaddr or * paddr is written via setVirt() or setPhys(), so it is always * valid as long as one of the address fields is valid. */ int size; /** Flag structure for the request. */ Flags flags; /** * The time this request was started. Used to calculate * latencies. This field is set to curTick any time paddr or vaddr * is written. */ Tick time; /** The address space ID. */ int asid; /** The virtual address of the request. */ Addr vaddr; /** * Extra data for the request, such as the return value of * store conditional or the compare value for a CAS. */ uint64_t extraData; /** The context ID (for statistics, typically). */ int _contextId; /** The thread ID (id within this CPU) */ int _threadId; /** program counter of initiating access; for tracing/debugging */ Addr pc; public: /** Minimal constructor. No fields are initialized. */ Request() {} /** * Constructor for physical (e.g. device) requests. Initializes * just physical address, size, flags, and timestamp (to curTick). * These fields are adequate to perform a request. */ Request(Addr paddr, int size, Flags flags) { setPhys(paddr, size, flags); } Request(int asid, Addr vaddr, int size, Flags flags, Addr pc, int cid, int tid) { setThreadContext(cid, tid); setVirt(asid, vaddr, size, flags, pc); } ~Request() {} // for FastAlloc /** * Set up CPU and thread numbers. */ void setThreadContext(int context_id, int thread_id) { _contextId = context_id; _threadId = thread_id; flags.set(VALID_CONTEXT_ID|VALID_THREAD_ID); } /** * Set up a physical (e.g. device) request in a previously * allocated Request object. */ void setPhys(Addr _paddr, int _size, Flags _flags) { assert(_size >= 0); paddr = _paddr; size = _size; time = curTick; flags.set(VALID_PADDR|VALID_SIZE); flags.clear(VALID_VADDR|VALID_PC|VALID_EXTRA_DATA|MMAPED_IPR); flags.update(_flags, PUBLIC_FLAGS); } /** * Set up a virtual (e.g., CPU) request in a previously * allocated Request object. */ void setVirt(int _asid, Addr _vaddr, int _size, Flags _flags, Addr _pc) { assert(_size >= 0); asid = _asid; vaddr = _vaddr; size = _size; pc = _pc; time = curTick; flags.set(VALID_VADDR|VALID_SIZE|VALID_PC); flags.clear(VALID_PADDR|VALID_EXTRA_DATA|MMAPED_IPR); flags.update(_flags, PUBLIC_FLAGS); } /** * Set just the physical address. This should only be used to * record the result of a translation, and thus the vaddr must be * valid before this method is called. Otherwise, use setPhys() * to guarantee that the size and flags are also set. */ void setPaddr(Addr _paddr) { assert(flags.isSet(VALID_VADDR)); paddr = _paddr; flags.set(VALID_PADDR); } /** * Generate two requests as if this request had been split into two * pieces. The original request can't have been translated already. */ void splitOnVaddr(Addr split_addr, RequestPtr &req1, RequestPtr &req2) { assert(flags.isSet(VALID_VADDR)); assert(flags.noneSet(VALID_PADDR)); assert(split_addr > vaddr && split_addr < vaddr + size); req1 = new Request; *req1 = *this; req2 = new Request; *req2 = *this; req1->size = split_addr - vaddr; req2->vaddr = split_addr; req2->size = size - req1->size; } /** * Accessor for paddr. */ Addr getPaddr() { assert(flags.isSet(VALID_PADDR)); return paddr; } /** * Accessor for size. */ int getSize() { assert(flags.isSet(VALID_SIZE)); return size; } /** Accessor for time. */ Tick getTime() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); return time; } void setTime(Tick when) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); time = when; } /** Accessor for flags. */ Flags getFlags() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); return flags & PUBLIC_FLAGS; } Flags anyFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); return flags.isSet(_flags); } Flags allFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); return flags.allSet(_flags); } /** Accessor for flags. */ void setFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); flags.set(_flags); } void clearFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); flags.clear(_flags); } void clearFlags() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); flags.clear(PUBLIC_FLAGS); } /** Accessor function for vaddr.*/ Addr getVaddr() { assert(flags.isSet(VALID_VADDR)); return vaddr; } /** Accessor function for asid.*/ int getAsid() { assert(flags.isSet(VALID_VADDR)); return asid; } /** Accessor function for asi.*/ uint8_t getAsi() { assert(flags.isSet(VALID_VADDR)); return flags & ASI_BITS; } /** Accessor function for asi.*/ void setAsi(uint8_t a) { assert(flags.isSet(VALID_VADDR)); flags.update(a, ASI_BITS); } /** Accessor function for asi.*/ bool isMmapedIpr() { assert(flags.isSet(VALID_PADDR)); return flags.isSet(MMAPED_IPR); } /** Accessor function for asi.*/ void setMmapedIpr(bool r) { assert(VALID_VADDR); flags.set(MMAPED_IPR); } /** Accessor function to check if sc result is valid. */ bool extraDataValid() { return flags.isSet(VALID_EXTRA_DATA); } /** Accessor function for store conditional return value.*/ uint64_t getExtraData() const { assert(flags.isSet(VALID_EXTRA_DATA)); return extraData; } /** Accessor function for store conditional return value.*/ void setExtraData(uint64_t _extraData) { extraData = _extraData; flags.set(VALID_EXTRA_DATA); } bool hasContextId() const { return flags.isSet(VALID_CONTEXT_ID); } /** Accessor function for context ID.*/ int contextId() const { assert(flags.isSet(VALID_CONTEXT_ID)); return _contextId; } /** Accessor function for thread ID. */ int threadId() const { assert(flags.isSet(VALID_THREAD_ID)); return _threadId; } bool hasPC() const { return flags.isSet(VALID_PC); } /** Accessor function for pc.*/ Addr getPC() const { assert(flags.isSet(VALID_PC)); return pc; } /** Accessor Function to Check Cacheability. */ bool isUncacheable() const { return flags.isSet(UNCACHEABLE); } bool isInstRead() const { return flags.isSet(INST_READ); } bool isLlsc() const { return flags.isSet(LLSC); } bool isSwap() const { return flags.isSet(MEM_SWAP|MEM_SWAP_COND); } bool isCondSwap() const { return flags.isSet(MEM_SWAP_COND); } bool isMisaligned() const { if (flags.isSet(NO_ALIGN_FAULT)) return false; if ((vaddr & 0x1)) return true; if (flags.isSet(NO_HALF_WORD_ALIGN_FAULT)) return false; if ((vaddr & 0x2)) return true; return false; } }; #endif // __MEM_REQUEST_HH__ <commit_msg>Memory: Add a LOCKED flag back in for x86 style locking.<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ron Dreslinski * Steve Reinhardt * Ali Saidi */ /** * @file * Declaration of a request, the overall memory request consisting of the parts of the request that are persistent throughout the transaction. */ #ifndef __MEM_REQUEST_HH__ #define __MEM_REQUEST_HH__ #include <cassert> #include "base/fast_alloc.hh" #include "base/flags.hh" #include "base/misc.hh" #include "sim/host.hh" #include "sim/core.hh" class Request; typedef Request* RequestPtr; class Request : public FastAlloc { friend class Packet; public: typedef uint32_t FlagsType; typedef ::Flags<FlagsType> Flags; /** ASI information for this request if it exists. */ static const FlagsType ASI_BITS = 0x000000FF; /** The request is a Load locked/store conditional. */ static const FlagsType LLSC = 0x00000100; /** The virtual address is also the physical address. */ static const FlagsType PHYSICAL = 0x00000200; /** The request is an ALPHA VPTE pal access (hw_ld). */ static const FlagsType VPTE = 0x00000400; /** Use the alternate mode bits in ALPHA. */ static const FlagsType ALTMODE = 0x00000800; /** The request is to an uncacheable address. */ static const FlagsType UNCACHEABLE = 0x00001000; /** The request should not cause a page fault. */ static const FlagsType NO_FAULT = 0x00002000; /** The request should not cause a memory access. */ static const FlagsType NO_ACCESS = 0x00004000; /** This request will lock or unlock the accessed memory. */ static const FlagsType LOCKED = 0x00008000; /** The request should be prefetched into the exclusive state. */ static const FlagsType PF_EXCLUSIVE = 0x00010000; /** The request should be marked as LRU. */ static const FlagsType EVICT_NEXT = 0x00020000; /** The request should ignore unaligned access faults */ static const FlagsType NO_ALIGN_FAULT = 0x00040000; /** The request was an instruction read. */ static const FlagsType INST_READ = 0x00080000; /** This request is for a memory swap. */ static const FlagsType MEM_SWAP = 0x00100000; static const FlagsType MEM_SWAP_COND = 0x00200000; /** The request should ignore unaligned access faults */ static const FlagsType NO_HALF_WORD_ALIGN_FAULT = 0x00400000; /** This request is to a memory mapped register. */ static const FlagsType MMAPED_IPR = 0x00800000; private: static const FlagsType PUBLIC_FLAGS = 0x00FFFFFF; static const FlagsType PRIVATE_FLAGS = 0xFF000000; /** Whether or not the size is valid. */ static const FlagsType VALID_SIZE = 0x01000000; /** Whether or not paddr is valid (has been written yet). */ static const FlagsType VALID_PADDR = 0x02000000; /** Whether or not the vaddr & asid are valid. */ static const FlagsType VALID_VADDR = 0x04000000; /** Whether or not the pc is valid. */ static const FlagsType VALID_PC = 0x10000000; /** Whether or not the context ID is valid. */ static const FlagsType VALID_CONTEXT_ID = 0x20000000; static const FlagsType VALID_THREAD_ID = 0x40000000; /** Whether or not the sc result is valid. */ static const FlagsType VALID_EXTRA_DATA = 0x80000000; private: /** * The physical address of the request. Valid only if validPaddr * is set. */ Addr paddr; /** * The size of the request. This field must be set when vaddr or * paddr is written via setVirt() or setPhys(), so it is always * valid as long as one of the address fields is valid. */ int size; /** Flag structure for the request. */ Flags flags; /** * The time this request was started. Used to calculate * latencies. This field is set to curTick any time paddr or vaddr * is written. */ Tick time; /** The address space ID. */ int asid; /** The virtual address of the request. */ Addr vaddr; /** * Extra data for the request, such as the return value of * store conditional or the compare value for a CAS. */ uint64_t extraData; /** The context ID (for statistics, typically). */ int _contextId; /** The thread ID (id within this CPU) */ int _threadId; /** program counter of initiating access; for tracing/debugging */ Addr pc; public: /** Minimal constructor. No fields are initialized. */ Request() {} /** * Constructor for physical (e.g. device) requests. Initializes * just physical address, size, flags, and timestamp (to curTick). * These fields are adequate to perform a request. */ Request(Addr paddr, int size, Flags flags) { setPhys(paddr, size, flags); } Request(int asid, Addr vaddr, int size, Flags flags, Addr pc, int cid, int tid) { setThreadContext(cid, tid); setVirt(asid, vaddr, size, flags, pc); } ~Request() {} // for FastAlloc /** * Set up CPU and thread numbers. */ void setThreadContext(int context_id, int thread_id) { _contextId = context_id; _threadId = thread_id; flags.set(VALID_CONTEXT_ID|VALID_THREAD_ID); } /** * Set up a physical (e.g. device) request in a previously * allocated Request object. */ void setPhys(Addr _paddr, int _size, Flags _flags) { assert(_size >= 0); paddr = _paddr; size = _size; time = curTick; flags.set(VALID_PADDR|VALID_SIZE); flags.clear(VALID_VADDR|VALID_PC|VALID_EXTRA_DATA|MMAPED_IPR); flags.update(_flags, PUBLIC_FLAGS); } /** * Set up a virtual (e.g., CPU) request in a previously * allocated Request object. */ void setVirt(int _asid, Addr _vaddr, int _size, Flags _flags, Addr _pc) { assert(_size >= 0); asid = _asid; vaddr = _vaddr; size = _size; pc = _pc; time = curTick; flags.set(VALID_VADDR|VALID_SIZE|VALID_PC); flags.clear(VALID_PADDR|VALID_EXTRA_DATA|MMAPED_IPR); flags.update(_flags, PUBLIC_FLAGS); } /** * Set just the physical address. This should only be used to * record the result of a translation, and thus the vaddr must be * valid before this method is called. Otherwise, use setPhys() * to guarantee that the size and flags are also set. */ void setPaddr(Addr _paddr) { assert(flags.isSet(VALID_VADDR)); paddr = _paddr; flags.set(VALID_PADDR); } /** * Generate two requests as if this request had been split into two * pieces. The original request can't have been translated already. */ void splitOnVaddr(Addr split_addr, RequestPtr &req1, RequestPtr &req2) { assert(flags.isSet(VALID_VADDR)); assert(flags.noneSet(VALID_PADDR)); assert(split_addr > vaddr && split_addr < vaddr + size); req1 = new Request; *req1 = *this; req2 = new Request; *req2 = *this; req1->size = split_addr - vaddr; req2->vaddr = split_addr; req2->size = size - req1->size; } /** * Accessor for paddr. */ Addr getPaddr() { assert(flags.isSet(VALID_PADDR)); return paddr; } /** * Accessor for size. */ int getSize() { assert(flags.isSet(VALID_SIZE)); return size; } /** Accessor for time. */ Tick getTime() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); return time; } void setTime(Tick when) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); time = when; } /** Accessor for flags. */ Flags getFlags() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); return flags & PUBLIC_FLAGS; } Flags anyFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); return flags.isSet(_flags); } Flags allFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); return flags.allSet(_flags); } /** Accessor for flags. */ void setFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); flags.set(_flags); } void clearFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); flags.clear(_flags); } void clearFlags() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); flags.clear(PUBLIC_FLAGS); } /** Accessor function for vaddr.*/ Addr getVaddr() { assert(flags.isSet(VALID_VADDR)); return vaddr; } /** Accessor function for asid.*/ int getAsid() { assert(flags.isSet(VALID_VADDR)); return asid; } /** Accessor function for asi.*/ uint8_t getAsi() { assert(flags.isSet(VALID_VADDR)); return flags & ASI_BITS; } /** Accessor function for asi.*/ void setAsi(uint8_t a) { assert(flags.isSet(VALID_VADDR)); flags.update(a, ASI_BITS); } /** Accessor function for asi.*/ bool isMmapedIpr() { assert(flags.isSet(VALID_PADDR)); return flags.isSet(MMAPED_IPR); } /** Accessor function for asi.*/ void setMmapedIpr(bool r) { assert(VALID_VADDR); flags.set(MMAPED_IPR); } /** Accessor function to check if sc result is valid. */ bool extraDataValid() { return flags.isSet(VALID_EXTRA_DATA); } /** Accessor function for store conditional return value.*/ uint64_t getExtraData() const { assert(flags.isSet(VALID_EXTRA_DATA)); return extraData; } /** Accessor function for store conditional return value.*/ void setExtraData(uint64_t _extraData) { extraData = _extraData; flags.set(VALID_EXTRA_DATA); } bool hasContextId() const { return flags.isSet(VALID_CONTEXT_ID); } /** Accessor function for context ID.*/ int contextId() const { assert(flags.isSet(VALID_CONTEXT_ID)); return _contextId; } /** Accessor function for thread ID. */ int threadId() const { assert(flags.isSet(VALID_THREAD_ID)); return _threadId; } bool hasPC() const { return flags.isSet(VALID_PC); } /** Accessor function for pc.*/ Addr getPC() const { assert(flags.isSet(VALID_PC)); return pc; } /** Accessor Function to Check Cacheability. */ bool isUncacheable() const { return flags.isSet(UNCACHEABLE); } bool isInstRead() const { return flags.isSet(INST_READ); } bool isLlsc() const { return flags.isSet(LLSC); } bool isLocked() const { return flags.isSet(LOCKED); } bool isSwap() const { return flags.isSet(MEM_SWAP|MEM_SWAP_COND); } bool isCondSwap() const { return flags.isSet(MEM_SWAP_COND); } bool isMisaligned() const { if (flags.isSet(NO_ALIGN_FAULT)) return false; if ((vaddr & 0x1)) return true; if (flags.isSet(NO_HALF_WORD_ALIGN_FAULT)) return false; if ((vaddr & 0x2)) return true; return false; } }; #endif // __MEM_REQUEST_HH__ <|endoftext|>
<commit_before> #include "CWindowManager.h" #include <GLFW/glfw3.h> namespace ion { void CWindowManager::Init(CGraphicsAPI * GraphicsAPI) { this->GraphicsAPI = GraphicsAPI; if (! glfwInit()) { std::cerr << "Error initializing glfw! " << std::endl; } SingletonPointer<CStateManager> StateManager; AddListener(StateManager.Get()); } CWindow * CWindowManager::CreateWindow(vec2i const & Size, std::string const & Title, EWindowType const Type) { CWindow * Window = nullptr; if (nullptr == GraphicsAPI) { Log::Error("Using WindowManager before initialization!"); } else { if (nullptr == PrimaryWindow) { GraphicsAPI->PreWindowCreationSetup(); } glfwWindowHint(GLFW_RESIZABLE, false); GLFWwindow * WindowHandle = glfwCreateWindow(Size.X, Size.Y, Title.c_str(), (Type == EWindowType::Fullscreen) ? glfwGetPrimaryMonitor() : nullptr, PrimaryWindow ? PrimaryWindow->GetHandle() : nullptr); if (nullptr == WindowHandle) { std::cerr << "Error opening glfw window! " << std::endl; } else { Window = new CWindow(WindowHandle); glfwGetWindowSize(WindowHandle, &Window->Size.X, &Window->Size.Y); glfwGetFramebufferSize(WindowHandle, &Window->FrameBufferSize.X, &Window->FrameBufferSize.Y); Windows[WindowHandle] = Window; glfwSetKeyCallback(WindowHandle, CWindowManager::KeyCallback); glfwSetMouseButtonCallback(WindowHandle, CWindowManager::MouseButtonCallback); glfwSetCursorPosCallback(WindowHandle, CWindowManager::MouseCursorCallback); glfwSetScrollCallback(WindowHandle, CWindowManager::MouseScrollCallback); glfwSetCharCallback(WindowHandle, CWindowManager::CharCallback); Window->AddListener(this); Window->MakeContextCurrent(); glfwSwapInterval(0); if (nullptr == PrimaryWindow) { GraphicsAPI->PostWindowCreationSetup(); } if (! PrimaryWindow) { PrimaryWindow = Window; } } } return Window; } CWindowManager::CWindowManager() : PrimaryWindow() {} void CWindowManager::PollEvents() { glfwPollEvents(); } bool CWindowManager::ShouldClose() const { for (auto it = Windows.begin(); it != Windows.end(); ++ it) { if (Windows.size() > 1) { it->second->MakeContextCurrent(); } if (it->second->ShouldClose()) { return true; } } if (Windows.size() > 1) { PrimaryWindow->MakeContextCurrent(); } return false; } bool CWindowManager::Run() { bool Done = ShouldClose(); PollEvents(); return ! Done; } } <commit_msg>[ionWindow] Turn on v-sync for fullscreen applications<commit_after> #include "CWindowManager.h" #include <GLFW/glfw3.h> namespace ion { void CWindowManager::Init(CGraphicsAPI * GraphicsAPI) { this->GraphicsAPI = GraphicsAPI; if (! glfwInit()) { std::cerr << "Error initializing glfw! " << std::endl; } SingletonPointer<CStateManager> StateManager; AddListener(StateManager.Get()); } CWindow * CWindowManager::CreateWindow(vec2i const & Size, std::string const & Title, EWindowType const Type) { CWindow * Window = nullptr; if (nullptr == GraphicsAPI) { Log::Error("Using WindowManager before initialization!"); } else { if (nullptr == PrimaryWindow) { GraphicsAPI->PreWindowCreationSetup(); } glfwWindowHint(GLFW_RESIZABLE, false); GLFWwindow * WindowHandle = glfwCreateWindow(Size.X, Size.Y, Title.c_str(), (Type == EWindowType::Fullscreen) ? glfwGetPrimaryMonitor() : nullptr, PrimaryWindow ? PrimaryWindow->GetHandle() : nullptr); if (nullptr == WindowHandle) { std::cerr << "Error opening glfw window! " << std::endl; } else { Window = new CWindow(WindowHandle); glfwGetWindowSize(WindowHandle, &Window->Size.X, &Window->Size.Y); glfwGetFramebufferSize(WindowHandle, &Window->FrameBufferSize.X, &Window->FrameBufferSize.Y); Windows[WindowHandle] = Window; glfwSetKeyCallback(WindowHandle, CWindowManager::KeyCallback); glfwSetMouseButtonCallback(WindowHandle, CWindowManager::MouseButtonCallback); glfwSetCursorPosCallback(WindowHandle, CWindowManager::MouseCursorCallback); glfwSetScrollCallback(WindowHandle, CWindowManager::MouseScrollCallback); glfwSetCharCallback(WindowHandle, CWindowManager::CharCallback); Window->AddListener(this); Window->MakeContextCurrent(); if (Type == EWindowType::Fullscreen) { glfwSwapInterval(1); } else { glfwSwapInterval(0); } if (nullptr == PrimaryWindow) { GraphicsAPI->PostWindowCreationSetup(); } if (! PrimaryWindow) { PrimaryWindow = Window; } } } return Window; } CWindowManager::CWindowManager() : PrimaryWindow() {} void CWindowManager::PollEvents() { glfwPollEvents(); } bool CWindowManager::ShouldClose() const { for (auto it = Windows.begin(); it != Windows.end(); ++ it) { if (Windows.size() > 1) { it->second->MakeContextCurrent(); } if (it->second->ShouldClose()) { return true; } } if (Windows.size() > 1) { PrimaryWindow->MakeContextCurrent(); } return false; } bool CWindowManager::Run() { bool Done = ShouldClose(); PollEvents(); return ! Done; } } <|endoftext|>
<commit_before>#ifndef JARNGREIPR_PDB_READER_HPP #define JARNGREIPR_PDB_READER_HPP #include <jarngreipr/pdb/PDBAtom.hpp> #include <jarngreipr/pdb/PDBChain.hpp> #include <mjolnir/util/throw_exception.hpp> #include <fstream> #include <sstream> namespace jarngreipr { // lazy pdb reader template<typename realT> class PDBReader { public: typedef PDBAtom<realT> atom_type; typedef PDBChain<realT> chain_type; typedef std::vector<chain_type> model_type; public: explicit PDBReader(const std::string& fname): filename_(fname), ifstrm_(fname) { if(!ifstrm_.good()) { throw std::runtime_error( "jarngreipr::PDBReader: file open error: " + fname); } } bool is_eof() const noexcept {return this->ifstrm_.eof();} void rewind() {this->ifstrm_.seekg(0, std::ios::beg);} // lazy functions. throws std::runtime_error if it reaches EOF. atom_type read_next_atom() { atom_type atm; while(!this->ifstrm_.eof()) { std::string line; std::getline(ifstrm_, line); std::istringstream iss(line); try { iss >> atm; } catch(std::runtime_error const& re) { ifstrm_.peek(); // set eof flag if it reached continue; } return atm; } mjolnir::throw_exception<std::runtime_error>("file ", this->filename_, " does not contain ATOM any more."); } chain_type read_next_chain() { std::vector<atom_type> atoms; while(!this->ifstrm_.eof()) { atom_type atm; std::string line; std::getline(ifstrm_, line); std::istringstream iss(line); ifstrm_.peek(); // set eof flag try { iss >> atm; atoms.push_back(atm); } catch(std::runtime_error const& re) { if(line.substr(0, 3) == "TER" || line.substr(0, 6) == "ENDMDL") { return chain_type(std::move(atoms)); } } continue; } if(!atoms.empty()) { return chain_type(std::move(atoms)); } mjolnir::throw_exception<std::runtime_error>("file ", this->filename_, " does not contain chain any more."); } model_type read_next_model() { std::vector<chain_type> chains; std::vector<atom_type> atoms; while(!this->ifstrm_.eof()) { atom_type atm; std::string line; std::getline(ifstrm_, line); std::istringstream iss(line); ifstrm_.peek(); // set eof flag try { iss >> atm; atoms.push_back(atm); } catch(std::runtime_error const& re) { if(line.substr(0, 3) == "TER" || line.substr(0, 6) == "ENDMDL") { chains.push_back(chain_type(std::move(atoms))); atoms = {}; } if(line.substr(0, 6) == "ENDMDL") { return chains; } } continue; } if(!chains.empty()) { return chains; } mjolnir::throw_exception<std::runtime_error>("file ", this->filename_, " does not contain chain any more."); } private: std::string filename_; std::ifstream ifstrm_; }; } // jarngreipr #endif// JARNGREIPR_PDB_READER_HPP <commit_msg>add read_chain with naive implementation<commit_after>#ifndef JARNGREIPR_PDB_READER_HPP #define JARNGREIPR_PDB_READER_HPP #include <jarngreipr/pdb/PDBAtom.hpp> #include <jarngreipr/pdb/PDBChain.hpp> #include <mjolnir/util/throw_exception.hpp> #include <fstream> #include <sstream> namespace jarngreipr { // lazy pdb reader template<typename realT> class PDBReader { public: typedef PDBAtom<realT> atom_type; typedef PDBChain<realT> chain_type; typedef std::vector<chain_type> model_type; public: explicit PDBReader(const std::string& fname) : filename_(fname), ifstrm_(fname) { if(!ifstrm_.good()) { throw std::runtime_error( "jarngreipr::PDBReader: file open error: " + fname); } } bool is_eof() const noexcept {return this->ifstrm_.eof();} void rewind() {this->ifstrm_.seekg(0, std::ios::beg);} chain_type read_chain(const char id) { this->rewind(); while(!this->ifstrm_.eof()) { try { const auto chain = this->read_next_chain(); if(chain.chain_id() == id) { return chain; } } catch(std::runtime_error const& re) { break; } } mjolnir::throw_exception<std::runtime_error>("file ", this->filename_, " does not contain chain ", id); } // lazy functions. throws std::runtime_error if it reaches EOF. atom_type read_next_atom() { atom_type atm; while(!this->ifstrm_.eof()) { std::string line; std::getline(ifstrm_, line); ifstrm_.peek(); // set eof flag if it reached std::istringstream iss(line); try { iss >> atm; } catch(std::runtime_error const& re) { continue; } return atm; } mjolnir::throw_exception<std::runtime_error>("file ", this->filename_, " does not contain ATOM any more."); } chain_type read_next_chain() { std::vector<atom_type> atoms; while(!this->ifstrm_.eof()) { atom_type atm; std::string line; std::getline(ifstrm_, line); ifstrm_.peek(); // set eof flag std::istringstream iss(line); try { iss >> atm; atoms.push_back(atm); } catch(std::runtime_error const& re) { if(line.substr(0, 3) == "TER" || line.substr(0, 6) == "ENDMDL") { return chain_type(std::move(atoms)); } } continue; } if(!atoms.empty()) { return chain_type(std::move(atoms)); } mjolnir::throw_exception<std::runtime_error>("file ", this->filename_, " does not contain chain any more."); } model_type read_next_model() { std::vector<chain_type> chains; std::vector<atom_type> atoms; while(!this->ifstrm_.eof()) { atom_type atm; std::string line; std::getline(ifstrm_, line); ifstrm_.peek(); // set eof flag std::istringstream iss(line); try { iss >> atm; atoms.push_back(atm); } catch(std::runtime_error const& re) { if(line.substr(0, 3) == "TER" || line.substr(0, 6) == "ENDMDL") { chains.push_back(chain_type(std::move(atoms))); atoms = {}; } if(line.substr(0, 6) == "ENDMDL") { return chains; } } continue; } if(!chains.empty()) { return chains; } mjolnir::throw_exception<std::runtime_error>("file ", this->filename_, " does not contain chain any more."); } private: std::string filename_; std::ifstream ifstrm_; }; } // jarngreipr #endif// JARNGREIPR_PDB_READER_HPP <|endoftext|>
<commit_before>#include "model.hpp" namespace Model { mesh_t::mesh_t(int w, int h, void (*fn) (float s, float t, std::vector<float> &vertices)) { for(int i = 0; i < w; i++) { for(int j = 0; j < h; j++) { auto index = 3*(j * w + i), i2 = 3, j2 = w*3; fn(float(i)/w, float(j)/h, vertices); if(i < w-1 && j < h-1) { faces.emplace_back(index); faces.emplace_back(index+i2); faces.emplace_back(index+i2+j2); faces.emplace_back(index); faces.emplace_back(index+i2+j2); faces.emplace_back(index+j2); } } } } } <commit_msg>Stretched mesh to include both ends of the parameter domain<commit_after>#include "model.hpp" namespace Model { mesh_t::mesh_t(int w, int h, void (*fn) (float s, float t, std::vector<float> &vertices)) { for(int i = 0; i < w; i++) { for(int j = 0; j < h; j++) { auto index = 3*(j * w + i), i2 = 3, j2 = w*3; fn(float(i)/(w-1), float(j)/(h-1), vertices); if(i < w-1 && j < h-1) { faces.emplace_back(index); faces.emplace_back(index+i2); faces.emplace_back(index+i2+j2); faces.emplace_back(index); faces.emplace_back(index+i2+j2); faces.emplace_back(index+j2); } } } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: Axis.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: bm $ $Date: 2004-01-26 09:12:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2003 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CHART_AXIS_HXX #define CHART_AXIS_HXX #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef CHART_MUTEXCONTAINER_HXX #include "MutexContainer.hxx" #endif #ifndef CHART_OPROPERTYSET_HXX #include "OPropertySet.hxx" #endif #ifndef _CPPUHELPER_IMPLBASE4_HXX_ #include <cppuhelper/implbase4.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #include "ServiceMacros.hxx" #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XAXIS_HPP_ #include <com/sun/star/chart2/XAxis.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XIDENTIFIABLE_HPP_ #include <com/sun/star/chart2/XIdentifiable.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XTITLED_HPP_ #include <com/sun/star/chart2/XTitled.hpp> #endif namespace chart { namespace impl { typedef ::cppu::WeakImplHelper4< ::com::sun::star::chart2::XAxis, ::com::sun::star::chart2::XIdentifiable, ::com::sun::star::chart2::XTitled, ::com::sun::star::lang::XServiceInfo > Axis_Base; } class Axis : public helper::MutexContainer, public impl::Axis_Base, public ::property::OPropertySet { public: Axis( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext ); virtual ~Axis(); /// establish methods for factory instatiation APPHELPER_SERVICE_FACTORY_HELPER( Axis ) /// XServiceInfo declarations APPHELPER_XSERVICEINFO_DECL() /// merge XInterface implementations DECLARE_XINTERFACE() /// merge XTypeProvider implementations DECLARE_XTYPEPROVIDER() protected: // ____ OPropertySet ____ virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const throw(::com::sun::star::beans::UnknownPropertyException); // ____ OPropertySet ____ virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); // ____ XPropertySet ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); // virtual sal_Bool SAL_CALL convertFastPropertyValue // ( ::com::sun::star::uno::Any & rConvertedValue, // ::com::sun::star::uno::Any & rOldValue, // sal_Int32 nHandle, // const ::com::sun::star::uno::Any& rValue ) // throw (::com::sun::star::lang::IllegalArgumentException); // ____ XAxis ____ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > > SAL_CALL getSubTickProperties() throw (::com::sun::star::uno::RuntimeException); // ____ XMeter ____ virtual void SAL_CALL attachCoordinateSystem( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem >& xCoordSys, sal_Int32 nRepresentedDimension ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > SAL_CALL getCoordinateSystem() throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getRepresentedDimension() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setIncrement( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XIncrement >& aIncrement ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XIncrement > SAL_CALL getIncrement() throw (::com::sun::star::uno::RuntimeException); // ____ XIdentifiable ____ virtual ::rtl::OUString SAL_CALL getIdentifier() throw (::com::sun::star::uno::RuntimeException); // ____ XTitled ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle > SAL_CALL getTitle() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTitle( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle >& Title ) throw (::com::sun::star::uno::RuntimeException); private: ::rtl::OUString m_aIdentifier; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > m_xCoordinateSystem; sal_Int32 m_nRepresentedDimension; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XIncrement > m_xIncrement; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle > m_xTitle; }; } // namespace chart // CHART_AXIS_HXX #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.110); FILE MERGED 2005/09/05 18:43:01 rt 1.4.110.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Axis.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 00:52:59 $ * * 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 CHART_AXIS_HXX #define CHART_AXIS_HXX #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef CHART_MUTEXCONTAINER_HXX #include "MutexContainer.hxx" #endif #ifndef CHART_OPROPERTYSET_HXX #include "OPropertySet.hxx" #endif #ifndef _CPPUHELPER_IMPLBASE4_HXX_ #include <cppuhelper/implbase4.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #include "ServiceMacros.hxx" #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XAXIS_HPP_ #include <com/sun/star/chart2/XAxis.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XIDENTIFIABLE_HPP_ #include <com/sun/star/chart2/XIdentifiable.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XTITLED_HPP_ #include <com/sun/star/chart2/XTitled.hpp> #endif namespace chart { namespace impl { typedef ::cppu::WeakImplHelper4< ::com::sun::star::chart2::XAxis, ::com::sun::star::chart2::XIdentifiable, ::com::sun::star::chart2::XTitled, ::com::sun::star::lang::XServiceInfo > Axis_Base; } class Axis : public helper::MutexContainer, public impl::Axis_Base, public ::property::OPropertySet { public: Axis( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext ); virtual ~Axis(); /// establish methods for factory instatiation APPHELPER_SERVICE_FACTORY_HELPER( Axis ) /// XServiceInfo declarations APPHELPER_XSERVICEINFO_DECL() /// merge XInterface implementations DECLARE_XINTERFACE() /// merge XTypeProvider implementations DECLARE_XTYPEPROVIDER() protected: // ____ OPropertySet ____ virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const throw(::com::sun::star::beans::UnknownPropertyException); // ____ OPropertySet ____ virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); // ____ XPropertySet ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); // virtual sal_Bool SAL_CALL convertFastPropertyValue // ( ::com::sun::star::uno::Any & rConvertedValue, // ::com::sun::star::uno::Any & rOldValue, // sal_Int32 nHandle, // const ::com::sun::star::uno::Any& rValue ) // throw (::com::sun::star::lang::IllegalArgumentException); // ____ XAxis ____ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > > SAL_CALL getSubTickProperties() throw (::com::sun::star::uno::RuntimeException); // ____ XMeter ____ virtual void SAL_CALL attachCoordinateSystem( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem >& xCoordSys, sal_Int32 nRepresentedDimension ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > SAL_CALL getCoordinateSystem() throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getRepresentedDimension() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setIncrement( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XIncrement >& aIncrement ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XIncrement > SAL_CALL getIncrement() throw (::com::sun::star::uno::RuntimeException); // ____ XIdentifiable ____ virtual ::rtl::OUString SAL_CALL getIdentifier() throw (::com::sun::star::uno::RuntimeException); // ____ XTitled ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle > SAL_CALL getTitle() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTitle( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle >& Title ) throw (::com::sun::star::uno::RuntimeException); private: ::rtl::OUString m_aIdentifier; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > m_xCoordinateSystem; sal_Int32 m_nRepresentedDimension; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XIncrement > m_xIncrement; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle > m_xTitle; }; } // namespace chart // CHART_AXIS_HXX #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2017, Ubiquity Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. * */ #include <ros/ros.h> #include <tf/transform_datatypes.h> #include <tf2/LinearMath/Transform.h> #include <tf2_ros/buffer.h> #include <tf2_ros/transform_listener.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Path.h> #include <actionlib/server/simple_action_server.h> #include <move_base_msgs/MoveBaseAction.h> #include <list> #include <string> typedef actionlib::SimpleActionServer<move_base_msgs::MoveBaseAction> MoveBaseActionServer; class MoveBasic { private: ros::Subscriber goalSub; ros::Publisher goalPub; ros::Publisher cmdPub; ros::Publisher pathPub; std::unique_ptr<MoveBaseActionServer> actionServer; tf2_ros::Buffer tfBuffer; tf2_ros::TransformListener listener; double angularVelocity; double angularTolerance; double linearVelocity; double linearTolerance; tf2::Transform goalOdom; void goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg); void executeAction(const move_base_msgs::MoveBaseGoalConstPtr& goal); void sendCmd(double angular, double linear); bool getTransform(const std::string& from, const std::string& to, tf2::Transform& tf); bool handleRotation(); bool handleLinear(); public: MoveBasic(); void run(); bool moveLinear(double requestedDistance); bool rotateTo(double requestedYaw); bool rotateRel(double yaw); }; // Radians to degrees static double rad2deg(double rad) { return rad * 180.0 / M_PI; } // Adjust angle to be between -PI and PI static void normalizeAngle(double& angle) { if (angle < -M_PI) { angle += 2 * M_PI; } if (angle > M_PI) { angle -= 2 * M_PI; } } // retreive the 3 DOF we are interested in from a Transform static void getPose(const tf2::Transform& tf, double& x, double& y, double& yaw) { tf2::Vector3 trans = tf.getOrigin(); x = trans.x(); y = trans.y(); double roll, pitch; tf.getBasis().getRPY(roll, pitch, yaw); } // Constructor MoveBasic::MoveBasic(): tfBuffer(ros::Duration(30.0)), listener(tfBuffer) { ros::NodeHandle nh("~"); nh.param<double>("angular_velocity", angularVelocity, 0.3); nh.param<double>("angular_tolerance", angularTolerance, 0.01); nh.param<double>("linear_velocity", linearVelocity, 0.4); nh.param<double>("linear_tolerance", linearTolerance, 0.01); cmdPub = ros::Publisher(nh.advertise<geometry_msgs::Twist>("/cmd_vel", 1)); pathPub = ros::Publisher(nh.advertise<nav_msgs::Path>("/plan", 1)); goalSub = nh.subscribe("/move_base_simple/goal", 1, &MoveBasic::goalCallback, this); ros::NodeHandle actionNh(""); actionServer.reset(new MoveBaseActionServer(actionNh, "move_base", boost::bind(&MoveBasic::executeAction, this, _1), false)); actionServer->start(); goalPub = actionNh.advertise<move_base_msgs::MoveBaseActionGoal>( "/move_base/goal", 1); ROS_INFO("Move Basic ready"); } // Lookup the specified transform, returns true on success bool MoveBasic::getTransform(const std::string& from, const std::string& to, tf2::Transform& tf) { try { geometry_msgs::TransformStamped tfs = tfBuffer.lookupTransform(to, from, ros::Time(0)); tf2::fromMsg(tfs.transform, tf); return true; } catch (tf2::TransformException &ex) { ROS_WARN("%s", ex.what()); return false; } } // Called when a simple goal message is received void MoveBasic::goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg) { ROS_INFO("Received simple goal"); // send the goal to the action server move_base_msgs::MoveBaseActionGoal actionGoal; actionGoal.header.stamp = ros::Time::now(); actionGoal.goal.target_pose = *msg; goalPub.publish(actionGoal); } // Called when an action goal is received void MoveBasic::executeAction(const move_base_msgs::MoveBaseGoalConstPtr& msg) { tf2::Transform goal; tf2::fromMsg(msg->target_pose.pose, goal); std::string frameId = msg->target_pose.header.frame_id; // Needed for RobotCommander if (frameId[0] == '/') frameId = frameId.substr(1); double x, y, yaw; getPose(goal, x, y, yaw); ROS_INFO("Received goal %f %f %f", x, y, rad2deg(yaw)); tf2::Transform tfMapOdom; if (!getTransform(frameId, "odom", tfMapOdom)) { actionServer->setAborted(move_base_msgs::MoveBaseResult(), "Cannot determine robot pose"); return; } goalOdom = tfMapOdom * goal; getPose(goalOdom, x, y, yaw); ROS_INFO("Goal in odom %f %f %f", x, y, rad2deg(yaw)); nav_msgs::Path path; geometry_msgs::PoseStamped p0, p1; path.header.frame_id = "odom"; p0.pose.position.x = x; p0.pose.position.y = y; path.poses.push_back(p0); tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for rotation"); return; } getPose(poseOdom, x, y, yaw); p1.pose.position.x = x; p1.pose.position.y = y; path.poses.push_back(p1); pathPub.publish(path); if (!handleRotation()) { actionServer->setAborted(move_base_msgs::MoveBaseResult(), "Rotation failed"); return; } if (!handleLinear()) { actionServer->setAborted(move_base_msgs::MoveBaseResult(), "Linear movement failed"); return; } getPose(goalOdom, x, y, yaw); rotateTo(yaw); actionServer->setSucceeded(); } // Send a motion command void MoveBasic::sendCmd(double angular, double linear) { geometry_msgs::Twist msg; msg.angular.z = angular; msg.linear.x = linear; cmdPub.publish(msg); } // Main loop void MoveBasic::run() { ros::Rate r(20); while (ros::ok()) { ros::spinOnce(); r.sleep(); } } // Do angular part of goal bool MoveBasic::handleRotation() { tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for rotation"); return false; } tf2::Vector3 linear = goalOdom.getOrigin() - poseOdom.getOrigin(); double requestedYaw = atan2(linear.y(), linear.x()); if (requestedYaw == 0) { return true; } return rotateTo(requestedYaw); } // Rotate relative to current orientation bool MoveBasic::rotateRel(double yaw) { tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for rotation"); return false; } double x, y, currentYaw; getPose(poseOdom, x, y, currentYaw); double requestedYaw = currentYaw + yaw; normalizeAngle(requestedYaw); return rotateTo(requestedYaw); } // Rotate to specified orientation (in radians) bool MoveBasic::rotateTo(double requestedYaw) { bool done = false; ros::Rate r(50); while (!done && ros::ok()) { ros::spinOnce(); r.sleep(); double x, y, currentYaw; tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for rotation"); return false; } getPose(poseOdom, x, y, currentYaw); double demand = requestedYaw - currentYaw; normalizeAngle(demand); double velocity = 0; if (demand < 0) { velocity = -angularVelocity; } else { velocity = angularVelocity; } if (actionServer->isNewGoalAvailable()) { ROS_INFO("Stopping rotation due to new goal"); done = true; velocity = 0; } // ROS_INFO("Demand %f %f %f", rad2deg(demand), demand, velocity); if (std::abs(demand) < angularTolerance) { velocity = 0; done = true; ROS_INFO("Done rotation, error %f radians %f degrees", demand, rad2deg(demand)); } sendCmd(velocity, 0); } return done; } // Do linear part of goal bool MoveBasic::handleLinear() { bool done = false; tf2::Transform poseOdomInitial; if (!getTransform("base_link", "odom", poseOdomInitial)) { ROS_WARN("Cannot determine robot pose for linrar"); return false; } tf2::Vector3 linear = goalOdom.getOrigin() - poseOdomInitial.getOrigin(); double requestedDistance = linear.length();; ROS_INFO("Requested distance %f", requestedDistance); return moveLinear(requestedDistance); } // Move foreward specified distance bool MoveBasic::moveLinear(double requestedDistance) { bool done = false; ros::Rate r(50); tf2::Transform poseOdomInitial; if (!getTransform("base_link", "odom", poseOdomInitial)) { ROS_WARN("Cannot determine robot pose for linrar"); return false; } while (!done && ros::ok()) { ros::spinOnce(); r.sleep(); tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for linear"); continue; } tf2::Vector3 travelled = poseOdomInitial.getOrigin() - poseOdom.getOrigin(); double distTravelled = travelled.length();; double demand = requestedDistance - distTravelled; double velocity = linearVelocity; if (actionServer->isNewGoalAvailable()) { ROS_INFO("Stopping rotation due to new goal"); done = true; velocity = 0; } // ROS_INFO("Demand %f %f", requestedDist-distTravelled, velocity); if (distTravelled > requestedDistance - linearTolerance) { velocity = 0; done = true; ROS_INFO("Done linear, error %f meters", demand); } sendCmd(0, velocity); } return done; } int main(int argc, char ** argv) { ros::init(argc, argv, "move_basic"); MoveBasic mb_node; mb_node.run(); return 0; } <commit_msg>don't do initial rotation if there is no translation<commit_after>/* * Copyright (c) 2017, Ubiquity Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. * */ #include <ros/ros.h> #include <tf/transform_datatypes.h> #include <tf2/LinearMath/Transform.h> #include <tf2_ros/buffer.h> #include <tf2_ros/transform_listener.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Path.h> #include <actionlib/server/simple_action_server.h> #include <move_base_msgs/MoveBaseAction.h> #include <list> #include <string> typedef actionlib::SimpleActionServer<move_base_msgs::MoveBaseAction> MoveBaseActionServer; class MoveBasic { private: ros::Subscriber goalSub; ros::Publisher goalPub; ros::Publisher cmdPub; ros::Publisher pathPub; std::unique_ptr<MoveBaseActionServer> actionServer; tf2_ros::Buffer tfBuffer; tf2_ros::TransformListener listener; double angularVelocity; double angularTolerance; double linearVelocity; double linearTolerance; tf2::Transform goalOdom; void goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg); void executeAction(const move_base_msgs::MoveBaseGoalConstPtr& goal); void sendCmd(double angular, double linear); bool getTransform(const std::string& from, const std::string& to, tf2::Transform& tf); bool handleRotation(); bool handleLinear(); public: MoveBasic(); void run(); bool moveLinear(double requestedDistance); bool rotateTo(double requestedYaw); bool rotateRel(double yaw); }; // Radians to degrees static double rad2deg(double rad) { return rad * 180.0 / M_PI; } // Adjust angle to be between -PI and PI static void normalizeAngle(double& angle) { if (angle < -M_PI) { angle += 2 * M_PI; } if (angle > M_PI) { angle -= 2 * M_PI; } } // retreive the 3 DOF we are interested in from a Transform static void getPose(const tf2::Transform& tf, double& x, double& y, double& yaw) { tf2::Vector3 trans = tf.getOrigin(); x = trans.x(); y = trans.y(); double roll, pitch; tf.getBasis().getRPY(roll, pitch, yaw); } // Constructor MoveBasic::MoveBasic(): tfBuffer(ros::Duration(30.0)), listener(tfBuffer) { ros::NodeHandle nh("~"); nh.param<double>("angular_velocity", angularVelocity, 0.3); nh.param<double>("angular_tolerance", angularTolerance, 0.01); nh.param<double>("linear_velocity", linearVelocity, 0.4); nh.param<double>("linear_tolerance", linearTolerance, 0.01); cmdPub = ros::Publisher(nh.advertise<geometry_msgs::Twist>("/cmd_vel", 1)); pathPub = ros::Publisher(nh.advertise<nav_msgs::Path>("/plan", 1)); goalSub = nh.subscribe("/move_base_simple/goal", 1, &MoveBasic::goalCallback, this); ros::NodeHandle actionNh(""); actionServer.reset(new MoveBaseActionServer(actionNh, "move_base", boost::bind(&MoveBasic::executeAction, this, _1), false)); actionServer->start(); goalPub = actionNh.advertise<move_base_msgs::MoveBaseActionGoal>( "/move_base/goal", 1); ROS_INFO("Move Basic ready"); } // Lookup the specified transform, returns true on success bool MoveBasic::getTransform(const std::string& from, const std::string& to, tf2::Transform& tf) { try { geometry_msgs::TransformStamped tfs = tfBuffer.lookupTransform(to, from, ros::Time(0)); tf2::fromMsg(tfs.transform, tf); return true; } catch (tf2::TransformException &ex) { ROS_WARN("%s", ex.what()); return false; } } // Called when a simple goal message is received void MoveBasic::goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg) { ROS_INFO("Received simple goal"); // send the goal to the action server move_base_msgs::MoveBaseActionGoal actionGoal; actionGoal.header.stamp = ros::Time::now(); actionGoal.goal.target_pose = *msg; goalPub.publish(actionGoal); } // Called when an action goal is received void MoveBasic::executeAction(const move_base_msgs::MoveBaseGoalConstPtr& msg) { tf2::Transform goal; tf2::fromMsg(msg->target_pose.pose, goal); std::string frameId = msg->target_pose.header.frame_id; // Needed for RobotCommander if (frameId[0] == '/') frameId = frameId.substr(1); double x, y, yaw; getPose(goal, x, y, yaw); ROS_INFO("Received goal %f %f %f", x, y, rad2deg(yaw)); tf2::Transform tfMapOdom; if (!getTransform(frameId, "odom", tfMapOdom)) { actionServer->setAborted(move_base_msgs::MoveBaseResult(), "Cannot determine robot pose"); return; } goalOdom = tfMapOdom * goal; getPose(goalOdom, x, y, yaw); ROS_INFO("Goal in odom %f %f %f", x, y, rad2deg(yaw)); nav_msgs::Path path; geometry_msgs::PoseStamped p0, p1; path.header.frame_id = "odom"; p0.pose.position.x = x; p0.pose.position.y = y; path.poses.push_back(p0); tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for rotation"); return; } getPose(poseOdom, x, y, yaw); p1.pose.position.x = x; p1.pose.position.y = y; path.poses.push_back(p1); pathPub.publish(path); if (!handleRotation()) { actionServer->setAborted(move_base_msgs::MoveBaseResult(), "Rotation failed"); return; } if (!handleLinear()) { actionServer->setAborted(move_base_msgs::MoveBaseResult(), "Linear movement failed"); return; } getPose(goalOdom, x, y, yaw); rotateTo(yaw); actionServer->setSucceeded(); } // Send a motion command void MoveBasic::sendCmd(double angular, double linear) { geometry_msgs::Twist msg; msg.angular.z = angular; msg.linear.x = linear; cmdPub.publish(msg); } // Main loop void MoveBasic::run() { ros::Rate r(20); while (ros::ok()) { ros::spinOnce(); r.sleep(); } } // Do angular part of goal bool MoveBasic::handleRotation() { tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for rotation"); return false; } tf2::Vector3 linear = goalOdom.getOrigin() - poseOdom.getOrigin(); // don't do initial rotation if there is no translation if (linear.length() == 0) { return true; } double requestedYaw = atan2(linear.y(), linear.x()); if (requestedYaw == 0) { return true; } return rotateTo(requestedYaw); } // Rotate relative to current orientation bool MoveBasic::rotateRel(double yaw) { tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for rotation"); return false; } double x, y, currentYaw; getPose(poseOdom, x, y, currentYaw); double requestedYaw = currentYaw + yaw; normalizeAngle(requestedYaw); return rotateTo(requestedYaw); } // Rotate to specified orientation (in radians) bool MoveBasic::rotateTo(double requestedYaw) { bool done = false; ros::Rate r(50); while (!done && ros::ok()) { ros::spinOnce(); r.sleep(); double x, y, currentYaw; tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for rotation"); return false; } getPose(poseOdom, x, y, currentYaw); double demand = requestedYaw - currentYaw; normalizeAngle(demand); double velocity = 0; if (demand < 0) { velocity = -angularVelocity; } else { velocity = angularVelocity; } if (actionServer->isNewGoalAvailable()) { ROS_INFO("Stopping rotation due to new goal"); done = true; velocity = 0; } // ROS_INFO("Demand %f %f %f", rad2deg(demand), demand, velocity); if (std::abs(demand) < angularTolerance) { velocity = 0; done = true; ROS_INFO("Done rotation, error %f radians %f degrees", demand, rad2deg(demand)); } sendCmd(velocity, 0); } return done; } // Do linear part of goal bool MoveBasic::handleLinear() { bool done = false; tf2::Transform poseOdomInitial; if (!getTransform("base_link", "odom", poseOdomInitial)) { ROS_WARN("Cannot determine robot pose for linrar"); return false; } tf2::Vector3 linear = goalOdom.getOrigin() - poseOdomInitial.getOrigin(); double requestedDistance = linear.length();; ROS_INFO("Requested distance %f", requestedDistance); return moveLinear(requestedDistance); } // Move foreward specified distance bool MoveBasic::moveLinear(double requestedDistance) { bool done = false; ros::Rate r(50); tf2::Transform poseOdomInitial; if (!getTransform("base_link", "odom", poseOdomInitial)) { ROS_WARN("Cannot determine robot pose for linrar"); return false; } while (!done && ros::ok()) { ros::spinOnce(); r.sleep(); tf2::Transform poseOdom; if (!getTransform("base_link", "odom", poseOdom)) { ROS_WARN("Cannot determine robot pose for linear"); continue; } tf2::Vector3 travelled = poseOdomInitial.getOrigin() - poseOdom.getOrigin(); double distTravelled = travelled.length();; double demand = requestedDistance - distTravelled; double velocity = linearVelocity; if (actionServer->isNewGoalAvailable()) { ROS_INFO("Stopping rotation due to new goal"); done = true; velocity = 0; } // ROS_INFO("Demand %f %f", requestedDist-distTravelled, velocity); if (distTravelled > requestedDistance - linearTolerance) { velocity = 0; done = true; ROS_INFO("Done linear, error %f meters", demand); } sendCmd(0, velocity); } return done; } int main(int argc, char ** argv) { ros::init(argc, argv, "move_basic"); MoveBasic mb_node; mb_node.run(); return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <fstream> #include <sstream> #include "pixelboost/data/json/writer.h" #include "pixelboost/file/fileHelpers.h" #include "command/manager.h" #include "http/commands/file.h" #include "http/commands/record.h" #include "http/commands/schema.h" #include "http/httpInterface.h" #include "project/entity.h" #include "project/project.h" #include "project/property.h" #include "project/record.h" #include "core.h" using namespace pb; using namespace pixeleditor; HttpInterface::HttpInterface() : pb::HttpServer() { } HttpInterface::~HttpInterface() { } void HttpInterface::Initialise() { _FileCommands = new FileCommands(); _SchemaCommands = new SchemaCommands(); _RecordCommands = new RecordCommands(); Start(9090, pb::FileHelpers::GetRootPath()+"/data/html/"); } void HttpInterface::RegisterCommand(const std::string& command, HttpServer::RequestType requestType, CommandDelegate delegate) { _Commands[CommandRequest(command, requestType)] = delegate; } bool HttpInterface::OnHttpRequest(HttpServer::RequestType type, const std::string& uri, const std::string& query, const std::string& data, pb::HttpConnection& connection) { ssize_t split = uri.find('/', 1); std::string command; std::string argumentString; std::string queryString = query; std::vector<std::string> urlArguments; std::map<std::string, std::string> queryArguments; if (split > 0) { command = uri.substr(1, split-1); argumentString = uri.substr(split); } else { command = uri.substr(1); } while (argumentString.length() > 1) { ssize_t split = argumentString.find('/', 1); std::string argument; if (split > 0) { argument = argumentString.substr(1, split-1); argumentString = argumentString.substr(split); } else { argument = argumentString.substr(1); argumentString = ""; } if (argument.length() > 0) urlArguments.push_back(argument); else break; } while (queryString.length() > 1) { ssize_t split = queryString.find('&', 1); std::string argument; if (split > 0) { argument = queryString.substr(0, split); queryString = queryString.substr(split+1); } else { argument = queryString.substr(0); queryString = ""; } if (argument.length() > 0) { std::string field; std::string value; int op = argument.find('='); if (op > 0) { field = argument.substr(0, op); value = argument.substr(op+1); } queryArguments[field] = value; } else break; } bool replied = false; CommandRequest request(command, type); CommandMap::iterator commandHandler = _Commands.find(request); if (commandHandler != _Commands.end()) { connection.AddHeader("Content-Type", "application/json;charset=utf-8"); replied = commandHandler->second(connection, urlArguments, queryArguments); } else { if (command == "images" && type == kRequestTypeGet) { connection.AddHeader("Content-Type", "image/png"); if (urlArguments.size() == 1) { replied = OnGetImage(connection, urlArguments[0]); } } else { connection.AddHeader("Content-Type", "application/json;charset=utf-8"); } if (command == "record" && type == kRequestTypeGet) { if (urlArguments.size() == 1) { Uid record = atoi(urlArguments[0].c_str()); replied = OnGetRecord(connection, record); } else if (urlArguments.size() >= 2 && urlArguments[1] == "property") { Uid record = atoi(urlArguments[0].c_str()); std::string path = "/"; for (int i=2; i < urlArguments.size(); i++) { path += urlArguments[i] + "/"; } replied = OnGetRecordProperty(connection, record, path); } else if (urlArguments.size() >= 4 && urlArguments[1] == "entity" && urlArguments[3] == "property") { Uid record = atoi(urlArguments[0].c_str()); Uid entity = atoi(urlArguments[2].c_str()); std::string path = "/"; for (int i=4; i < urlArguments.size(); i++) { path += urlArguments[i] + "/"; } replied = OnGetEntityProperty(connection, record, entity, path); } } else if (command == "record" && (type == kRequestTypePost || type == kRequestTypePut)) { if (urlArguments.size() >= 2 && urlArguments[1] == "property") { Uid record = atoi(urlArguments[0].c_str()); std::string type = queryArguments["type"]; std::string value = queryArguments["value"]; std::string path = "/"; for (int i=2; i < urlArguments.size(); i++) { path += urlArguments[i] + "/"; } replied = OnSetRecordProperty(connection, record, path, type, value); } else if (urlArguments.size() == 2 && urlArguments[1] == "entities" && type == kRequestTypePost) { Uid record = atoi(urlArguments[0].c_str()); replied = OnCreateEntity(connection, record, queryArguments["type"]); } else if (urlArguments.size() >= 4 && urlArguments[1] == "entity" && type == kRequestTypePut) { Uid record = atoi(urlArguments[0].c_str()); Uid entity = atoi(urlArguments[2].c_str()); if (urlArguments[3] == "transform") { replied = OnSetTransform(connection, record, entity, Vec3(atof(queryArguments["tx"].c_str()), atof(queryArguments["ty"].c_str()), atof(queryArguments["tz"].c_str())), 0, Vec3(1,1,1)); } else if (urlArguments[3] == "property") { std::string type = queryArguments["type"]; std::string value = queryArguments["value"]; std::string path = "/"; for (int i=4; i < urlArguments.size(); i++) { path += urlArguments[i] + "/"; } replied = OnSetEntityProperty(connection, record, entity, path, type, value); } } } else if (command == "records" && type == kRequestTypePost) { if (urlArguments.size() == 0) { replied = OnCreateRecord(connection, queryArguments["name"], queryArguments["type"]); } } } if (replied == true) { connection.Send(); return true; } if (type == kRequestTypeGet) return false; // No over-ride, default to finding html else return true; } bool HttpInterface::OnCreateRecord(pb::HttpConnection& connection, const std::string& name, const std::string& type) { if (name == "") return false; Project* project = Core::Instance()->GetProject(); project->AddRecord(name, type); return true; } bool HttpInterface::OnCreateEntity(pb::HttpConnection& connection, Uid recordId, const std::string& type) { char arguments[256]; sprintf(arguments, "-r %d -t %s -p 0,0", recordId, type.c_str()); Core::Instance()->GetCommandManager()->Exec("createEntity", arguments); return true; } bool HttpInterface::OnSetTransform(pb::HttpConnection& connection, Uid recordId, Uid entityId, const Vec3& position, float rotation, const Vec3& scale) { Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; Entity* entity = record->GetEntity(entityId); if (!entity) return false; entity->SetPosition(position); entity->SetRotation(rotation); entity->SetScale(scale); return true; } bool HttpInterface::OnGetRecord(pb::HttpConnection& connection, Uid recordId) { json::Object data; Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; record->ExportJson(data); std::stringstream contentStream; json::Writer::Write(data, contentStream); std::string content = contentStream.str(); char contentLength[64]; sprintf(contentLength, "%d", static_cast<int>(content.length())); connection.AddHeader("Content-Length", contentLength); connection.SetContent(content); return true; } bool HttpInterface::OnGetEntity(pb::HttpConnection& connection, Uid recordId, Uid entityId) { json::Object data; Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; Entity* entity = record->GetEntity(entityId); if (!entity) return false; entity->ExportJson(data); std::stringstream contentStream; json::Writer::Write(data, contentStream); std::string content = contentStream.str(); char contentLength[64]; sprintf(contentLength, "%d", static_cast<int>(content.length())); connection.AddHeader("Content-Length", contentLength); connection.SetContent(content); return true; } bool HttpInterface::OnGetRecordProperty(pb::HttpConnection& connection, Uid recordId, const std::string& path) { Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return true; return OnGetStructProperty(connection, record->GetProperty(path)); } bool HttpInterface::OnGetEntityProperty(pb::HttpConnection& connection, Uid recordId, Uid entityId, const std::string& path) { Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return true; Entity* entity = record->GetEntity(entityId); if (!entity) return true; return OnGetStructProperty(connection, entity->GetProperty(path)); } bool HttpInterface::OnGetStructProperty(pb::HttpConnection& connection, const Property* property) { json::Object data; if (!property) return true; if (property->GetType() == Property::kPropertyAtom) { data["type"] = json::String("atom"); data["value"] = json::String(static_cast<const PropertyAtom*>(property)->GetStringValue()); } std::stringstream contentStream; json::Writer::Write(data, contentStream); std::string content = contentStream.str(); char contentLength[64]; sprintf(contentLength, "%d", static_cast<int>(content.length())); connection.AddHeader("Content-Length", contentLength); connection.SetContent(content); return true; } bool HttpInterface::OnSetRecordProperty(pb::HttpConnection& connection, Uid recordId, const std::string& path, const std::string& type, const std::string& value) { std::string propertyValue; json::Object data; Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; if (type == "atom") { PropertyAtom* property = record->AcquireAtom(path); if (!property) return false; property->SetStringValue(value); } return true; } bool HttpInterface::OnSetEntityProperty(pb::HttpConnection& connection, Uid recordId, Uid entityId, const std::string& path, const std::string& type, const std::string& value) { std::string propertyValue; json::Object data; Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; Entity* entity = record->GetEntity(entityId); if (!entity) return false; if (type == "atom") { PropertyAtom* property = entity->AcquireAtom(path); if (!property) return false; property->SetStringValue(value); } return true; } bool HttpInterface::OnGetImage(pb::HttpConnection& connection, const std::string& image) { Project* project = Core::Instance()->GetProject(); const Project::ProjectConfig& config = project->GetConfig(); std::fstream file; for (std::vector<std::string>::const_iterator it = config.imageRoots.begin(); it != config.imageRoots.end(); ++it) { file.open((*it + image).c_str()); if (file.is_open()) break; } if (file.is_open()) { std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); char contentLength[64]; sprintf(contentLength, "%d", static_cast<int>(content.length())); connection.AddHeader("Content-Length", contentLength); connection.SetContent(content); return true; } return false; } <commit_msg>Fix up file handle not being closed<commit_after>#include <cstdio> #include <cstdlib> #include <fstream> #include <sstream> #include "pixelboost/data/json/writer.h" #include "pixelboost/file/fileHelpers.h" #include "command/manager.h" #include "http/commands/file.h" #include "http/commands/record.h" #include "http/commands/schema.h" #include "http/httpInterface.h" #include "project/entity.h" #include "project/project.h" #include "project/property.h" #include "project/record.h" #include "core.h" using namespace pb; using namespace pixeleditor; HttpInterface::HttpInterface() : pb::HttpServer() { } HttpInterface::~HttpInterface() { } void HttpInterface::Initialise() { _FileCommands = new FileCommands(); _SchemaCommands = new SchemaCommands(); _RecordCommands = new RecordCommands(); Start(9090, pb::FileHelpers::GetRootPath()+"/data/html/"); } void HttpInterface::RegisterCommand(const std::string& command, HttpServer::RequestType requestType, CommandDelegate delegate) { _Commands[CommandRequest(command, requestType)] = delegate; } bool HttpInterface::OnHttpRequest(HttpServer::RequestType type, const std::string& uri, const std::string& query, const std::string& data, pb::HttpConnection& connection) { ssize_t split = uri.find('/', 1); std::string command; std::string argumentString; std::string queryString = query; std::vector<std::string> urlArguments; std::map<std::string, std::string> queryArguments; if (split > 0) { command = uri.substr(1, split-1); argumentString = uri.substr(split); } else { command = uri.substr(1); } while (argumentString.length() > 1) { ssize_t split = argumentString.find('/', 1); std::string argument; if (split > 0) { argument = argumentString.substr(1, split-1); argumentString = argumentString.substr(split); } else { argument = argumentString.substr(1); argumentString = ""; } if (argument.length() > 0) urlArguments.push_back(argument); else break; } while (queryString.length() > 1) { ssize_t split = queryString.find('&', 1); std::string argument; if (split > 0) { argument = queryString.substr(0, split); queryString = queryString.substr(split+1); } else { argument = queryString.substr(0); queryString = ""; } if (argument.length() > 0) { std::string field; std::string value; int op = argument.find('='); if (op > 0) { field = argument.substr(0, op); value = argument.substr(op+1); } queryArguments[field] = value; } else break; } bool replied = false; CommandRequest request(command, type); CommandMap::iterator commandHandler = _Commands.find(request); if (commandHandler != _Commands.end()) { connection.AddHeader("Content-Type", "application/json;charset=utf-8"); replied = commandHandler->second(connection, urlArguments, queryArguments); } else { if (command == "images" && type == kRequestTypeGet) { connection.AddHeader("Content-Type", "image/png"); if (urlArguments.size() == 1) { replied = OnGetImage(connection, urlArguments[0]); } } else { connection.AddHeader("Content-Type", "application/json;charset=utf-8"); } if (command == "record" && type == kRequestTypeGet) { if (urlArguments.size() == 1) { Uid record = atoi(urlArguments[0].c_str()); replied = OnGetRecord(connection, record); } else if (urlArguments.size() >= 2 && urlArguments[1] == "property") { Uid record = atoi(urlArguments[0].c_str()); std::string path = "/"; for (int i=2; i < urlArguments.size(); i++) { path += urlArguments[i] + "/"; } replied = OnGetRecordProperty(connection, record, path); } else if (urlArguments.size() >= 4 && urlArguments[1] == "entity" && urlArguments[3] == "property") { Uid record = atoi(urlArguments[0].c_str()); Uid entity = atoi(urlArguments[2].c_str()); std::string path = "/"; for (int i=4; i < urlArguments.size(); i++) { path += urlArguments[i] + "/"; } replied = OnGetEntityProperty(connection, record, entity, path); } } else if (command == "record" && (type == kRequestTypePost || type == kRequestTypePut)) { if (urlArguments.size() >= 2 && urlArguments[1] == "property") { Uid record = atoi(urlArguments[0].c_str()); std::string type = queryArguments["type"]; std::string value = queryArguments["value"]; std::string path = "/"; for (int i=2; i < urlArguments.size(); i++) { path += urlArguments[i] + "/"; } replied = OnSetRecordProperty(connection, record, path, type, value); } else if (urlArguments.size() == 2 && urlArguments[1] == "entities" && type == kRequestTypePost) { Uid record = atoi(urlArguments[0].c_str()); replied = OnCreateEntity(connection, record, queryArguments["type"]); } else if (urlArguments.size() >= 4 && urlArguments[1] == "entity" && type == kRequestTypePut) { Uid record = atoi(urlArguments[0].c_str()); Uid entity = atoi(urlArguments[2].c_str()); if (urlArguments[3] == "transform") { replied = OnSetTransform(connection, record, entity, Vec3(atof(queryArguments["tx"].c_str()), atof(queryArguments["ty"].c_str()), atof(queryArguments["tz"].c_str())), 0, Vec3(1,1,1)); } else if (urlArguments[3] == "property") { std::string type = queryArguments["type"]; std::string value = queryArguments["value"]; std::string path = "/"; for (int i=4; i < urlArguments.size(); i++) { path += urlArguments[i] + "/"; } replied = OnSetEntityProperty(connection, record, entity, path, type, value); } } } else if (command == "records" && type == kRequestTypePost) { if (urlArguments.size() == 0) { replied = OnCreateRecord(connection, queryArguments["name"], queryArguments["type"]); } } } if (replied == true) { connection.Send(); return true; } if (type == kRequestTypeGet) return false; // No over-ride, default to finding html else return true; } bool HttpInterface::OnCreateRecord(pb::HttpConnection& connection, const std::string& name, const std::string& type) { if (name == "") return false; Project* project = Core::Instance()->GetProject(); project->AddRecord(name, type); return true; } bool HttpInterface::OnCreateEntity(pb::HttpConnection& connection, Uid recordId, const std::string& type) { char arguments[256]; sprintf(arguments, "-r %d -t %s -p 0,0", recordId, type.c_str()); Core::Instance()->GetCommandManager()->Exec("createEntity", arguments); return true; } bool HttpInterface::OnSetTransform(pb::HttpConnection& connection, Uid recordId, Uid entityId, const Vec3& position, float rotation, const Vec3& scale) { Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; Entity* entity = record->GetEntity(entityId); if (!entity) return false; entity->SetPosition(position); entity->SetRotation(rotation); entity->SetScale(scale); return true; } bool HttpInterface::OnGetRecord(pb::HttpConnection& connection, Uid recordId) { json::Object data; Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; record->ExportJson(data); std::stringstream contentStream; json::Writer::Write(data, contentStream); std::string content = contentStream.str(); char contentLength[64]; sprintf(contentLength, "%d", static_cast<int>(content.length())); connection.AddHeader("Content-Length", contentLength); connection.SetContent(content); return true; } bool HttpInterface::OnGetEntity(pb::HttpConnection& connection, Uid recordId, Uid entityId) { json::Object data; Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; Entity* entity = record->GetEntity(entityId); if (!entity) return false; entity->ExportJson(data); std::stringstream contentStream; json::Writer::Write(data, contentStream); std::string content = contentStream.str(); char contentLength[64]; sprintf(contentLength, "%d", static_cast<int>(content.length())); connection.AddHeader("Content-Length", contentLength); connection.SetContent(content); return true; } bool HttpInterface::OnGetRecordProperty(pb::HttpConnection& connection, Uid recordId, const std::string& path) { Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return true; return OnGetStructProperty(connection, record->GetProperty(path)); } bool HttpInterface::OnGetEntityProperty(pb::HttpConnection& connection, Uid recordId, Uid entityId, const std::string& path) { Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return true; Entity* entity = record->GetEntity(entityId); if (!entity) return true; return OnGetStructProperty(connection, entity->GetProperty(path)); } bool HttpInterface::OnGetStructProperty(pb::HttpConnection& connection, const Property* property) { json::Object data; if (!property) return true; if (property->GetType() == Property::kPropertyAtom) { data["type"] = json::String("atom"); data["value"] = json::String(static_cast<const PropertyAtom*>(property)->GetStringValue()); } std::stringstream contentStream; json::Writer::Write(data, contentStream); std::string content = contentStream.str(); char contentLength[64]; sprintf(contentLength, "%d", static_cast<int>(content.length())); connection.AddHeader("Content-Length", contentLength); connection.SetContent(content); return true; } bool HttpInterface::OnSetRecordProperty(pb::HttpConnection& connection, Uid recordId, const std::string& path, const std::string& type, const std::string& value) { std::string propertyValue; json::Object data; Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; if (type == "atom") { PropertyAtom* property = record->AcquireAtom(path); if (!property) return false; property->SetStringValue(value); } return true; } bool HttpInterface::OnSetEntityProperty(pb::HttpConnection& connection, Uid recordId, Uid entityId, const std::string& path, const std::string& type, const std::string& value) { std::string propertyValue; json::Object data; Project* project = Core::Instance()->GetProject(); Record* record = project->GetRecord(recordId); if (!record) return false; Entity* entity = record->GetEntity(entityId); if (!entity) return false; if (type == "atom") { PropertyAtom* property = entity->AcquireAtom(path); if (!property) return false; property->SetStringValue(value); } return true; } bool HttpInterface::OnGetImage(pb::HttpConnection& connection, const std::string& image) { Project* project = Core::Instance()->GetProject(); const Project::ProjectConfig& config = project->GetConfig(); std::fstream file; for (std::vector<std::string>::const_iterator it = config.imageRoots.begin(); it != config.imageRoots.end(); ++it) { file.open((*it + image).c_str()); if (file.is_open()) break; } if (file.is_open()) { std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); char contentLength[64]; sprintf(contentLength, "%d", static_cast<int>(content.length())); connection.AddHeader("Content-Length", contentLength); connection.SetContent(content); file.close(); return true; } return false; } <|endoftext|>
<commit_before>/* * W.J. van der Laan 2011-2012 */ #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTimer> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal), Q_ARG(unsigned int, style)); } else { LogPrintf("%s: %s\n", caption, message); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63)); QApplication::instance()->processEvents(); } LogPrintf("init message: %s\n", message); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Clam can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } /* qDebug() message handler --> debug.log */ #if QT_VERSION < 0x050000 void DebugMessageHandler(QtMsgType type, const char * msg) { const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg); } #else void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg) { const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", QString::toStdString(msg)); } #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { fHaveGUI = true; // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Install qDebug() message handler to route to debug.log #if QT_VERSION < 0x050000 qInstallMsgHandler(DebugMessageHandler); #else qInstallMessageHandler(DebugMessageHandler); #endif // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Clam", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Clam"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Clam-Qt-testnet"); else app.setApplicationName("Clam-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). paymentServer->setOptionsModel(&optionsModel); if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <commit_msg>Fix the Qt5 build after d95ba75<commit_after>/* * W.J. van der Laan 2011-2012 */ #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTimer> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal), Q_ARG(unsigned int, style)); } else { LogPrintf("%s: %s\n", caption, message); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63)); QApplication::instance()->processEvents(); } LogPrintf("init message: %s\n", message); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Clam can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } /* qDebug() message handler --> debug.log */ #if QT_VERSION < 0x050000 void DebugMessageHandler(QtMsgType type, const char * msg) { const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg); } #else void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg) { const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg.toStdString()); } #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { fHaveGUI = true; // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Install qDebug() message handler to route to debug.log #if QT_VERSION < 0x050000 qInstallMsgHandler(DebugMessageHandler); #else qInstallMessageHandler(DebugMessageHandler); #endif // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Clam", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Clam"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Clam-Qt-testnet"); else app.setApplicationName("Clam-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). paymentServer->setOptionsModel(&optionsModel); if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <|endoftext|>
<commit_before>// // nthRoot.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "nthRoot.h" nthRoot::nthRoot(int root, int operand, int coefficient) { this->type = "nthRoot"; this->operand = operand; this->root = root; this->coefficient = coefficient; } nthRoot::~nthRoot() { } int* nthRoot::primeFactorization(int n) { int k = 0; while (n%2 == 0) { factors[k] = 2; k++; n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { while (n%1 == 0) { factors[k] = 2; k++; n = n/i; } } if (n > 2) { factors[k] = n; } return factors; // added bonus: factors should be sorted already } Expression* nthRoot::simplify(){ //if coefficient == 0 then return 0? int* factorsArray = primeFactorization(operand); int i = 0; while (i <= factors.size()) { int j = i; int count = 0; while (j <= factors.size() && factors[j + 1] == factors[j]) { count++; j++; } if (count >= root) { coefficient *= (factors[i] ^ (count/root)); operand = operand / (factors[i] ^ (count - (count % root))); } i = j + 1; } if (operand == 1) { Integer newInt = new Integer(coefficient); return newInt; } else { Expression* newRoot = new nthRoot(root, operand, coefficient); delete this; //is this necessary? return newRoot; } } Expression* nthRoot::add(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot && operand == asOperand) { int newCoefficient = asCoefficient + coefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); return newNthRoot; } else { return this; } } Expression* nthRoot::subtract(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot && operand == asOperand) { int newCoefficient = coefficient - asCoefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); return newNthRoot; } else { return this; } } Expression* nthRoot::multiply(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot) { int newCoefficient = asCoefficient * coefficient; int newOperand = operand * asOperand; //asOperand doesnt exist? nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplified Version; } else { return this; } } Expression* nthRoot::divide(Expression* a) { nthRoot *b = (nthRoot *)a; int asRoot = b->getRoot(); int asOperand = b->getOperand(); int asCoefficient = b->getCoefficient(); if (root == asRoot) { int newCoefficient = coefficient / asCoefficient; int newOperand = operand / asOperand; nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else { return this; } } int nthRoot::getRoot() { return root; } int nthRoot::getOperand() { return operand; } int nthRoot::getCoefficient() { return coefficient; } void nthRoot::setCoefficient(int n) { this->coefficient = n; } void nthRoot::setOperand(int n) { this->operand = n; } void nthRoot::setRoot(int n) { this->root = n; } ostream& nthRoot::print(std::ostream& output) const { output << this->coefficient << "*" << this->root << "rt:" << this->operand; return output; } string nthRoot::toString() { stringstream s; s << coefficient << "*" << root << "rt:" << operand; return s.str(); } <commit_msg>syntax fixes<commit_after>// // nthRoot.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "nthRoot.h" nthRoot::nthRoot(int root, int operand, int coefficient) { this->type = "nthRoot"; this->operand = operand; this->root = root; this->coefficient = coefficient; } nthRoot::~nthRoot() { } int* nthRoot::primeFactorization(int n) { int k = 0; while (n%2 == 0) { factors[k] = 2; k++; n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { while (n%1 == 0) { factors[k] = 2; k++; n = n/i; } } if (n > 2) { factors[k] = n; } return factors; // added bonus: factors should be sorted already } Expression* nthRoot::simplify(){ //if coefficient == 0 then return 0? // int* factorsArray = primeFactorization(operand); int i = 0; int factorsSize = sizeof(factors)/sizeof(factors[0]); while (i <= factorsSize) { int j = i; int count = 0; while (j <= factorsSize && factors[j + 1] == factors[j]) { count++; j++; } if (count >= root) { coefficient *= (factors[i] ^ (count/root)); operand = operand / (factors[i] ^ (count - (count % root))); } i = j + 1; } if (operand == 1) { Integer* newInt = new Integer(coefficient); return newInt; } else { Expression* newRoot = new nthRoot(root, operand, coefficient); delete this; //is this necessary? return newRoot; } } Expression* nthRoot::add(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot && operand == asOperand) { int newCoefficient = asCoefficient + coefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); return newNthRoot; } else { return this; } } Expression* nthRoot::subtract(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot && operand == asOperand) { int newCoefficient = coefficient - asCoefficient; nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient); return newNthRoot; } else { return this; } } Expression* nthRoot::multiply(Expression* a) { nthRoot *b = (nthRoot *)a; int asCoefficient = b->getCoefficient(); int asOperand = b->getOperand(); int asRoot = b->getRoot(); if (root == asRoot) { int newCoefficient = asCoefficient * coefficient; int newOperand = operand * asOperand; //asOperand doesnt exist? nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else { return this; } } Expression* nthRoot::divide(Expression* a) { nthRoot *b = (nthRoot *)a; int asRoot = b->getRoot(); int asOperand = b->getOperand(); int asCoefficient = b->getCoefficient(); if (root == asRoot) { int newCoefficient = coefficient / asCoefficient; int newOperand = operand / asOperand; nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient); nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify(); return simplifiedVersion; } else { return this; } } int nthRoot::getRoot() { return root; } int nthRoot::getOperand() { return operand; } int nthRoot::getCoefficient() { return coefficient; } void nthRoot::setCoefficient(int n) { this->coefficient = n; } void nthRoot::setOperand(int n) { this->operand = n; } void nthRoot::setRoot(int n) { this->root = n; } ostream& nthRoot::print(std::ostream& output) const { output << this->coefficient << "*" << this->root << "rt:" << this->operand; return output; } string nthRoot::toString() { stringstream s; s << coefficient << "*" << root << "rt:" << operand; return s.str(); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //misc #define _USE_MATH_DEFINES #include <math.h> // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "QmitkDiffusionRegistrationView.h" // MITK #include <mitkImageCast.h> #include <mitkImageToItk.h> #include <mitkImageAccessByItk.h> #include <mitkProgressBar.h> #include <mitkIOUtil.h> #include <mitkDiffusionPropertyHelper.h> // Qt #include <QMessageBox> #include <QFileDialog> #include <QDir> #include <QDirIterator> #include <QTimer> #include <mitkDWIHeadMotionCorrectionFilter.h> #define _USE_MATH_DEFINES #include <math.h> QmitkRegistrationWorker::QmitkRegistrationWorker(QmitkDiffusionRegistrationView* view) : m_View(view) { } void QmitkRegistrationWorker::run() { typedef mitk::DiffusionPropertyHelper::BValueMapType BValueMap; unsigned int totalImagesCount; if( !m_View->m_IsBatch ) { totalImagesCount = m_View->m_SelectedDiffusionNodes.size(); } else { totalImagesCount = m_View->m_BatchList.size(); } m_View->m_TotalFiles = totalImagesCount; QString inputPath = m_View->m_Controls->m_InputFolderTextbox->text(); QString outputPath = m_View->m_Controls->m_OutputFolderTextbox->text(); for(unsigned int i=0; i< totalImagesCount; i++) { if(m_View->m_IsAborted){ m_View->m_RegistrationThread.quit(); return; } m_View->m_CurrentFile = i+1; m_View->m_GlobalRegisterer = QmitkDiffusionRegistrationView::DWIHeadMotionCorrectionFilterType::New(); //mitk::DataNode::Pointer node = m_View->m_SelectedDiffusionNodes.at(i); mitk::Image::Pointer inImage; mitk::DataNode::Pointer node; if( !m_View->m_IsBatch ) { node = m_View->m_SelectedDiffusionNodes.at(i); inImage = dynamic_cast<mitk::Image*>(node->GetData()); } else { mitk::Image::Pointer inImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::Load( m_View->m_BatchList.at(i).toStdString() )[0].GetPointer()); mitk::GradientDirectionsProperty::Pointer gradDir = static_cast<mitk::GradientDirectionsProperty*>(inImage->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer()); } bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( inImage ) ); if(!isDiffusionImage) { MITK_ERROR << "Error occured: can't get input image. \nAborting"; return; } m_View->m_GlobalRegisterer->SetInput(inImage); try { m_View->m_GlobalRegisterer->Update(); } catch( mitk::Exception e ) { MITK_ERROR << "Internal error occured: " << e.what() << "\nAborting"; } if( m_View->m_GlobalRegisterer->GetIsInValidState() ) { if(! m_View->m_IsBatch) { mitk::Image::Pointer image = m_View->m_GlobalRegisterer->GetOutput(); mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); imageNode->SetData( image ); QString name = node->GetName().c_str(); imageNode->SetName((name+"_MC").toStdString().c_str()); m_View->GetDataStorage()->Add(imageNode); } else { QString name = m_View->m_BatchList.at(i); name = name.replace(".dwi", "_MC.dwi", Qt::CaseInsensitive); name = name.replace(inputPath, outputPath, Qt::CaseInsensitive); try { mitk::IOUtil::Save(m_View->m_GlobalRegisterer->GetOutput(), name.toStdString().c_str()); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "Catched exception: " << e.what(); mitkThrow() << "Failed with exception from subprocess!"; } } } } m_View->m_RegistrationThread.quit(); } const std::string QmitkDiffusionRegistrationView::VIEW_ID = "org.mitk.views.diffusionregistrationview"; QmitkDiffusionRegistrationView::QmitkDiffusionRegistrationView() : QmitkAbstractView() , m_Controls( 0 ) , m_DiffusionImage( nullptr ) , m_ThreadIsRunning(false) , m_Steps(100) , m_LastStep(0) , m_GlobalRegisterer(nullptr) , m_RegistrationWorker(this) { m_RegistrationWorker.moveToThread(&m_RegistrationThread); connect(&m_RegistrationThread, SIGNAL(started()), this, SLOT(BeforeThread())); connect(&m_RegistrationThread, SIGNAL(started()), &m_RegistrationWorker, SLOT(run())); connect(&m_RegistrationThread, SIGNAL(finished()), this, SLOT(AfterThread())); connect(&m_RegistrationThread, SIGNAL(terminated()), this, SLOT(AfterThread())); m_RegistrationTimer = new QTimer(this); } // Destructor QmitkDiffusionRegistrationView::~QmitkDiffusionRegistrationView() { delete m_RegistrationTimer; } // update Registration status and generate fiber bundle void QmitkDiffusionRegistrationView::TimerUpdate() { int currentStep = m_GlobalRegisterer->GetCurrentStep(); mitk::ProgressBar::GetInstance()->Progress(currentStep-m_LastStep); UpdateRegistrationStatus(); m_LastStep = currentStep; } // update gui elements after registration is finished void QmitkDiffusionRegistrationView::AfterThread() { m_ThreadIsRunning = false; m_RegistrationTimer->stop(); mitk::ProgressBar::GetInstance()->Progress(m_GlobalRegisterer->GetSteps()-m_LastStep+1); UpdateGUI(); if( !m_GlobalRegisterer->GetIsInValidState() ) { QMessageBox::critical( nullptr, "Registration", "An internal error occured, or user canceled the Registration.\n Please check the log for details." ); return; } UpdateRegistrationStatus(); m_GlobalRegisterer = 0; } // start Registration timer and update gui elements before Registration is started void QmitkDiffusionRegistrationView::BeforeThread() { m_ThreadIsRunning = true; m_RegistrationTime = QTime::currentTime(); m_ElapsedTime = 0; m_RegistrationTimer->start(1000); m_LastStep = 0; UpdateGUI(); } void QmitkDiffusionRegistrationView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkDiffusionRegistrationViewControls; m_Controls->setupUi( parent ); AdvancedSettings(); connect( m_RegistrationTimer, SIGNAL(timeout()), this, SLOT(TimerUpdate()) ); connect( m_Controls->m_RegistrationStopButton, SIGNAL(clicked()), this, SLOT(StopRegistration()) ); connect( m_Controls->m_RegistrationStartButton, SIGNAL(clicked()), this, SLOT(StartRegistration()) ); connect( m_Controls->m_AdvancedSettingsCheckbox, SIGNAL(clicked()), this, SLOT(AdvancedSettings()) ); connect( m_Controls->m_SelectInputButton, SIGNAL(clicked()), this, SLOT(AddInputFolderName()) ); connect( m_Controls->m_SelectOutputButton, SIGNAL(clicked()), this, SLOT(AddOutputFolderName()) ); connect( m_Controls->m_StartBatchButton, SIGNAL(clicked()), this, SLOT(StartBatch()) ); this->m_Parent = parent; } } // show/hide advanced settings frame void QmitkDiffusionRegistrationView::AdvancedSettings() { m_Controls->m_AdvancedFrame->setVisible(m_Controls->m_AdvancedSettingsCheckbox->isChecked()); } void QmitkDiffusionRegistrationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& nodes) { if (m_ThreadIsRunning) return; bool foundDwiVolume = false; QString tempSelectedNames = ""; m_DiffusionImage = nullptr; m_SelectedDiffusionNodes.clear(); // iterate selection for (mitk::DataNode::Pointer node: nodes) { bool isDiffusionImage(false); if( node.IsNotNull() ) { isDiffusionImage = mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast<mitk::Image *>(node->GetData())); } if( isDiffusionImage ) { foundDwiVolume = true; m_SelectedDiffusionNodes.push_back(node); if(m_SelectedDiffusionNodes.size() > 0){tempSelectedNames += "\n";} tempSelectedNames += (node->GetName().c_str()); } } m_Controls->m_RegistrationStartButton->setEnabled(foundDwiVolume); if (foundDwiVolume) { m_Controls->m_DiffusionImageLabel->setText(tempSelectedNames); m_Controls->m_InputData->setTitle("Input Data"); } else { m_Controls->m_DiffusionImageLabel->setText("<font color='red'>mandatory</font>"); m_Controls->m_InputData->setTitle("Please Select Input Data"); } UpdateGUI(); } // update gui elements displaying Registrations status void QmitkDiffusionRegistrationView::UpdateRegistrationStatus() { if (m_GlobalRegisterer.IsNull()) return; m_ElapsedTime += m_RegistrationTime.elapsed()/1000; m_RegistrationTime.restart(); unsigned long hours = m_ElapsedTime/3600; unsigned long minutes = (m_ElapsedTime%3600)/60; unsigned long seconds = m_ElapsedTime%60; m_Controls->m_RegistrationTimeLabel->setText( QString::number(hours)+QString("h ")+QString::number(minutes)+QString("m ")+QString::number(seconds)+QString("s") ); m_Controls->m_CurrentStepLabel->setText( QString::number((int)(100*(float)(m_GlobalRegisterer->GetCurrentStep()-1)/m_GlobalRegisterer->GetSteps()))+"%" ); m_Controls->m_CurrentFileLabel->setText( QString::number(m_CurrentFile)+" / "+QString::number(m_TotalFiles) ); } void QmitkDiffusionRegistrationView::UpdateGUI() { if (!m_ThreadIsRunning && (m_SelectedDiffusionNodes.size() > 0) ) { m_Controls->m_RegistrationStopButton->setEnabled(false); m_Controls->m_RegistrationStartButton->setEnabled(true); m_Controls->m_StartBatchButton->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_RegistrationStopButton->setText("Stop"); m_Controls->m_RegistrationStartButton->setToolTip("Start Registration"); m_Controls->m_RegistrationStopButton->setToolTip(""); } else if (!m_ThreadIsRunning) { m_Controls->m_RegistrationStopButton->setEnabled(false); m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_RegistrationStopButton->setText("Stop"); m_Controls->m_RegistrationStartButton->setToolTip("No Diffusion image selected."); m_Controls->m_RegistrationStopButton->setToolTip(""); } else { m_Controls->m_RegistrationStopButton->setEnabled(true); m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(false); m_Controls->m_AdvancedFrame->setEnabled(false); m_Controls->m_RegistrationStartButton->setToolTip("Registration in progress."); m_Controls->m_RegistrationStopButton->setToolTip("Cancel Registration"); } } void QmitkDiffusionRegistrationView::SetFocus() { m_Controls->m_RegistrationStartButton->setFocus(); } void QmitkDiffusionRegistrationView::StartRegistration() { if(m_ThreadIsRunning) { MITK_WARN("QmitkDiffusionRegistrationView")<<"Thread already running!"; return; } m_GlobalRegisterer = nullptr; if (m_SelectedDiffusionNodes.size()<1) { QMessageBox::information( nullptr, "Warning", "Please load and select a diffusion image before starting image processing."); return; } m_IsBatch = false; m_IsAborted = false; m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(false); // start worker thread m_RegistrationThread.start(QThread::NormalPriority); return; } void QmitkDiffusionRegistrationView::StopRegistration() { if (m_GlobalRegisterer.IsNull()) return; m_IsAborted = true; m_GlobalRegisterer->SetAbortRegistration(true); m_Controls->m_RegistrationStopButton->setEnabled(false); m_Controls->m_RegistrationStopButton->setText("Stopping ..."); return; } void QmitkDiffusionRegistrationView::AddInputFolderName() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( m_Parent, QString("Select the input folder with DWI files within") ); w->setFileMode( QFileDialog::Directory ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; m_Controls->m_InputFolderTextbox->setText(w->selectedFiles()[0]); } void QmitkDiffusionRegistrationView::AddOutputFolderName() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( m_Parent, QString("Select the output folder") ); w->setFileMode( QFileDialog::Directory ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; m_Controls->m_OutputFolderTextbox->setText(w->selectedFiles()[0]); } void QmitkDiffusionRegistrationView::StartBatch() { QString inputPath = m_Controls->m_InputFolderTextbox->text(); QString outputPath = m_Controls->m_OutputFolderTextbox->text(); if(inputPath == outputPath){ QMessageBox::information( nullptr, "Error", "Input and Output folders can't be the same"); return; } QStringList list, filters; filters<<"*.dwi"; QDirIterator dirIterator(inputPath, filters, QDir::Files|QDir::NoSymLinks); while (dirIterator.hasNext()) { dirIterator.next(); list.append(dirIterator.fileInfo().absoluteFilePath()); std::cout << dirIterator.fileInfo().absoluteFilePath().toStdString() << endl; m_BatchList = list; m_IsBatch = true; m_IsAborted = false; if(m_ThreadIsRunning) { MITK_WARN("QmitkDiffusionRegistrationView")<<"Thread already running!"; return; } m_GlobalRegisterer = nullptr; if (m_BatchList.size()<1) { QMessageBox::information( nullptr, "Error", "No diffusion images were found in the selected input folder."); return; } m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(false); // start worker thread m_RegistrationThread.start(QThread::NormalPriority); } } <commit_msg>Add missing std namespace to endl<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //misc #define _USE_MATH_DEFINES #include <math.h> // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "QmitkDiffusionRegistrationView.h" // MITK #include <mitkImageCast.h> #include <mitkImageToItk.h> #include <mitkImageAccessByItk.h> #include <mitkProgressBar.h> #include <mitkIOUtil.h> #include <mitkDiffusionPropertyHelper.h> // Qt #include <QMessageBox> #include <QFileDialog> #include <QDir> #include <QDirIterator> #include <QTimer> #include <mitkDWIHeadMotionCorrectionFilter.h> #define _USE_MATH_DEFINES #include <math.h> QmitkRegistrationWorker::QmitkRegistrationWorker(QmitkDiffusionRegistrationView* view) : m_View(view) { } void QmitkRegistrationWorker::run() { typedef mitk::DiffusionPropertyHelper::BValueMapType BValueMap; unsigned int totalImagesCount; if( !m_View->m_IsBatch ) { totalImagesCount = m_View->m_SelectedDiffusionNodes.size(); } else { totalImagesCount = m_View->m_BatchList.size(); } m_View->m_TotalFiles = totalImagesCount; QString inputPath = m_View->m_Controls->m_InputFolderTextbox->text(); QString outputPath = m_View->m_Controls->m_OutputFolderTextbox->text(); for(unsigned int i=0; i< totalImagesCount; i++) { if(m_View->m_IsAborted){ m_View->m_RegistrationThread.quit(); return; } m_View->m_CurrentFile = i+1; m_View->m_GlobalRegisterer = QmitkDiffusionRegistrationView::DWIHeadMotionCorrectionFilterType::New(); //mitk::DataNode::Pointer node = m_View->m_SelectedDiffusionNodes.at(i); mitk::Image::Pointer inImage; mitk::DataNode::Pointer node; if( !m_View->m_IsBatch ) { node = m_View->m_SelectedDiffusionNodes.at(i); inImage = dynamic_cast<mitk::Image*>(node->GetData()); } else { mitk::Image::Pointer inImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::Load( m_View->m_BatchList.at(i).toStdString() )[0].GetPointer()); mitk::GradientDirectionsProperty::Pointer gradDir = static_cast<mitk::GradientDirectionsProperty*>(inImage->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer()); } bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( inImage ) ); if(!isDiffusionImage) { MITK_ERROR << "Error occured: can't get input image. \nAborting"; return; } m_View->m_GlobalRegisterer->SetInput(inImage); try { m_View->m_GlobalRegisterer->Update(); } catch( mitk::Exception e ) { MITK_ERROR << "Internal error occured: " << e.what() << "\nAborting"; } if( m_View->m_GlobalRegisterer->GetIsInValidState() ) { if(! m_View->m_IsBatch) { mitk::Image::Pointer image = m_View->m_GlobalRegisterer->GetOutput(); mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); imageNode->SetData( image ); QString name = node->GetName().c_str(); imageNode->SetName((name+"_MC").toStdString().c_str()); m_View->GetDataStorage()->Add(imageNode); } else { QString name = m_View->m_BatchList.at(i); name = name.replace(".dwi", "_MC.dwi", Qt::CaseInsensitive); name = name.replace(inputPath, outputPath, Qt::CaseInsensitive); try { mitk::IOUtil::Save(m_View->m_GlobalRegisterer->GetOutput(), name.toStdString().c_str()); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "Catched exception: " << e.what(); mitkThrow() << "Failed with exception from subprocess!"; } } } } m_View->m_RegistrationThread.quit(); } const std::string QmitkDiffusionRegistrationView::VIEW_ID = "org.mitk.views.diffusionregistrationview"; QmitkDiffusionRegistrationView::QmitkDiffusionRegistrationView() : QmitkAbstractView() , m_Controls( 0 ) , m_DiffusionImage( nullptr ) , m_ThreadIsRunning(false) , m_Steps(100) , m_LastStep(0) , m_GlobalRegisterer(nullptr) , m_RegistrationWorker(this) { m_RegistrationWorker.moveToThread(&m_RegistrationThread); connect(&m_RegistrationThread, SIGNAL(started()), this, SLOT(BeforeThread())); connect(&m_RegistrationThread, SIGNAL(started()), &m_RegistrationWorker, SLOT(run())); connect(&m_RegistrationThread, SIGNAL(finished()), this, SLOT(AfterThread())); connect(&m_RegistrationThread, SIGNAL(terminated()), this, SLOT(AfterThread())); m_RegistrationTimer = new QTimer(this); } // Destructor QmitkDiffusionRegistrationView::~QmitkDiffusionRegistrationView() { delete m_RegistrationTimer; } // update Registration status and generate fiber bundle void QmitkDiffusionRegistrationView::TimerUpdate() { int currentStep = m_GlobalRegisterer->GetCurrentStep(); mitk::ProgressBar::GetInstance()->Progress(currentStep-m_LastStep); UpdateRegistrationStatus(); m_LastStep = currentStep; } // update gui elements after registration is finished void QmitkDiffusionRegistrationView::AfterThread() { m_ThreadIsRunning = false; m_RegistrationTimer->stop(); mitk::ProgressBar::GetInstance()->Progress(m_GlobalRegisterer->GetSteps()-m_LastStep+1); UpdateGUI(); if( !m_GlobalRegisterer->GetIsInValidState() ) { QMessageBox::critical( nullptr, "Registration", "An internal error occured, or user canceled the Registration.\n Please check the log for details." ); return; } UpdateRegistrationStatus(); m_GlobalRegisterer = 0; } // start Registration timer and update gui elements before Registration is started void QmitkDiffusionRegistrationView::BeforeThread() { m_ThreadIsRunning = true; m_RegistrationTime = QTime::currentTime(); m_ElapsedTime = 0; m_RegistrationTimer->start(1000); m_LastStep = 0; UpdateGUI(); } void QmitkDiffusionRegistrationView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkDiffusionRegistrationViewControls; m_Controls->setupUi( parent ); AdvancedSettings(); connect( m_RegistrationTimer, SIGNAL(timeout()), this, SLOT(TimerUpdate()) ); connect( m_Controls->m_RegistrationStopButton, SIGNAL(clicked()), this, SLOT(StopRegistration()) ); connect( m_Controls->m_RegistrationStartButton, SIGNAL(clicked()), this, SLOT(StartRegistration()) ); connect( m_Controls->m_AdvancedSettingsCheckbox, SIGNAL(clicked()), this, SLOT(AdvancedSettings()) ); connect( m_Controls->m_SelectInputButton, SIGNAL(clicked()), this, SLOT(AddInputFolderName()) ); connect( m_Controls->m_SelectOutputButton, SIGNAL(clicked()), this, SLOT(AddOutputFolderName()) ); connect( m_Controls->m_StartBatchButton, SIGNAL(clicked()), this, SLOT(StartBatch()) ); this->m_Parent = parent; } } // show/hide advanced settings frame void QmitkDiffusionRegistrationView::AdvancedSettings() { m_Controls->m_AdvancedFrame->setVisible(m_Controls->m_AdvancedSettingsCheckbox->isChecked()); } void QmitkDiffusionRegistrationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& nodes) { if (m_ThreadIsRunning) return; bool foundDwiVolume = false; QString tempSelectedNames = ""; m_DiffusionImage = nullptr; m_SelectedDiffusionNodes.clear(); // iterate selection for (mitk::DataNode::Pointer node: nodes) { bool isDiffusionImage(false); if( node.IsNotNull() ) { isDiffusionImage = mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast<mitk::Image *>(node->GetData())); } if( isDiffusionImage ) { foundDwiVolume = true; m_SelectedDiffusionNodes.push_back(node); if(m_SelectedDiffusionNodes.size() > 0){tempSelectedNames += "\n";} tempSelectedNames += (node->GetName().c_str()); } } m_Controls->m_RegistrationStartButton->setEnabled(foundDwiVolume); if (foundDwiVolume) { m_Controls->m_DiffusionImageLabel->setText(tempSelectedNames); m_Controls->m_InputData->setTitle("Input Data"); } else { m_Controls->m_DiffusionImageLabel->setText("<font color='red'>mandatory</font>"); m_Controls->m_InputData->setTitle("Please Select Input Data"); } UpdateGUI(); } // update gui elements displaying Registrations status void QmitkDiffusionRegistrationView::UpdateRegistrationStatus() { if (m_GlobalRegisterer.IsNull()) return; m_ElapsedTime += m_RegistrationTime.elapsed()/1000; m_RegistrationTime.restart(); unsigned long hours = m_ElapsedTime/3600; unsigned long minutes = (m_ElapsedTime%3600)/60; unsigned long seconds = m_ElapsedTime%60; m_Controls->m_RegistrationTimeLabel->setText( QString::number(hours)+QString("h ")+QString::number(minutes)+QString("m ")+QString::number(seconds)+QString("s") ); m_Controls->m_CurrentStepLabel->setText( QString::number((int)(100*(float)(m_GlobalRegisterer->GetCurrentStep()-1)/m_GlobalRegisterer->GetSteps()))+"%" ); m_Controls->m_CurrentFileLabel->setText( QString::number(m_CurrentFile)+" / "+QString::number(m_TotalFiles) ); } void QmitkDiffusionRegistrationView::UpdateGUI() { if (!m_ThreadIsRunning && (m_SelectedDiffusionNodes.size() > 0) ) { m_Controls->m_RegistrationStopButton->setEnabled(false); m_Controls->m_RegistrationStartButton->setEnabled(true); m_Controls->m_StartBatchButton->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_RegistrationStopButton->setText("Stop"); m_Controls->m_RegistrationStartButton->setToolTip("Start Registration"); m_Controls->m_RegistrationStopButton->setToolTip(""); } else if (!m_ThreadIsRunning) { m_Controls->m_RegistrationStopButton->setEnabled(false); m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_RegistrationStopButton->setText("Stop"); m_Controls->m_RegistrationStartButton->setToolTip("No Diffusion image selected."); m_Controls->m_RegistrationStopButton->setToolTip(""); } else { m_Controls->m_RegistrationStopButton->setEnabled(true); m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(false); m_Controls->m_AdvancedFrame->setEnabled(false); m_Controls->m_RegistrationStartButton->setToolTip("Registration in progress."); m_Controls->m_RegistrationStopButton->setToolTip("Cancel Registration"); } } void QmitkDiffusionRegistrationView::SetFocus() { m_Controls->m_RegistrationStartButton->setFocus(); } void QmitkDiffusionRegistrationView::StartRegistration() { if(m_ThreadIsRunning) { MITK_WARN("QmitkDiffusionRegistrationView")<<"Thread already running!"; return; } m_GlobalRegisterer = nullptr; if (m_SelectedDiffusionNodes.size()<1) { QMessageBox::information( nullptr, "Warning", "Please load and select a diffusion image before starting image processing."); return; } m_IsBatch = false; m_IsAborted = false; m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(false); // start worker thread m_RegistrationThread.start(QThread::NormalPriority); return; } void QmitkDiffusionRegistrationView::StopRegistration() { if (m_GlobalRegisterer.IsNull()) return; m_IsAborted = true; m_GlobalRegisterer->SetAbortRegistration(true); m_Controls->m_RegistrationStopButton->setEnabled(false); m_Controls->m_RegistrationStopButton->setText("Stopping ..."); return; } void QmitkDiffusionRegistrationView::AddInputFolderName() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( m_Parent, QString("Select the input folder with DWI files within") ); w->setFileMode( QFileDialog::Directory ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; m_Controls->m_InputFolderTextbox->setText(w->selectedFiles()[0]); } void QmitkDiffusionRegistrationView::AddOutputFolderName() { // SELECT FOLDER DIALOG QFileDialog* w = new QFileDialog( m_Parent, QString("Select the output folder") ); w->setFileMode( QFileDialog::Directory ); // RETRIEVE SELECTION if ( w->exec() != QDialog::Accepted ) return; m_Controls->m_OutputFolderTextbox->setText(w->selectedFiles()[0]); } void QmitkDiffusionRegistrationView::StartBatch() { QString inputPath = m_Controls->m_InputFolderTextbox->text(); QString outputPath = m_Controls->m_OutputFolderTextbox->text(); if(inputPath == outputPath){ QMessageBox::information( nullptr, "Error", "Input and Output folders can't be the same"); return; } QStringList list, filters; filters<<"*.dwi"; QDirIterator dirIterator(inputPath, filters, QDir::Files|QDir::NoSymLinks); while (dirIterator.hasNext()) { dirIterator.next(); list.append(dirIterator.fileInfo().absoluteFilePath()); std::cout << dirIterator.fileInfo().absoluteFilePath().toStdString() << std::endl; m_BatchList = list; m_IsBatch = true; m_IsAborted = false; if(m_ThreadIsRunning) { MITK_WARN("QmitkDiffusionRegistrationView")<<"Thread already running!"; return; } m_GlobalRegisterer = nullptr; if (m_BatchList.size()<1) { QMessageBox::information( nullptr, "Error", "No diffusion images were found in the selected input folder."); return; } m_Controls->m_RegistrationStartButton->setEnabled(false); m_Controls->m_StartBatchButton->setEnabled(false); // start worker thread m_RegistrationThread.start(QThread::NormalPriority); } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/accelerated_surface_container_manager_mac.h" #include "base/logging.h" #include "chrome/browser/renderer_host/accelerated_surface_container_mac.h" #include "webkit/glue/plugins/webplugin.h" AcceleratedSurfaceContainerManagerMac::AcceleratedSurfaceContainerManagerMac() : current_id_(0) { } gfx::PluginWindowHandle AcceleratedSurfaceContainerManagerMac::AllocateFakePluginWindowHandle( bool opaque) { AcceleratedSurfaceContainerMac* container = new AcceleratedSurfaceContainerMac(this, opaque); gfx::PluginWindowHandle res = static_cast<gfx::PluginWindowHandle>(++current_id_); plugin_window_to_container_map_.insert(std::make_pair(res, container)); return res; } void AcceleratedSurfaceContainerManagerMac::DestroyFakePluginWindowHandle( gfx::PluginWindowHandle id) { AcceleratedSurfaceContainerMac* container = MapIDToContainer(id); if (container) delete container; plugin_window_to_container_map_.erase(id); } void AcceleratedSurfaceContainerManagerMac::SetSizeAndIOSurface( gfx::PluginWindowHandle id, int32 width, int32 height, uint64 io_surface_identifier) { AcceleratedSurfaceContainerMac* container = MapIDToContainer(id); if (container) container->SetSizeAndIOSurface(width, height, io_surface_identifier); } void AcceleratedSurfaceContainerManagerMac::SetSizeAndTransportDIB( gfx::PluginWindowHandle id, int32 width, int32 height, TransportDIB::Handle transport_dib) { AcceleratedSurfaceContainerMac* container = MapIDToContainer(id); if (container) container->SetSizeAndTransportDIB(width, height, transport_dib); } void AcceleratedSurfaceContainerManagerMac::MovePluginContainer( const webkit_glue::WebPluginGeometry& move) { AcceleratedSurfaceContainerMac* container = MapIDToContainer(move.window); if (container) container->MoveTo(move); } void AcceleratedSurfaceContainerManagerMac::Draw(CGLContextObj context) { // Clean up old texture objects. This is essentially a pre-emptive // cleanup, as the resources will be released when the OpenGL // context associated with the CAOpenGLLayer is destroyed. However, // if we render many plugins in the same layer, we should try to // eagerly reclaim their resources. Note also that the OpenGL // context must be current when performing the deletion, and it // seems risky to make the OpenGL context current at an arbitrary // point in time, which is why the deletion does not occur in the // container's destructor. for (std::vector<GLuint>::iterator iter = textures_pending_deletion_.begin(); iter != textures_pending_deletion_.end(); ++iter) { GLuint texture = *iter; glDeleteTextures(1, &texture); } textures_pending_deletion_.clear(); glColorMask(true, true, true, true); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); GLenum target = GL_TEXTURE_RECTANGLE_ARB; glTexEnvi(target, GL_TEXTURE_ENV_MODE, GL_REPLACE); for (PluginWindowToContainerMap::const_iterator i = plugin_window_to_container_map_.begin(); i != plugin_window_to_container_map_.end(); ++i) { AcceleratedSurfaceContainerMac* container = i->second; container->Draw(context); } // Unbind any texture from the texture target to ensure that the // next time through we will have to re-bind the texture and thereby // pick up modifications from the other process. glBindTexture(target, 0); glFlush(); } void AcceleratedSurfaceContainerManagerMac::ForceTextureReload() { for (PluginWindowToContainerMap::const_iterator i = plugin_window_to_container_map_.begin(); i != plugin_window_to_container_map_.end(); ++i) { AcceleratedSurfaceContainerMac* container = i->second; container->ForceTextureReload(); } } void AcceleratedSurfaceContainerManagerMac::EnqueueTextureForDeletion( GLuint texture) { if (texture) { textures_pending_deletion_.push_back(texture); } } AcceleratedSurfaceContainerMac* AcceleratedSurfaceContainerManagerMac::MapIDToContainer( gfx::PluginWindowHandle id) { PluginWindowToContainerMap::const_iterator i = plugin_window_to_container_map_.find(id); if (i != plugin_window_to_container_map_.end()) return i->second; LOG(ERROR) << "Request for plugin container for unknown window id " << id; return NULL; } <commit_msg>Fix argument to glTexEnvi in accelerated Mac surface<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/accelerated_surface_container_manager_mac.h" #include "base/logging.h" #include "chrome/browser/renderer_host/accelerated_surface_container_mac.h" #include "webkit/glue/plugins/webplugin.h" AcceleratedSurfaceContainerManagerMac::AcceleratedSurfaceContainerManagerMac() : current_id_(0) { } gfx::PluginWindowHandle AcceleratedSurfaceContainerManagerMac::AllocateFakePluginWindowHandle( bool opaque) { AcceleratedSurfaceContainerMac* container = new AcceleratedSurfaceContainerMac(this, opaque); gfx::PluginWindowHandle res = static_cast<gfx::PluginWindowHandle>(++current_id_); plugin_window_to_container_map_.insert(std::make_pair(res, container)); return res; } void AcceleratedSurfaceContainerManagerMac::DestroyFakePluginWindowHandle( gfx::PluginWindowHandle id) { AcceleratedSurfaceContainerMac* container = MapIDToContainer(id); if (container) delete container; plugin_window_to_container_map_.erase(id); } void AcceleratedSurfaceContainerManagerMac::SetSizeAndIOSurface( gfx::PluginWindowHandle id, int32 width, int32 height, uint64 io_surface_identifier) { AcceleratedSurfaceContainerMac* container = MapIDToContainer(id); if (container) container->SetSizeAndIOSurface(width, height, io_surface_identifier); } void AcceleratedSurfaceContainerManagerMac::SetSizeAndTransportDIB( gfx::PluginWindowHandle id, int32 width, int32 height, TransportDIB::Handle transport_dib) { AcceleratedSurfaceContainerMac* container = MapIDToContainer(id); if (container) container->SetSizeAndTransportDIB(width, height, transport_dib); } void AcceleratedSurfaceContainerManagerMac::MovePluginContainer( const webkit_glue::WebPluginGeometry& move) { AcceleratedSurfaceContainerMac* container = MapIDToContainer(move.window); if (container) container->MoveTo(move); } void AcceleratedSurfaceContainerManagerMac::Draw(CGLContextObj context) { // Clean up old texture objects. This is essentially a pre-emptive // cleanup, as the resources will be released when the OpenGL // context associated with the CAOpenGLLayer is destroyed. However, // if we render many plugins in the same layer, we should try to // eagerly reclaim their resources. Note also that the OpenGL // context must be current when performing the deletion, and it // seems risky to make the OpenGL context current at an arbitrary // point in time, which is why the deletion does not occur in the // container's destructor. for (std::vector<GLuint>::iterator iter = textures_pending_deletion_.begin(); iter != textures_pending_deletion_.end(); ++iter) { GLuint texture = *iter; glDeleteTextures(1, &texture); } textures_pending_deletion_.clear(); glColorMask(true, true, true, true); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); for (PluginWindowToContainerMap::const_iterator i = plugin_window_to_container_map_.begin(); i != plugin_window_to_container_map_.end(); ++i) { AcceleratedSurfaceContainerMac* container = i->second; container->Draw(context); } // Unbind any texture from the texture target to ensure that the // next time through we will have to re-bind the texture and thereby // pick up modifications from the other process. GLenum target = GL_TEXTURE_RECTANGLE_ARB; glBindTexture(target, 0); glFlush(); } void AcceleratedSurfaceContainerManagerMac::ForceTextureReload() { for (PluginWindowToContainerMap::const_iterator i = plugin_window_to_container_map_.begin(); i != plugin_window_to_container_map_.end(); ++i) { AcceleratedSurfaceContainerMac* container = i->second; container->ForceTextureReload(); } } void AcceleratedSurfaceContainerManagerMac::EnqueueTextureForDeletion( GLuint texture) { if (texture) { textures_pending_deletion_.push_back(texture); } } AcceleratedSurfaceContainerMac* AcceleratedSurfaceContainerManagerMac::MapIDToContainer( gfx::PluginWindowHandle id) { PluginWindowToContainerMap::const_iterator i = plugin_window_to_container_map_.find(id); if (i != plugin_window_to_container_map_.end()) return i->second; LOG(ERROR) << "Request for plugin container for unknown window id " << id; return NULL; } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief vplayer メイン関係 @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <iostream> #include "vplayer.hpp" #include "core/glcore.hpp" #include <boost/format.hpp> namespace app { void vplayer::output_term_(const std::string& text) { if(terminal_core_ == nullptr) return; if(text.empty()) return; terminal_core_->output(text); } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void vplayer::initialize() { // AV Decoder 初期化 decoder_.initialize(); camera_.set_eye(vtx::fvtx(-100.0f, 0.0f, 200.0f)); camera_.set_target(vtx::fvtx(0.0f, 0.0f, 200.0f)); camera_.set_up(vtx::fvtx(0.0f, 0.0f, 1.0f)); // 半球ドーム作成 surface_.create_dome(vtx::fvtx(500.0f, 500.0f, 500.0f), 64); gl::core& core = gl::core::get_instance(); using namespace gui; widget_director& wd = director_.at().widget_director_; { // ツールパレット widget::param wp(vtx::srect(10, 10, 200, 350)); widget_frame::param wp_; tools_frame_ = wd.add_widget<widget_frame>(wp, wp_); tools_frame_->set_state(widget::state::SIZE_LOCK); } { // オープンファイルボタン widget::param wp(vtx::srect(10, 10, 180, 40), tools_frame_); widget_button::param wp_("load"); wp_.select_func_ = [this] () { if(load_ctx_) { bool f = load_ctx_->get_state(gui::widget::state::ENABLE); load_ctx_->enable(!f); } }; open_file_ = wd.add_widget<widget_button>(wp, wp_); } { // ボリューム・スライダー widget::param wp(vtx::srect(10, 60, 180, 20), tools_frame_); widget_slider::param wp_; wp_.select_func_ = [this] (float value) { auto& s = director_.at().sound_; s.set_gain_audio(value); }; volume_ = wd.add_widget<widget_slider>(wp, wp_); } { // Play/Pause ボタン widget::param wp(vtx::srect( 10, 90, 85, 40), tools_frame_); widget_button::param wp_("Play"); wp_.select_func_ = [this] () { if(decode_open_) { bool f = director_.at().sound_.status_audio(); if(f) { decode_pause_ = true; director_.at().sound_.pause_audio(); } else { decode_pause_ = false; director_.at().sound_.play_audio(); } } }; play_pause_ = wd.add_widget<widget_button>(wp, wp_); } { // Stop ボタン widget::param wp(vtx::srect(100, 90, 85, 40), tools_frame_); widget_button::param wp_("Stop"); wp_.select_func_ = [this] () { decoder_.close(); decode_open_ = false; decode_pause_ = false; director_.at().sound_.stop_audio(); }; stop_ = wd.add_widget<widget_button>(wp, wp_); } { // チェックボックスのテスト widget::param wp(vtx::srect(10, 130, 180, 40), tools_frame_); widget_check::param wp_("Dome Map"); dome_ = wd.add_widget<widget_check>(wp, wp_); } #if 0 if(1) { // ラジオボタンのテスト widget::param wpr(vtx::srect(20, 20, 130, 130), 0); widget_null::param wpr_; widget* root = wd.add_widget<widget_null>(wpr, wpr_); root->set_state(widget::state::POSITION_LOCK); widget::param wp(vtx::srect(0, 0, 130, 30), root); widget_radio::param wp_("Enable"); for(int i = 0; i < 3; ++i) { if(i == 2) wp_.check_ = true; widget_radio* w = wd.add_widget<widget_radio>(wp, wp_); w->at_local_param().select_func_ = [this](bool f, int n) { std::cout << "Radio button: " << static_cast<int>(f) << " (" << n << ")" << std::endl; }; wp.rect_.org.y += 40; } } #endif { // load ファイラー本体 widget::param wp(vtx::srect(10, 30, 300, 200)); widget_filer::param wp_(core.get_current_path()); wp_.select_file_func_ = [this] (const std::string& path) { bool open = decoder_.open(path); if(open) { decode_open_ = true; decode_pause_ = false; frame_time_ = 0.0; output_term_("File: " + path + '\n'); auto x = decoder_.get_frame_size().x; auto y = decoder_.get_frame_size().y; output_term_((boost::format("Frame size: %d, %d\n") % x % y).str()); auto fr = decoder_.get_frame_rate(); output_term_((boost::format("Frame rate: %2.2f [fps]\n") % fr).str()); auto ar = decoder_.get_audio_rate(); output_term_((boost::format("Audio sample rate: %d [Hz]\n") % ar).str()); auto ac = decoder_.get_audio_chanel(); output_term_((boost::format("Audio chanel%s: %d\n") % ((ac > 1) ? "s" : "") % ac).str()); auto af = decoder_.get_audio_format(); std::string s; if(af == av::decoder::audio_format::none) { s = "none"; } else if(af == av::decoder::audio_format::u8) { s = "u8"; } else if(af == av::decoder::audio_format::s16) { s = "s16"; } else if(af == av::decoder::audio_format::f32) { s = "f32"; } else if(af == av::decoder::audio_format::invalid) { s = "invalid"; } output_term_("Audio format: " + s + '\n'); int depth = 24; texfb_.initialize(x, y, depth); } else { if(dialog_) { dialog_->enable(); dialog_->set_text("ファイル\n" + path + "\nは開けませんでした。"); } } }; load_ctx_ = wd.add_widget<widget_filer>(wp, wp_); load_ctx_->enable(false); } { // ダイアログ本体 widget::param wp(vtx::srect(300, 300, 400, 200)); widget_dialog::param wp_; // wp_.style_ = widget_dialog::param::style::CANCEL_OK; dialog_ = wd.add_widget<widget_dialog>(wp, wp_); dialog_->enable(false); } { // ターミナル { widget::param wp(vtx::srect(300, 300, 200, 200)); widget_frame::param wp_; wp_.plate_param_.set_caption(20); terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_); } { widget::param wp(vtx::srect(0), terminal_frame_); widget_terminal::param wp_; wp_.echo_ = false; terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_); } } // プリファレンスの取得 sys::preference& pre = director_.at().preference_; if(tools_frame_) tools_frame_->load(pre, false, false); if(volume_) volume_->load(pre); if(dome_) dome_->load(pre); if(load_ctx_) load_ctx_->load(pre); if(terminal_frame_) terminal_frame_->load(pre); } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void vplayer::update() { gl::core& core = gl::core::get_instance(); gui::widget_director& wd = director_.at().widget_director_; // AV デコーダー更新 if(decode_open_ && !decode_pause_) { frame_time_ += 1.0 / 60.0; double vt = decoder_.get_video_time(); if(vt < frame_time_) { bool f = decoder_.update(); if(f) { output_term_((boost::format("Total: %d Frames\n") % decoder_.get_frame_no()).str()); decoder_.close(); decode_open_ = false; } else { const void* img = decoder_.get_image(); if(img) { texfb_.rendering(gl::texfb::image::RGB, img); texfb_.flip(); } } } double at = decoder_.get_audio_time(); // if(at < frame_time_) { av::decoder::audio_deque& a = decoder_.at_audio(); for(int i = 0; i < a.size(); ++i) { al::audio ai = a.front(); if(director_.at().sound_.queue_audio(ai)) { a.pop_front(); } } // } } // ボタンの状態を設定 if(play_pause_) { if(decode_pause_) { play_pause_->set_text("Play"); } else { play_pause_->set_text("Pause"); } play_pause_->set_stall(!decode_open_); } if(stop_) { stop_->set_stall(!decode_open_); } // GUI が操作されない場合、カメラ操作 if(!wd.update()) { camera_.update(); } } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void vplayer::render() { if(decode_open_) { if(dome_ != nullptr && dome_->get_check()) { camera_.service(); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glEnable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glBindTexture(GL_TEXTURE_2D, texfb_.get_texture_id()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); surface_.draw(gl::surface::draw_type::fill); // surface_.draw(gl::surface::draw_type::line); } else { gl::core& core = gl::core::get_instance(); texfb_.setup_matrix(0, 0, core.get_size().x, core.get_size().y); texfb_.set_disp_start(vtx::ipos(0, 0)); texfb_.draw(); } } glEnable(GL_TEXTURE_2D); director_.at().widget_director_.service(); director_.at().widget_director_.render(); } //-----------------------------------------------------------------// /*! @brief 廃棄 */ //-----------------------------------------------------------------// void vplayer::destroy() { sys::preference& pre = director_.at().preference_; if(terminal_frame_) terminal_frame_->save(pre); if(load_ctx_) load_ctx_->save(pre); if(tools_frame_) tools_frame_->save(pre); if(volume_) volume_->save(pre); if(dome_) dome_->save(pre); } } <commit_msg>change srect to irect<commit_after>//=====================================================================// /*! @file @brief vplayer メイン関係 @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <iostream> #include "vplayer.hpp" #include "core/glcore.hpp" #include <boost/format.hpp> namespace app { void vplayer::output_term_(const std::string& text) { if(terminal_core_ == nullptr) return; if(text.empty()) return; terminal_core_->output(text); } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void vplayer::initialize() { // AV Decoder 初期化 decoder_.initialize(); camera_.set_eye(vtx::fvtx(-100.0f, 0.0f, 200.0f)); camera_.set_target(vtx::fvtx(0.0f, 0.0f, 200.0f)); camera_.set_up(vtx::fvtx(0.0f, 0.0f, 1.0f)); // 半球ドーム作成 surface_.create_dome(vtx::fvtx(500.0f, 500.0f, 500.0f), 64); gl::core& core = gl::core::get_instance(); using namespace gui; widget_director& wd = director_.at().widget_director_; { // ツールパレット widget::param wp(vtx::irect(10, 10, 200, 350)); widget_frame::param wp_; tools_frame_ = wd.add_widget<widget_frame>(wp, wp_); tools_frame_->set_state(widget::state::SIZE_LOCK); } { // オープンファイルボタン widget::param wp(vtx::irect(10, 10, 180, 40), tools_frame_); widget_button::param wp_("load"); wp_.select_func_ = [this] () { if(load_ctx_) { bool f = load_ctx_->get_state(gui::widget::state::ENABLE); load_ctx_->enable(!f); } }; open_file_ = wd.add_widget<widget_button>(wp, wp_); } { // ボリューム・スライダー widget::param wp(vtx::irect(10, 60, 180, 20), tools_frame_); widget_slider::param wp_; wp_.select_func_ = [this] (float value) { auto& s = director_.at().sound_; s.set_gain_audio(value); }; volume_ = wd.add_widget<widget_slider>(wp, wp_); } { // Play/Pause ボタン widget::param wp(vtx::irect( 10, 90, 85, 40), tools_frame_); widget_button::param wp_("Play"); wp_.select_func_ = [this] () { if(decode_open_) { bool f = director_.at().sound_.status_audio(); if(f) { decode_pause_ = true; director_.at().sound_.pause_audio(); } else { decode_pause_ = false; director_.at().sound_.play_audio(); } } }; play_pause_ = wd.add_widget<widget_button>(wp, wp_); } { // Stop ボタン widget::param wp(vtx::irect(100, 90, 85, 40), tools_frame_); widget_button::param wp_("Stop"); wp_.select_func_ = [this] () { decoder_.close(); decode_open_ = false; decode_pause_ = false; director_.at().sound_.stop_audio(); }; stop_ = wd.add_widget<widget_button>(wp, wp_); } { // チェックボックスのテスト widget::param wp(vtx::irect(10, 130, 180, 40), tools_frame_); widget_check::param wp_("Dome Map"); dome_ = wd.add_widget<widget_check>(wp, wp_); } #if 0 if(1) { // ラジオボタンのテスト widget::param wpr(vtx::irect(20, 20, 130, 130), 0); widget_null::param wpr_; widget* root = wd.add_widget<widget_null>(wpr, wpr_); root->set_state(widget::state::POSITION_LOCK); widget::param wp(vtx::irect(0, 0, 130, 30), root); widget_radio::param wp_("Enable"); for(int i = 0; i < 3; ++i) { if(i == 2) wp_.check_ = true; widget_radio* w = wd.add_widget<widget_radio>(wp, wp_); w->at_local_param().select_func_ = [this](bool f, int n) { std::cout << "Radio button: " << static_cast<int>(f) << " (" << n << ")" << std::endl; }; wp.rect_.org.y += 40; } } #endif { // load ファイラー本体 widget::param wp(vtx::irect(10, 30, 300, 200)); widget_filer::param wp_(core.get_current_path()); wp_.select_file_func_ = [this] (const std::string& path) { bool open = decoder_.open(path); if(open) { decode_open_ = true; decode_pause_ = false; frame_time_ = 0.0; output_term_("File: " + path + '\n'); auto x = decoder_.get_frame_size().x; auto y = decoder_.get_frame_size().y; output_term_((boost::format("Frame size: %d, %d\n") % x % y).str()); auto fr = decoder_.get_frame_rate(); output_term_((boost::format("Frame rate: %2.2f [fps]\n") % fr).str()); auto ar = decoder_.get_audio_rate(); output_term_((boost::format("Audio sample rate: %d [Hz]\n") % ar).str()); auto ac = decoder_.get_audio_chanel(); output_term_((boost::format("Audio chanel%s: %d\n") % ((ac > 1) ? "s" : "") % ac).str()); auto af = decoder_.get_audio_format(); std::string s; if(af == av::decoder::audio_format::none) { s = "none"; } else if(af == av::decoder::audio_format::u8) { s = "u8"; } else if(af == av::decoder::audio_format::s16) { s = "s16"; } else if(af == av::decoder::audio_format::f32) { s = "f32"; } else if(af == av::decoder::audio_format::invalid) { s = "invalid"; } output_term_("Audio format: " + s + '\n'); int depth = 24; texfb_.initialize(x, y, depth); } else { if(dialog_) { dialog_->enable(); dialog_->set_text("ファイル\n" + path + "\nは開けませんでした。"); } } }; load_ctx_ = wd.add_widget<widget_filer>(wp, wp_); load_ctx_->enable(false); } { // ダイアログ本体 widget::param wp(vtx::irect(300, 300, 400, 200)); widget_dialog::param wp_; // wp_.style_ = widget_dialog::param::style::CANCEL_OK; dialog_ = wd.add_widget<widget_dialog>(wp, wp_); dialog_->enable(false); } { // ターミナル { widget::param wp(vtx::irect(300, 300, 200, 200)); widget_frame::param wp_; wp_.plate_param_.set_caption(20); terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_); } { widget::param wp(vtx::irect(0), terminal_frame_); widget_terminal::param wp_; wp_.echo_ = false; terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_); } } // プリファレンスの取得 sys::preference& pre = director_.at().preference_; if(tools_frame_) tools_frame_->load(pre, false, false); if(volume_) volume_->load(pre); if(dome_) dome_->load(pre); if(load_ctx_) load_ctx_->load(pre); if(terminal_frame_) terminal_frame_->load(pre); } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void vplayer::update() { gl::core& core = gl::core::get_instance(); gui::widget_director& wd = director_.at().widget_director_; // AV デコーダー更新 if(decode_open_ && !decode_pause_) { frame_time_ += 1.0 / 60.0; double vt = decoder_.get_video_time(); if(vt < frame_time_) { bool f = decoder_.update(); if(f) { output_term_((boost::format("Total: %d Frames\n") % decoder_.get_frame_no()).str()); decoder_.close(); decode_open_ = false; } else { const void* img = decoder_.get_image(); if(img) { texfb_.rendering(gl::texfb::image::RGB, img); texfb_.flip(); } } } double at = decoder_.get_audio_time(); // if(at < frame_time_) { av::decoder::audio_deque& a = decoder_.at_audio(); for(int i = 0; i < a.size(); ++i) { al::audio ai = a.front(); if(director_.at().sound_.queue_audio(ai)) { a.pop_front(); } } // } } // ボタンの状態を設定 if(play_pause_) { if(decode_pause_) { play_pause_->set_text("Play"); } else { play_pause_->set_text("Pause"); } play_pause_->set_stall(!decode_open_); } if(stop_) { stop_->set_stall(!decode_open_); } // GUI が操作されない場合、カメラ操作 if(!wd.update()) { camera_.update(); } } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void vplayer::render() { if(decode_open_) { if(dome_ != nullptr && dome_->get_check()) { camera_.service(); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glEnable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glBindTexture(GL_TEXTURE_2D, texfb_.get_texture_id()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); surface_.draw(gl::surface::draw_type::fill); // surface_.draw(gl::surface::draw_type::line); } else { gl::core& core = gl::core::get_instance(); texfb_.setup_matrix(0, 0, core.get_size().x, core.get_size().y); texfb_.set_disp_start(vtx::ipos(0, 0)); texfb_.draw(); } } glEnable(GL_TEXTURE_2D); director_.at().widget_director_.service(); director_.at().widget_director_.render(); } //-----------------------------------------------------------------// /*! @brief 廃棄 */ //-----------------------------------------------------------------// void vplayer::destroy() { sys::preference& pre = director_.at().preference_; if(terminal_frame_) terminal_frame_->save(pre); if(load_ctx_) load_ctx_->save(pre); if(tools_frame_) tools_frame_->save(pre); if(volume_) volume_->save(pre); if(dome_) dome_->save(pre); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: shapes.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2007-04-26 10:02: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_goodies.hxx" #include "shapes.hxx" #include "invader.hrc" #include "expl.hxx" #include <vcl/outdev.hxx> #include <vcl/virdev.hxx> #include <vcl/bitmap.hxx> Image* ImplLoadImage( USHORT nId, ResMgr* pRes ) { return new Image( Bitmap( ResId( nId, *pRes ) ), COL_WHITE ); } // ------------------------------------------------------------------------ Fighter::Fighter(Size& rOut, ResMgr* pRes) : pFightr(NULL), pFightl(NULL), eMode(FIGHT_NORM), bNoKey(FALSE), nDelay(0), pFight1(NULL) { pFight1 = ImplLoadImage( FIGHTER1, pRes ); pFightr = ImplLoadImage( FIGHTERR, pRes ); pFightl = ImplLoadImage( FIGHTERL, pRes ); aSize = pFight1->GetSizePixel(); aOut.X() = rOut.Width()/2-aSize.Width()/2; aOut.Y() = rOut.Height()-aSize.Height()-10; aStart = aOut; nMax = rOut.Width() - aSize.Width(); } Fighter::~Fighter() { delete pFight1; delete pFightr; delete pFightl; } void Fighter::Init() { aOut = aStart; eMode = FIGHT_NORM; } void Fighter::Paint(OutputDevice& rDev) { if(eMode == FIGHT_DEST) return; switch(eMode) { case FIGHT_NORM: rDev.DrawImage(aOut,*pFight1); break; case FIGHT_RIGHT: rDev.DrawImage(aOut,*pFightr); break; case FIGHT_LEFT: rDev.DrawImage(aOut,*pFightl); break; case FIGHT_DEST: break; } if(nDelay <= 0) eMode = FIGHT_NORM; else nDelay--; bNoKey = FALSE; } void Fighter::Move(long nDirect) { if(eMode == FIGHT_DEST) return; if(nDirect < 0) { aOut.X() -= KANONEX; eMode = FIGHT_LEFT; } else { aOut.X() += KANONEX; eMode = FIGHT_RIGHT; } nDelay = 5; if(aOut.X() <= 0) aOut.X() = 1; if(aOut.X() > nMax) aOut.X() = nMax; bNoKey = TRUE; } BOOL Fighter::Kollision(Rectangle aRect, Explosion* pExpl) { if((aOut.X() <= aRect.Left() && aOut.X()+aSize.Width() >= aRect.Right()) && (aOut.Y() <= aRect.Top() && aOut.Y()+aSize.Height() >= aRect.Bottom())) { pExpl->InsertExpl(aOut); eMode = FIGHT_DEST; return TRUE; } return FALSE; } Munition::Munition(ResMgr* pRes) : MunitionListe(0,1), pMunition2( NULL ), pMunition1( NULL ) { pMunition1 = ImplLoadImage( MUNITION1,pRes ); pMunition2 = ImplLoadImage( MUNITION2,pRes ); aSize = pMunition1->GetSizePixel(); } Munition::~Munition() { ClearAll(); delete pMunition1; delete pMunition2; } void Munition::Start(Point& rPoint) { if( Count() >= MUNMAX) return; Munition_Impl* pWork = new Munition_Impl(); pWork->aPoint = rPoint; pWork->eMode = MUNI_MODE1; Insert(pWork); } void Munition::Paint(OutputDevice& rDev) { unsigned long i; for(i=0; i<Count();i++) { switch(GetMode(i)) { case MUNI_MODE1: rDev.DrawImage(GetPoint(i),*pMunition1); SetMode(i,MUNI_MODE2); break; case MUNI_MODE2: rDev.DrawImage(GetPoint(i),*pMunition2); SetMode(i,MUNI_MODE1); break; case MUNI_DEL: break; } SetKoll(i,Rectangle(Point(GetPoint(i).X()+aSize.Width()/2,GetPoint(i).Y()), Point(GetPoint(i).X()+aSize.Width()/2, GetPoint(i).Y()))); SetPoint(i,Point(GetPoint(i).X(),GetPoint(i).Y() - MUNIY)); if(GetPoint(i).Y() <= aSize.Height()*-1) { SetMode(i,MUNI_DEL); } } } long Munition::RemoveMunition() { for(long i=Count()-1; i>=0; i--) { if(GetMode(i) == MUNI_DEL) { Munition_Impl* pWork = GetObject(i); Remove(pWork); delete pWork; } } return 5-Count(); } void Munition::ClearAll() { for(long i=Count()-1; i>=0; i--) delete GetObject(i); Clear(); } Bombe::Bombe(ResMgr* pRes) : BombenListe(0,1) { pBombe = ImplLoadImage( BOMBE,pRes ); aSize = pBombe->GetSizePixel(); nSpeed = BOMBEY; } Bombe::~Bombe() { ClearAll(); delete pBombe; } void Bombe::Paint(OutputDevice& rDev) { unsigned long i; for(i=0; i<Count();i++) { rDev.DrawImage(GetPoint(i),*pBombe); SetKoll(i,Rectangle(Point(GetPoint(i).X()+aSize.Width()/2, GetPoint(i).Y()+aSize.Height()), Point(GetPoint(i).X()+aSize.Width()/2, GetPoint(i).Y()+aSize.Height()))); SetPoint(i,Point(GetPoint(i).X(),GetPoint(i).Y() + MUNIY)); } } void Bombe::InsertBombe(const Point& rPoint) { Bombe_Impl* pWork = new Bombe_Impl; pWork->aXY = rPoint; pWork->bDelete = FALSE; Insert(pWork); } void Bombe::RemoveBomben() { for(long i=Count()-1; i>=0; i--) { Bombe_Impl* pWork = GetObject(i); if(pWork->bDelete) { Remove(pWork); delete pWork; } } } void Bombe::ClearAll() { unsigned long i; for(i=0;i<Count();i++) delete GetObject(i); Clear(); } BOOL Bombe::Kollision(Rectangle aRect, Explosion* pExpl) { unsigned long i; for(i=0;i<Count();i++) { if((GetPoint(i).X() <= aRect.Left() && GetPoint(i).X()+aSize.Width() >= aRect.Right()) && (GetPoint(i).Y() <= aRect.Top() && GetPoint(i).Y()+aSize.Height() >= aRect.Bottom())) { pExpl->InsertExpl(GetPoint(i)); SetDelete(i); return TRUE; } } return FALSE; } Wall::Wall(ResMgr* pRes) : WallListe(0,1), pWall1(0L), pWall2(0L), pWall3(0L), pWall4(0L), pWall5(0L), pWall6(0L), pWall7(0L), pWall8(0L), pWall9(0L), pWall10(0L) { pWall1 = ImplLoadImage( WALL1,pRes ); pWall2 = ImplLoadImage( WALL2,pRes ); pWall3 = ImplLoadImage( WALL3,pRes ); pWall4 = ImplLoadImage( WALL4,pRes ); pWall5 = ImplLoadImage( WALL5,pRes ); pWall6 = ImplLoadImage( WALL6,pRes ); pWall7 = ImplLoadImage( WALL7,pRes ); pWall8 = ImplLoadImage( WALL8,pRes ); pWall9 = ImplLoadImage( WALL9,pRes ); pWall10 = ImplLoadImage( WALL10,pRes ); aSize = pWall1->GetSizePixel(); } Wall::~Wall() { ClearAll(); delete pWall1; delete pWall2; delete pWall3; delete pWall4; delete pWall5; delete pWall6; delete pWall7; delete pWall8; delete pWall9; delete pWall10; } void Wall::Paint(OutputDevice& rDev) { unsigned long i; for(i=0; i<Count(); i++) { switch(GetMode(i)) { case WALL_MOD1: rDev.DrawImage(GetPoint(i),*pWall1); break; case WALL_MOD2: rDev.DrawImage(GetPoint(i),*pWall2); break; case WALL_MOD3: rDev.DrawImage(GetPoint(i),*pWall3); break; case WALL_MOD4: rDev.DrawImage(GetPoint(i),*pWall4); break; case WALL_MOD5: rDev.DrawImage(GetPoint(i),*pWall5); break; case WALL_MOD6: rDev.DrawImage(GetPoint(i),*pWall6); break; case WALL_MOD7: rDev.DrawImage(GetPoint(i),*pWall7); break; case WALL_MOD8: rDev.DrawImage(GetPoint(i),*pWall8); break; case WALL_MOD9: rDev.DrawImage(GetPoint(i),*pWall9); break; case WALL_MOD10: rDev.DrawImage(GetPoint(i),*pWall10); break; case WALL_DEL: break; } } } void Wall::InsertWall(const Point& rPoint) { Wall_Impl* pWork = new Wall_Impl(); pWork->aXY = rPoint; pWork->aXY.Y() = WALLY; pWork->eMode = WALL_MOD1; Insert(pWork); } void Wall::ClearAll() { unsigned long i; for(i=0; i<Count(); i++) delete GetObject(i); Clear(); } BOOL Wall::Kollision(Rectangle& rRect, BOOL bDel) { BOOL nTreffer = FALSE; Rectangle aWork; unsigned long i; for(i=0; i<Count();i++) { Point aPoint = GetPoint(i); aWork = Rectangle(Point(aPoint.X(),aPoint.Y()-WALLKOLL), Point(aPoint.X()+aSize.Width(), aPoint.Y()+aSize.Height()-WALLKOLL)); if((aWork.Left() <= rRect.Left() && aWork.Right() >= rRect.Right()) && (aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) && GetMode(i) != WALL_DEL) { switch(GetMode(i)) { case WALL_MOD1: SetMode(i,WALL_MOD2); break; case WALL_MOD2: SetMode(i,WALL_MOD3); break; case WALL_MOD3: SetMode(i,WALL_MOD4); break; case WALL_MOD4: SetMode(i,WALL_MOD5); break; case WALL_MOD5: SetMode(i,WALL_MOD6); break; case WALL_MOD6: SetMode(i,WALL_MOD7); break; case WALL_MOD7: SetMode(i,WALL_MOD8); break; case WALL_MOD8: SetMode(i,WALL_MOD9); break; case WALL_MOD9: SetMode(i,WALL_MOD10); break; case WALL_MOD10: SetMode(i,WALL_DEL); break; case WALL_DEL: break; } if(bDel) SetMode(i,WALL_DEL); nTreffer = TRUE; } } return nTreffer; } <commit_msg>INTEGRATION: CWS changefileheader (1.6.78); FILE MERGED 2008/03/31 13:39:44 rt 1.6.78.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: shapes.cxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_goodies.hxx" #include "shapes.hxx" #include "invader.hrc" #include "expl.hxx" #include <vcl/outdev.hxx> #include <vcl/virdev.hxx> #include <vcl/bitmap.hxx> Image* ImplLoadImage( USHORT nId, ResMgr* pRes ) { return new Image( Bitmap( ResId( nId, *pRes ) ), COL_WHITE ); } // ------------------------------------------------------------------------ Fighter::Fighter(Size& rOut, ResMgr* pRes) : pFightr(NULL), pFightl(NULL), eMode(FIGHT_NORM), bNoKey(FALSE), nDelay(0), pFight1(NULL) { pFight1 = ImplLoadImage( FIGHTER1, pRes ); pFightr = ImplLoadImage( FIGHTERR, pRes ); pFightl = ImplLoadImage( FIGHTERL, pRes ); aSize = pFight1->GetSizePixel(); aOut.X() = rOut.Width()/2-aSize.Width()/2; aOut.Y() = rOut.Height()-aSize.Height()-10; aStart = aOut; nMax = rOut.Width() - aSize.Width(); } Fighter::~Fighter() { delete pFight1; delete pFightr; delete pFightl; } void Fighter::Init() { aOut = aStart; eMode = FIGHT_NORM; } void Fighter::Paint(OutputDevice& rDev) { if(eMode == FIGHT_DEST) return; switch(eMode) { case FIGHT_NORM: rDev.DrawImage(aOut,*pFight1); break; case FIGHT_RIGHT: rDev.DrawImage(aOut,*pFightr); break; case FIGHT_LEFT: rDev.DrawImage(aOut,*pFightl); break; case FIGHT_DEST: break; } if(nDelay <= 0) eMode = FIGHT_NORM; else nDelay--; bNoKey = FALSE; } void Fighter::Move(long nDirect) { if(eMode == FIGHT_DEST) return; if(nDirect < 0) { aOut.X() -= KANONEX; eMode = FIGHT_LEFT; } else { aOut.X() += KANONEX; eMode = FIGHT_RIGHT; } nDelay = 5; if(aOut.X() <= 0) aOut.X() = 1; if(aOut.X() > nMax) aOut.X() = nMax; bNoKey = TRUE; } BOOL Fighter::Kollision(Rectangle aRect, Explosion* pExpl) { if((aOut.X() <= aRect.Left() && aOut.X()+aSize.Width() >= aRect.Right()) && (aOut.Y() <= aRect.Top() && aOut.Y()+aSize.Height() >= aRect.Bottom())) { pExpl->InsertExpl(aOut); eMode = FIGHT_DEST; return TRUE; } return FALSE; } Munition::Munition(ResMgr* pRes) : MunitionListe(0,1), pMunition2( NULL ), pMunition1( NULL ) { pMunition1 = ImplLoadImage( MUNITION1,pRes ); pMunition2 = ImplLoadImage( MUNITION2,pRes ); aSize = pMunition1->GetSizePixel(); } Munition::~Munition() { ClearAll(); delete pMunition1; delete pMunition2; } void Munition::Start(Point& rPoint) { if( Count() >= MUNMAX) return; Munition_Impl* pWork = new Munition_Impl(); pWork->aPoint = rPoint; pWork->eMode = MUNI_MODE1; Insert(pWork); } void Munition::Paint(OutputDevice& rDev) { unsigned long i; for(i=0; i<Count();i++) { switch(GetMode(i)) { case MUNI_MODE1: rDev.DrawImage(GetPoint(i),*pMunition1); SetMode(i,MUNI_MODE2); break; case MUNI_MODE2: rDev.DrawImage(GetPoint(i),*pMunition2); SetMode(i,MUNI_MODE1); break; case MUNI_DEL: break; } SetKoll(i,Rectangle(Point(GetPoint(i).X()+aSize.Width()/2,GetPoint(i).Y()), Point(GetPoint(i).X()+aSize.Width()/2, GetPoint(i).Y()))); SetPoint(i,Point(GetPoint(i).X(),GetPoint(i).Y() - MUNIY)); if(GetPoint(i).Y() <= aSize.Height()*-1) { SetMode(i,MUNI_DEL); } } } long Munition::RemoveMunition() { for(long i=Count()-1; i>=0; i--) { if(GetMode(i) == MUNI_DEL) { Munition_Impl* pWork = GetObject(i); Remove(pWork); delete pWork; } } return 5-Count(); } void Munition::ClearAll() { for(long i=Count()-1; i>=0; i--) delete GetObject(i); Clear(); } Bombe::Bombe(ResMgr* pRes) : BombenListe(0,1) { pBombe = ImplLoadImage( BOMBE,pRes ); aSize = pBombe->GetSizePixel(); nSpeed = BOMBEY; } Bombe::~Bombe() { ClearAll(); delete pBombe; } void Bombe::Paint(OutputDevice& rDev) { unsigned long i; for(i=0; i<Count();i++) { rDev.DrawImage(GetPoint(i),*pBombe); SetKoll(i,Rectangle(Point(GetPoint(i).X()+aSize.Width()/2, GetPoint(i).Y()+aSize.Height()), Point(GetPoint(i).X()+aSize.Width()/2, GetPoint(i).Y()+aSize.Height()))); SetPoint(i,Point(GetPoint(i).X(),GetPoint(i).Y() + MUNIY)); } } void Bombe::InsertBombe(const Point& rPoint) { Bombe_Impl* pWork = new Bombe_Impl; pWork->aXY = rPoint; pWork->bDelete = FALSE; Insert(pWork); } void Bombe::RemoveBomben() { for(long i=Count()-1; i>=0; i--) { Bombe_Impl* pWork = GetObject(i); if(pWork->bDelete) { Remove(pWork); delete pWork; } } } void Bombe::ClearAll() { unsigned long i; for(i=0;i<Count();i++) delete GetObject(i); Clear(); } BOOL Bombe::Kollision(Rectangle aRect, Explosion* pExpl) { unsigned long i; for(i=0;i<Count();i++) { if((GetPoint(i).X() <= aRect.Left() && GetPoint(i).X()+aSize.Width() >= aRect.Right()) && (GetPoint(i).Y() <= aRect.Top() && GetPoint(i).Y()+aSize.Height() >= aRect.Bottom())) { pExpl->InsertExpl(GetPoint(i)); SetDelete(i); return TRUE; } } return FALSE; } Wall::Wall(ResMgr* pRes) : WallListe(0,1), pWall1(0L), pWall2(0L), pWall3(0L), pWall4(0L), pWall5(0L), pWall6(0L), pWall7(0L), pWall8(0L), pWall9(0L), pWall10(0L) { pWall1 = ImplLoadImage( WALL1,pRes ); pWall2 = ImplLoadImage( WALL2,pRes ); pWall3 = ImplLoadImage( WALL3,pRes ); pWall4 = ImplLoadImage( WALL4,pRes ); pWall5 = ImplLoadImage( WALL5,pRes ); pWall6 = ImplLoadImage( WALL6,pRes ); pWall7 = ImplLoadImage( WALL7,pRes ); pWall8 = ImplLoadImage( WALL8,pRes ); pWall9 = ImplLoadImage( WALL9,pRes ); pWall10 = ImplLoadImage( WALL10,pRes ); aSize = pWall1->GetSizePixel(); } Wall::~Wall() { ClearAll(); delete pWall1; delete pWall2; delete pWall3; delete pWall4; delete pWall5; delete pWall6; delete pWall7; delete pWall8; delete pWall9; delete pWall10; } void Wall::Paint(OutputDevice& rDev) { unsigned long i; for(i=0; i<Count(); i++) { switch(GetMode(i)) { case WALL_MOD1: rDev.DrawImage(GetPoint(i),*pWall1); break; case WALL_MOD2: rDev.DrawImage(GetPoint(i),*pWall2); break; case WALL_MOD3: rDev.DrawImage(GetPoint(i),*pWall3); break; case WALL_MOD4: rDev.DrawImage(GetPoint(i),*pWall4); break; case WALL_MOD5: rDev.DrawImage(GetPoint(i),*pWall5); break; case WALL_MOD6: rDev.DrawImage(GetPoint(i),*pWall6); break; case WALL_MOD7: rDev.DrawImage(GetPoint(i),*pWall7); break; case WALL_MOD8: rDev.DrawImage(GetPoint(i),*pWall8); break; case WALL_MOD9: rDev.DrawImage(GetPoint(i),*pWall9); break; case WALL_MOD10: rDev.DrawImage(GetPoint(i),*pWall10); break; case WALL_DEL: break; } } } void Wall::InsertWall(const Point& rPoint) { Wall_Impl* pWork = new Wall_Impl(); pWork->aXY = rPoint; pWork->aXY.Y() = WALLY; pWork->eMode = WALL_MOD1; Insert(pWork); } void Wall::ClearAll() { unsigned long i; for(i=0; i<Count(); i++) delete GetObject(i); Clear(); } BOOL Wall::Kollision(Rectangle& rRect, BOOL bDel) { BOOL nTreffer = FALSE; Rectangle aWork; unsigned long i; for(i=0; i<Count();i++) { Point aPoint = GetPoint(i); aWork = Rectangle(Point(aPoint.X(),aPoint.Y()-WALLKOLL), Point(aPoint.X()+aSize.Width(), aPoint.Y()+aSize.Height()-WALLKOLL)); if((aWork.Left() <= rRect.Left() && aWork.Right() >= rRect.Right()) && (aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) && GetMode(i) != WALL_DEL) { switch(GetMode(i)) { case WALL_MOD1: SetMode(i,WALL_MOD2); break; case WALL_MOD2: SetMode(i,WALL_MOD3); break; case WALL_MOD3: SetMode(i,WALL_MOD4); break; case WALL_MOD4: SetMode(i,WALL_MOD5); break; case WALL_MOD5: SetMode(i,WALL_MOD6); break; case WALL_MOD6: SetMode(i,WALL_MOD7); break; case WALL_MOD7: SetMode(i,WALL_MOD8); break; case WALL_MOD8: SetMode(i,WALL_MOD9); break; case WALL_MOD9: SetMode(i,WALL_MOD10); break; case WALL_MOD10: SetMode(i,WALL_DEL); break; case WALL_DEL: break; } if(bDel) SetMode(i,WALL_DEL); nTreffer = TRUE; } } return nTreffer; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; static const std::string OPENCV_WINDOW = "Image window"; int findBiggestContour(vector<vector<Point> >); class ImageConverter { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; public: ImageConverter() : it_(nh_) { // Subscrive to input video feed and publish output video feed image_sub_ = it_.subscribe("/camera/color/image_raw", 1, &ImageConverter::imageCb, this); image_pub_ = it_.advertise("/image_converter/output_video", 1); cv::namedWindow(OPENCV_WINDOW); } ~ImageConverter() { cv::destroyWindow(OPENCV_WINDOW); } int findBiggestContour(vector<vector<Point> > contours){ int indexOfBiggestContour = -1; int sizeOfBiggestContour = 0; for (int i = 0; i < contours.size(); i++){ if(contours[i].size() > sizeOfBiggestContour){ sizeOfBiggestContour = contours[i].size(); indexOfBiggestContour = i; } } return indexOfBiggestContour; } void imageCb(const sensor_msgs::ImageConstPtr& msg) { cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } cv::Mat downsampled; cv::Mat result; // segmentation result (4 possible values) cv::Mat bgModel; cv::Mat fgModel; // the models (internally used) cv::Mat blurred; cv::Mat hsv; cv::Mat bw; cv::pyrDown(cv_ptr->image, downsampled, cv::Size(cv_ptr->image.cols/2, cv_ptr->image.rows/2)); // //Skin Detection // cv::blur( downsampled, blurred, cv::Size(3,3) ); // cv::cvtColor(blurred, hsv, CV_BGR2HSV); // cv::inRange(hsv, cv::Scalar(0, 10, 60), cv::Scalar(20, 150, 255), bw); // // Mat canny_output; // vector<vector<Point> > contours; // vector<Vec4i> hierarchy; // // findContours( bw, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); // int s = findBiggestContour(contours); // // Mat drawing = Mat::zeros( downsampled.size(), CV_8UC1 ); // drawContours( drawing, contours, s, Scalar(255), -1, 8, hierarchy, 0, Point() ); // // // cv::imshow("Skin Detection", bw); // imshow("drw", drawing); //Test Mask Grabcut cv::Mat1b markers(cv_ptr->image.rows, cv_ptr->image.cols); // let's set all of them to possible background first markers.setTo(cv::GC_PR_BGD); // cut out a small area in the middle of the image int m_rows = cv_ptr->image.rows; int m_cols = 0.5 * cv_ptr->image.cols; // of course here you could also use cv::Rect() instead of cv::Range to select // the region of interest cv::Mat1b fg_seed = markers(cv::Range(cv_ptr->image.rows/2 - m_rows/2, cv_ptr->image.rows/2 + m_rows/2), cv::Range(cv_ptr->image.cols/2 - m_cols/2, cv_ptr->image.cols/2 + m_cols/2)); // mark it as foreground fg_seed.setTo(cv::GC_PR_FGD); // select first 5 rows of the image as background cv::Mat1b bg_seed = markers(cv::Range(0, 10),cv::Range::all()); bg_seed.setTo(cv::GC_BGD); bg_seed = markers(cv::Range(470, 480),cv::Range::all()); bg_seed.setTo(cv::GC_BGD); cv::Mat bgd, fgd; int iterations = 1; cv::grabCut(cv_ptr->image, markers, cv::Rect(), bgd, fgd, iterations, cv::GC_INIT_WITH_MASK); // let's get all foreground and possible foreground pixels cv::Mat1b mask_fgpf = ( markers == cv::GC_FGD) | ( markers == cv::GC_PR_FGD); // and copy all the foreground-pixels to a temporary image cv::Mat3b tmp = cv::Mat3b::zeros(cv_ptr->image.rows, cv_ptr->image.cols); cv_ptr->image.copyTo(tmp, mask_fgpf); // show it cv::imshow("foreground", tmp); cv::waitKey(3); // cv::Rect rectangle(100,0,350,480); // // cv::grabCut(downsampled,result,rectangle,bgModel,fgModel,2,cv::GC_INIT_WITH_RECT); // use rectangle // cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ); // cv::Mat resultUp; // cv::pyrUp(result, resultUp, cv::Size(result.cols*2, result.rows*2)); // cv::Mat foreground(cv_ptr->image.size(),CV_8UC3,cv::Scalar(255,255,255)); // cv_ptr->image.copyTo(foreground,resultUp); // bg pixels not copied // cv::rectangle(foreground, rectangle, cv::Scalar(0,0,255),1); // // // Update GUI Window // cv::imshow("Masked Image", foreground); // cv::waitKey(3); // // // Output modified video stream // image_pub_.publish(cv_ptr->toImageMsg()); } }; int main(int argc, char** argv) { ros::init(argc, argv, "image_converter"); ImageConverter ic; ros::spin(); return 0; } <commit_msg>Working with grabcut and downsample<commit_after>#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; static const std::string OPENCV_WINDOW = "Image window"; int findBiggestContour(vector<vector<Point> >); class ImageConverter { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; public: ImageConverter() : it_(nh_) { // Subscrive to input video feed and publish output video feed image_sub_ = it_.subscribe("/camera/color/image_raw", 1, &ImageConverter::imageCb, this); image_pub_ = it_.advertise("/image_converter/output_video", 1); cv::namedWindow(OPENCV_WINDOW); } ~ImageConverter() { cv::destroyWindow(OPENCV_WINDOW); } int findBiggestContour(vector<vector<Point> > contours){ int indexOfBiggestContour = -1; int sizeOfBiggestContour = 0; for (int i = 0; i < contours.size(); i++){ if(contours[i].size() > sizeOfBiggestContour){ sizeOfBiggestContour = contours[i].size(); indexOfBiggestContour = i; } } return indexOfBiggestContour; } void imageCb(const sensor_msgs::ImageConstPtr& msg) { cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } cv::Mat downsampled; cv::Mat result; // segmentation result (4 possible values) cv::Mat bgModel; cv::Mat fgModel; // the models (internally used) cv::Mat blurred; cv::Mat hsv; cv::Mat bw; cv::pyrDown(cv_ptr->image, downsampled, cv::Size(cv_ptr->image.cols/2, cv_ptr->image.rows/2)); cv::imshow("downsampled", downsampled); // //Skin Detection // cv::blur( downsampled, blurred, cv::Size(3,3) ); // cv::cvtColor(blurred, hsv, CV_BGR2HSV); // cv::inRange(hsv, cv::Scalar(0, 10, 60), cv::Scalar(20, 150, 255), bw); // // Mat canny_output; // vector<vector<Point> > contours; // vector<Vec4i> hierarchy; // // findContours( bw, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); // int s = findBiggestContour(contours); // // Mat drawing = Mat::zeros( downsampled.size(), CV_8UC1 ); // drawContours( drawing, contours, s, Scalar(255), -1, 8, hierarchy, 0, Point() ); // // // cv::imshow("Skin Detection", bw); // imshow("drw", drawing); //Test Mask Grabcut cv::Mat1b markers(cv_ptr->image.rows/2, cv_ptr->image.cols/2); // let's set all of them to possible background first markers.setTo(cv::GC_PR_BGD); // cut out a small area in the middle of the image int m_rows = cv_ptr->image.rows; int m_cols = 0.5 * cv_ptr->image.cols; // of course here you could also use cv::Rect() instead of cv::Range to select // the region of interest cv::Mat1b fg_seed = markers(cv::Range(cv_ptr->image.rows/4 - m_rows/4, cv_ptr->image.rows/4 + m_rows/4), cv::Range(cv_ptr->image.cols/4 - m_cols/4, cv_ptr->image.cols/4 + m_cols/4)); // mark it as foreground fg_seed.setTo(cv::GC_PR_FGD); // select first 5 rows of the image as background cv::Mat1b bg_seed = markers(cv::Range(0, 2),cv::Range::all()); bg_seed.setTo(cv::GC_BGD); bg_seed = markers(cv::Range(10, 11),cv::Range::all()); bg_seed.setTo(cv::GC_BGD); cv::Mat bgd, fgd; int iterations = 1; cv::grabCut(downsampled, markers, cv::Rect(), bgd, fgd, iterations, cv::GC_INIT_WITH_MASK); cv::Mat resultUp; // let's get all foreground and possible foreground pixels cv::Mat1b mask_fgpf = ( markers == cv::GC_FGD) | ( markers == cv::GC_PR_FGD); // and copy all the foreground-pixels to a temporary image cv::pyrUp(mask_fgpf, resultUp, cv::Size(result.cols*2, result.rows*2)); cv::Mat3b tmp = cv::Mat3b::zeros(cv_ptr->image.rows, cv_ptr->image.cols); cv_ptr->image.copyTo(tmp, resultUp); // show it cv::imshow("foreground", tmp); cv::waitKey(3); // cv::Rect rectangle(100,0,350,480); // // cv::grabCut(downsampled,result,rectangle,bgModel,fgModel,2,cv::GC_INIT_WITH_RECT); // use rectangle // cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ); // cv::Mat resultUp; // cv::pyrUp(result, resultUp, cv::Size(result.cols*2, result.rows*2)); // cv::Mat foreground(cv_ptr->image.size(),CV_8UC3,cv::Scalar(255,255,255)); // cv_ptr->image.copyTo(foreground,resultUp); // bg pixels not copied // cv::rectangle(foreground, rectangle, cv::Scalar(0,0,255),1); // // // Update GUI Window // cv::imshow("Masked Image", foreground); // cv::waitKey(3); // // // Output modified video stream // image_pub_.publish(cv_ptr->toImageMsg()); } }; int main(int argc, char** argv) { ros::init(argc, argv, "image_converter"); ImageConverter ic; ros::spin(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkXRenderWindow.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 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 <math.h> #include <stdlib.h> #include <iostream.h> #include "vtkXRenderWindow.h" #include "vtkXRenderWindowInteractor.h" vtkXRenderWindow::vtkXRenderWindow() { this->DisplayId = (Display *)NULL; this->WindowId = (Window)NULL; this->ParentId = (Window)NULL; this->NextWindowId = (Window)NULL; this->ColorMap = (Colormap)NULL; this->ScreenSize[0] = 0; this->ScreenSize[1] = 0; } vtkXRenderWindow::~vtkXRenderWindow() { if (this->Interactor) this->Interactor->Delete(); } int vtkXRenderWindowFoundMatch; Bool vtkXRenderWindowPredProc(Display *disp, XEvent *event, char *arg) { Window win = (Window)arg; if ((((XAnyEvent *)event)->window == win) && ((event->type == ButtonPress))) vtkXRenderWindowFoundMatch = 1; return 0; } int vtkXRenderWindow::GetEventPending() { XEvent report; vtkXRenderWindowFoundMatch = 0; XCheckIfEvent(this->DisplayId, &report, vtkXRenderWindowPredProc, (char *)this->WindowId); return vtkXRenderWindowFoundMatch; } // Description: // Get the size of the screen in pixels int *vtkXRenderWindow::GetScreenSize() { // get the default display connection if (!this->DisplayId) { this->DisplayId = XOpenDisplay((char *)NULL); if (this->DisplayId == NULL) { vtkErrorMacro(<< "bad X server connection.\n"); } } this->ScreenSize[0] = DisplayWidth(this->DisplayId, DefaultScreen(this->DisplayId)); this->ScreenSize[1] = DisplayHeight(this->DisplayId, DefaultScreen(this->DisplayId)); return this->ScreenSize; } // Description: // Get the current size of the window in pixels. int *vtkXRenderWindow::GetSize(void) { XWindowAttributes attribs; // if we aren't mapped then just return the ivar if (!this->Mapped) { return(this->Size); } // Find the current window size XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs); this->Size[0] = attribs.width; this->Size[1] = attribs.height; return this->Size; } // Description: // Get the position in screen coordinates (pixels) of the window. int *vtkXRenderWindow::GetPosition(void) { XWindowAttributes attribs; int x,y; Window child; // if we aren't mapped then just return the ivar if (!this->Mapped) { return(this->Position); } // Find the current window size XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs); x = attribs.x; y = attribs.y; XTranslateCoordinates(this->DisplayId,this->WindowId, RootWindowOfScreen(ScreenOfDisplay(this->DisplayId,0)), x,y,&this->Position[0],&this->Position[1],&child); return this->Position; } // Description: // Get this RenderWindow's X display id. Display *vtkXRenderWindow::GetDisplayId() { vtkDebugMacro(<< "Returning DisplayId of " << (void *)this->DisplayId << "\n"); return this->DisplayId; } // Description: // Get this RenderWindow's parent X window id. Window vtkXRenderWindow::GetParentId() { vtkDebugMacro(<< "Returning ParentId of " << (void *)this->ParentId << "\n"); return this->ParentId; } // Description: // Get this RenderWindow's X window id. Window vtkXRenderWindow::GetWindowId() { vtkDebugMacro(<< "Returning WindowId of " << (void *)this->WindowId << "\n"); return this->WindowId; } // Description: // Move the window to a new position on the display. void vtkXRenderWindow::SetPosition(int x, int y) { // if we aren't mapped then just set the ivars if (!this->Mapped) { if ((this->Position[0] != x)||(this->Position[1] != y)) { this->Modified(); } this->Position[0] = x; this->Position[1] = y; return; } XMoveResizeWindow(this->DisplayId,this->WindowId,x,y, this->Size[0], this->Size[1]); XSync(this->DisplayId,False); } // Description: // Sets the parent of the window that WILL BE created. void vtkXRenderWindow::SetParentId(Window arg) { if (this->ParentId) { vtkErrorMacro("ParentId is already set."); return; } vtkDebugMacro(<< "Setting ParentId to " << (void *)arg << "\n"); this->ParentId = arg; } // Description: // Set this RenderWindow's X window id to a pre-existing window. void vtkXRenderWindow::SetWindowId(Window arg) { vtkDebugMacro(<< "Setting WindowId to " << (void *)arg << "\n"); this->WindowId = arg; } void vtkXRenderWindow::SetWindowId(void *arg) { this->SetWindowId((Window)arg); } void vtkXRenderWindow::SetWindowName(char * name) { XTextProperty win_name_text_prop; vtkRenderWindow::SetWindowName( name ); if (this->Mapped) { if( XStringListToTextProperty( &name, 1, &win_name_text_prop ) == 0 ) { vtkWarningMacro(<< "Can't rename window"); return; } XSetWMName( this->DisplayId, this->WindowId, &win_name_text_prop ); XSetWMIconName( this->DisplayId, this->WindowId, &win_name_text_prop ); } } // Description: // Specify the X window id to use if a WindowRemap is done. void vtkXRenderWindow::SetNextWindowId(Window arg) { vtkDebugMacro(<< "Setting NextWindowId to " << (void *)arg << "\n"); this->NextWindowId = arg; } // Description: // Set the X display id for this RenderWindow to use to a pre-existing // X display id. void vtkXRenderWindow::SetDisplayId(Display *arg) { vtkDebugMacro(<< "Setting DisplayId to " << (void *)arg << "\n"); this->DisplayId = arg; } void vtkXRenderWindow::SetDisplayId(void *arg) { this->SetDisplayId((Display *)arg); } void vtkXRenderWindow::PrintSelf(ostream& os, vtkIndent indent) { this->vtkRenderWindow::PrintSelf(os,indent); os << indent << "Color Map: " << this->ColorMap << "\n"; os << indent << "Display Id: " << this->GetDisplayId() << "\n"; os << indent << "Next Window Id: " << this->NextWindowId << "\n"; os << indent << "Window Id: " << this->GetWindowId() << "\n"; } <commit_msg>fixed warning and delete of interactor<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkXRenderWindow.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 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 <math.h> #include <stdlib.h> #include <iostream.h> #include "vtkXRenderWindow.h" #include "vtkXRenderWindowInteractor.h" vtkXRenderWindow::vtkXRenderWindow() { this->DisplayId = (Display *)NULL; this->WindowId = (Window)NULL; this->ParentId = (Window)NULL; this->NextWindowId = (Window)NULL; this->ColorMap = (Colormap)NULL; this->ScreenSize[0] = 0; this->ScreenSize[1] = 0; } vtkXRenderWindow::~vtkXRenderWindow() { } int vtkXRenderWindowFoundMatch; Bool vtkXRenderWindowPredProc(Display *vtkNotUsed(disp), XEvent *event, char *arg) { Window win = (Window)arg; if ((((XAnyEvent *)event)->window == win) && ((event->type == ButtonPress))) vtkXRenderWindowFoundMatch = 1; return 0; } int vtkXRenderWindow::GetEventPending() { XEvent report; vtkXRenderWindowFoundMatch = 0; XCheckIfEvent(this->DisplayId, &report, vtkXRenderWindowPredProc, (char *)this->WindowId); return vtkXRenderWindowFoundMatch; } // Description: // Get the size of the screen in pixels int *vtkXRenderWindow::GetScreenSize() { // get the default display connection if (!this->DisplayId) { this->DisplayId = XOpenDisplay((char *)NULL); if (this->DisplayId == NULL) { vtkErrorMacro(<< "bad X server connection.\n"); } } this->ScreenSize[0] = DisplayWidth(this->DisplayId, DefaultScreen(this->DisplayId)); this->ScreenSize[1] = DisplayHeight(this->DisplayId, DefaultScreen(this->DisplayId)); return this->ScreenSize; } // Description: // Get the current size of the window in pixels. int *vtkXRenderWindow::GetSize(void) { XWindowAttributes attribs; // if we aren't mapped then just return the ivar if (!this->Mapped) { return(this->Size); } // Find the current window size XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs); this->Size[0] = attribs.width; this->Size[1] = attribs.height; return this->Size; } // Description: // Get the position in screen coordinates (pixels) of the window. int *vtkXRenderWindow::GetPosition(void) { XWindowAttributes attribs; int x,y; Window child; // if we aren't mapped then just return the ivar if (!this->Mapped) { return(this->Position); } // Find the current window size XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs); x = attribs.x; y = attribs.y; XTranslateCoordinates(this->DisplayId,this->WindowId, RootWindowOfScreen(ScreenOfDisplay(this->DisplayId,0)), x,y,&this->Position[0],&this->Position[1],&child); return this->Position; } // Description: // Get this RenderWindow's X display id. Display *vtkXRenderWindow::GetDisplayId() { vtkDebugMacro(<< "Returning DisplayId of " << (void *)this->DisplayId << "\n"); return this->DisplayId; } // Description: // Get this RenderWindow's parent X window id. Window vtkXRenderWindow::GetParentId() { vtkDebugMacro(<< "Returning ParentId of " << (void *)this->ParentId << "\n"); return this->ParentId; } // Description: // Get this RenderWindow's X window id. Window vtkXRenderWindow::GetWindowId() { vtkDebugMacro(<< "Returning WindowId of " << (void *)this->WindowId << "\n"); return this->WindowId; } // Description: // Move the window to a new position on the display. void vtkXRenderWindow::SetPosition(int x, int y) { // if we aren't mapped then just set the ivars if (!this->Mapped) { if ((this->Position[0] != x)||(this->Position[1] != y)) { this->Modified(); } this->Position[0] = x; this->Position[1] = y; return; } XMoveResizeWindow(this->DisplayId,this->WindowId,x,y, this->Size[0], this->Size[1]); XSync(this->DisplayId,False); } // Description: // Sets the parent of the window that WILL BE created. void vtkXRenderWindow::SetParentId(Window arg) { if (this->ParentId) { vtkErrorMacro("ParentId is already set."); return; } vtkDebugMacro(<< "Setting ParentId to " << (void *)arg << "\n"); this->ParentId = arg; } // Description: // Set this RenderWindow's X window id to a pre-existing window. void vtkXRenderWindow::SetWindowId(Window arg) { vtkDebugMacro(<< "Setting WindowId to " << (void *)arg << "\n"); this->WindowId = arg; } void vtkXRenderWindow::SetWindowId(void *arg) { this->SetWindowId((Window)arg); } void vtkXRenderWindow::SetWindowName(char * name) { XTextProperty win_name_text_prop; vtkRenderWindow::SetWindowName( name ); if (this->Mapped) { if( XStringListToTextProperty( &name, 1, &win_name_text_prop ) == 0 ) { vtkWarningMacro(<< "Can't rename window"); return; } XSetWMName( this->DisplayId, this->WindowId, &win_name_text_prop ); XSetWMIconName( this->DisplayId, this->WindowId, &win_name_text_prop ); } } // Description: // Specify the X window id to use if a WindowRemap is done. void vtkXRenderWindow::SetNextWindowId(Window arg) { vtkDebugMacro(<< "Setting NextWindowId to " << (void *)arg << "\n"); this->NextWindowId = arg; } // Description: // Set the X display id for this RenderWindow to use to a pre-existing // X display id. void vtkXRenderWindow::SetDisplayId(Display *arg) { vtkDebugMacro(<< "Setting DisplayId to " << (void *)arg << "\n"); this->DisplayId = arg; } void vtkXRenderWindow::SetDisplayId(void *arg) { this->SetDisplayId((Display *)arg); } void vtkXRenderWindow::PrintSelf(ostream& os, vtkIndent indent) { this->vtkRenderWindow::PrintSelf(os,indent); os << indent << "Color Map: " << this->ColorMap << "\n"; os << indent << "Display Id: " << this->GetDisplayId() << "\n"; os << indent << "Next Window Id: " << this->NextWindowId << "\n"; os << indent << "Window Id: " << this->GetWindowId() << "\n"; } <|endoftext|>
<commit_before>// $Id$ Reve::Track* esd_make_track(Reve::TrackRnrStyle* rnrStyle, Int_t index, AliESDtrack* at, AliExternalTrackParam* tp=0) { // Helper function Double_t pbuf[3], vbuf[3]; Reve::RecTrack rt; if(tp == 0) tp = at; rt.label = at->GetLabel(); rt.index = index; rt.status = (Int_t) at->GetStatus(); rt.sign = tp->GetSign(); tp->GetXYZ(vbuf); rt.V.Set(vbuf); tp->GetPxPyPz(pbuf); rt.P.Set(pbuf); Double_t ep = at->GetP(), mc = at->GetMass(); rt.beta = ep/TMath::Sqrt(ep*ep + mc*mc); Reve::Track* track = new Reve::Track(&rt, rnrStyle); //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH track->SetName(Form("ESDTrack %d", rt.label)); //PH track->SetTitle(Form("pT=%.3f, pZ=%.3f; V=(%.3f, %.3f, %.3f)", //PH rt.sign*TMath::Hypot(rt.P.x, rt.P.y), rt.P.z, //PH rt.V.x, rt.V.y, rt.V.z)); char form[1000]; sprintf(form,"Track %d", rt.index); track->SetName(form); track->SetStdTitle(); return track; } Bool_t gkFixFailedITSExtr = kFALSE; Reve::TrackList* esd_tracks(Double_t min_pt=0.1, Double_t max_pt=100) { AliESDEvent* esd = Alieve::Event::AssertESD(); Double_t minptsq = min_pt*min_pt; Double_t maxptsq = max_pt*max_pt; Double_t ptsq; Reve::TrackList* cont = new Reve::TrackList("ESD Tracks"); cont->SetMainColor(Color_t(6)); Reve::TrackRnrStyle* rnrStyle = cont->GetRnrStyle(); rnrStyle->SetMagField( esd->GetMagneticField() ); gReve->AddRenderElement(cont); Int_t count = 0; Double_t pbuf[3]; for (Int_t n=0; n<esd->GetNumberOfTracks(); n++) { AliESDtrack* at = esd->GetTrack(n); // Here would be sweet to have TObjectFormula. at->GetPxPyPz(pbuf); ptsq = pbuf[0]*pbuf[0] + pbuf[1]*pbuf[1]; if(ptsq < minptsq || ptsq > maxptsq) continue; ++count; // If gkFixFailedITSExtr is TRUE (FALSE by default) and // if ITS refit failed, take track parameters at inner TPC radius. AliExternalTrackParam* tp = at; if (gkFixFailedITSExtr && !at->IsOn(AliESDtrack::kITSrefit)) { tp = at->GetInnerParam(); } Reve::Track* track = esd_make_track(rnrStyle, n, at, tp); track->SetAttLineAttMarker(cont); gReve->AddRenderElement(track, cont); } //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH const Text_t* tooltip = Form("pT ~ (%.2lf, %.2lf), N=%d", min_pt, max_pt, count); char tooltip[1000]; sprintf(tooltip,"pT ~ (%.2lf, %.2lf), N=%d", min_pt, max_pt, count); cont->SetTitle(tooltip); // Not broadcasted automatically ... cont->UpdateItems(); cont->MakeTracks(); gReve->Redraw3D(); return cont; } /**************************************************************************/ // esd_tracks_from_array() /**************************************************************************/ Reve::TrackList* esd_tracks_from_array(TCollection* col, AliESDEvent* esd=0) { // Retrieves AliESDTrack's from collection. // See example usage with AliAnalysisTrackCuts in the next function. if(esd == 0) esd = Alieve::Event::AssertESD(); Reve::TrackList* cont = new Reve::TrackList("ESD Tracks"); cont->SetMainColor(Color_t(6)); Reve::TrackRnrStyle* rnrStyle = cont->GetRnrStyle(); rnrStyle->SetMagField( esd->GetMagneticField() ); gReve->AddRenderElement(cont); Int_t count = 0; TIter next(col); TObject *obj; while((obj = next()) != 0) { if(obj->IsA()->InheritsFrom("AliESDtrack") == kFALSE) { Warning("Object '%s', '%s' is not an AliESDtrack.", obj->GetName(), obj->GetTitle()); continue; } ++count; AliESDtrack* at = (AliESDtrack*) obj; Reve::Track* track = esd_make_track(rnrStyle, count, at); track->SetAttLineAttMarker(cont); gReve->AddRenderElement(track, cont); } //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH const Text_t* tooltip = Form("N=%d", count); const tooltip[1000]; sprintf(tooltip,"N=%d", count); cont->SetTitle(tooltip); // Not broadcasted automatically ... cont->UpdateItems(); cont->MakeTracks(); gReve->Redraw3D(); return cont; } void esd_tracks_alianalcuts_demo() { AliESDEvent* esd = Alieve::Event::AssertESD(); gSystem->Load("libANALYSIS"); AliAnalysisTrackCuts atc; atc.SetPtRange(0.1, 5); atc.SetRapRange(-1, 1); esd_tracks_from_array(atc.GetAcceptedParticles(esd), esd); } /**************************************************************************/ // esd_tracks_vertex_cut /**************************************************************************/ Float_t get_sigma_to_vertex(AliESDtrack* esdTrack) { // Taken from: PWG0/esdTrackCuts/AliESDtrackCuts.cxx // Float_t AliESDtrackCuts::GetSigmaToVertex(AliESDtrack* esdTrack) Float_t b[2]; Float_t bRes[2]; Float_t bCov[3]; esdTrack->GetImpactParameters(b,bCov); if (bCov[0]<=0 || bCov[2]<=0) { printf("Estimated b resolution lower or equal zero!\n"); bCov[0]=0; bCov[2]=0; } bRes[0] = TMath::Sqrt(bCov[0]); bRes[1] = TMath::Sqrt(bCov[2]); // ----------------------------------- // How to get to a n-sigma cut? // // The accumulated statistics from 0 to d is // // -> Erf(d/Sqrt(2)) for a 1-dim gauss (d = n_sigma) // -> 1 - Exp(-d**2) for a 2-dim gauss (d*d = dx*dx + dy*dy != n_sigma) // // It means that for a 2-dim gauss: n_sigma(d) = Sqrt(2)*ErfInv(1 - Exp((-x**2)/2) // Can this be expressed in a different way? if (bRes[0] == 0 || bRes[1] ==0) return -1; Float_t d = TMath::Sqrt(TMath::Power(b[0]/bRes[0],2) + TMath::Power(b[1]/bRes[1],2)); // stupid rounding problem screws up everything: // if d is too big, TMath::Exp(...) gets 0, and TMath::ErfInverse(1) that should be infinite, gets 0 :( if (TMath::Exp(-d * d / 2) < 1e-10) return 1000; d = TMath::ErfInverse(1 - TMath::Exp(-d * d / 2)) * TMath::Sqrt(2); return d; } Reve::RenderElementList* esd_tracks_vertex_cut() { // Import ESD tracks, separate them into five containers according to // primary-vertex cut and ITS refit status. AliESDEvent* esd = Alieve::Event::AssertESD(); Reve::RenderElementList* cont = new Reve::RenderElementList("ESD Tracks", 0, kTRUE); gReve->AddRenderElement(cont); Reve::TrackList *tl[5]; Int_t tc[5]; Int_t count = 0; tl[0] = new Reve::TrackList("Sigma < 3"); tc[0] = 0; tl[0]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[0]->SetMainColor(Color_t(3)); gReve->AddRenderElement(tl[0], cont); tl[1] = new Reve::TrackList("3 < Sigma < 5"); tc[1] = 0; tl[1]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[1]->SetMainColor(Color_t(7)); gReve->AddRenderElement(tl[1], cont); tl[2] = new Reve::TrackList("5 < Sigma"); tc[2] = 0; tl[2]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[2]->SetMainColor(Color_t(46)); gReve->AddRenderElement(tl[2], cont); tl[3] = new Reve::TrackList("no ITS refit; Sigma < 5"); tc[3] = 0; tl[3]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[3]->SetMainColor(Color_t(41)); gReve->AddRenderElement(tl[3], cont); tl[4] = new Reve::TrackList("no ITS refit; Sigma > 5"); tc[4] = 0; tl[4]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[4]->SetMainColor(Color_t(48)); gReve->AddRenderElement(tl[4], cont); for (Int_t n=0; n<esd->GetNumberOfTracks(); n++) { AliESDtrack* at = esd->GetTrack(n); Float_t s = get_sigma_to_vertex(at); Int_t ti; if (s < 3) ti = 0; else if (s <= 5) ti = 1; else ti = 2; AliExternalTrackParam* tp = at; // If ITS refit failed, optionally take track parameters at inner // TPC radius and put track in a special container. // This ignores state of gkFixFailedITSExtr (used in esd_tracks()). // Use BOTH functions to compare results. if (!at->IsOn(AliESDtrack::kITSrefit)) { // tp = at->GetInnerParam(); ti = (ti == 2) ? 4 : 3; } Reve::TrackList* tlist = tl[ti]; ++tc[ti]; ++count; Reve::Track* track = esd_make_track(tlist->GetRnrStyle(), n, at, tp); track->SetAttLineAttMarker(tlist); //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH track->SetName(Form("track %d, sigma=%5.3f", at->GetLabel(), s)); char form[1000]; sprintf(form,"Track idx=%d, sigma=%5.3f", at->GetIndex(), s); track->SetName(form); gReve->AddRenderElement(track, tlist); } for (Int_t ti=0; ti<5; ++ti) { Reve::TrackList* tlist = tl[ti]; //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH const Text_t* tooltip = Form("N tracks=%d", tc[ti]); //MT Modified somewhat. char buff[1000]; sprintf(buff, "%s [%d]", tlist->GetName(), tlist->GetNChildren()); tlist->SetName(buff); sprintf(buff, "N tracks=%d", tc[ti]); tlist->SetTitle(buff); // Not broadcasted automatically ... tlist->UpdateItems(); tlist->MakeTracks(); } //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH cont->SetTitle(Form("N all tracks = %d", count)); char form[1000]; sprintf(form,"N all tracks = %d", count); cont->SetTitle(form); cont->UpdateItems(); gReve->Redraw3D(); return cont; } <commit_msg>Follow rename of method in AliESDtrack.<commit_after>// $Id$ Reve::Track* esd_make_track(Reve::TrackRnrStyle* rnrStyle, Int_t index, AliESDtrack* at, AliExternalTrackParam* tp=0) { // Helper function Double_t pbuf[3], vbuf[3]; Reve::RecTrack rt; if(tp == 0) tp = at; rt.label = at->GetLabel(); rt.index = index; rt.status = (Int_t) at->GetStatus(); rt.sign = tp->GetSign(); tp->GetXYZ(vbuf); rt.V.Set(vbuf); tp->GetPxPyPz(pbuf); rt.P.Set(pbuf); Double_t ep = at->GetP(), mc = at->GetMass(); rt.beta = ep/TMath::Sqrt(ep*ep + mc*mc); Reve::Track* track = new Reve::Track(&rt, rnrStyle); //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH track->SetName(Form("ESDTrack %d", rt.label)); //PH track->SetTitle(Form("pT=%.3f, pZ=%.3f; V=(%.3f, %.3f, %.3f)", //PH rt.sign*TMath::Hypot(rt.P.x, rt.P.y), rt.P.z, //PH rt.V.x, rt.V.y, rt.V.z)); char form[1000]; sprintf(form,"Track %d", rt.index); track->SetName(form); track->SetStdTitle(); return track; } Bool_t gkFixFailedITSExtr = kFALSE; Reve::TrackList* esd_tracks(Double_t min_pt=0.1, Double_t max_pt=100) { AliESDEvent* esd = Alieve::Event::AssertESD(); Double_t minptsq = min_pt*min_pt; Double_t maxptsq = max_pt*max_pt; Double_t ptsq; Reve::TrackList* cont = new Reve::TrackList("ESD Tracks"); cont->SetMainColor(Color_t(6)); Reve::TrackRnrStyle* rnrStyle = cont->GetRnrStyle(); rnrStyle->SetMagField( esd->GetMagneticField() ); gReve->AddRenderElement(cont); Int_t count = 0; Double_t pbuf[3]; for (Int_t n=0; n<esd->GetNumberOfTracks(); n++) { AliESDtrack* at = esd->GetTrack(n); // Here would be sweet to have TObjectFormula. at->GetPxPyPz(pbuf); ptsq = pbuf[0]*pbuf[0] + pbuf[1]*pbuf[1]; if(ptsq < minptsq || ptsq > maxptsq) continue; ++count; // If gkFixFailedITSExtr is TRUE (FALSE by default) and // if ITS refit failed, take track parameters at inner TPC radius. AliExternalTrackParam* tp = at; if (gkFixFailedITSExtr && !at->IsOn(AliESDtrack::kITSrefit)) { tp = at->GetInnerParam(); } Reve::Track* track = esd_make_track(rnrStyle, n, at, tp); track->SetAttLineAttMarker(cont); gReve->AddRenderElement(track, cont); } //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH const Text_t* tooltip = Form("pT ~ (%.2lf, %.2lf), N=%d", min_pt, max_pt, count); char tooltip[1000]; sprintf(tooltip,"pT ~ (%.2lf, %.2lf), N=%d", min_pt, max_pt, count); cont->SetTitle(tooltip); // Not broadcasted automatically ... cont->UpdateItems(); cont->MakeTracks(); gReve->Redraw3D(); return cont; } /**************************************************************************/ // esd_tracks_from_array() /**************************************************************************/ Reve::TrackList* esd_tracks_from_array(TCollection* col, AliESDEvent* esd=0) { // Retrieves AliESDTrack's from collection. // See example usage with AliAnalysisTrackCuts in the next function. if(esd == 0) esd = Alieve::Event::AssertESD(); Reve::TrackList* cont = new Reve::TrackList("ESD Tracks"); cont->SetMainColor(Color_t(6)); Reve::TrackRnrStyle* rnrStyle = cont->GetRnrStyle(); rnrStyle->SetMagField( esd->GetMagneticField() ); gReve->AddRenderElement(cont); Int_t count = 0; TIter next(col); TObject *obj; while((obj = next()) != 0) { if(obj->IsA()->InheritsFrom("AliESDtrack") == kFALSE) { Warning("Object '%s', '%s' is not an AliESDtrack.", obj->GetName(), obj->GetTitle()); continue; } ++count; AliESDtrack* at = (AliESDtrack*) obj; Reve::Track* track = esd_make_track(rnrStyle, count, at); track->SetAttLineAttMarker(cont); gReve->AddRenderElement(track, cont); } //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH const Text_t* tooltip = Form("N=%d", count); const tooltip[1000]; sprintf(tooltip,"N=%d", count); cont->SetTitle(tooltip); // Not broadcasted automatically ... cont->UpdateItems(); cont->MakeTracks(); gReve->Redraw3D(); return cont; } void esd_tracks_alianalcuts_demo() { AliESDEvent* esd = Alieve::Event::AssertESD(); gSystem->Load("libANALYSIS"); AliAnalysisTrackCuts atc; atc.SetPtRange(0.1, 5); atc.SetRapRange(-1, 1); esd_tracks_from_array(atc.GetAcceptedParticles(esd), esd); } /**************************************************************************/ // esd_tracks_vertex_cut /**************************************************************************/ Float_t get_sigma_to_vertex(AliESDtrack* esdTrack) { // Taken from: PWG0/esdTrackCuts/AliESDtrackCuts.cxx // Float_t AliESDtrackCuts::GetSigmaToVertex(AliESDtrack* esdTrack) Float_t b[2]; Float_t bRes[2]; Float_t bCov[3]; esdTrack->GetImpactParameters(b,bCov); if (bCov[0]<=0 || bCov[2]<=0) { printf("Estimated b resolution lower or equal zero!\n"); bCov[0]=0; bCov[2]=0; } bRes[0] = TMath::Sqrt(bCov[0]); bRes[1] = TMath::Sqrt(bCov[2]); // ----------------------------------- // How to get to a n-sigma cut? // // The accumulated statistics from 0 to d is // // -> Erf(d/Sqrt(2)) for a 1-dim gauss (d = n_sigma) // -> 1 - Exp(-d**2) for a 2-dim gauss (d*d = dx*dx + dy*dy != n_sigma) // // It means that for a 2-dim gauss: n_sigma(d) = Sqrt(2)*ErfInv(1 - Exp((-x**2)/2) // Can this be expressed in a different way? if (bRes[0] == 0 || bRes[1] ==0) return -1; Float_t d = TMath::Sqrt(TMath::Power(b[0]/bRes[0],2) + TMath::Power(b[1]/bRes[1],2)); // stupid rounding problem screws up everything: // if d is too big, TMath::Exp(...) gets 0, and TMath::ErfInverse(1) that should be infinite, gets 0 :( if (TMath::Exp(-d * d / 2) < 1e-10) return 1000; d = TMath::ErfInverse(1 - TMath::Exp(-d * d / 2)) * TMath::Sqrt(2); return d; } Reve::RenderElementList* esd_tracks_vertex_cut() { // Import ESD tracks, separate them into five containers according to // primary-vertex cut and ITS refit status. AliESDEvent* esd = Alieve::Event::AssertESD(); Reve::RenderElementList* cont = new Reve::RenderElementList("ESD Tracks", 0, kTRUE); gReve->AddRenderElement(cont); Reve::TrackList *tl[5]; Int_t tc[5]; Int_t count = 0; tl[0] = new Reve::TrackList("Sigma < 3"); tc[0] = 0; tl[0]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[0]->SetMainColor(Color_t(3)); gReve->AddRenderElement(tl[0], cont); tl[1] = new Reve::TrackList("3 < Sigma < 5"); tc[1] = 0; tl[1]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[1]->SetMainColor(Color_t(7)); gReve->AddRenderElement(tl[1], cont); tl[2] = new Reve::TrackList("5 < Sigma"); tc[2] = 0; tl[2]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[2]->SetMainColor(Color_t(46)); gReve->AddRenderElement(tl[2], cont); tl[3] = new Reve::TrackList("no ITS refit; Sigma < 5"); tc[3] = 0; tl[3]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[3]->SetMainColor(Color_t(41)); gReve->AddRenderElement(tl[3], cont); tl[4] = new Reve::TrackList("no ITS refit; Sigma > 5"); tc[4] = 0; tl[4]->GetRnrStyle()->SetMagField( esd->GetMagneticField() ); tl[4]->SetMainColor(Color_t(48)); gReve->AddRenderElement(tl[4], cont); for (Int_t n=0; n<esd->GetNumberOfTracks(); n++) { AliESDtrack* at = esd->GetTrack(n); Float_t s = get_sigma_to_vertex(at); Int_t ti; if (s < 3) ti = 0; else if (s <= 5) ti = 1; else ti = 2; AliExternalTrackParam* tp = at; // If ITS refit failed, optionally take track parameters at inner // TPC radius and put track in a special container. // This ignores state of gkFixFailedITSExtr (used in esd_tracks()). // Use BOTH functions to compare results. if (!at->IsOn(AliESDtrack::kITSrefit)) { // tp = at->GetInnerParam(); ti = (ti == 2) ? 4 : 3; } Reve::TrackList* tlist = tl[ti]; ++tc[ti]; ++count; Reve::Track* track = esd_make_track(tlist->GetRnrStyle(), n, at, tp); track->SetAttLineAttMarker(tlist); //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH track->SetName(Form("track %d, sigma=%5.3f", at->GetLabel(), s)); char form[1000]; sprintf(form,"Track idx=%d, sigma=%5.3f", at->GetID(), s); track->SetName(form); gReve->AddRenderElement(track, tlist); } for (Int_t ti=0; ti<5; ++ti) { Reve::TrackList* tlist = tl[ti]; //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH const Text_t* tooltip = Form("N tracks=%d", tc[ti]); //MT Modified somewhat. char buff[1000]; sprintf(buff, "%s [%d]", tlist->GetName(), tlist->GetNChildren()); tlist->SetName(buff); sprintf(buff, "N tracks=%d", tc[ti]); tlist->SetTitle(buff); // Not broadcasted automatically ... tlist->UpdateItems(); tlist->MakeTracks(); } //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) //PH cont->SetTitle(Form("N all tracks = %d", count)); char form[1000]; sprintf(form,"N all tracks = %d", count); cont->SetTitle(form); cont->UpdateItems(); gReve->Redraw3D(); return cont; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ip_type.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 16:19:36 $ * * 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 ARY_IDL_IP_TYPE_HXX #define ARY_IDL_IP_TYPE_HXX // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS #include <ary/idl/i_language.hxx> namespace ary { class QualifiedName; namespace idl { class Type; class ExplicitNameRoom; class TypePilot { public: // LIFECYCLE virtual TypePilot::~TypePilot() {} // OPERATIONS const Type & CheckIn_Type( QualifiedName & i_rFullName, uintt i_nSequenceCount, Ce_id i_nModuleOfOccurrence, Type_id i_nTemplateType ); // INQUIRY const Type & Find_Type( Type_id i_nType ) const; String Search_LocalNameOf( Type_id i_nType ) const; Ce_id Search_CeRelatedTo( Type_id i_nType ) const; const ExplicitNameRoom & Find_XNameRoom( Type_id i_nType ) const; bool IsBuiltInOrRelated( const Type & i_rType ) const; private: // Locals virtual const Type & do_CheckIn_Type( QualifiedName & i_rFullName, uintt i_nSequenceCount, Ce_id i_nModuleOfOccurrence, Type_id i_nTemplateType ) = 0; virtual const Type & inq_Find_Type( Type_id i_nType ) const = 0; virtual String inq_Search_LocalNameOf( Type_id i_nType ) const = 0; virtual Ce_id inq_Search_CeRelatedTo( Type_id i_nType ) const = 0; virtual const ExplicitNameRoom & inq_Find_XNameRoom( Type_id i_nType ) const = 0; virtual bool inq_IsBuiltInOrRelated( const Type & i_rType ) const = 0; }; // IMPLEMENTATION inline const Type & TypePilot::CheckIn_Type( QualifiedName & i_rFullName, uintt i_nSequenceCount, Ce_id i_nModuleOfOccurrence, Type_id i_nTemplateType ) { return do_CheckIn_Type(i_rFullName, i_nSequenceCount, i_nModuleOfOccurrence, i_nTemplateType); } inline const Type & TypePilot::Find_Type( Type_id i_nType ) const { return inq_Find_Type(i_nType); } inline String TypePilot::Search_LocalNameOf( Type_id i_nType ) const { return inq_Search_LocalNameOf(i_nType); } inline Ce_id TypePilot::Search_CeRelatedTo( Type_id i_nType ) const { return inq_Search_CeRelatedTo(i_nType); } inline const ExplicitNameRoom & TypePilot::Find_XNameRoom( Type_id i_nType ) const { return inq_Find_XNameRoom(i_nType); } inline bool TypePilot::IsBuiltInOrRelated( const Type & i_rType ) const { return inq_IsBuiltInOrRelated( i_rType ); } } // namespace idl } // namespace ary #endif <commit_msg>INTEGRATION: CWS gcc41 (1.4.14); FILE MERGED 2005/12/07 12:31:05 pmladek 1.4.14.1: #i58967# Removed extra qualification to fix build with gcc-4.1<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ip_type.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-01-19 17:57: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 * ************************************************************************/ #ifndef ARY_IDL_IP_TYPE_HXX #define ARY_IDL_IP_TYPE_HXX // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS #include <ary/idl/i_language.hxx> namespace ary { class QualifiedName; namespace idl { class Type; class ExplicitNameRoom; class TypePilot { public: // LIFECYCLE virtual ~TypePilot() {} // OPERATIONS const Type & CheckIn_Type( QualifiedName & i_rFullName, uintt i_nSequenceCount, Ce_id i_nModuleOfOccurrence, Type_id i_nTemplateType ); // INQUIRY const Type & Find_Type( Type_id i_nType ) const; String Search_LocalNameOf( Type_id i_nType ) const; Ce_id Search_CeRelatedTo( Type_id i_nType ) const; const ExplicitNameRoom & Find_XNameRoom( Type_id i_nType ) const; bool IsBuiltInOrRelated( const Type & i_rType ) const; private: // Locals virtual const Type & do_CheckIn_Type( QualifiedName & i_rFullName, uintt i_nSequenceCount, Ce_id i_nModuleOfOccurrence, Type_id i_nTemplateType ) = 0; virtual const Type & inq_Find_Type( Type_id i_nType ) const = 0; virtual String inq_Search_LocalNameOf( Type_id i_nType ) const = 0; virtual Ce_id inq_Search_CeRelatedTo( Type_id i_nType ) const = 0; virtual const ExplicitNameRoom & inq_Find_XNameRoom( Type_id i_nType ) const = 0; virtual bool inq_IsBuiltInOrRelated( const Type & i_rType ) const = 0; }; // IMPLEMENTATION inline const Type & TypePilot::CheckIn_Type( QualifiedName & i_rFullName, uintt i_nSequenceCount, Ce_id i_nModuleOfOccurrence, Type_id i_nTemplateType ) { return do_CheckIn_Type(i_rFullName, i_nSequenceCount, i_nModuleOfOccurrence, i_nTemplateType); } inline const Type & TypePilot::Find_Type( Type_id i_nType ) const { return inq_Find_Type(i_nType); } inline String TypePilot::Search_LocalNameOf( Type_id i_nType ) const { return inq_Search_LocalNameOf(i_nType); } inline Ce_id TypePilot::Search_CeRelatedTo( Type_id i_nType ) const { return inq_Search_CeRelatedTo(i_nType); } inline const ExplicitNameRoom & TypePilot::Find_XNameRoom( Type_id i_nType ) const { return inq_Find_XNameRoom(i_nType); } inline bool TypePilot::IsBuiltInOrRelated( const Type & i_rType ) const { return inq_IsBuiltInOrRelated( i_rType ); } } // namespace idl } // namespace ary #endif <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <vector> #include <utility> #include <string> #include <stdlib.h> #include <unistd.h> #include "../macros.h" #include "../varkey.h" #include "../thread.h" #include "../util.h" #include "../spinbarrier.h" #include "bench.h" using namespace std; using namespace util; static size_t nkeys; class ycsb_worker : public bench_worker { public: ycsb_worker(unsigned long seed, abstract_db *db, const map<string, abstract_ordered_index *> &open_tables, spin_barrier *barrier_a, spin_barrier *barrier_b) : bench_worker(seed, db, open_tables, barrier_a, barrier_b), tbl(open_tables.at("USERTABLE")) { } void txn_read() { void *txn = db->new_txn(txn_flags); string k = u64_varkey(r.next() % nkeys).str(); try { char *v = 0; size_t vlen = 0; ALWAYS_ASSERT(tbl->get(txn, k.data(), k.size(), v, vlen)); free(v); if (db->commit_txn(txn)) ntxn_commits++; } catch (abstract_db::abstract_abort_exception &ex) { db->abort_txn(txn); ntxn_aborts++; } } static void TxnRead(bench_worker *w) { static_cast<ycsb_worker *>(w)->txn_read(); } void txn_write() { void *txn = db->new_txn(txn_flags); string k = u64_varkey(r.next() % nkeys).str(); try { string v(128, 'b'); tbl->put(txn, k.data(), k.size(), v.data(), v.size()); if (db->commit_txn(txn)) ntxn_commits++; } catch (abstract_db::abstract_abort_exception &ex) { db->abort_txn(txn); ntxn_aborts++; } } static void TxnWrite(bench_worker *w) { static_cast<ycsb_worker *>(w)->txn_write(); } void txn_rmw() { void *txn = db->new_txn(txn_flags); string k = u64_varkey(r.next() % nkeys).str(); try { char *v = 0; size_t vlen = 0; ALWAYS_ASSERT(tbl->get(txn, k.data(), k.size(), v, vlen)); free(v); string vnew(128, 'c'); tbl->put(txn, k.data(), k.size(), vnew.data(), vnew.size()); if (db->commit_txn(txn)) ntxn_commits++; } catch (abstract_db::abstract_abort_exception &ex) { db->abort_txn(txn); ntxn_aborts++; } } static void TxnRmw(bench_worker *w) { static_cast<ycsb_worker *>(w)->txn_rmw(); } class worker_scan_callback : public abstract_ordered_index::scan_callback { public: virtual bool invoke(const char *key, size_t key_len, const char *value, size_t value_len) { return true; } }; void txn_scan() { void *txn = db->new_txn(txn_flags); size_t kstart = r.next() % nkeys; string kbegin = u64_varkey(kstart).str(); string kend = u64_varkey(kstart + 100).str(); worker_scan_callback c; try { tbl->scan(txn, kbegin.data(), kbegin.size(), kend.data(), kend.size(), true, c); if (db->commit_txn(txn)) ntxn_commits++; } catch (abstract_db::abstract_abort_exception &ex) { db->abort_txn(txn); ntxn_aborts++; } } static void TxnScan(bench_worker *w) { static_cast<ycsb_worker *>(w)->txn_scan(); } virtual workload_desc get_workload() { workload_desc w; w.push_back(make_pair(0.85, TxnRead)); w.push_back(make_pair(0.10, TxnScan)); w.push_back(make_pair(0.04, TxnRmw)); w.push_back(make_pair(0.01, TxnWrite)); return w; } private: abstract_ordered_index *tbl; }; void ycsb_do_test(abstract_db *db) { nkeys = size_t(scale_factor * 1000.0); assert(nkeys > 0); spin_barrier barrier_a(nthreads); spin_barrier barrier_b(1); db->thread_init(); abstract_ordered_index *tbl = db->open_index("USERTABLE"); map<string, abstract_ordered_index *> open_tables; open_tables["USERTABLE"] = tbl; // load const size_t batchsize = (db->txn_max_batch_size() == -1) ? 10000 : db->txn_max_batch_size(); ALWAYS_ASSERT(batchsize > 0); size_t nbatches = nkeys / batchsize; for (size_t i = 0; i < nbatches; i++) { size_t keyend = (i == nbatches - 1) ? nkeys : (i + 1) * batchsize; void *txn = db->new_txn(txn_flags); for (size_t j = i * batchsize; j < keyend; j++) { string k = u64_varkey(j).str(); string v(128, 'a'); tbl->insert(txn, k.data(), k.size(), v.data(), v.size()); } if (verbose) cerr << "batch " << (i + 1) << "/" << nbatches << " done" << endl; ALWAYS_ASSERT(db->commit_txn(txn)); } fast_random r(8544290); vector<ycsb_worker *> workers; for (size_t i = 0; i < nthreads; i++) workers.push_back(new ycsb_worker(r.next(), db, open_tables, &barrier_a, &barrier_b)); for (size_t i = 0; i < nthreads; i++) workers[i]->start(); barrier_a.wait_for(); barrier_b.count_down(); timer t; sleep(30); running = false; __sync_synchronize(); unsigned long elapsed = t.lap(); size_t n_commits = 0; size_t n_aborts = 0; for (size_t i = 0; i < nthreads; i++) { workers[i]->join(); n_commits += workers[i]->get_ntxn_commits(); n_aborts += workers[i]->get_ntxn_aborts(); } double agg_throughput = double(n_commits) / (double(elapsed) / 1000000.0); double avg_per_core_throughput = agg_throughput / double(nthreads); double agg_abort_rate = double(n_aborts) / (double(elapsed) / 1000000.0); double avg_per_core_abort_rate = agg_abort_rate / double(nthreads); if (verbose) { cerr << "agg_throughput: " << agg_throughput << " ops/sec" << endl; cerr << "avg_per_core_throughput: " << avg_per_core_throughput << " ops/sec/core" << endl; cerr << "agg_abort_rate: " << agg_abort_rate << " aborts/sec" << endl; cerr << "avg_per_core_abort_rate: " << avg_per_core_abort_rate << " aborts/sec/core" << endl; } cout << agg_throughput << endl; db->thread_end(); } <commit_msg>different ycsb workloads<commit_after>#include <iostream> #include <sstream> #include <vector> #include <utility> #include <string> #include <stdlib.h> #include <unistd.h> #include "../macros.h" #include "../varkey.h" #include "../thread.h" #include "../util.h" #include "../spinbarrier.h" #include "bench.h" using namespace std; using namespace util; static size_t nkeys; class ycsb_worker : public bench_worker { public: ycsb_worker(unsigned long seed, abstract_db *db, const map<string, abstract_ordered_index *> &open_tables, spin_barrier *barrier_a, spin_barrier *barrier_b) : bench_worker(seed, db, open_tables, barrier_a, barrier_b), tbl(open_tables.at("USERTABLE")) { } void txn_read() { void *txn = db->new_txn(txn_flags); string k = u64_varkey(r.next() % nkeys).str(); try { char *v = 0; size_t vlen = 0; ALWAYS_ASSERT(tbl->get(txn, k.data(), k.size(), v, vlen)); free(v); if (db->commit_txn(txn)) ntxn_commits++; } catch (abstract_db::abstract_abort_exception &ex) { db->abort_txn(txn); ntxn_aborts++; } } static void TxnRead(bench_worker *w) { static_cast<ycsb_worker *>(w)->txn_read(); } void txn_write() { void *txn = db->new_txn(txn_flags); string k = u64_varkey(r.next() % nkeys).str(); try { string v(128, 'b'); tbl->put(txn, k.data(), k.size(), v.data(), v.size()); if (db->commit_txn(txn)) ntxn_commits++; } catch (abstract_db::abstract_abort_exception &ex) { db->abort_txn(txn); ntxn_aborts++; } } static void TxnWrite(bench_worker *w) { static_cast<ycsb_worker *>(w)->txn_write(); } void txn_rmw() { void *txn = db->new_txn(txn_flags); string k = u64_varkey(r.next() % nkeys).str(); try { char *v = 0; size_t vlen = 0; ALWAYS_ASSERT(tbl->get(txn, k.data(), k.size(), v, vlen)); free(v); string vnew(128, 'c'); tbl->put(txn, k.data(), k.size(), vnew.data(), vnew.size()); if (db->commit_txn(txn)) ntxn_commits++; } catch (abstract_db::abstract_abort_exception &ex) { db->abort_txn(txn); ntxn_aborts++; } } static void TxnRmw(bench_worker *w) { static_cast<ycsb_worker *>(w)->txn_rmw(); } class worker_scan_callback : public abstract_ordered_index::scan_callback { public: virtual bool invoke(const char *key, size_t key_len, const char *value, size_t value_len) { return true; } }; void txn_scan() { void *txn = db->new_txn(txn_flags); size_t kstart = r.next() % nkeys; string kbegin = u64_varkey(kstart).str(); string kend = u64_varkey(kstart + 100).str(); worker_scan_callback c; try { tbl->scan(txn, kbegin.data(), kbegin.size(), kend.data(), kend.size(), true, c); if (db->commit_txn(txn)) ntxn_commits++; } catch (abstract_db::abstract_abort_exception &ex) { db->abort_txn(txn); ntxn_aborts++; } } static void TxnScan(bench_worker *w) { static_cast<ycsb_worker *>(w)->txn_scan(); } virtual workload_desc get_workload() { workload_desc w; //w.push_back(make_pair(1.00, TxnRead)); //w.push_back(make_pair(0.85, TxnRead)); //w.push_back(make_pair(0.10, TxnScan)); //w.push_back(make_pair(0.04, TxnRmw)); //w.push_back(make_pair(0.01, TxnWrite)); w.push_back(make_pair(0.95, TxnRead)); w.push_back(make_pair(0.04, TxnRmw)); w.push_back(make_pair(0.01, TxnWrite)); return w; } private: abstract_ordered_index *tbl; }; void ycsb_do_test(abstract_db *db) { nkeys = size_t(scale_factor * 1000.0); assert(nkeys > 0); spin_barrier barrier_a(nthreads); spin_barrier barrier_b(1); db->thread_init(); abstract_ordered_index *tbl = db->open_index("USERTABLE"); map<string, abstract_ordered_index *> open_tables; open_tables["USERTABLE"] = tbl; // load const size_t batchsize = (db->txn_max_batch_size() == -1) ? 10000 : db->txn_max_batch_size(); ALWAYS_ASSERT(batchsize > 0); size_t nbatches = nkeys / batchsize; for (size_t i = 0; i < nbatches; i++) { size_t keyend = (i == nbatches - 1) ? nkeys : (i + 1) * batchsize; void *txn = db->new_txn(txn_flags); for (size_t j = i * batchsize; j < keyend; j++) { string k = u64_varkey(j).str(); string v(128, 'a'); tbl->insert(txn, k.data(), k.size(), v.data(), v.size()); } if (verbose) cerr << "batch " << (i + 1) << "/" << nbatches << " done" << endl; ALWAYS_ASSERT(db->commit_txn(txn)); } fast_random r(8544290); vector<ycsb_worker *> workers; for (size_t i = 0; i < nthreads; i++) workers.push_back(new ycsb_worker(r.next(), db, open_tables, &barrier_a, &barrier_b)); for (size_t i = 0; i < nthreads; i++) workers[i]->start(); barrier_a.wait_for(); barrier_b.count_down(); timer t; sleep(30); running = false; __sync_synchronize(); unsigned long elapsed = t.lap(); size_t n_commits = 0; size_t n_aborts = 0; for (size_t i = 0; i < nthreads; i++) { workers[i]->join(); n_commits += workers[i]->get_ntxn_commits(); n_aborts += workers[i]->get_ntxn_aborts(); } double agg_throughput = double(n_commits) / (double(elapsed) / 1000000.0); double avg_per_core_throughput = agg_throughput / double(nthreads); double agg_abort_rate = double(n_aborts) / (double(elapsed) / 1000000.0); double avg_per_core_abort_rate = agg_abort_rate / double(nthreads); if (verbose) { cerr << "agg_throughput: " << agg_throughput << " ops/sec" << endl; cerr << "avg_per_core_throughput: " << avg_per_core_throughput << " ops/sec/core" << endl; cerr << "agg_abort_rate: " << agg_abort_rate << " aborts/sec" << endl; cerr << "avg_per_core_abort_rate: " << avg_per_core_abort_rate << " aborts/sec/core" << endl; } cout << agg_throughput << endl; db->thread_end(); } <|endoftext|>
<commit_before>/*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkCommonExtPlugin.h" #include <QmitkExtRegisterClasses.h> #include "QmitkAppInstancesPreferencePage.h" #include "QmitkInputDevicesPrefPage.h" #include "QmitkModuleView.h" #include <mitkDataNodeFactory.h> #include <mitkIDataStorageService.h> #include <mitkSceneIO.h> #include <mitkProgressBar.h> #include <mitkRenderingManager.h> #include <berryPlatformUI.h> #include <berryIPreferencesService.h> #include <Poco/Util/OptionProcessor.h> #include <QProcess> #include <QMainWindow> #include <QtPlugin> ctkPluginContext* QmitkCommonExtPlugin::_context = 0; void QmitkCommonExtPlugin::start(ctkPluginContext* context) { this->_context = context; QmitkExtRegisterClasses(); BERRY_REGISTER_EXTENSION_CLASS(QmitkAppInstancesPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkInputDevicesPrefPage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkModuleView, context) if (qApp->metaObject()->indexOfSignal("messageReceived(QByteArray)") > -1) { connect(qApp, SIGNAL(messageReceived(QByteArray)), this, SLOT(handleIPCMessage(QByteArray))); } std::vector<std::string> args = berry::Platform::GetApplicationArgs(); QStringList qargs; for (std::vector<std::string>::const_iterator it = args.begin(); it != args.end(); ++it) { qargs << QString::fromStdString(*it); } // This is a potentially long running operation. loadDataFromDisk(qargs, true); } void QmitkCommonExtPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) this->_context = 0; } ctkPluginContext* QmitkCommonExtPlugin::getContext() { return _context; } void QmitkCommonExtPlugin::loadDataFromDisk(const QStringList &arguments, bool globalReinit) { if (!arguments.empty()) { ctkServiceReference serviceRef = _context->getServiceReference<mitk::IDataStorageService>(); if (serviceRef) { mitk::IDataStorageService* dataStorageService = _context->getService<mitk::IDataStorageService>(serviceRef); mitk::DataStorage::Pointer dataStorage = dataStorageService->GetDefaultDataStorage()->GetDataStorage(); int argumentsAdded = 0; for (int i = 0; i < arguments.size(); ++i) { if (arguments[i].right(5) == ".mitk") { mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); bool clearDataStorageFirst(false); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); dataStorage = sceneIO->LoadScene( arguments[i].toLocal8Bit().constData(), dataStorage, clearDataStorageFirst ); mitk::ProgressBar::GetInstance()->Progress(2); argumentsAdded++; } else { mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); try { nodeReader->SetFileName(arguments[i].toStdString()); nodeReader->Update(); for (unsigned int j = 0 ; j < nodeReader->GetNumberOfOutputs( ); ++j) { mitk::DataNode::Pointer node = nodeReader->GetOutput(j); if (node->GetData() != 0) { dataStorage->Add(node); argumentsAdded++; } } } catch(...) { MITK_WARN << "Failed to load command line argument: " << arguments[i].toStdString(); } } } // end for each command line argument if (argumentsAdded > 0 && globalReinit) { // calculate bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(dataStorage->ComputeBoundingGeometry3D()); } } else { MITK_ERROR << "A service reference for mitk::IDataStorageService does not exist"; } } } void QmitkCommonExtPlugin::startNewInstance(const QStringList &args, const QStringList& files) { if (!files.empty()) { QStringList newArgs(args); #ifdef Q_OS_UNIX newArgs << QString("--") + QString::fromStdString(berry::Platform::ARG_NEWINSTANCE); #else newArgs << QString("/") + QString::fromStdString(berry::Platform::ARG_NEWINSTANCE); #endif newArgs << files; QProcess::startDetached(qApp->applicationFilePath(), newArgs); } } void QmitkCommonExtPlugin::handleIPCMessage(const QByteArray& msg) { QDataStream ds(msg); QString msgType; ds >> msgType; // we only handle messages containing command line arguments if (msgType != "$cmdLineArgs") return; // activate the current workbench window berry::IWorkbenchWindow::Pointer window = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(); QMainWindow* mainWindow = static_cast<QMainWindow*> (window->GetShell()->GetControl()); mainWindow->setWindowState(mainWindow->windowState() & ~Qt::WindowMinimized); mainWindow->raise(); mainWindow->activateWindow(); // Get the preferences for the instantiation behavior berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById<berry::IPreferencesService>(berry::IPreferencesService::ID); berry::IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node("/General"); bool newInstanceAlways = prefs->GetBool("newInstance.always", false); bool newInstanceScene = prefs->GetBool("newInstance.scene", true); QStringList args; ds >> args; QStringList fileArgs; QStringList sceneArgs; Poco::Util::OptionSet os; berry::Platform::GetOptionSet(os); Poco::Util::OptionProcessor processor(os); #if !defined(POCO_OS_FAMILY_UNIX) processor.setUnixStyle(false); #endif args.pop_front(); QStringList::Iterator it = args.begin(); while (it != args.end()) { std::string name; std::string value; if (processor.process(it->toStdString(), name, value)) { ++it; } else { if (it->endsWith(".mitk")) { sceneArgs << *it; } else { fileArgs << *it; } it = args.erase(it); } } if (newInstanceAlways) { if (newInstanceScene) { startNewInstance(args, fileArgs); foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { fileArgs.append(sceneArgs); startNewInstance(args, fileArgs); } } else { loadDataFromDisk(fileArgs, false); if (newInstanceScene) { foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { loadDataFromDisk(sceneArgs, false); } } } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_ext, QmitkCommonExtPlugin) <commit_msg>Always start a new process, even when no args are given.<commit_after>/*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkCommonExtPlugin.h" #include <QmitkExtRegisterClasses.h> #include "QmitkAppInstancesPreferencePage.h" #include "QmitkInputDevicesPrefPage.h" #include "QmitkModuleView.h" #include <mitkDataNodeFactory.h> #include <mitkIDataStorageService.h> #include <mitkSceneIO.h> #include <mitkProgressBar.h> #include <mitkRenderingManager.h> #include <berryPlatformUI.h> #include <berryIPreferencesService.h> #include <Poco/Util/OptionProcessor.h> #include <QProcess> #include <QMainWindow> #include <QtPlugin> ctkPluginContext* QmitkCommonExtPlugin::_context = 0; void QmitkCommonExtPlugin::start(ctkPluginContext* context) { this->_context = context; QmitkExtRegisterClasses(); BERRY_REGISTER_EXTENSION_CLASS(QmitkAppInstancesPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkInputDevicesPrefPage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkModuleView, context) if (qApp->metaObject()->indexOfSignal("messageReceived(QByteArray)") > -1) { connect(qApp, SIGNAL(messageReceived(QByteArray)), this, SLOT(handleIPCMessage(QByteArray))); } std::vector<std::string> args = berry::Platform::GetApplicationArgs(); QStringList qargs; for (std::vector<std::string>::const_iterator it = args.begin(); it != args.end(); ++it) { qargs << QString::fromStdString(*it); } // This is a potentially long running operation. loadDataFromDisk(qargs, true); } void QmitkCommonExtPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) this->_context = 0; } ctkPluginContext* QmitkCommonExtPlugin::getContext() { return _context; } void QmitkCommonExtPlugin::loadDataFromDisk(const QStringList &arguments, bool globalReinit) { if (!arguments.empty()) { ctkServiceReference serviceRef = _context->getServiceReference<mitk::IDataStorageService>(); if (serviceRef) { mitk::IDataStorageService* dataStorageService = _context->getService<mitk::IDataStorageService>(serviceRef); mitk::DataStorage::Pointer dataStorage = dataStorageService->GetDefaultDataStorage()->GetDataStorage(); int argumentsAdded = 0; for (int i = 0; i < arguments.size(); ++i) { if (arguments[i].right(5) == ".mitk") { mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); bool clearDataStorageFirst(false); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); dataStorage = sceneIO->LoadScene( arguments[i].toLocal8Bit().constData(), dataStorage, clearDataStorageFirst ); mitk::ProgressBar::GetInstance()->Progress(2); argumentsAdded++; } else { mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); try { nodeReader->SetFileName(arguments[i].toStdString()); nodeReader->Update(); for (unsigned int j = 0 ; j < nodeReader->GetNumberOfOutputs( ); ++j) { mitk::DataNode::Pointer node = nodeReader->GetOutput(j); if (node->GetData() != 0) { dataStorage->Add(node); argumentsAdded++; } } } catch(...) { MITK_WARN << "Failed to load command line argument: " << arguments[i].toStdString(); } } } // end for each command line argument if (argumentsAdded > 0 && globalReinit) { // calculate bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(dataStorage->ComputeBoundingGeometry3D()); } } else { MITK_ERROR << "A service reference for mitk::IDataStorageService does not exist"; } } } void QmitkCommonExtPlugin::startNewInstance(const QStringList &args, const QStringList& files) { QStringList newArgs(args); #ifdef Q_OS_UNIX newArgs << QString("--") + QString::fromStdString(berry::Platform::ARG_NEWINSTANCE); #else newArgs << QString("/") + QString::fromStdString(berry::Platform::ARG_NEWINSTANCE); #endif newArgs << files; QProcess::startDetached(qApp->applicationFilePath(), newArgs); } void QmitkCommonExtPlugin::handleIPCMessage(const QByteArray& msg) { QDataStream ds(msg); QString msgType; ds >> msgType; // we only handle messages containing command line arguments if (msgType != "$cmdLineArgs") return; // activate the current workbench window berry::IWorkbenchWindow::Pointer window = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(); QMainWindow* mainWindow = static_cast<QMainWindow*> (window->GetShell()->GetControl()); mainWindow->setWindowState(mainWindow->windowState() & ~Qt::WindowMinimized); mainWindow->raise(); mainWindow->activateWindow(); // Get the preferences for the instantiation behavior berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById<berry::IPreferencesService>(berry::IPreferencesService::ID); berry::IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node("/General"); bool newInstanceAlways = prefs->GetBool("newInstance.always", false); bool newInstanceScene = prefs->GetBool("newInstance.scene", true); QStringList args; ds >> args; QStringList fileArgs; QStringList sceneArgs; Poco::Util::OptionSet os; berry::Platform::GetOptionSet(os); Poco::Util::OptionProcessor processor(os); #if !defined(POCO_OS_FAMILY_UNIX) processor.setUnixStyle(false); #endif args.pop_front(); QStringList::Iterator it = args.begin(); while (it != args.end()) { std::string name; std::string value; if (processor.process(it->toStdString(), name, value)) { ++it; } else { if (it->endsWith(".mitk")) { sceneArgs << *it; } else { fileArgs << *it; } it = args.erase(it); } } if (newInstanceAlways) { if (newInstanceScene) { startNewInstance(args, fileArgs); foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { fileArgs.append(sceneArgs); startNewInstance(args, fileArgs); } } else { loadDataFromDisk(fileArgs, false); if (newInstanceScene) { foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { loadDataFromDisk(sceneArgs, false); } } } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_ext, QmitkCommonExtPlugin) <|endoftext|>
<commit_before>/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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 "itkCollidingFrontsImageFilter.h" #include "itkCastImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkImageFileWriter.h" #include "itkTestingMacros.h" int itkCollidingFrontsImageFilterTest(int argc, char * argv[]) { if (argc < 4) { std::cerr << "Missing parameters." << std::endl; std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " negativeEpsilon applyConnectivity stopOnTargets [outputFilename]" << std::endl; return EXIT_FAILURE; } constexpr unsigned int ImageDimension = 2; using PixelType = unsigned char; using InternalPixelType = float; using ImageType = itk::Image<PixelType, ImageDimension>; using InternalImageType = itk::Image<InternalPixelType, ImageDimension>; // setup uniform image ImageType::SizeType imageSize; imageSize[0] = 128; imageSize[1] = 128; ImageType::RegionType imageRegion; imageRegion.SetSize(imageSize); PixelType background = 64; auto inputImage = ImageType::New(); inputImage->SetRegions(imageRegion); inputImage->Allocate(); inputImage->FillBuffer(background); using CastFilterType = itk::CastImageFilter<ImageType, InternalImageType>; auto caster = CastFilterType::New(); caster->SetInput(inputImage); using CollidingFrontsFilterType = itk::CollidingFrontsImageFilter<InternalImageType, InternalImageType>; auto collidingFronts = CollidingFrontsFilterType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(collidingFronts, CollidingFrontsImageFilter, ImageToImageFilter); using NodeContainer = CollidingFrontsFilterType::NodeContainer; using NodeType = typename CollidingFrontsFilterType::NodeType; // select seeds 20 pixels apart auto seeds1 = NodeContainer::New(); InternalImageType::IndexType seedPosition1; seedPosition1[0] = 50; seedPosition1[1] = 60; NodeType node1; node1.SetIndex(seedPosition1); node1.SetValue(0.0); seeds1->Initialize(); seeds1->InsertElement(0, node1); auto seeds2 = NodeContainer::New(); InternalImageType::IndexType seedPosition2; seedPosition2[0] = 70; seedPosition2[1] = 60; NodeType node2; node2.SetIndex(seedPosition2); node2.SetValue(0.0); seeds2->Initialize(); seeds2->InsertElement(0, node2); InternalImageType::OffsetType offset = { { 60, 60 } }; double radius = seedPosition2[0] - offset[0]; collidingFronts->SetInput(caster->GetOutput()); collidingFronts->SetSeedPoints1(seeds1); collidingFronts->SetSeedPoints2(seeds2); auto negativeEpsilon = std::stod(argv[1]); collidingFronts->SetNegativeEpsilon(negativeEpsilon); ITK_TEST_SET_GET_VALUE(negativeEpsilon, collidingFronts->GetNegativeEpsilon()); auto applyConnectivity = static_cast<bool>(std::stoi(argv[2])); ITK_TEST_SET_GET_BOOLEAN(collidingFronts, ApplyConnectivity, applyConnectivity); try { collidingFronts->Update(); } catch (const itk::ExceptionObject & err) { std::cout << err << std::endl; } InternalImageType::Pointer output = collidingFronts->GetOutput(); itk::ImageRegionIterator<InternalImageType> iterator(output, output->GetBufferedRegion()); bool passed = true; for (; !iterator.IsAtEnd(); ++iterator) { InternalImageType::IndexType tempIndex; tempIndex = iterator.GetIndex(); tempIndex -= offset; double distance = 0.0; for (int j = 0; j < 2; ++j) { distance += tempIndex[j] * tempIndex[j]; } distance = std::sqrt(distance); InternalImageType::PixelType outputPixel = iterator.Get(); // for test to pass, the circle of radius 10 centered in offset // must be made up only of negative pixels and vice-versa if (outputPixel < 0.0) { // allow half a pixel diagonal tolerance if (distance > radius + 1.414 / 2.0) { std::cout << outputPixel << " " << distance << std::endl; passed = false; } } else { if (distance < radius) { std::cout << outputPixel << " " << distance << std::endl; passed = false; } } } // Optionally writing out the two images if (argc > 4) { using WriterType = itk::ImageFileWriter<ImageType>; auto writer = WriterType::New(); using RescaleFilterType = itk::RescaleIntensityImageFilter<InternalImageType, ImageType>; auto rescaler = RescaleFilterType::New(); writer->SetFileName(argv[4]); writer->SetInput(inputImage); writer->Update(); rescaler->SetInput(collidingFronts->GetOutput()); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); writer->SetFileName(argv[4]); writer->SetInput(rescaler->GetOutput()); writer->Update(); } if (!passed) { std::cout << "Colliding Fronts test failed. " << std::endl; return EXIT_FAILURE; } auto stopOnTargets = static_cast<bool>(std::stoi(argv[3])); ITK_TEST_SET_GET_BOOLEAN(collidingFronts, StopOnTargets, stopOnTargets); try { collidingFronts->Update(); } catch (const itk::ExceptionObject & err) { std::cout << err << std::endl; } std::cout << "Colliding Fronts test passed. " << std::endl; using DoubleImageType = itk::Image<double, ImageDimension>; using CollidingFrontsFilterType2 = itk::CollidingFrontsImageFilter<DoubleImageType, InternalImageType>; auto collidingFronts2 = CollidingFrontsFilterType2::New(); return EXIT_SUCCESS; } <commit_msg>STYLE: Prefer using `ITK_TRY_EXPECT_NO_EXCEPTION` macro in tests<commit_after>/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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 "itkCollidingFrontsImageFilter.h" #include "itkCastImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkImageFileWriter.h" #include "itkTestingMacros.h" int itkCollidingFrontsImageFilterTest(int argc, char * argv[]) { if (argc < 4) { std::cerr << "Missing parameters." << std::endl; std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " negativeEpsilon applyConnectivity stopOnTargets [outputFilename]" << std::endl; return EXIT_FAILURE; } constexpr unsigned int ImageDimension = 2; using PixelType = unsigned char; using InternalPixelType = float; using ImageType = itk::Image<PixelType, ImageDimension>; using InternalImageType = itk::Image<InternalPixelType, ImageDimension>; // setup uniform image ImageType::SizeType imageSize; imageSize[0] = 128; imageSize[1] = 128; ImageType::RegionType imageRegion; imageRegion.SetSize(imageSize); PixelType background = 64; auto inputImage = ImageType::New(); inputImage->SetRegions(imageRegion); inputImage->Allocate(); inputImage->FillBuffer(background); using CastFilterType = itk::CastImageFilter<ImageType, InternalImageType>; auto caster = CastFilterType::New(); caster->SetInput(inputImage); using CollidingFrontsFilterType = itk::CollidingFrontsImageFilter<InternalImageType, InternalImageType>; auto collidingFronts = CollidingFrontsFilterType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(collidingFronts, CollidingFrontsImageFilter, ImageToImageFilter); using NodeContainer = CollidingFrontsFilterType::NodeContainer; using NodeType = typename CollidingFrontsFilterType::NodeType; // select seeds 20 pixels apart auto seeds1 = NodeContainer::New(); InternalImageType::IndexType seedPosition1; seedPosition1[0] = 50; seedPosition1[1] = 60; NodeType node1; node1.SetIndex(seedPosition1); node1.SetValue(0.0); seeds1->Initialize(); seeds1->InsertElement(0, node1); auto seeds2 = NodeContainer::New(); InternalImageType::IndexType seedPosition2; seedPosition2[0] = 70; seedPosition2[1] = 60; NodeType node2; node2.SetIndex(seedPosition2); node2.SetValue(0.0); seeds2->Initialize(); seeds2->InsertElement(0, node2); InternalImageType::OffsetType offset = { { 60, 60 } }; double radius = seedPosition2[0] - offset[0]; collidingFronts->SetInput(caster->GetOutput()); collidingFronts->SetSeedPoints1(seeds1); collidingFronts->SetSeedPoints2(seeds2); auto negativeEpsilon = std::stod(argv[1]); collidingFronts->SetNegativeEpsilon(negativeEpsilon); ITK_TEST_SET_GET_VALUE(negativeEpsilon, collidingFronts->GetNegativeEpsilon()); auto applyConnectivity = static_cast<bool>(std::stoi(argv[2])); ITK_TEST_SET_GET_BOOLEAN(collidingFronts, ApplyConnectivity, applyConnectivity); ITK_TRY_EXPECT_NO_EXCEPTION(collidingFronts->Update()); InternalImageType::Pointer output = collidingFronts->GetOutput(); itk::ImageRegionIterator<InternalImageType> iterator(output, output->GetBufferedRegion()); bool passed = true; for (; !iterator.IsAtEnd(); ++iterator) { InternalImageType::IndexType tempIndex; tempIndex = iterator.GetIndex(); tempIndex -= offset; double distance = 0.0; for (int j = 0; j < 2; ++j) { distance += tempIndex[j] * tempIndex[j]; } distance = std::sqrt(distance); InternalImageType::PixelType outputPixel = iterator.Get(); // for test to pass, the circle of radius 10 centered in offset // must be made up only of negative pixels and vice-versa if (outputPixel < 0.0) { // allow half a pixel diagonal tolerance if (distance > radius + 1.414 / 2.0) { std::cout << outputPixel << " " << distance << std::endl; passed = false; } } else { if (distance < radius) { std::cout << outputPixel << " " << distance << std::endl; passed = false; } } } // Optionally writing out the two images if (argc > 4) { using WriterType = itk::ImageFileWriter<ImageType>; auto writer = WriterType::New(); using RescaleFilterType = itk::RescaleIntensityImageFilter<InternalImageType, ImageType>; auto rescaler = RescaleFilterType::New(); writer->SetFileName(argv[4]); writer->SetInput(inputImage); writer->Update(); rescaler->SetInput(collidingFronts->GetOutput()); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); writer->SetFileName(argv[4]); writer->SetInput(rescaler->GetOutput()); writer->Update(); } if (!passed) { std::cout << "Colliding Fronts test failed. " << std::endl; return EXIT_FAILURE; } auto stopOnTargets = static_cast<bool>(std::stoi(argv[3])); ITK_TEST_SET_GET_BOOLEAN(collidingFronts, StopOnTargets, stopOnTargets); ITK_TRY_EXPECT_NO_EXCEPTION(collidingFronts->Update()); std::cout << "Colliding Fronts test passed. " << std::endl; using DoubleImageType = itk::Image<double, ImageDimension>; using CollidingFrontsFilterType2 = itk::CollidingFrontsImageFilter<DoubleImageType, InternalImageType>; auto collidingFronts2 = CollidingFrontsFilterType2::New(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <QtGui/QGuiApplication> #include "player.h" #include <gst/gst.h> #include <iostream> GstElement *findSink(GstElement *pipeline) { for (int x = 0; x < GST_BIN_NUMCHILDREN (GST_BIN (pipeline)); x++) { gpointer data = g_list_nth_data (GST_BIN (pipeline)->children, x); if (GST_IS_ELEMENT (data)) { GstElement *elem = GST_ELEMENT (data); if (GST_PLUGIN_FEATURE_NAME (GST_PLUGIN_FEATURE (gst_element_get_factory (elem))) == QLatin1String ("droideglsink")) { return elem; } } } return NULL; } int main(int argc, char **argv) { setenv ("QT_WAYLAND_DISABLE_WINDOWDECORATION", "1", 1); QGuiApplication app(argc, argv); gst_init (&argc, &argv); if (argc < 2) { std::cout << "Usage: " << argv[0] << " <pipeline description> or file to play" << std::endl; return 1; } Player player; if (argc == 2) { // Most likely it's a file. gchar *file = g_strdup_printf ("file://%s/%s", g_get_current_dir (), argv[1]); GstElement *pipe = gst_element_factory_make ("playbin2", NULL); GstElement *sink = gst_element_factory_make ("droideglsink", NULL); g_object_set (pipe, "video-sink", sink, "flags", 99, "uri", file, NULL); g_free (file); player.setPipeline(pipe); player.setSink(sink); } else { gchar **argvn = g_new0 (char *, argc); memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1)); GstElement *pipe = gst_parse_launchv ((const gchar **) argvn, NULL); g_free (argvn); if (!pipe) { std::cout << "Failed to construct pipeline" << std::endl; return 1; } GstElement *sink = findSink (pipe); if (!sink) { std::cout << "No sink found"; return 1; } player.setPipeline(pipe); player.setSink(sink); } player.resize(768, 1280); player.show(); if (!player.start()) { std::cout << "Failed to start" << std::endl; return 1; } return app.exec(); } <commit_msg>Adjust window resolution to boston resolution<commit_after>#include <QtGui/QGuiApplication> #include "player.h" #include <gst/gst.h> #include <iostream> GstElement *findSink(GstElement *pipeline) { for (int x = 0; x < GST_BIN_NUMCHILDREN (GST_BIN (pipeline)); x++) { gpointer data = g_list_nth_data (GST_BIN (pipeline)->children, x); if (GST_IS_ELEMENT (data)) { GstElement *elem = GST_ELEMENT (data); if (GST_PLUGIN_FEATURE_NAME (GST_PLUGIN_FEATURE (gst_element_get_factory (elem))) == QLatin1String ("droideglsink")) { return elem; } } } return NULL; } int main(int argc, char **argv) { setenv ("QT_WAYLAND_DISABLE_WINDOWDECORATION", "1", 1); QGuiApplication app(argc, argv); gst_init (&argc, &argv); if (argc < 2) { std::cout << "Usage: " << argv[0] << " <pipeline description> or file to play" << std::endl; return 1; } Player player; if (argc == 2) { // Most likely it's a file. gchar *file = g_strdup_printf ("file://%s/%s", g_get_current_dir (), argv[1]); GstElement *pipe = gst_element_factory_make ("playbin2", NULL); GstElement *sink = gst_element_factory_make ("droideglsink", NULL); g_object_set (pipe, "video-sink", sink, "flags", 99, "uri", file, NULL); g_free (file); player.setPipeline(pipe); player.setSink(sink); } else { gchar **argvn = g_new0 (char *, argc); memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1)); GstElement *pipe = gst_parse_launchv ((const gchar **) argvn, NULL); g_free (argvn); if (!pipe) { std::cout << "Failed to construct pipeline" << std::endl; return 1; } GstElement *sink = findSink (pipe); if (!sink) { std::cout << "No sink found"; return 1; } player.setPipeline(pipe); player.setSink(sink); } player.resize(540, 960); player.show(); if (!player.start()) { std::cout << "Failed to start" << std::endl; return 1; } return app.exec(); } <|endoftext|>
<commit_before><commit_msg>Partial revert of r330042 "Draw the offscreen texture to reflector's surface without extra copy"<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_NULL_HPP #define REALM_NULL_HPP #include <cmath> #include <realm/util/features.h> #include <realm/util/optional.hpp> #include <realm/utilities.hpp> #include <realm/exceptions.hpp> namespace realm { /* Represents null in Query, find(), get(), set(), etc. Todo, maybe move this outside string_data.hpp. Float/Double: Realm can both store user-given NaNs and null. Any user-given signaling NaN is converted to 0x7fa00000 (if float) or 0x7ff4000000000000 (if double). Any user-given quiet NaN is converted to 0x7fc00000 (if float) or 0x7ff8000000000000 (if double). So Realm does not preserve the optional bits in user-given NaNs. However, since both clang and gcc on x64 and ARM, and also Java on x64, return these bit patterns when requesting NaNs, these will actually seem to roundtrip bit-exact for the end-user in most cases. If set_null() is called, a null is stored in form of the bit pattern 0xffffffff (if float) or 0xffffffffffffffff (if double). These are quiet NaNs. Executing a query that involves a float/double column that contains NaNs gives an undefined result. If it contains signaling NaNs, it may throw an exception. Notes on IEEE: A NaN float is any bit pattern `s 11111111 S xxxxxxxxxxxxxxxxxxxxxx` where `s` and `x` are arbitrary, but at least 1 `x` must be 1. If `S` is 1, it's a quiet NaN, else it's a signaling NaN. A NaN doubule is the same as above, but for `s eeeeeeeeeee S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` The `S` bit is at position 22 (float) or 51 (double). */ struct null { null(int) {} null() {} operator int64_t() { throw(LogicError::type_mismatch); } template<class T> operator util::Optional<T>() { return util::none; } template<class T> bool operator == (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator != (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator > (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator >= (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator <= (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator < (const T&) const { REALM_ASSERT(false); return false; } /// Returns whether `v` bitwise equals the null bit-pattern template<class T> static bool is_null_float(T v) { T i = null::get_null_float<T>(); return std::memcmp(&i, &v, sizeof(T)) == 0; } /// Returns the quiet NaNs that represent null for floats/doubles in Realm in stored payload. template<class T> static T get_null_float() { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; int64_t double_nan = 0x7ff80000000000aa; i = std::is_same<T, float>::value ? 0x7fc000aa : static_cast<decltype(i)>(double_nan); T d = type_punning<T, decltype(i)>(i); REALM_ASSERT_DEBUG(std::isnan(static_cast<double>(d))); REALM_ASSERT_DEBUG(!is_signaling(d)); return d; } /// Takes a NaN as argument and returns whether or not it's signaling template<class T> static bool is_signaling(T v) { REALM_ASSERT(std::isnan(static_cast<double>(v))); typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; size_t signal_bit = std::is_same<T, float>::value ? 22 : 51; // If this bit is set, it's quiet i = type_punning<decltype(i), T>(v); return !(i & (1ull << signal_bit)); } /// Converts any signaling or quiet NaN to their their respective bit patterns that are used on x64 gcc+clang, /// ARM clang and x64 Java. template<class T> static T to_realm(T v) { if (std::isnan(static_cast<double>(v))) { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; if (std::is_same<T, float>::value) { i = is_signaling(v) ? 0x7fa00000 : 0x7fc00000; } else { i = static_cast<decltype(i)>(is_signaling(v) ? 0x7ff4000000000000 : 0x7ff8000000000000); } return type_punning<T, decltype(i)>(i); } else { return v; } } }; } // namespace realm #endif // REALM_NULL_HPP <commit_msg>Removed TODO comment<commit_after>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_NULL_HPP #define REALM_NULL_HPP #include <cmath> #include <realm/util/features.h> #include <realm/util/optional.hpp> #include <realm/utilities.hpp> #include <realm/exceptions.hpp> namespace realm { /* Represents null in Query, find(), get(), set(), etc. Float/Double: Realm can both store user-given NaNs and null. Any user-given signaling NaN is converted to 0x7fa00000 (if float) or 0x7ff4000000000000 (if double). Any user-given quiet NaN is converted to 0x7fc00000 (if float) or 0x7ff8000000000000 (if double). So Realm does not preserve the optional bits in user-given NaNs. However, since both clang and gcc on x64 and ARM, and also Java on x64, return these bit patterns when requesting NaNs, these will actually seem to roundtrip bit-exact for the end-user in most cases. If set_null() is called, a null is stored in form of the bit pattern 0xffffffff (if float) or 0xffffffffffffffff (if double). These are quiet NaNs. Executing a query that involves a float/double column that contains NaNs gives an undefined result. If it contains signaling NaNs, it may throw an exception. Notes on IEEE: A NaN float is any bit pattern `s 11111111 S xxxxxxxxxxxxxxxxxxxxxx` where `s` and `x` are arbitrary, but at least 1 `x` must be 1. If `S` is 1, it's a quiet NaN, else it's a signaling NaN. A NaN doubule is the same as above, but for `s eeeeeeeeeee S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` The `S` bit is at position 22 (float) or 51 (double). */ struct null { null(int) {} null() {} operator int64_t() { throw(LogicError::type_mismatch); } template<class T> operator util::Optional<T>() { return util::none; } template<class T> bool operator == (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator != (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator > (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator >= (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator <= (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator < (const T&) const { REALM_ASSERT(false); return false; } /// Returns whether `v` bitwise equals the null bit-pattern template<class T> static bool is_null_float(T v) { T i = null::get_null_float<T>(); return std::memcmp(&i, &v, sizeof(T)) == 0; } /// Returns the quiet NaNs that represent null for floats/doubles in Realm in stored payload. template<class T> static T get_null_float() { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; int64_t double_nan = 0x7ff80000000000aa; i = std::is_same<T, float>::value ? 0x7fc000aa : static_cast<decltype(i)>(double_nan); T d = type_punning<T, decltype(i)>(i); REALM_ASSERT_DEBUG(std::isnan(static_cast<double>(d))); REALM_ASSERT_DEBUG(!is_signaling(d)); return d; } /// Takes a NaN as argument and returns whether or not it's signaling template<class T> static bool is_signaling(T v) { REALM_ASSERT(std::isnan(static_cast<double>(v))); typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; size_t signal_bit = std::is_same<T, float>::value ? 22 : 51; // If this bit is set, it's quiet i = type_punning<decltype(i), T>(v); return !(i & (1ull << signal_bit)); } /// Converts any signaling or quiet NaN to their their respective bit patterns that are used on x64 gcc+clang, /// ARM clang and x64 Java. template<class T> static T to_realm(T v) { if (std::isnan(static_cast<double>(v))) { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; if (std::is_same<T, float>::value) { i = is_signaling(v) ? 0x7fa00000 : 0x7fc00000; } else { i = static_cast<decltype(i)>(is_signaling(v) ? 0x7ff4000000000000 : 0x7ff8000000000000); } return type_punning<T, decltype(i)>(i); } else { return v; } } }; } // namespace realm #endif // REALM_NULL_HPP <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "registrardb.hh" #include "registrardb-internal.hh" #ifdef ENABLE_REDIS #include "registrardb-redis.hh" #endif #include "common.hh" #include "configmanager.hh" #include <sstream> #include <ctime> #include <cstdio> #include <algorithm> #include <sofia-sip/sip_protos.h> using namespace ::std; sip_contact_t *Record::extendedContactToSofia(su_home_t *home, const ExtendedContact &ec, time_t now) { sip_contact_t *contact = NULL; int expire = ec.mExpireAt - now; if (expire > 0) { if (ec.mQ == 0) { contact = sip_contact_format(home, "%s;expires=%i", ec.mSipUri, expire); } else { contact = sip_contact_format(home, "%s;q=%4.2f;expires=%i", ec.mSipUri, ec.mQ, expire); } } return contact; } const sip_contact_t *Record::getContacts(su_home_t *home, time_t now) { sip_contact_t *alist = NULL; for (auto it = mContacts.begin(); it != mContacts.end(); ++it) { sip_contact_t *current = extendedContactToSofia(home, **it, now); if (current && alist) { current->m_next = alist; } alist = current; } return alist; } bool Record::isInvalidRegister(const char *call_id, uint32_t cseq) { for (auto it = mContacts.begin(); it != mContacts.end(); ++it) { shared_ptr<ExtendedContact> ec = (*it); if ((0 == strcmp(ec->mCallId, call_id)) && cseq <= ec->mCSeq) { return true; } } return false; } /** * Should first have checked the validity of the register with isValidRegister. */ void Record::clean(const sip_contact_t *sip, const char *call_id, uint32_t cseq, time_t now) { sip_contact_t *s = (sip_contact_t *) sip; const char *line_value = (sLineFieldName.size() > 0 && sip) ? msg_header_find_item(s->m_common, sLineFieldName.c_str()) : NULL; auto it = mContacts.begin(); while (it != mContacts.end()) { shared_ptr<ExtendedContact> ec = (*it); if ((now >= ec->mExpireAt) || (ec->mLineValueCopy && line_value && 0 == strcmp(ec->mLineValueCopy, line_value)) || (0 == strcmp(ec->mCallId, call_id))) { it = mContacts.erase(it); } else { ++it; } } if (IS_LOGD) print(); } /* static int countContacts(const sip_contact_t *contacts) { sip_contact_t *c=(sip_contact_t *)contacts; int count=0; for(;c;c=c->m_next) { ++count; } return count; } static bool ec_sort(ExtendedContact *ec1, ExtendedContact *ec2) { return ec1->mUpdatedTime < ec2->mUpdatedTime; } void Record::makeSpace(int slots) { int spaceNeeded=countContacts(contacts); int spaceLeft=sMaxContacts - mContacts.size() - count; if (spaceLeft >=0) return; LOGD("Need to make space for received contacts (need %i slots)", -spaceLeft); sort (mContacts.begin(), mContacts.end(), ec_sort); print(); list<ExtendedContact *>::iterator it; for (it=mContacts.begin(); spaceLeft == 0; ++it) { it=mContacts.erase(it); ++spaceLeft; } print(); } */ /** * Should first have checked the validity of the register with isValidRegister. */ void Record::clean(time_t now) { auto it = mContacts.begin(); while (it != mContacts.end()) { shared_ptr<ExtendedContact> ec = (*it); if (now >= ec->mExpireAt) { it = mContacts.erase(it); } else { ++it; } } } void Record::insertOrUpdateBinding(const shared_ptr<ExtendedContact> &ec) { // Try to locate an existing contact shared_ptr<ExtendedContact> olderEc; for (auto it = mContacts.begin(); it != mContacts.end(); ++it) { if (0 == strcmp(ec->mContactId, (*it)->mContactId)) { mContacts.erase(it); mContacts.push_back(ec); return; } if (!olderEc || olderEc->mUpdatedTime > (*it)->mUpdatedTime) { olderEc = (*it); } } // If contact doesn't exist and there is space left if (mContacts.size() < (unsigned int) sMaxContacts) { mContacts.push_back(ec); } else { // no space mContacts.remove(olderEc); mContacts.push_back(ec); } } static void defineContactId(ostringstream &oss, const url_t *url, const char *transport) { if (transport) oss << transport << ":"; if (url->url_user) oss << url->url_user << ":"; oss << url->url_host; if (url->url_port) oss << ":" << url->url_port; } void Record::bind(const sip_contact_t *contacts, const char* route, int globalExpire, const char *call_id, uint32_t cseq, time_t now, bool alias) { sip_contact_t *c = (sip_contact_t *) contacts; while (c) { const char *lineValue = msg_header_find_item(c->m_common, sLineFieldName.c_str()); const char *transport = msg_header_find_item(c->m_common, "transport"); ostringstream contactId; defineContactId(contactId, c->m_url, transport); insertOrUpdateBinding(make_shared<ExtendedContact>(c, contactId.str().c_str(), route, lineValue, globalExpire, call_id, cseq, now, alias)); c = c->m_next; } if (IS_LOGD) print(); } void Record::bind(const char *c, const char *contactId, const char* route, const char *lineValue, long expireAt, float q, const char *call_id, uint32_t cseq, time_t updated_time, bool alias) { insertOrUpdateBinding(make_shared<ExtendedContact>(c, contactId, route, lineValue, expireAt, q, call_id, cseq, updated_time, alias)); } void Record::print() { LOGD("Record contains %zu contacts", mContacts.size()); for (auto it = mContacts.begin(); it != mContacts.end(); ++it) { shared_ptr<ExtendedContact> ec = (*it); LOGD("%s %lu route=%s", ec->mSipUri, ec->mExpireAt, ec->mRoute); } LOGD("=========================="); } int Record::sMaxContacts = -1; string Record::sLineFieldName = ""; Record::Record() { if (sMaxContacts == -1) init(); } Record::~Record() { } void Record::init() { GenericStruct *registrar = GenericManager::get()->getRoot()->get<GenericStruct>("module::Registrar"); sMaxContacts = registrar->get<ConfigInt>("max-contacts-by-aor")->read(); sLineFieldName = registrar->get<ConfigString>("line-field-name")->read(); } RegistrarDb::RegistrarDb() { } int RegistrarDb::count_sip_contacts(const sip_contact_t *contact) { int count = 0; sip_contact_t *current = (sip_contact_t *) contact; while (current) { current = current->m_next; ++count; } return count; } void RegistrarDb::defineKeyFromUrl(char *key, int len, const url_t *url) { snprintf(key, len - 1, "%s@%s", url->url_user, url->url_host); } bool RegistrarDb::errorOnTooMuchContactInBind(const sip_contact_t *sip_contact, const char *key, const shared_ptr<RegistrarDbListener> &listener) { if (count_sip_contacts(sip_contact) > Record::getMaxContacts()) { LOGD("Too many contacts in register %s %i > %i", key, count_sip_contacts(sip_contact), Record::getMaxContacts()); return true; } return false; } RegistrarDb *RegistrarDb::sUnique = NULL; RegistrarDb *RegistrarDb::get(Agent *ag) { if (sUnique == NULL) { GenericStruct *cr = GenericManager::get()->getRoot(); GenericStruct *mr = cr->get<GenericStruct>("module::Registrar"); string dbImplementation = mr->get<ConfigString>("db-implementation")->read(); if ("internal" == dbImplementation) { LOGI("RegistrarDB implementation is internal"); sUnique = new RegistrarDbInternal(); #ifdef ENABLE_REDIS } else if ("redis-sync"==dbImplementation) { LOGI("RegistrarDB implementation is synchronous REDIS"); sUnique=new RegistrarDbRedisSync(); } else if ("redis-async"==dbImplementation) { LOGI("RegistrarDB implementation is asynchronous REDIS"); sUnique=new RegistrarDbRedisAsync(ag); #endif } else { LOGF("unsupported implementation %s", dbImplementation.c_str()) } } return sUnique; } void RegistrarDb::bind(const url_t* fromUrl, const sip_contact_t *sip_contact, const char * calld_id, uint32_t cs_seq, const char *route, int global_expire, bool alias, const shared_ptr<RegistrarDbListener> &listener) { doBind(fromUrl, sip_contact, calld_id, cs_seq, route, global_expire, alias, listener); } void RegistrarDb::clear(const sip_t *sip, const shared_ptr<RegistrarDbListener> &listener) { doClear(sip, listener); } class RecursiveRegistrarDbListener: public RegistrarDbListener, public enable_shared_from_this<RecursiveRegistrarDbListener> { private: RegistrarDb *m_database; shared_ptr<RegistrarDbListener> m_original_listerner; Record *m_record; su_home_t m_home; int m_request; int m_step; static int sMaxStep; public: RecursiveRegistrarDbListener(RegistrarDb *database, const shared_ptr<RegistrarDbListener> &original_listerner, int step = sMaxStep) : m_database(database), m_original_listerner(original_listerner), m_record(new Record()), m_request(1), m_step(step) { su_home_init(&m_home); } ~RecursiveRegistrarDbListener() { su_home_deinit(&m_home); delete m_record; } void onRecordFound(Record *r) { if (r != NULL) { for (auto it = r->mContacts.begin(); it != r->mContacts.end(); ++it) { shared_ptr<ExtendedContact> ec = *it; if (!ec->mAlias) { m_record->mContacts.push_back(ec); } else { if (m_step > 0) { sip_contact_t *contact = sip_contact_format(&m_home, "%s", ec->mSipUri); if (contact != NULL) { ++m_request; m_database->fetch(contact->m_url, make_shared<RecursiveRegistrarDbListener>(m_database, this->shared_from_this(), m_step - 1), false); } } else { m_record->mContacts.push_back(ec); } } } } if (check()) { m_original_listerner->onRecordFound(NULL); } } void onError() { if (check()) { m_original_listerner->onError(); } } void onInvalid() { if (check()) { m_original_listerner->onInvalid(); } } private: bool check() { if (--m_request == 0) { if (m_record->mContacts.size() == 0) { return true; } m_original_listerner->onRecordFound(m_record); } return false; } }; int RecursiveRegistrarDbListener::sMaxStep = 1; void RegistrarDb::fetch(const url_t *url, const shared_ptr<RegistrarDbListener> &listener, bool recursive) { if (recursive) doFetch(url, make_shared<RecursiveRegistrarDbListener>(this, listener)); else doFetch(url, listener); } void RegistrarDb::bind(const sip_t *sip, const char* route, int globalExpire, bool alias, const shared_ptr<RegistrarDbListener> &listener) { bind(sip->sip_from->a_url, sip->sip_contact, sip->sip_call_id->i_id, sip->sip_cseq->cs_seq, route, globalExpire, alias, listener); } <commit_msg>Fix handling of line and transport in registrar.<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "registrardb.hh" #include "registrardb-internal.hh" #ifdef ENABLE_REDIS #include "registrardb-redis.hh" #endif #include "common.hh" #include "configmanager.hh" #include <sstream> #include <ctime> #include <cstdio> #include <algorithm> #include <sofia-sip/sip_protos.h> using namespace ::std; sip_contact_t *Record::extendedContactToSofia(su_home_t *home, const ExtendedContact &ec, time_t now) { sip_contact_t *contact = NULL; int expire = ec.mExpireAt - now; if (expire > 0) { if (ec.mQ == 0) { contact = sip_contact_format(home, "%s;expires=%i", ec.mSipUri, expire); } else { contact = sip_contact_format(home, "%s;q=%4.2f;expires=%i", ec.mSipUri, ec.mQ, expire); } } return contact; } const sip_contact_t *Record::getContacts(su_home_t *home, time_t now) { sip_contact_t *alist = NULL; for (auto it = mContacts.begin(); it != mContacts.end(); ++it) { sip_contact_t *current = extendedContactToSofia(home, **it, now); if (current && alist) { current->m_next = alist; } alist = current; } return alist; } bool Record::isInvalidRegister(const char *call_id, uint32_t cseq) { for (auto it = mContacts.begin(); it != mContacts.end(); ++it) { shared_ptr<ExtendedContact> ec = (*it); if ((0 == strcmp(ec->mCallId, call_id)) && cseq <= ec->mCSeq) { return true; } } return false; } /** * Should first have checked the validity of the register with isValidRegister. */ void Record::clean(const sip_contact_t *sip, const char *call_id, uint32_t cseq, time_t now) { char lineValue [20]; char *lineValuePtr=lineValue; if (!url_param(sip->m_url->url_params,sLineFieldName.c_str(),lineValue,sizeof(lineValue)-1)) { lineValuePtr=NULL; } auto it = mContacts.begin(); while (it != mContacts.end()) { shared_ptr<ExtendedContact> ec = (*it); if (now >= ec->mExpireAt) { LOGD("Cleaning expired contact %s", ec->mContactId); it = mContacts.erase(it); } else if (ec->mLineValueCopy && lineValuePtr != NULL && 0 == strcmp(ec->mLineValueCopy, lineValuePtr)) { LOGD("Cleaning older line '%s' for contact %s", lineValuePtr, ec->mContactId); it = mContacts.erase(it); } else if (0 == strcmp(ec->mCallId, call_id)) { LOGD("Cleaning same call id contact %s", ec->mContactId); it = mContacts.erase(it); } else { ++it; } } if (IS_LOGD) print(); } /* static int countContacts(const sip_contact_t *contacts) { sip_contact_t *c=(sip_contact_t *)contacts; int count=0; for(;c;c=c->m_next) { ++count; } return count; } static bool ec_sort(ExtendedContact *ec1, ExtendedContact *ec2) { return ec1->mUpdatedTime < ec2->mUpdatedTime; } void Record::makeSpace(int slots) { int spaceNeeded=countContacts(contacts); int spaceLeft=sMaxContacts - mContacts.size() - count; if (spaceLeft >=0) return; LOGD("Need to make space for received contacts (need %i slots)", -spaceLeft); sort (mContacts.begin(), mContacts.end(), ec_sort); print(); list<ExtendedContact *>::iterator it; for (it=mContacts.begin(); spaceLeft == 0; ++it) { it=mContacts.erase(it); ++spaceLeft; } print(); } */ /** * Should first have checked the validity of the register with isValidRegister. */ void Record::clean(time_t now) { auto it = mContacts.begin(); while (it != mContacts.end()) { shared_ptr<ExtendedContact> ec = (*it); if (now >= ec->mExpireAt) { it = mContacts.erase(it); } else { ++it; } } } void Record::insertOrUpdateBinding(const shared_ptr<ExtendedContact> &ec) { // Try to locate an existing contact shared_ptr<ExtendedContact> olderEc; for (auto it = mContacts.begin(); it != mContacts.end(); ++it) { if (0 == strcmp(ec->mContactId, (*it)->mContactId)) { LOGD("Removing older contact with same id %s", (*it)->mContactId); mContacts.erase(it); mContacts.push_back(ec); return; } if (!olderEc || olderEc->mUpdatedTime > (*it)->mUpdatedTime) { olderEc = (*it); } } // If contact doesn't exist and there is space left if (mContacts.size() < (unsigned int) sMaxContacts) { mContacts.push_back(ec); } else { // no space mContacts.remove(olderEc); mContacts.push_back(ec); } } static void defineContactId(ostringstream &oss, const url_t *url, const char *transport) { if (transport!=NULL) oss << transport << ":"; if (url->url_user != NULL) oss << url->url_user << ":"; oss << url->url_host; if (url->url_port) oss << ":" << url->url_port; } void Record::bind(const sip_contact_t *contacts, const char* route, int globalExpire, const char *call_id, uint32_t cseq, time_t now, bool alias) { sip_contact_t *c = (sip_contact_t *) contacts; while (c) { char lineValue [20]; char *lineValuePtr=lineValue; if (!url_param(c->m_url->url_params,sLineFieldName.c_str(),lineValue,sizeof(lineValue)-1)) { lineValuePtr=NULL; } char transport [20]; char *transportPtr=transport; if (!url_param(c->m_url->url_params,"transport",transport,sizeof(transport)-1)) { transportPtr=NULL; } ostringstream contactId; defineContactId(contactId, c->m_url, transportPtr); insertOrUpdateBinding(make_shared<ExtendedContact>(c, contactId.str().c_str(), route, lineValuePtr, globalExpire, call_id, cseq, now, alias)); c = c->m_next; } if (IS_LOGD) print(); } void Record::bind(const char *c, const char *contactId, const char* route, const char *lineValue, long expireAt, float q, const char *call_id, uint32_t cseq, time_t updated_time, bool alias) { insertOrUpdateBinding(make_shared<ExtendedContact>(c, contactId, route, lineValue, expireAt, q, call_id, cseq, updated_time, alias)); } void Record::print() { LOGD("Record contains %zu contacts", mContacts.size()); for (auto it = mContacts.begin(); it != mContacts.end(); ++it) { shared_ptr<ExtendedContact> ec = (*it); struct tm *ptm=localtime(&ec->mExpireAt); LOGD("%s route=%s expire=%2d:%02d (%lu)", ec->mSipUri, ec->mRoute, ptm->tm_hour%24, ptm->tm_min, ec->mExpireAt); } LOGD("=========================="); } int Record::sMaxContacts = -1; string Record::sLineFieldName = ""; Record::Record() { if (sMaxContacts == -1) init(); } Record::~Record() { } void Record::init() { GenericStruct *registrar = GenericManager::get()->getRoot()->get<GenericStruct>("module::Registrar"); sMaxContacts = registrar->get<ConfigInt>("max-contacts-by-aor")->read(); sLineFieldName = registrar->get<ConfigString>("line-field-name")->read(); } RegistrarDb::RegistrarDb() { } int RegistrarDb::count_sip_contacts(const sip_contact_t *contact) { int count = 0; sip_contact_t *current = (sip_contact_t *) contact; while (current) { current = current->m_next; ++count; } return count; } void RegistrarDb::defineKeyFromUrl(char *key, int len, const url_t *url) { snprintf(key, len - 1, "%s@%s", url->url_user, url->url_host); } bool RegistrarDb::errorOnTooMuchContactInBind(const sip_contact_t *sip_contact, const char *key, const shared_ptr<RegistrarDbListener> &listener) { if (count_sip_contacts(sip_contact) > Record::getMaxContacts()) { LOGD("Too many contacts in register %s %i > %i", key, count_sip_contacts(sip_contact), Record::getMaxContacts()); return true; } return false; } RegistrarDb *RegistrarDb::sUnique = NULL; RegistrarDb *RegistrarDb::get(Agent *ag) { if (sUnique == NULL) { GenericStruct *cr = GenericManager::get()->getRoot(); GenericStruct *mr = cr->get<GenericStruct>("module::Registrar"); string dbImplementation = mr->get<ConfigString>("db-implementation")->read(); if ("internal" == dbImplementation) { LOGI("RegistrarDB implementation is internal"); sUnique = new RegistrarDbInternal(); #ifdef ENABLE_REDIS } else if ("redis-sync"==dbImplementation) { LOGI("RegistrarDB implementation is synchronous REDIS"); sUnique=new RegistrarDbRedisSync(); } else if ("redis-async"==dbImplementation) { LOGI("RegistrarDB implementation is asynchronous REDIS"); sUnique=new RegistrarDbRedisAsync(ag); #endif } else { LOGF("unsupported implementation %s", dbImplementation.c_str()) } } return sUnique; } void RegistrarDb::bind(const url_t* fromUrl, const sip_contact_t *sip_contact, const char * calld_id, uint32_t cs_seq, const char *route, int global_expire, bool alias, const shared_ptr<RegistrarDbListener> &listener) { doBind(fromUrl, sip_contact, calld_id, cs_seq, route, global_expire, alias, listener); } void RegistrarDb::clear(const sip_t *sip, const shared_ptr<RegistrarDbListener> &listener) { doClear(sip, listener); } class RecursiveRegistrarDbListener: public RegistrarDbListener, public enable_shared_from_this<RecursiveRegistrarDbListener> { private: RegistrarDb *m_database; shared_ptr<RegistrarDbListener> m_original_listerner; Record *m_record; su_home_t m_home; int m_request; int m_step; static int sMaxStep; public: RecursiveRegistrarDbListener(RegistrarDb *database, const shared_ptr<RegistrarDbListener> &original_listerner, int step = sMaxStep) : m_database(database), m_original_listerner(original_listerner), m_record(new Record()), m_request(1), m_step(step) { su_home_init(&m_home); } ~RecursiveRegistrarDbListener() { su_home_deinit(&m_home); delete m_record; } void onRecordFound(Record *r) { if (r != NULL) { for (auto it = r->mContacts.begin(); it != r->mContacts.end(); ++it) { shared_ptr<ExtendedContact> ec = *it; if (!ec->mAlias) { m_record->mContacts.push_back(ec); } else { if (m_step > 0) { sip_contact_t *contact = sip_contact_format(&m_home, "%s", ec->mSipUri); if (contact != NULL) { ++m_request; m_database->fetch(contact->m_url, make_shared<RecursiveRegistrarDbListener>(m_database, this->shared_from_this(), m_step - 1), false); } } else { m_record->mContacts.push_back(ec); } } } } if (check()) { m_original_listerner->onRecordFound(NULL); } } void onError() { if (check()) { m_original_listerner->onError(); } } void onInvalid() { if (check()) { m_original_listerner->onInvalid(); } } private: bool check() { if (--m_request == 0) { if (m_record->mContacts.size() == 0) { return true; } m_original_listerner->onRecordFound(m_record); } return false; } }; int RecursiveRegistrarDbListener::sMaxStep = 1; void RegistrarDb::fetch(const url_t *url, const shared_ptr<RegistrarDbListener> &listener, bool recursive) { if (recursive) doFetch(url, make_shared<RecursiveRegistrarDbListener>(this, listener)); else doFetch(url, listener); } void RegistrarDb::bind(const sip_t *sip, const char* route, int globalExpire, bool alias, const shared_ptr<RegistrarDbListener> &listener) { bind(sip->sip_from->a_url, sip->sip_contact, sip->sip_call_id->i_id, sip->sip_cseq->cs_seq, route, globalExpire, alias, listener); } <|endoftext|>
<commit_before>/* headers.cpp ⠭ */ /* Revision: 1.02 11.07.2000 $ */ /* Modify: 27.06.2000 AT + ᤥ ᯮ짮 ।஢ 07.07.2000 SVS + stdarg.h - FarAdvControl 11.07.2000 SVS ! 樨 BC & VC */ #define STRICT #if !defined(_INC_WINDOWS) && !defined(_WINDOWS_) #if defined(_MSC_VER) #define _WINCON_ // to prevent including wincon.h #pragma pack(push,2) #include <windows.h> #undef _WINCON_ #pragma pack(pop) #include <wincon.h> //this file wants 8-byte alignment #else #include <windows.h> #endif #endif #include <winioctl.h> #ifndef __DOS_H #include <dos.h> // FA_* #endif #ifndef __DIR_H #ifdef _MSC_VER #include <direct.h> // chdir #else #include <dir.h> // chdir #endif #endif //__DIR_H #if !defined(__NEW_H) #if defined(__BORLANDC__) #pragma option -p- #endif #include <new.h> #if defined(__BORLANDC__) #pragma option -p. #endif #endif //!defined(__NEW_H) #ifndef __ALLOC_H #ifdef _MSC_VER #include <malloc.h> #else #include <alloc.h> #endif #endif #ifndef __FCNTL_H #include <fcntl.h> #endif #ifndef __IO_H #include <io.h> #endif #ifndef __PROCESS_H #include <process.h> #endif #ifndef __STDIO_H #include <stdio.h> #endif #ifndef __STDLIB_H #include <stdlib.h> #endif #ifndef __STRING_H #include <string.h> #endif #ifndef __STAT_H #include <sys\stat.h> // S_IREAD... #endif #ifndef __TIME_H #include <time.h> #endif #ifndef __STDARG_H #include <stdarg.h> #endif #if _MSC_VER #define _export #define FA_DIREC _A_SUBDIR #define FA_RDONLY _A_RDONLY #define FA_HIDDEN _A_HIDDEN #define FA_SYSTEM _A_SYSTEM #define FA_RDONLY _A_RDONLY #define FA_ARCH _A_ARCH #define setdisk(n) _chdrive((n)+1) #define getdisk() _getdrive()-1 #define randomize() srand(67898) #define random(x) ( (int) rand() * (x) ) #pragma warning (once:4018) #endif <commit_msg>FAR patch 00053.headers.hpp Дата : 12.07.2000 Сделал : Oleg Taranenko Описание : Исправление бага, из-за которго не работал ScreenSaver после компиляции VC++ Измененные файлы : headers.hpp Состав : headers.hpp.OT.txt headers.hpp.OT.diff Основан на патче : 51 Дополнение :<commit_after>/* headers.cpp ⠭ */ /* Revision: 1.03 12.07.2000 $ */ /* Modify: 27.06.2000 AT + ᤥ ᯮ짮 ।஢ 07.07.2000 SVS + stdarg.h - FarAdvControl 11.07.2000 SVS ! 樨 BC & VC 12.07.2000 OT - ࠢ , - ࣮ ࠡ⠫ ScreenSaver ᫥ 樨 VC++ */ #define STRICT #if !defined(_INC_WINDOWS) && !defined(_WINDOWS_) #if defined(_MSC_VER) #define _WINCON_ // to prevent including wincon.h #pragma pack(push,2) #include <windows.h> #undef _WINCON_ #pragma pack(pop) #include <wincon.h> //this file wants 8-byte alignment #else #include <windows.h> #endif #endif #include <winioctl.h> #ifndef __DOS_H #include <dos.h> // FA_* #endif #ifndef __DIR_H #ifdef _MSC_VER #include <direct.h> // chdir #else #include <dir.h> // chdir #endif #endif //__DIR_H #if !defined(__NEW_H) #if defined(__BORLANDC__) #pragma option -p- #endif #include <new.h> #if defined(__BORLANDC__) #pragma option -p. #endif #endif //!defined(__NEW_H) #ifndef __ALLOC_H #ifdef _MSC_VER #include <malloc.h> #else #include <alloc.h> #endif #endif #ifndef __FCNTL_H #include <fcntl.h> #endif #ifndef __IO_H #include <io.h> #endif #ifndef __PROCESS_H #include <process.h> #endif #ifndef __STDIO_H #include <stdio.h> #endif #ifndef __STDLIB_H #include <stdlib.h> #endif #ifndef __STRING_H #include <string.h> #endif #ifndef __STAT_H #include <sys\stat.h> // S_IREAD... #endif #ifndef __TIME_H #include <time.h> #endif #ifndef __STDARG_H #include <stdarg.h> #endif #if _MSC_VER #define _export #define FA_DIREC _A_SUBDIR #define FA_RDONLY _A_RDONLY #define FA_HIDDEN _A_HIDDEN #define FA_SYSTEM _A_SYSTEM #define FA_RDONLY _A_RDONLY #define FA_ARCH _A_ARCH #define setdisk(n) _chdrive((n)+1) #define getdisk() _getdrive()-1 /* $ 12.07.2000 OT - ࠢ , - ࣮ ࠡ⠫ ScreenSaver ᫥ 樨 VC++ */ #ifndef RAND_MAX #define RAND_MAX 0x7fff #endif #define randomize() srand(67898) #define random(x) ((int) (((x) * rand()) / RAND_MAX) ) /* OT $ */ #pragma warning (once:4018) #endif <|endoftext|>
<commit_before>#include <Poco/UUIDGenerator.h> #include <Poco/UUID.h> #include "../lib/rapidjson/prettywriter.h" #include "../lib/rapidjson/stringbuffer.h" #include "job.h" using namespace Batyr; Job::Job() : status(FAILED) { // generate an UUID as id for the job Poco::UUIDGenerator & uuidGen = Poco::UUIDGenerator::defaultGenerator(); Poco::UUID uuid(uuidGen.createRandom()); id = uuid.toString(); } void Job::toJsonValue(rapidjson::Value & targetValue, rapidjson::Document::AllocatorType & allocator) const { targetValue.SetObject(); targetValue.AddMember("id", id.c_str(), allocator); std::string statusString; switch (status) { case QUEUED: statusString = "queued"; break; case IN_PROCESS: statusString = "in_process"; break; case FINISHED: statusString = "finished"; break; case FAILED: statusString = "failed"; break; } targetValue.AddMember("status", statusString.c_str(), allocator); if (!errorMessage.empty()) { targetValue.AddMember("errorMessage", errorMessage.c_str(), allocator); } } std::string Job::toString() const { // usage of rapidjson: // http://www.thomaswhitton.com/blog/2013/06/27/json-c-plus-plus-examples/ rapidjson::Document data; toJsonValue(data, data.GetAllocator()); // stringify rapidjson::GenericStringBuffer< rapidjson::UTF8<> > buffer; rapidjson::Writer< rapidjson::GenericStringBuffer< rapidjson::UTF8<> > > writer(buffer); data.Accept(writer); return std::string(buffer.GetString()); } std::ostream& Batyr::operator<< (std::ostream& stream, const Job& r) { stream << r.toString(); return stream; } <commit_msg>avoid using a free'd std::string to store the job status<commit_after>#include <Poco/UUIDGenerator.h> #include <Poco/UUID.h> #include "../lib/rapidjson/prettywriter.h" #include "../lib/rapidjson/stringbuffer.h" #include "job.h" using namespace Batyr; Job::Job() : status(FAILED) { // generate an UUID as id for the job Poco::UUIDGenerator & uuidGen = Poco::UUIDGenerator::defaultGenerator(); Poco::UUID uuid(uuidGen.createRandom()); id = uuid.toString(); } void Job::toJsonValue(rapidjson::Value & targetValue, rapidjson::Document::AllocatorType & allocator) const { targetValue.SetObject(); targetValue.AddMember("id", id.c_str(), allocator); const char * statusString; switch (status) { case QUEUED: statusString = "queued"; break; case IN_PROCESS: statusString = "in_process"; break; case FINISHED: statusString = "finished"; break; case FAILED: statusString = "failed"; break; } targetValue.AddMember("status", statusString, allocator); if (!errorMessage.empty()) { targetValue.AddMember("errorMessage", errorMessage.c_str(), allocator); } } std::string Job::toString() const { // usage of rapidjson: // http://www.thomaswhitton.com/blog/2013/06/27/json-c-plus-plus-examples/ rapidjson::Document data; toJsonValue(data, data.GetAllocator()); // stringify rapidjson::GenericStringBuffer< rapidjson::UTF8<> > buffer; rapidjson::Writer< rapidjson::GenericStringBuffer< rapidjson::UTF8<> > > writer(buffer); data.Accept(writer); return std::string(buffer.GetString()); } std::ostream& Batyr::operator<< (std::ostream& stream, const Job& r) { stream << r.toString(); return stream; } <|endoftext|>
<commit_before>// Copyright 2017 The Johns Hopkins University Applied Physics Laboratory. // Licensed under the MIT License. See LICENSE.txt in the project root for full license information. #include <cstdio> #include <ctime> #include "orthoimage.h" #include "shr3d.h" // Print command line arguments. void printArguments() { printf("Command line arguments: <Input File (LAS|TIF)> <Options>\n"); printf("Required Options:\n"); printf(" DH= horizontal uncertainty (meters)\n"); printf(" DZ= vertical uncertainty (meters)\n"); printf(" AGL= minimum building height above ground level (meters)\n"); printf("Options:\n"); printf(" AREA= minimum building area (meters)\n"); printf(" EGM96 set this flag to write vertical datum = EGM96\n"); printf("Examples:\n"); printf(" For EO DSM: shr3d dsm.tif DH=5.0 DZ=1.0 AGL=2 AREA=50.0 EGM96\n"); printf(" For lidar DSM: shr3d dsm.tif DH=1.0 DZ=1.0 AGL=2.0 AREA=50.0\n"); printf(" For lidar LAS: shr3d pts.las DH=1.0 DZ=1.0 AGL=2.0 AREA=50.0\n"); } // Main program for bare earth classification. int main(int argc, char **argv) { // If no parameters, then print command line arguments. if (argc < 4) { printf("Number of arguments = %d\n", argc); for (int i = 0; i < argc; i++) { printf("ARG[%d] = %s\n", i, argv[i]); } printArguments(); return -1; } // Get command line arguments and confirm they are valid. double dh_meters = 0.0; double dz_meters = 0.0; double agl_meters = 0.0; double min_area_meters = 50.0; bool egm96 = false; bool convert = false; char inputFileName[1024]; strcpy(inputFileName, argv[1]); for (int i = 2; i < argc; i++) { if (strstr(argv[i], "DH=")) { dh_meters = atof(&(argv[i][3])); } if (strstr(argv[i], "DZ=")) { dz_meters = atof(&(argv[i][3])); } if (strstr(argv[i], "AGL=")) { agl_meters = atof(&(argv[i][4])); } if (strstr(argv[i], "AREA=")) { min_area_meters = atof(&(argv[i][5])); } if (strstr(argv[i], "EGM96")) { egm96 = true; } if (strstr(argv[i], "CONVERT")) { convert = true; } } if ((dh_meters == 0.0) || (dz_meters == 0.0) || (agl_meters == 0.0)) { printf("DH_METERS = %f\n", dh_meters); printf("DZ_METERS = %f\n", dz_meters); printf("AGL_METERS = %f\n", agl_meters); printf("Error: All three values must be nonzero.\n"); printArguments(); return -1; } // Initialize the timer. time_t t0; time(&t0); // If specified, then convert to GDAL TIFF. char readFileName[1024]; strcpy(readFileName, inputFileName); if (convert) { char cmd[4096]; sprintf(readFileName, "temp.tif"); sprintf(cmd, ".\\gdal\\gdal_translate %s temp.tif\n", inputFileName); system(cmd); } // Read DSM as SHORT. // Input can be GeoTIFF or LAS. shr3d::OrthoImage<unsigned short> dsmImage; shr3d::OrthoImage<unsigned short> minImage; printf("Reading DSM as SHORT.\n"); int len = (int) strlen(inputFileName); char *ext = &inputFileName[len - 3]; printf("File Type = .%s\n", ext); if (strcmp(ext, "tif") == 0) { bool ok = dsmImage.read(readFileName); if (!ok) return -1; // Copy DSM minImage = dsmImage; // Min filter, replacing only points differing by more than the AGL threshold. minImage.minFilter(4, (unsigned int) (agl_meters / minImage.scale)); // Fill small voids in the DSM. minImage.fillVoidsPyramid(true, 2); #ifdef DEBUG // Write the MIN image as FLOAT. char minOutFileName[1024]; sprintf(minOutFileName, "%s_MIN.tif", inputFileName); minImage.write(minOutFileName, true); #endif } else if ((strcmp(ext, "las") == 0) || (strcmp(ext, "bpf") == 0)) { // First get the max Z values for the DSM. // Read a PSET file (e.g., BPF or LAS). shr3d::PointCloud pset; bool ok = pset.Read(inputFileName); if (!ok) return -1; ok = dsmImage.readFromPointCloud(pset, (float) dh_meters, shr3d::MAX_VALUE); if (!ok) return -1; // Median filter, replacing only points differing by more than the AGL threshold. dsmImage.medianFilter(1, (unsigned int) (agl_meters / dsmImage.scale)); // Fill small voids in the DSM. dsmImage.fillVoidsPyramid(true, 2); // Write the DSM image as FLOAT. char dsmOutFileName[1024]; sprintf(dsmOutFileName, "%s_DSM.tif", inputFileName); dsmImage.write(dsmOutFileName, true); // Now get the minimum Z values for the DTM. ok = minImage.readFromPointCloud(pset, (float) dh_meters, shr3d::MIN_VALUE); if (!ok) return -1; // Median filter, replacing only points differing by more than the AGL threshold. minImage.medianFilter(1, (unsigned int) (agl_meters / minImage.scale)); // Fill small voids in the DSM. minImage.fillVoidsPyramid(true, 2); #ifdef DEBUG // Write the MIN image as FLOAT. char minOutFileName[1024]; sprintf(minOutFileName, "%s_MIN.tif", inputFileName); minImage.write(minOutFileName, true); #endif // Find many of the trees by comparing MIN and MAX. Set their values to void. shr3d::OrthoImage<unsigned short> varImage = dsmImage - minImage; unsigned short maxTreeHeightScaled = (40.0 / minImage.scale); unsigned short threshold = (dz_meters / dsmImage.scale); // Apply tree filter shr3d::Image<unsigned short>::filter(&dsmImage, &varImage, [&](unsigned short* val, const unsigned short& ref, std::vector<unsigned short> &ngbrs) { // CAUTION: This is a hack to address an observed lidar sensor issue and may not generalize well. if (ref <= maxTreeHeightScaled) { // Set dsm to void if none of the neighbors are solid (var is < threshold) if (std::none_of(ngbrs.begin(), ngbrs.end(), [&](unsigned short v){ return v<=threshold; })) *val = 0; } }, 1, 0, false); // Write the DSM2 image as FLOAT. #ifdef DEBUG char dsm2OutFileName[1024]; sprintf(dsm2OutFileName, "%s_DSM2.tif", inputFileName); dsmImage.write(dsm2OutFileName, true); #endif } else { printf("Error: Unrecognized file type."); return -1; } // Convert horizontal and vertical uncertainty values to bin units. int dh_bins = MAX(1, (int) floor(dh_meters / dsmImage.gsd)); printf("DZ_METERS = %f\n", dz_meters); printf("DH_METERS = %f\n", dh_meters); printf("DH_BINS = %d\n", dh_bins); unsigned int dz_short = (unsigned int) (dz_meters / dsmImage.scale); printf("DZ_SHORT = %d\n", dz_short); printf("AGL_METERS = %f\n", agl_meters); unsigned int agl_short = (unsigned int) (agl_meters / dsmImage.scale); printf("AGL_SHORT = %d\n", agl_short); printf("AREA_METERS = %f\n", min_area_meters); // Generate label image. shr3d::OrthoImage<unsigned long> labelImage; labelImage.Allocate(dsmImage.width, dsmImage.height); labelImage.easting = dsmImage.easting; labelImage.northing = dsmImage.northing; labelImage.zone = dsmImage.zone; labelImage.gsd = dsmImage.gsd; // Allocate a DTM image as SHORT and copy in the Min DSM values. shr3d::OrthoImage<unsigned short> dtmImage(minImage); // Classify ground points. shr3d::Shr3dder::classifyGround(labelImage, dsmImage, dtmImage, dh_bins, dz_short); // For DSM voids, also set DTM value to void. printf("Setting DTM values to VOID where DSM is VOID...\n"); for (unsigned int j = 0; j < dsmImage.height; j++) { for (unsigned int i = 0; i < dsmImage.width; i++) { if (dsmImage.data[j][i] == 0) dtmImage.data[j][i] = 0; } } // Median filter, replacing only points differing by more than the DZ threshold. dtmImage.medianFilter(1, (unsigned int) (dz_meters / dsmImage.scale)); // Refine the object label image and export building outlines. shr3d::Shr3dder::classifyNonGround(dsmImage, dtmImage, labelImage, dz_short, agl_short, (float) min_area_meters); // Fill small voids in the DTM after all processing is complete. dtmImage.fillVoidsPyramid(true, 2); // Write the DTM image as FLOAT. char dtmOutFileName[1024]; sprintf(dtmOutFileName, "%s_DTM.tif", inputFileName); dtmImage.write(dtmOutFileName, true, egm96); // Produce a classification raster image with LAS standard point classes. shr3d::OrthoImage<unsigned char> classImage; classImage.Allocate(labelImage.width, labelImage.height); classImage.easting = dsmImage.easting; classImage.northing = dsmImage.northing; classImage.zone = dsmImage.zone; classImage.gsd = dsmImage.gsd; for (unsigned int j = 0; j < classImage.height; j++) { for (unsigned int i = 0; i < classImage.width; i++) { // Set default as unlabeled. classImage.data[j][i] = LAS_UNCLASSIFIED; // Label trees. if ((dsmImage.data[j][i] == 0) || (fabs((float) dsmImage.data[j][i] - (float) dtmImage.data[j][i]) > agl_short)) classImage.data[j][i] = LAS_TREE; // Label buildings. if (labelImage.data[j][i] == 1) classImage.data[j][i] = LAS_BUILDING; // Label ground. if (fabs((float) dsmImage.data[j][i] - (float) dtmImage.data[j][i]) < dz_short) classImage.data[j][i] = LAS_GROUND; } } // Fill missing labels inside building regions. shr3d::Shr3dder::fillInsideBuildings(classImage); // Write the classification image. char classOutFileName[1024]; sprintf(classOutFileName, "%s_class.tif", inputFileName); classImage.write(classOutFileName, false, egm96); for (unsigned int j = 0; j < classImage.height; j++) { for (unsigned int i = 0; i < classImage.width; i++) { if (classImage.data[j][i] != LAS_BUILDING) classImage.data[j][i] = 0; } } sprintf(classOutFileName, "%s_buildings.tif", inputFileName); classImage.write(classOutFileName, false, egm96); // Report total elapsed time. time_t t1; time(&t1); printf("Total time elapsed = %f seconds\n", double(t1 - t0)); } <commit_msg>Fix bug where areas under trees tend to appear as voids in the DTM<commit_after>// Copyright 2017 The Johns Hopkins University Applied Physics Laboratory. // Licensed under the MIT License. See LICENSE.txt in the project root for full license information. #include <cstdio> #include <ctime> #include "orthoimage.h" #include "shr3d.h" // Print command line arguments. void printArguments() { printf("Command line arguments: <Input File (LAS|TIF)> <Options>\n"); printf("Required Options:\n"); printf(" DH= horizontal uncertainty (meters)\n"); printf(" DZ= vertical uncertainty (meters)\n"); printf(" AGL= minimum building height above ground level (meters)\n"); printf("Options:\n"); printf(" AREA= minimum building area (meters)\n"); printf(" EGM96 set this flag to write vertical datum = EGM96\n"); printf("Examples:\n"); printf(" For EO DSM: shr3d dsm.tif DH=5.0 DZ=1.0 AGL=2 AREA=50.0 EGM96\n"); printf(" For lidar DSM: shr3d dsm.tif DH=1.0 DZ=1.0 AGL=2.0 AREA=50.0\n"); printf(" For lidar LAS: shr3d pts.las DH=1.0 DZ=1.0 AGL=2.0 AREA=50.0\n"); } // Main program for bare earth classification. int main(int argc, char **argv) { // If no parameters, then print command line arguments. if (argc < 4) { printf("Number of arguments = %d\n", argc); for (int i = 0; i < argc; i++) { printf("ARG[%d] = %s\n", i, argv[i]); } printArguments(); return -1; } // Get command line arguments and confirm they are valid. double dh_meters = 0.0; double dz_meters = 0.0; double agl_meters = 0.0; double min_area_meters = 50.0; bool egm96 = false; bool convert = false; char inputFileName[1024]; strcpy(inputFileName, argv[1]); for (int i = 2; i < argc; i++) { if (strstr(argv[i], "DH=")) { dh_meters = atof(&(argv[i][3])); } if (strstr(argv[i], "DZ=")) { dz_meters = atof(&(argv[i][3])); } if (strstr(argv[i], "AGL=")) { agl_meters = atof(&(argv[i][4])); } if (strstr(argv[i], "AREA=")) { min_area_meters = atof(&(argv[i][5])); } if (strstr(argv[i], "EGM96")) { egm96 = true; } if (strstr(argv[i], "CONVERT")) { convert = true; } } if ((dh_meters == 0.0) || (dz_meters == 0.0) || (agl_meters == 0.0)) { printf("DH_METERS = %f\n", dh_meters); printf("DZ_METERS = %f\n", dz_meters); printf("AGL_METERS = %f\n", agl_meters); printf("Error: All three values must be nonzero.\n"); printArguments(); return -1; } // Initialize the timer. time_t t0; time(&t0); // If specified, then convert to GDAL TIFF. char readFileName[1024]; strcpy(readFileName, inputFileName); if (convert) { char cmd[4096]; sprintf(readFileName, "temp.tif"); sprintf(cmd, ".\\gdal\\gdal_translate %s temp.tif\n", inputFileName); system(cmd); } // Read DSM as SHORT. // Input can be GeoTIFF or LAS. shr3d::OrthoImage<unsigned short> dsmImage; shr3d::OrthoImage<unsigned short> minImage; printf("Reading DSM as SHORT.\n"); int len = (int) strlen(inputFileName); char *ext = &inputFileName[len - 3]; printf("File Type = .%s\n", ext); if (strcmp(ext, "tif") == 0) { bool ok = dsmImage.read(readFileName); if (!ok) return -1; // Copy DSM minImage = dsmImage; // Min filter, replacing only points differing by more than the AGL threshold. minImage.minFilter(4, (unsigned int) (agl_meters / minImage.scale)); // Fill small voids in the DSM. minImage.fillVoidsPyramid(true, 2); #ifdef DEBUG // Write the MIN image as FLOAT. char minOutFileName[1024]; sprintf(minOutFileName, "%s_MIN.tif", inputFileName); minImage.write(minOutFileName, true); #endif } else if ((strcmp(ext, "las") == 0) || (strcmp(ext, "bpf") == 0)) { // First get the max Z values for the DSM. // Read a PSET file (e.g., BPF or LAS). shr3d::PointCloud pset; bool ok = pset.Read(inputFileName); if (!ok) return -1; ok = dsmImage.readFromPointCloud(pset, (float) dh_meters, shr3d::MAX_VALUE); if (!ok) return -1; // Median filter, replacing only points differing by more than the AGL threshold. dsmImage.medianFilter(1, (unsigned int) (agl_meters / dsmImage.scale)); // Fill small voids in the DSM. dsmImage.fillVoidsPyramid(true, 2); // Write the DSM image as FLOAT. char dsmOutFileName[1024]; sprintf(dsmOutFileName, "%s_DSM.tif", inputFileName); dsmImage.write(dsmOutFileName, true); // Now get the minimum Z values for the DTM. ok = minImage.readFromPointCloud(pset, (float) dh_meters, shr3d::MIN_VALUE); if (!ok) return -1; // Median filter, replacing only points differing by more than the AGL threshold. minImage.medianFilter(1, (unsigned int) (agl_meters / minImage.scale)); // Fill small voids in the DSM. minImage.fillVoidsPyramid(true, 2); #ifdef DEBUG // Write the MIN image as FLOAT. char minOutFileName[1024]; sprintf(minOutFileName, "%s_MIN.tif", inputFileName); minImage.write(minOutFileName, true); #endif // Find many of the trees by comparing MIN and MAX. Set their values to void. shr3d::OrthoImage<unsigned short> varImage = dsmImage - minImage; unsigned short maxTreeHeightScaled = (40.0 / minImage.scale); unsigned short threshold = (dz_meters / dsmImage.scale); // Apply tree filter shr3d::Image<unsigned short>::filter(&dsmImage, &varImage, [&](unsigned short* val, const unsigned short& ref, std::vector<unsigned short> &ngbrs) { // CAUTION: This is a hack to address an observed lidar sensor issue and may not generalize well. if (ref <= maxTreeHeightScaled) { // Set dsm to void if none of the neighbors are solid (var is < threshold) if (std::none_of(ngbrs.begin(), ngbrs.end(), [&](unsigned short v){ return v<=threshold; })) *val = 0; } }, 1, 0, false); // Write the DSM2 image as FLOAT. #ifdef DEBUG char dsm2OutFileName[1024]; sprintf(dsm2OutFileName, "%s_DSM2.tif", inputFileName); dsmImage.write(dsm2OutFileName, true); #endif } else { printf("Error: Unrecognized file type."); return -1; } // Convert horizontal and vertical uncertainty values to bin units. int dh_bins = MAX(1, (int) floor(dh_meters / dsmImage.gsd)); printf("DZ_METERS = %f\n", dz_meters); printf("DH_METERS = %f\n", dh_meters); printf("DH_BINS = %d\n", dh_bins); unsigned int dz_short = (unsigned int) (dz_meters / dsmImage.scale); printf("DZ_SHORT = %d\n", dz_short); printf("AGL_METERS = %f\n", agl_meters); unsigned int agl_short = (unsigned int) (agl_meters / dsmImage.scale); printf("AGL_SHORT = %d\n", agl_short); printf("AREA_METERS = %f\n", min_area_meters); // Generate label image. shr3d::OrthoImage<unsigned long> labelImage; labelImage.Allocate(dsmImage.width, dsmImage.height); labelImage.easting = dsmImage.easting; labelImage.northing = dsmImage.northing; labelImage.zone = dsmImage.zone; labelImage.gsd = dsmImage.gsd; // Allocate a DTM image as SHORT and copy in the Min DSM values. shr3d::OrthoImage<unsigned short> dtmImage(minImage); // Classify ground points. shr3d::Shr3dder::classifyGround(labelImage, dsmImage, dtmImage, dh_bins, dz_short); // For DSM voids, also set DTM value to void. // Note: because we've changed the DSM by this point (setting voids where all the trees are), // use the minImage which will have the same voids as the original DSM printf("Setting DTM values to VOID where DSM is VOID...\n"); for (unsigned int j = 0; j < minImage.height; j++) { for (unsigned int i = 0; i < minImage.width; i++) { if (minImage.data[j][i] == 0) dtmImage.data[j][i] = 0; } } // Median filter, replacing only points differing by more than the DZ threshold. dtmImage.medianFilter(1, (unsigned int) (dz_meters / dsmImage.scale)); // Refine the object label image and export building outlines. shr3d::Shr3dder::classifyNonGround(dsmImage, dtmImage, labelImage, dz_short, agl_short, (float) min_area_meters); // Fill small voids in the DTM after all processing is complete. dtmImage.fillVoidsPyramid(true, 2); // Write the DTM image as FLOAT. char dtmOutFileName[1024]; sprintf(dtmOutFileName, "%s_DTM.tif", inputFileName); dtmImage.write(dtmOutFileName, true, egm96); // Produce a classification raster image with LAS standard point classes. shr3d::OrthoImage<unsigned char> classImage; classImage.Allocate(labelImage.width, labelImage.height); classImage.easting = dsmImage.easting; classImage.northing = dsmImage.northing; classImage.zone = dsmImage.zone; classImage.gsd = dsmImage.gsd; for (unsigned int j = 0; j < classImage.height; j++) { for (unsigned int i = 0; i < classImage.width; i++) { // Set default as unlabeled. classImage.data[j][i] = LAS_UNCLASSIFIED; // Label trees. if ((dsmImage.data[j][i] == 0) || (fabs((float) dsmImage.data[j][i] - (float) dtmImage.data[j][i]) > agl_short)) classImage.data[j][i] = LAS_TREE; // Label buildings. if (labelImage.data[j][i] == 1) classImage.data[j][i] = LAS_BUILDING; // Label ground. if (fabs((float) dsmImage.data[j][i] - (float) dtmImage.data[j][i]) < dz_short) classImage.data[j][i] = LAS_GROUND; } } // Fill missing labels inside building regions. shr3d::Shr3dder::fillInsideBuildings(classImage); // Write the classification image. char classOutFileName[1024]; sprintf(classOutFileName, "%s_class.tif", inputFileName); classImage.write(classOutFileName, false, egm96); for (unsigned int j = 0; j < classImage.height; j++) { for (unsigned int i = 0; i < classImage.width; i++) { if (classImage.data[j][i] != LAS_BUILDING) classImage.data[j][i] = 0; } } sprintf(classOutFileName, "%s_buildings.tif", inputFileName); classImage.write(classOutFileName, false, egm96); // Report total elapsed time. time_t t1; time(&t1); printf("Total time elapsed = %f seconds\n", double(t1 - t0)); } <|endoftext|>
<commit_before>#include "CppUnitTest.h" #include <string> #include <vector> #include <array> using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace std; namespace algo { template<class Traits> class tokens { typedef vector<typename Traits::type> token_vector; token_vector tokens_; public: typedef typename token_vector::iterator iterator; typedef typename token_vector::const_iterator const_iterator; tokens() {} explicit tokens(size_t count) : tokens_(count) {} bool empty() const { return tokens_.size() == 0; } size_t size() const { return tokens_.size(); } iterator begin() { return tokens_.begin(); } const_iterator begin() const { return tokens_.begin(); } const_iterator cbegin() const { return tokens_.cbegin(); } iterator end() { return tokens_.end(); } const_iterator end() const { return tokens_.end(); } const_iterator cend() const { return tokens_.cend(); } void from_string(string s) { auto newTokens = Traits::tokenize(s); tokens_.insert(tokens_.end(), newTokens.begin(), newTokens.end()); } }; } namespace algo { namespace spec { struct s {}; template<size_t N> struct test_token_traits { typedef s type; static array<s, N> tokenize(const string&) { return array<s, N>(); } }; template<size_t N> using test_tokens = tokens<test_token_traits<N>>; TEST_CLASS(can_recognize_tokens) { public: TEST_METHOD(should_not_have_any_tokens_when_default_constructed) { test_tokens<0> testTokens; Assert::IsTrue(testTokens.empty()); } TEST_METHOD(should_recognize_a_token_in_a_string) { test_tokens<1> testTokens; testTokens.from_string("irrelevant"); Assert::IsFalse(testTokens.empty()); } TEST_METHOD(should_recognize_more_than_one_token_in_a_string) { test_tokens<3> testTokens; testTokens.from_string("irrelevant"); Assert::AreEqual(3U, testTokens.size()); } TEST_METHOD(should_accumulate_tokens_from_successive_strings) { test_tokens<2> testTokens(3); testTokens.from_string("irrelevant"); Assert::AreEqual(5U, testTokens.size()); } TEST_METHOD(should_be_able_to_enumerate_tokens) { test_tokens<0> testTokens(3); size_t i = 0; for (s tok : testTokens) { ++i; } Assert::AreEqual(3U, i); } TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_const_container) { const test_tokens<0> testTokens(3); size_t i = 0; for (const s tok : testTokens) { ++i; } Assert::AreEqual(3U, i); } TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_non_const_container) { typedef test_tokens<0>::const_iterator const_iter; test_tokens<0> testTokens(3); size_t i = 0; for (const_iter it = testTokens.cbegin(); it != testTokens.cend(); ++it) { ++i; } Assert::AreEqual(3U, i); } }; }} <commit_msg>add operator[] access to tokens<commit_after>#include "CppUnitTest.h" #include <string> #include <vector> #include <array> using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace std; namespace algo { template<class Traits> class tokens { typedef vector<typename Traits::type> token_vector; token_vector tokens_; public: typedef typename token_vector::iterator iterator; typedef typename token_vector::const_iterator const_iterator; typedef typename Traits::type token_type; tokens() {} explicit tokens(size_t count) : tokens_(count) {} tokens(std::initializer_list<token_type> init) : tokens_(init) {} bool empty() const { return tokens_.size() == 0; } size_t size() const { return tokens_.size(); } token_type& operator[](size_t i) { return tokens_[i]; }; iterator begin() { return tokens_.begin(); } const_iterator begin() const { return tokens_.begin(); } const_iterator cbegin() const { return tokens_.cbegin(); } iterator end() { return tokens_.end(); } const_iterator end() const { return tokens_.end(); } const_iterator cend() const { return tokens_.cend(); } void from_string(string s) { auto newTokens = Traits::tokenize(s); tokens_.insert(tokens_.end(), newTokens.begin(), newTokens.end()); } }; } namespace algo { namespace spec { struct s { string val; }; template<size_t N> struct test_token_traits { typedef s type; static array<s, N> tokenize(const string&) { return array<s, N>(); } }; template<size_t N> using test_tokens = tokens<test_token_traits<N>>; TEST_CLASS(can_recognize_tokens) { public: TEST_METHOD(should_not_have_any_tokens_when_default_constructed) { test_tokens<0> testTokens; Assert::IsTrue(testTokens.empty()); } TEST_METHOD(should_recognize_a_token_in_a_string) { test_tokens<1> testTokens; testTokens.from_string("irrelevant"); Assert::IsFalse(testTokens.empty()); } TEST_METHOD(should_recognize_more_than_one_token_in_a_string) { test_tokens<3> testTokens; testTokens.from_string("irrelevant"); Assert::AreEqual(3U, testTokens.size()); } TEST_METHOD(should_accumulate_tokens_from_successive_strings) { test_tokens<2> testTokens(3); testTokens.from_string("irrelevant"); Assert::AreEqual(5U, testTokens.size()); } TEST_METHOD(should_be_able_to_enumerate_tokens) { test_tokens<0> testTokens(3); size_t i = 0; for (s tok : testTokens) { ++i; } Assert::AreEqual(3U, i); } TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_const_container) { const test_tokens<0> testTokens(3); size_t i = 0; for (const s tok : testTokens) { ++i; } Assert::AreEqual(3U, i); } TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_non_const_container) { typedef test_tokens<0>::const_iterator const_iter; test_tokens<0> testTokens(3); size_t i = 0; for (const_iter it = testTokens.cbegin(); it != testTokens.cend(); ++it) { ++i; } Assert::AreEqual(3U, i); } TEST_METHOD(should_be_able_to_access_tokens_by_their_index) { test_tokens<0> testTokens = { { "one" }, { "two" }, { "three" } }; Assert::AreEqual("one", testTokens[0].val.c_str()); Assert::AreEqual("two", testTokens[1].val.c_str()); Assert::AreEqual("three", testTokens[2].val.c_str()); } }; }} <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: buffer.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2003-03-18 16:28:34 $ * * 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 "sbcomp.hxx" #pragma hdrstop #include "buffer.hxx" #include <string.h> // Der SbiBuffer wird in Inkrements von mindestens 16 Bytes erweitert. // Dies ist notwendig, da viele Klassen von einer Pufferlaenge // von x*16 Bytes ausgehen. SbiBuffer::SbiBuffer( SbiParser* p, short n ) { pParser = p; n = ( (n + 15 ) / 16 ) * 16; if( !n ) n = 16; pBuf = NULL; pCur = NULL; nInc = n; nSize = nOff = 0; } SbiBuffer::~SbiBuffer() { delete[] pBuf; } // Rausreichen des Puffers // Dies fuehrt zur Loeschung des Puffers! char* SbiBuffer::GetBuffer() { char* p = pBuf; pBuf = NULL; pCur = NULL; return p; } // Test, ob der Puffer n Bytes aufnehmen kann. // Im Zweifelsfall wird er vergroessert BOOL SbiBuffer::Check( USHORT n ) { if( !n ) return TRUE; if( ((long) nOff + n ) > (long) nSize ) { USHORT nn = 0; while( nn < n ) nn += nInc; char* p; if( ((long) nSize + nn ) > 0xFF00L ) p = NULL; else p = new char [nSize + nn]; if( !p ) { pParser->Error( SbERR_PROG_TOO_LARGE ); nInc = 0; delete[] pBuf; pBuf = NULL; return FALSE; } else { if( nSize ) memcpy( p, pBuf, nSize ); delete[] pBuf; pBuf = p; pCur = pBuf + nOff; nSize += nn; } } return TRUE; } // Angleich des Puffers auf die uebergebene Byte-Grenze void SbiBuffer::Align( short n ) { if( nOff % n ) { USHORT nn =( ( nOff + n ) / n ) * n; if( nn <= 0xFF00 ) { nn -= nOff; if( Check( nn ) ) { memset( pCur, 0, nn ); pCur += nn; nOff += nn; } } } } // Patch einer Location void SbiBuffer::Patch( USHORT off, UINT16 val ) { if( ( off + sizeof( UINT16 ) ) < nOff ) { BYTE* p = (BYTE*) pBuf + off; *p++ = (char) ( val & 0xFF ); *p = (char) ( val >> 8 ); } } // Forward References auf Labels und Prozeduren // bauen eine Kette auf. Der Anfang der Kette ist beim uebergebenen // Parameter, das Ende der Kette ist 0. void SbiBuffer::Chain( USHORT off ) { if( off && pBuf ) { BYTE *ip; USHORT i = off; USHORT val = nOff; do { ip = (BYTE*) pBuf + i; i = ( *ip ) | ( *(ip+1) << 8 ); if( i >= nOff ) { pParser->Error( SbERR_INTERNAL_ERROR, "BACKCHAIN" ); break; } *ip++ = (char) ( val & 0xFF ); *ip = (char) ( val >> 8 ); } while( i ); } } BOOL SbiBuffer::operator +=( INT8 n ) { if( Check( 1 ) ) { *pCur++ = (char) n; nOff++; return TRUE; } else return FALSE; } BOOL SbiBuffer::operator +=( UINT8 n ) { if( Check( 1 ) ) { *pCur++ = (char) n; nOff++; return TRUE; } else return FALSE; } BOOL SbiBuffer::operator +=( INT16 n ) { if( Check( 2 ) ) { *pCur++ = (char) ( n & 0xFF ); *pCur++ = (char) ( n >> 8 ); nOff += 2; return TRUE; } else return FALSE; } BOOL SbiBuffer::operator +=( UINT16 n ) { if( Check( 2 ) ) { *pCur++ = (char) ( n & 0xFF ); *pCur++ = (char) ( n >> 8 ); nOff += 2; return TRUE; } else return FALSE; } BOOL SbiBuffer::operator +=( const String& n ) { USHORT l = n.Len() + 1; if( Check( l ) ) { ByteString aByteStr( n, gsl_getSystemTextEncoding() ); memcpy( pCur, aByteStr.GetBuffer(), l ); pCur += l; nOff += l; return TRUE; } else return FALSE; } BOOL SbiBuffer::Add( const void* p, USHORT len ) { if( Check( len ) ) { memcpy( pCur, p, len ); pCur += len; nOff += len; return TRUE; } else return FALSE; } <commit_msg>INTEGRATION: CWS ab11clonepp4 (1.3.214); FILE MERGED 2004/10/18 14:38:53 ab 1.3.214.1: #118086# PP4 migration tasks -> SO 8<commit_after>/************************************************************************* * * $RCSfile: buffer.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: pjunck $ $Date: 2004-11-02 11:52:59 $ * * 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 "sbcomp.hxx" #pragma hdrstop #include "buffer.hxx" #include <string.h> // Der SbiBuffer wird in Inkrements von mindestens 16 Bytes erweitert. // Dies ist notwendig, da viele Klassen von einer Pufferlaenge // von x*16 Bytes ausgehen. SbiBuffer::SbiBuffer( SbiParser* p, short n ) { pParser = p; n = ( (n + 15 ) / 16 ) * 16; if( !n ) n = 16; pBuf = NULL; pCur = NULL; nInc = n; nSize = nOff = 0; } SbiBuffer::~SbiBuffer() { delete[] pBuf; } // Rausreichen des Puffers // Dies fuehrt zur Loeschung des Puffers! char* SbiBuffer::GetBuffer() { char* p = pBuf; pBuf = NULL; pCur = NULL; return p; } // Test, ob der Puffer n Bytes aufnehmen kann. // Im Zweifelsfall wird er vergroessert BOOL SbiBuffer::Check( USHORT n ) { if( !n ) return TRUE; if( ((long) nOff + n ) > (long) nSize ) { if( nInc == 0 ) return FALSE; USHORT nn = 0; while( nn < n ) nn += nInc; char* p; if( ((long) nSize + nn ) > 0xFF00L ) p = NULL; else p = new char [nSize + nn]; if( !p ) { pParser->Error( SbERR_PROG_TOO_LARGE ); nInc = 0; delete[] pBuf; pBuf = NULL; return FALSE; } else { if( nSize ) memcpy( p, pBuf, nSize ); delete[] pBuf; pBuf = p; pCur = pBuf + nOff; nSize += nn; } } return TRUE; } // Angleich des Puffers auf die uebergebene Byte-Grenze void SbiBuffer::Align( short n ) { if( nOff % n ) { USHORT nn =( ( nOff + n ) / n ) * n; if( nn <= 0xFF00 ) { nn -= nOff; if( Check( nn ) ) { memset( pCur, 0, nn ); pCur += nn; nOff += nn; } } } } // Patch einer Location void SbiBuffer::Patch( USHORT off, UINT16 val ) { if( ( off + sizeof( UINT16 ) ) < nOff ) { BYTE* p = (BYTE*) pBuf + off; *p++ = (char) ( val & 0xFF ); *p = (char) ( val >> 8 ); } } // Forward References auf Labels und Prozeduren // bauen eine Kette auf. Der Anfang der Kette ist beim uebergebenen // Parameter, das Ende der Kette ist 0. void SbiBuffer::Chain( USHORT off ) { if( off && pBuf ) { BYTE *ip; USHORT i = off; USHORT val = nOff; do { ip = (BYTE*) pBuf + i; i = ( *ip ) | ( *(ip+1) << 8 ); if( i >= nOff ) { pParser->Error( SbERR_INTERNAL_ERROR, "BACKCHAIN" ); break; } *ip++ = (char) ( val & 0xFF ); *ip = (char) ( val >> 8 ); } while( i ); } } BOOL SbiBuffer::operator +=( INT8 n ) { if( Check( 1 ) ) { *pCur++ = (char) n; nOff++; return TRUE; } else return FALSE; } BOOL SbiBuffer::operator +=( UINT8 n ) { if( Check( 1 ) ) { *pCur++ = (char) n; nOff++; return TRUE; } else return FALSE; } BOOL SbiBuffer::operator +=( INT16 n ) { if( Check( 2 ) ) { *pCur++ = (char) ( n & 0xFF ); *pCur++ = (char) ( n >> 8 ); nOff += 2; return TRUE; } else return FALSE; } BOOL SbiBuffer::operator +=( UINT16 n ) { if( Check( 2 ) ) { *pCur++ = (char) ( n & 0xFF ); *pCur++ = (char) ( n >> 8 ); nOff += 2; return TRUE; } else return FALSE; } BOOL SbiBuffer::operator +=( const String& n ) { USHORT l = n.Len() + 1; if( Check( l ) ) { ByteString aByteStr( n, gsl_getSystemTextEncoding() ); memcpy( pCur, aByteStr.GetBuffer(), l ); pCur += l; nOff += l; return TRUE; } else return FALSE; } BOOL SbiBuffer::Add( const void* p, USHORT len ) { if( Check( len ) ) { memcpy( pCur, p, len ); pCur += len; nOff += len; return TRUE; } else return FALSE; } <|endoftext|>
<commit_before><commit_msg>coverity#441077 Dereference after null check<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkPushImageReader.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 "vtkPushImageReader.h" #include "vtkObjectFactory.h" #include "vtkCommand.h" #include "vtkByteSwap.h" #include "vtkPushPipeline.h" class vtkPIRIncrementSlice : public vtkCommand { public: static vtkPIRIncrementSlice *New() { return new vtkPIRIncrementSlice;} // when a push is received move to the next slice, // when the last slice is reached, invoke a // EndOfData event virtual void Execute(vtkObject *caller, unsigned long, void *) { vtkPushImageReader *pir = vtkPushImageReader::SafeDownCast(caller); if (pir) { int n = pir->GetCurrentSlice(); n = n+1; // On the last slice invoke an EndOfData event if (n == pir->GetDataExtent()[5]) { pir->InvokeEvent(vtkCommand::EndOfDataEvent,NULL); } if (n > pir->GetDataExtent()[5]) { n = pir->GetDataExtent()[4]; } if (n < pir->GetDataExtent()[4]) { n = pir->GetDataExtent()[4]; } pir->SetCurrentSlice(n); } } }; vtkCxxRevisionMacro(vtkPushImageReader, "1.6"); vtkStandardNewMacro(vtkPushImageReader); vtkPushImageReader::vtkPushImageReader() { this->CurrentSlice = -1; vtkPIRIncrementSlice *is = vtkPIRIncrementSlice::New(); this->AddObserver(vtkCommand::NextDataEvent,is); is->Delete(); this->PushPipeline = NULL; } vtkPushImageReader::~vtkPushImageReader() { if (this->PushPipeline) { this->PushPipeline->Delete(); } } void vtkPushImageReader::ExecuteInformation() { vtkImageData *output = this->GetOutput(); output->SetWholeExtent(this->DataExtent[0],this->DataExtent[1], this->DataExtent[2],this->DataExtent[3], 0, 0); output->SetSpacing(this->DataSpacing); output->SetOrigin(this->DataOrigin); output->SetScalarType(this->DataScalarType); output->SetNumberOfScalarComponents(this->NumberOfScalarComponents); } //---------------------------------------------------------------------------- // This function reads in one data of data. // templated to handle different data types. template <class OT> void vtkPushImageReaderUpdate(vtkPushImageReader *self, vtkImageData *data, OT *outPtr) { int outIncr[3]; OT *outPtr1, *outPtr2; long streamRead; int idx1, idx2, nComponents; int outExtent[6]; unsigned long count = 0; unsigned long target; // Get the requested extents and increments data->GetExtent(outExtent); data->GetIncrements(outIncr); nComponents = data->GetNumberOfScalarComponents(); // length of a row, num pixels read at a time int pixelRead = outExtent[1] - outExtent[0] + 1; streamRead = (long)(pixelRead*nComponents*sizeof(OT)); // create a buffer to hold a row of the data target = (unsigned long)((outExtent[3]-outExtent[2]+1)/50.0); target++; // read the data row by row if (self->GetFileDimensionality() == 3) { self->ComputeInternalFileName(0); if ( !self->OpenFile() ) { return; } } outPtr2 = outPtr; int currSlice = self->GetCurrentSlice(); for (idx2 = currSlice; idx2 <= currSlice; ++idx2) { if (self->GetFileDimensionality() == 2) { self->ComputeInternalFileName(idx2); if ( !self->OpenFile() ) { return; } } outPtr1 = outPtr2; for (idx1 = outExtent[2]; !self->AbortExecute && idx1 <= outExtent[3]; ++idx1) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; // seek to the correct row self->SeekFile(outExtent[0],idx1,idx2); // read the row. if ( !self->GetFile()->read((char *)outPtr1, streamRead)) { vtkGenericWarningMacro("File operation failed. row = " << idx1 << ", Read = " << streamRead << ", FilePos = " << self->GetFile()->tellg()); return; } // handle swapping if (self->GetSwapBytes() && sizeof(OT) > 1) { vtkByteSwap::SwapVoidRange(outPtr1, pixelRead*nComponents, sizeof(OT)); } outPtr1 += outIncr[1]; } // move to the next image in the file and data outPtr2 += outIncr[2]; } } //---------------------------------------------------------------------------- // This function reads a data from a file. The datas extent/axes // are assumed to be the same as the file extent/order. void vtkPushImageReader::ExecuteData(vtkDataObject *output) { vtkImageData *data = this->AllocateOutputData(output); void *ptr = NULL; int *ext; if (!this->FileName && !this->FilePattern) { vtkErrorMacro(<<"Either a FileName or FilePattern must be specified."); return; } ext = data->GetExtent(); data->GetPointData()->GetScalars()->SetName("ImageFile"); vtkDebugMacro("Reading extent: " << ext[0] << ", " << ext[1] << ", " << ext[2] << ", " << ext[3] << ", " << ext[4] << ", " << ext[5]); this->ComputeDataIncrements(); // Call the correct templated function for the output ptr = data->GetScalarPointer(); switch (this->GetDataScalarType()) { vtkTemplateMacro3(vtkPushImageReaderUpdate, this, data, (VTK_TT *)(ptr)); default: vtkErrorMacro(<< "UpdateFromFile: Unknown data type"); } } vtkCxxSetObjectMacro(vtkPushImageReader,PushPipeline,vtkPushPipeline) void vtkPushImageReader::Push() { if (!this->PushPipeline) { this->PushPipeline = vtkPushPipeline::New(); } this->PushPipeline->Push(this); } void vtkPushImageReader::Run() { if (!this->PushPipeline) { this->PushPipeline = vtkPushPipeline::New(); } this->PushPipeline->Run(this); } void vtkPushImageReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "CurrentSlice: " << this->CurrentSlice << "\n"; os << indent << "PushPipeline: " << this->PushPipeline << "\n"; } <commit_msg>hopefully fixed<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkPushImageReader.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 "vtkPushImageReader.h" #include "vtkObjectFactory.h" #include "vtkCommand.h" #include "vtkByteSwap.h" #include "vtkPushPipeline.h" class vtkPIRIncrementSlice : public vtkCommand { public: static vtkPIRIncrementSlice *New() { return new vtkPIRIncrementSlice;} // when a push is received move to the next slice, // when the last slice is reached, invoke a // EndOfData event virtual void Execute(vtkObject *caller, unsigned long, void *) { vtkPushImageReader *pir = vtkPushImageReader::SafeDownCast(caller); if (pir) { int n = pir->GetCurrentSlice(); n = n+1; // On the last slice invoke an EndOfData event if (n == pir->GetDataExtent()[5]) { pir->InvokeEvent(vtkCommand::EndOfDataEvent,NULL); } if (n > pir->GetDataExtent()[5]) { n = pir->GetDataExtent()[4]; } if (n < pir->GetDataExtent()[4]) { n = pir->GetDataExtent()[4]; } pir->SetCurrentSlice(n); } } }; vtkCxxRevisionMacro(vtkPushImageReader, "1.7"); vtkStandardNewMacro(vtkPushImageReader); vtkPushImageReader::vtkPushImageReader() { this->CurrentSlice = -1; vtkPIRIncrementSlice *is = vtkPIRIncrementSlice::New(); this->AddObserver(vtkCommand::NextDataEvent,is); is->Delete(); this->PushPipeline = NULL; } vtkPushImageReader::~vtkPushImageReader() { if (this->PushPipeline) { this->PushPipeline = NULL; } } void vtkPushImageReader::ExecuteInformation() { vtkImageData *output = this->GetOutput(); output->SetWholeExtent(this->DataExtent[0],this->DataExtent[1], this->DataExtent[2],this->DataExtent[3], 0, 0); output->SetSpacing(this->DataSpacing); output->SetOrigin(this->DataOrigin); output->SetScalarType(this->DataScalarType); output->SetNumberOfScalarComponents(this->NumberOfScalarComponents); } //---------------------------------------------------------------------------- // This function reads in one data of data. // templated to handle different data types. template <class OT> void vtkPushImageReaderUpdate(vtkPushImageReader *self, vtkImageData *data, OT *outPtr) { int outIncr[3]; OT *outPtr1, *outPtr2; long streamRead; int idx1, idx2, nComponents; int outExtent[6]; unsigned long count = 0; unsigned long target; // Get the requested extents and increments data->GetExtent(outExtent); data->GetIncrements(outIncr); nComponents = data->GetNumberOfScalarComponents(); // length of a row, num pixels read at a time int pixelRead = outExtent[1] - outExtent[0] + 1; streamRead = (long)(pixelRead*nComponents*sizeof(OT)); // create a buffer to hold a row of the data target = (unsigned long)((outExtent[3]-outExtent[2]+1)/50.0); target++; // read the data row by row if (self->GetFileDimensionality() == 3) { self->ComputeInternalFileName(0); if ( !self->OpenFile() ) { return; } } outPtr2 = outPtr; int currSlice = self->GetCurrentSlice(); for (idx2 = currSlice; idx2 <= currSlice; ++idx2) { if (self->GetFileDimensionality() == 2) { self->ComputeInternalFileName(idx2); if ( !self->OpenFile() ) { return; } } outPtr1 = outPtr2; for (idx1 = outExtent[2]; !self->AbortExecute && idx1 <= outExtent[3]; ++idx1) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; // seek to the correct row self->SeekFile(outExtent[0],idx1,idx2); // read the row. if ( !self->GetFile()->read((char *)outPtr1, streamRead)) { vtkGenericWarningMacro("File operation failed. row = " << idx1 << ", Read = " << streamRead << ", FilePos = " << self->GetFile()->tellg()); return; } // handle swapping if (self->GetSwapBytes() && sizeof(OT) > 1) { vtkByteSwap::SwapVoidRange(outPtr1, pixelRead*nComponents, sizeof(OT)); } outPtr1 += outIncr[1]; } // move to the next image in the file and data outPtr2 += outIncr[2]; } } //---------------------------------------------------------------------------- // This function reads a data from a file. The datas extent/axes // are assumed to be the same as the file extent/order. void vtkPushImageReader::ExecuteData(vtkDataObject *output) { vtkImageData *data = this->AllocateOutputData(output); void *ptr = NULL; int *ext; if (!this->FileName && !this->FilePattern) { vtkErrorMacro(<<"Either a FileName or FilePattern must be specified."); return; } ext = data->GetExtent(); data->GetPointData()->GetScalars()->SetName("ImageFile"); vtkDebugMacro("Reading extent: " << ext[0] << ", " << ext[1] << ", " << ext[2] << ", " << ext[3] << ", " << ext[4] << ", " << ext[5]); this->ComputeDataIncrements(); // Call the correct templated function for the output ptr = data->GetScalarPointer(); switch (this->GetDataScalarType()) { vtkTemplateMacro3(vtkPushImageReaderUpdate, this, data, (VTK_TT *)(ptr)); default: vtkErrorMacro(<< "UpdateFromFile: Unknown data type"); } } void vtkPushImageReader::SetPushPipeline(vtkPushPipeline *pp) { // not ref counted to avoid loops this->PushPipeline = pp; } void vtkPushImageReader::Push() { if (!this->PushPipeline) { this->PushPipeline = vtkPushPipeline::New(); } this->PushPipeline->Push(this); } void vtkPushImageReader::Run() { if (!this->PushPipeline) { this->PushPipeline = vtkPushPipeline::New(); } this->PushPipeline->Run(this); } void vtkPushImageReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "CurrentSlice: " << this->CurrentSlice << "\n"; os << indent << "PushPipeline: " << this->PushPipeline << "\n"; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkMedicalImageReader2.cxx Copyright (c) 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 "vtkMedicalImageReader2.h" #include "vtkObjectFactory.h" #include "vtkMedicalImageProperties.h" //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkMedicalImageReader2, "1.6"); vtkStandardNewMacro(vtkMedicalImageReader2); //---------------------------------------------------------------------------- vtkMedicalImageReader2::vtkMedicalImageReader2() { this->MedicalImageProperties = vtkMedicalImageProperties::New(); } //---------------------------------------------------------------------------- vtkMedicalImageReader2::~vtkMedicalImageReader2() { if (this->MedicalImageProperties) { this->MedicalImageProperties->Delete(); this->MedicalImageProperties = NULL; } } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetPatientName(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetPatientName(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetPatientName() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetPatientName(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetPatientID(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetPatientID(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetPatientID() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetPatientID(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetDate(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetImageDate(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetDate() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetImageDate(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetSeries(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetSeries(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetSeries() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetSeries(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetStudy(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetStudy(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetStudy() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetStudy(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetImageNumber(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetImageNumber(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetImageNumber() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetImageNumber(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetModality(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetModality(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetModality() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetModality(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if (this->MedicalImageProperties) { os << indent << "Medical Image Properties:\n"; this->MedicalImageProperties->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "MedicalImageProperties: (none)\n"; } } <commit_msg>ENH: Need to sync with VTK CVS to get GDCM working with VTK5<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkMedicalImageReader2.cxx Copyright (c) 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 "vtkMedicalImageReader2.h" #include "vtkObjectFactory.h" #include "vtkMedicalImageProperties.h" //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkMedicalImageReader2, "1.6.4.1"); vtkStandardNewMacro(vtkMedicalImageReader2); //---------------------------------------------------------------------------- vtkMedicalImageReader2::vtkMedicalImageReader2() { this->MedicalImageProperties = vtkMedicalImageProperties::New(); } //---------------------------------------------------------------------------- vtkMedicalImageReader2::~vtkMedicalImageReader2() { if (this->MedicalImageProperties) { this->MedicalImageProperties->Delete(); this->MedicalImageProperties = NULL; } } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetPatientName(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetPatientName(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetPatientName() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetPatientName(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetPatientID(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetPatientID(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetPatientID() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetPatientID(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetDate(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetImageDate(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetDate() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetImageDate(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetSeries(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetSeriesNumber(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetSeries() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetSeriesNumber(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetStudy(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetStudyID(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetStudy() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetStudyID(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetImageNumber(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetImageNumber(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetImageNumber() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetImageNumber(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::SetModality(const char *arg) { if (this->MedicalImageProperties) { this->MedicalImageProperties->SetModality(arg); } } //---------------------------------------------------------------------------- const char* vtkMedicalImageReader2::GetModality() { if (this->MedicalImageProperties) { return this->MedicalImageProperties->GetModality(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageReader2::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if (this->MedicalImageProperties) { os << indent << "Medical Image Properties:\n"; this->MedicalImageProperties->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "MedicalImageProperties: (none)\n"; } } <|endoftext|>
<commit_before>#include <Img/Image.h> #include <Camera/OpenniProvider.h> #include <opencv2/opencv.hpp> namespace Camera{ OpenNIProvider::OpenNIProvider(const std::string& ID) : ImageProvider(ID), _capture(CV_CAP_OPENNI) { // if(!_capture.isOpened()){ // _capture.open(cv::CV_CAP_OPENNI2); if(!_capture.isOpened()){ throw std::string("couldn't open the capture device"); } //} } Img::Image OpenNIProvider::getFrame() const { Image::Matrix depthMap, rgb; std::cout << "I'm taking a photo\n"; _capture.grab(); _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP); _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE); return Image(depthMap, rgb); } } <commit_msg>Force image registration for OpenNI<commit_after>#include <Img/Image.h> #include <Camera/OpenniProvider.h> #include <opencv2/opencv.hpp> namespace Camera{ OpenNIProvider::OpenNIProvider(const std::string& ID) : ImageProvider(ID), _capture(CV_CAP_OPENNI) { // if(!_capture.isOpened()){ // _capture.open(cv::CV_CAP_OPENNI2); if(!_capture.isOpened()){ throw std::string("couldn't open the capture device"); } if(!_capture.get( CV_CAP_PROP_OPENNI_REGISTRATION ) ){ std::cout << "Setting OPENNI registration flag,,\n"; _capture.set(CV_CAP_PROP_OPENNI_REGISTRATION,1); if(!_capture.get( CV_CAP_PROP_OPENNI_REGISTRATION ) ){ throw std::string("couldn't set registration flag"); } } //} } Img::Image OpenNIProvider::getFrame() const { Image::Matrix depthMap, rgb; std::cout << "I'm taking a photo\n"; _capture.grab(); _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP); _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE); return Image(depthMap, rgb); } } <|endoftext|>
<commit_before>/*========================================================================= Library : Image Registration Toolkit (IRTK) Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date: 2013-01-14$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkMeanFilter.h> template <class VoxelType> irtkMeanFilter<VoxelType>::irtkMeanFilter() { // Default kernel radius. this->_radius_x = 2; this->_radius_y = 2; this->_radius_z = 2; } template <class VoxelType> irtkMeanFilter<VoxelType>::~irtkMeanFilter(void) { } template <class VoxelType> const char *irtkMeanFilter<VoxelType>::NameOfClass() { return "irtkMeanFilter"; } template <class VoxelType> void irtkMeanFilter<VoxelType>::Initialize() { // Do the initial set up this->irtkImageToImage<VoxelType>::Initialize(); } template <class VoxelType> bool irtkMeanFilter<VoxelType>::RequiresBuffering(void) { return true; } template <class VoxelType> void irtkMeanFilter<VoxelType>::Run() { int x, y, z, t; //int dim = 2*_kernelRadius + 1; // Do the initial set up this->Initialize(); for (t = 0; t < this->_input->GetT(); t++) { for (z = 0; z < this->_input->GetZ(); z++) { for (y = 0; y < this->_input->GetY(); y++) { for (x = 0; x < this->_input->GetX(); x++) { double sum = 0, count = 0; for( int zz = z - _radius_z; zz <= z + _radius_z; ++zz ) { for( int yy = y - _radius_y; yy <= y + _radius_y; ++yy ) { for( int xx = x - _radius_x; xx <= x + _radius_x; ++xx ) { if ((xx < 0) || (xx > this->_input->GetX() - 1) || (yy < 0) || (yy > this->_input->GetY() - 1) || (zz < 0) || (zz > this->_input->GetZ() - 1)) { } else { sum += this->_input->Get(xx, yy, zz, t); count += 1.0; } } } } if( count > 0 ) { this->_output->Put(x, y, z, t, sum/count); }else { this->_output->Put(x, y, z, t, this->_input->Get(x, y, z, t)); } } } } } // Do the final cleaning up this->Finalize(); } template <class VoxelType> void irtkMeanFilter<VoxelType>::SetkernelRadius(double radius) { if(_input != NULL){ this->_radius_x = round(radius / _input->GetXSize()); this->_radius_y = round(radius / _input->GetYSize()); this->_radius_z = round(radius / _input->GetZSize()); }else{ this->_radius_x = radius; this->_radius_y = radius; this->_radius_z = radius; } if(this->_radius_x < 1) this->_radius_x = 1; if(this->_radius_y < 1) this->_radius_y = 1; if(this->_radius_z < 1) this->_radius_z = 1; } template class irtkMeanFilter<irtkBytePixel>; template class irtkMeanFilter<irtkGreyPixel>; template class irtkMeanFilter<irtkRealPixel>; <commit_msg>Minor bug fix to allow compilation on non-windows platforms.<commit_after>/*========================================================================= Library : Image Registration Toolkit (IRTK) Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date: 2013-01-14$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkMeanFilter.h> template <class VoxelType> irtkMeanFilter<VoxelType>::irtkMeanFilter() { // Default kernel radius. this->_radius_x = 2; this->_radius_y = 2; this->_radius_z = 2; } template <class VoxelType> irtkMeanFilter<VoxelType>::~irtkMeanFilter(void) { } template <class VoxelType> const char *irtkMeanFilter<VoxelType>::NameOfClass() { return "irtkMeanFilter"; } template <class VoxelType> void irtkMeanFilter<VoxelType>::Initialize() { // Do the initial set up this->irtkImageToImage<VoxelType>::Initialize(); } template <class VoxelType> bool irtkMeanFilter<VoxelType>::RequiresBuffering(void) { return true; } template <class VoxelType> void irtkMeanFilter<VoxelType>::Run() { int x, y, z, t; //int dim = 2*_kernelRadius + 1; // Do the initial set up this->Initialize(); for (t = 0; t < this->_input->GetT(); t++) { for (z = 0; z < this->_input->GetZ(); z++) { for (y = 0; y < this->_input->GetY(); y++) { for (x = 0; x < this->_input->GetX(); x++) { double sum = 0, count = 0; for( int zz = z - _radius_z; zz <= z + _radius_z; ++zz ) { for( int yy = y - _radius_y; yy <= y + _radius_y; ++yy ) { for( int xx = x - _radius_x; xx <= x + _radius_x; ++xx ) { if ((xx < 0) || (xx > this->_input->GetX() - 1) || (yy < 0) || (yy > this->_input->GetY() - 1) || (zz < 0) || (zz > this->_input->GetZ() - 1)) { } else { sum += this->_input->Get(xx, yy, zz, t); count += 1.0; } } } } if( count > 0 ) { this->_output->Put(x, y, z, t, sum/count); }else { this->_output->Put(x, y, z, t, this->_input->Get(x, y, z, t)); } } } } } // Do the final cleaning up this->Finalize(); } template <class VoxelType> void irtkMeanFilter<VoxelType>::SetkernelRadius(double radius) { if(this->_input != NULL){ this->_radius_x = round(radius / this->_input->GetXSize()); this->_radius_y = round(radius / this->_input->GetYSize()); this->_radius_z = round(radius / this->_input->GetZSize()); }else{ this->_radius_x = radius; this->_radius_y = radius; this->_radius_z = radius; } if(this->_radius_x < 1) this->_radius_x = 1; if(this->_radius_y < 1) this->_radius_y = 1; if(this->_radius_z < 1) this->_radius_z = 1; } template class irtkMeanFilter<irtkBytePixel>; template class irtkMeanFilter<irtkGreyPixel>; template class irtkMeanFilter<irtkRealPixel>; <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ASSERT #include "libtorrent/config.hpp" #if (!defined TORRENT_DEBUG && !TORRENT_PRODUCTION_ASSERTS && TORRENT_RELEASE_ASSERTS) \ || TORRENT_NO_ASSERTS #define TORRENT_ASSERT(a) do {} while(false) #define TORRENT_ASSERT_VAL(a, b) do {} while(false) #else #if TORRENT_PRODUCTION_ASSERTS extern char const* libtorrent_assert_log; #endif #include <string> #ifdef __GNUC__ std::string demangle(char const* name); #endif #if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !TORRENT_USE_SYSTEM_ASSERT #if TORRENT_USE_IOSTREAM #include <sstream> #endif TORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function, char const* val); #define TORRENT_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__, 0); } while (false) #if TORRENT_USE_IOSTREAM #define TORRENT_ASSERT_VAL(x, y) do { if (x) {} else { std::stringstream __s__; __s__ << #y ": " << y; assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__, __s__.str().c_str()); } } while (false) #else #define TORRENT_ASSERT_VAL(x, y) TORRENT_ASSERT(x) #endif #else #include <cassert> #define TORRENT_ASSERT(x) assert(x) #define TORRENT_ASSERT_VAL(x, y) assert(x) #endif #endif #endif <commit_msg>fixed typo in release assert support<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ASSERT #include "libtorrent/config.hpp" #if (!defined TORRENT_DEBUG && !TORRENT_PRODUCTION_ASSERTS && !TORRENT_RELEASE_ASSERTS) \ || TORRENT_NO_ASSERTS #define TORRENT_ASSERT(a) do {} while(false) #define TORRENT_ASSERT_VAL(a, b) do {} while(false) #else #if TORRENT_PRODUCTION_ASSERTS extern char const* libtorrent_assert_log; #endif #include <string> #ifdef __GNUC__ std::string demangle(char const* name); #endif #if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !TORRENT_USE_SYSTEM_ASSERT #if TORRENT_USE_IOSTREAM #include <sstream> #endif TORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function, char const* val); #define TORRENT_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__, 0); } while (false) #if TORRENT_USE_IOSTREAM #define TORRENT_ASSERT_VAL(x, y) do { if (x) {} else { std::stringstream __s__; __s__ << #y ": " << y; assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__, __s__.str().c_str()); } } while (false) #else #define TORRENT_ASSERT_VAL(x, y) TORRENT_ASSERT(x) #endif #else #include <cassert> #define TORRENT_ASSERT(x) assert(x) #define TORRENT_ASSERT_VAL(x, y) assert(x) #endif #endif #endif <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SOCKET_HPP_INCLUDED #define TORRENT_SOCKET_HPP_INCLUDED #ifdef _MSC_VER #pragma warning(push, 1) #endif // if building as Objective C++, asio's template // parameters Protocol has to be renamed to avoid // colliding with keywords #ifdef __OBJC__ #define Protocol Protocol_ #endif #include <asio/ip/tcp.hpp> #include <asio/ip/udp.hpp> #include <asio/io_service.hpp> #include <asio/deadline_timer.hpp> #include <asio/write.hpp> #ifdef __OBJC__ #undef Protocol #endif #include "libtorrent/io.hpp" #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { /* namespace asio = boost::asio; using boost::asio::ipv4::tcp; using boost::asio::ipv4::address; using boost::asio::stream_socket; using boost::asio::datagram_socket; using boost::asio::socket_acceptor; using boost::asio::demuxer; using boost::asio::ipv4::host_resolver; using boost::asio::async_write; using boost::asio::ipv4::host; using boost::asio::deadline_timer; */ namespace asio = ::asio; using asio::ip::tcp; using asio::ip::udp; typedef asio::ip::tcp::socket stream_socket; typedef asio::ip::address_v4 address; typedef asio::ip::udp::socket datagram_socket; typedef asio::ip::tcp::acceptor socket_acceptor; typedef asio::io_service demuxer; using asio::async_write; using asio::deadline_timer; namespace detail { template<class Endpoint, class OutIt> void write_endpoint(Endpoint const& e, OutIt& out) { write_uint32(e.address().to_v4().to_ulong(), out); write_uint16(e.port(), out); } template<class Endpoint, class InIt> Endpoint read_endpoint(InIt& in) { unsigned int ip = read_uint32(in); int port = read_uint16(in); return Endpoint(address(ip), port); } } } #endif // TORRENT_SOCKET_HPP_INCLUDED <commit_msg>removed redundant namespace alias that may be a problem with GCC 3.4.2 on FreeBSD<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SOCKET_HPP_INCLUDED #define TORRENT_SOCKET_HPP_INCLUDED #ifdef _MSC_VER #pragma warning(push, 1) #endif // if building as Objective C++, asio's template // parameters Protocol has to be renamed to avoid // colliding with keywords #ifdef __OBJC__ #define Protocol Protocol_ #endif #include <asio/ip/tcp.hpp> #include <asio/ip/udp.hpp> #include <asio/io_service.hpp> #include <asio/deadline_timer.hpp> #include <asio/write.hpp> #ifdef __OBJC__ #undef Protocol #endif #include "libtorrent/io.hpp" #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { /* namespace asio = boost::asio; using boost::asio::ipv4::tcp; using boost::asio::ipv4::address; using boost::asio::stream_socket; using boost::asio::datagram_socket; using boost::asio::socket_acceptor; using boost::asio::demuxer; using boost::asio::ipv4::host_resolver; using boost::asio::async_write; using boost::asio::ipv4::host; using boost::asio::deadline_timer; */ // namespace asio = ::asio; using asio::ip::tcp; using asio::ip::udp; typedef asio::ip::tcp::socket stream_socket; typedef asio::ip::address_v4 address; typedef asio::ip::udp::socket datagram_socket; typedef asio::ip::tcp::acceptor socket_acceptor; typedef asio::io_service demuxer; using asio::async_write; using asio::deadline_timer; namespace detail { template<class Endpoint, class OutIt> void write_endpoint(Endpoint const& e, OutIt& out) { write_uint32(e.address().to_v4().to_ulong(), out); write_uint16(e.port(), out); } template<class Endpoint, class InIt> Endpoint read_endpoint(InIt& in) { unsigned int ip = read_uint32(in); int port = read_uint16(in); return Endpoint(address(ip), port); } } } #endif // TORRENT_SOCKET_HPP_INCLUDED <|endoftext|>
<commit_before>#include <string> #include <sstream> #include <iostream> #include <cstddef> #include <iomanip> #include "ast.hpp" #include "json.hpp" #include "context.hpp" #include "position.hpp" #include "source_map.hpp" namespace Sass { using std::ptrdiff_t; SourceMap::SourceMap() : current_position(0, 0, 0), file("stdin") { } SourceMap::SourceMap(const string& file) : current_position(0, 0, 0), file(file) { } string SourceMap::generate_source_map(Context &ctx) { const bool include_sources = ctx.source_map_contents; const vector<string> includes = ctx.include_links; const vector<char*> sources = ctx.sources; JsonNode* json_srcmap = json_mkobject(); json_append_member(json_srcmap, "version", json_mknumber(3)); // pass-through sourceRoot option if (!ctx.source_map_root.empty()) { JsonNode* root = json_mkstring(ctx.source_map_root.c_str()); json_append_member(json_srcmap, "sourceRoot", root); } const char *include = file.c_str(); JsonNode *json_include = json_mkstring(include); json_append_member(json_srcmap, "file", json_include); JsonNode *json_includes = json_mkarray(); for (size_t i = 0; i < source_index.size(); ++i) { const char *include = includes[source_index[i]].c_str(); JsonNode *json_include = json_mkstring(include); json_append_element(json_includes, json_include); } json_append_member(json_srcmap, "sources", json_includes); JsonNode *json_contents = json_mkarray(); if (include_sources) { for (size_t i = 0; i < source_index.size(); ++i) { const char *content = sources[source_index[i]]; JsonNode *json_content = json_mkstring(content); json_append_element(json_contents, json_content); } } json_append_member(json_srcmap, "sourcesContent", json_contents); string mappings = serialize_mappings(); JsonNode *json_mappings = json_mkstring(mappings.c_str()); json_append_member(json_srcmap, "mappings", json_mappings); JsonNode *json_names = json_mkarray(); // so far we have no implementation for names // no problem as we do not alter any identifiers json_append_member(json_srcmap, "names", json_names); char *str = json_stringify(json_srcmap, "\t"); string result = string(str); free(str); json_delete(json_srcmap); return result; } string SourceMap::serialize_mappings() { string result = ""; size_t previous_generated_line = 0; size_t previous_generated_column = 0; size_t previous_original_line = 0; size_t previous_original_column = 0; size_t previous_original_file = 0; for (size_t i = 0; i < mappings.size(); ++i) { const size_t generated_line = mappings[i].generated_position.line; const size_t generated_column = mappings[i].generated_position.column; const size_t original_line = mappings[i].original_position.line; const size_t original_column = mappings[i].original_position.column; const size_t original_file = mappings[i].original_position.file; if (generated_line != previous_generated_line) { previous_generated_column = 0; if (generated_line > previous_generated_line) { result += std::string(generated_line - previous_generated_line, ';'); previous_generated_line = generated_line; } } else if (i > 0) { result += ","; } // generated column result += base64vlq.encode(static_cast<int>(generated_column) - static_cast<int>(previous_generated_column)); previous_generated_column = generated_column; // file result += base64vlq.encode(static_cast<int>(original_file) - static_cast<int>(previous_original_file)); previous_original_file = original_file; // source line result += base64vlq.encode(static_cast<int>(original_line) - static_cast<int>(previous_original_line)); previous_original_line = original_line; // source column result += base64vlq.encode(static_cast<int>(original_column) - static_cast<int>(previous_original_column)); previous_original_column = original_column; } return result; } void SourceMap::prepend(const OutputBuffer& out) { Offset size(out.smap.current_position); for (Mapping mapping : out.smap.mappings) { if (mapping.generated_position.line > size.line) { throw(runtime_error("prepend sourcemap has illegal line")); } if (mapping.generated_position.line == size.line) { if (mapping.generated_position.column > size.column) { throw(runtime_error("prepend sourcemap has illegal column")); } } } // will adjust the offset prepend(Offset(out.buffer)); // now add the new mappings VECTOR_UNSHIFT(mappings, out.smap.mappings); } void SourceMap::append(const OutputBuffer& out) { append(Offset(out.buffer)); } void SourceMap::prepend(const Offset& offset) { if (offset.line != 0 || offset.column != 0) { for (Mapping& mapping : mappings) { // move stuff on the first old line if (mapping.generated_position.line == 0) { mapping.generated_position.column += offset.column; } // make place for the new lines mapping.generated_position.line += offset.line; } } if (current_position.line == 0) { current_position.column += offset.column; } current_position.line += offset.line; } void SourceMap::append(const Offset& offset) { current_position += offset; } void SourceMap::add_open_mapping(AST_Node* node) { mappings.push_back(Mapping(node->pstate(), current_position)); } void SourceMap::add_close_mapping(AST_Node* node) { mappings.push_back(Mapping(node->pstate() + node->pstate().offset, current_position)); } ParserState SourceMap::remap(const ParserState& pstate) { for (size_t i = 0; i < mappings.size(); ++i) { if ( mappings[i].generated_position.file == pstate.file && mappings[i].generated_position.line == pstate.line && mappings[i].generated_position.column == pstate.column ) return ParserState(pstate.path, pstate.src, mappings[i].original_position, pstate.offset); } return ParserState(pstate.path, pstate.src, Position(-1, -1, -1), Offset(0, 0)); } } <commit_msg>Don't emit sourcesContent if empty<commit_after>#include <string> #include <sstream> #include <iostream> #include <cstddef> #include <iomanip> #include "ast.hpp" #include "json.hpp" #include "context.hpp" #include "position.hpp" #include "source_map.hpp" namespace Sass { using std::ptrdiff_t; SourceMap::SourceMap() : current_position(0, 0, 0), file("stdin") { } SourceMap::SourceMap(const string& file) : current_position(0, 0, 0), file(file) { } string SourceMap::generate_source_map(Context &ctx) { const bool include_sources = ctx.source_map_contents; const vector<string> includes = ctx.include_links; const vector<char*> sources = ctx.sources; JsonNode* json_srcmap = json_mkobject(); json_append_member(json_srcmap, "version", json_mknumber(3)); // pass-through sourceRoot option if (!ctx.source_map_root.empty()) { JsonNode* root = json_mkstring(ctx.source_map_root.c_str()); json_append_member(json_srcmap, "sourceRoot", root); } const char *include = file.c_str(); JsonNode *json_include = json_mkstring(include); json_append_member(json_srcmap, "file", json_include); JsonNode *json_includes = json_mkarray(); for (size_t i = 0; i < source_index.size(); ++i) { const char *include = includes[source_index[i]].c_str(); JsonNode *json_include = json_mkstring(include); json_append_element(json_includes, json_include); } json_append_member(json_srcmap, "sources", json_includes); JsonNode *json_contents = json_mkarray(); if (include_sources) { for (size_t i = 0; i < source_index.size(); ++i) { const char *content = sources[source_index[i]]; JsonNode *json_content = json_mkstring(content); json_append_element(json_contents, json_content); } if (json_contents->children.head) json_append_member(json_srcmap, "sourcesContent", json_contents); } string mappings = serialize_mappings(); JsonNode *json_mappings = json_mkstring(mappings.c_str()); json_append_member(json_srcmap, "mappings", json_mappings); JsonNode *json_names = json_mkarray(); // so far we have no implementation for names // no problem as we do not alter any identifiers json_append_member(json_srcmap, "names", json_names); char *str = json_stringify(json_srcmap, "\t"); string result = string(str); free(str); json_delete(json_srcmap); return result; } string SourceMap::serialize_mappings() { string result = ""; size_t previous_generated_line = 0; size_t previous_generated_column = 0; size_t previous_original_line = 0; size_t previous_original_column = 0; size_t previous_original_file = 0; for (size_t i = 0; i < mappings.size(); ++i) { const size_t generated_line = mappings[i].generated_position.line; const size_t generated_column = mappings[i].generated_position.column; const size_t original_line = mappings[i].original_position.line; const size_t original_column = mappings[i].original_position.column; const size_t original_file = mappings[i].original_position.file; if (generated_line != previous_generated_line) { previous_generated_column = 0; if (generated_line > previous_generated_line) { result += std::string(generated_line - previous_generated_line, ';'); previous_generated_line = generated_line; } } else if (i > 0) { result += ","; } // generated column result += base64vlq.encode(static_cast<int>(generated_column) - static_cast<int>(previous_generated_column)); previous_generated_column = generated_column; // file result += base64vlq.encode(static_cast<int>(original_file) - static_cast<int>(previous_original_file)); previous_original_file = original_file; // source line result += base64vlq.encode(static_cast<int>(original_line) - static_cast<int>(previous_original_line)); previous_original_line = original_line; // source column result += base64vlq.encode(static_cast<int>(original_column) - static_cast<int>(previous_original_column)); previous_original_column = original_column; } return result; } void SourceMap::prepend(const OutputBuffer& out) { Offset size(out.smap.current_position); for (Mapping mapping : out.smap.mappings) { if (mapping.generated_position.line > size.line) { throw(runtime_error("prepend sourcemap has illegal line")); } if (mapping.generated_position.line == size.line) { if (mapping.generated_position.column > size.column) { throw(runtime_error("prepend sourcemap has illegal column")); } } } // will adjust the offset prepend(Offset(out.buffer)); // now add the new mappings VECTOR_UNSHIFT(mappings, out.smap.mappings); } void SourceMap::append(const OutputBuffer& out) { append(Offset(out.buffer)); } void SourceMap::prepend(const Offset& offset) { if (offset.line != 0 || offset.column != 0) { for (Mapping& mapping : mappings) { // move stuff on the first old line if (mapping.generated_position.line == 0) { mapping.generated_position.column += offset.column; } // make place for the new lines mapping.generated_position.line += offset.line; } } if (current_position.line == 0) { current_position.column += offset.column; } current_position.line += offset.line; } void SourceMap::append(const Offset& offset) { current_position += offset; } void SourceMap::add_open_mapping(AST_Node* node) { mappings.push_back(Mapping(node->pstate(), current_position)); } void SourceMap::add_close_mapping(AST_Node* node) { mappings.push_back(Mapping(node->pstate() + node->pstate().offset, current_position)); } ParserState SourceMap::remap(const ParserState& pstate) { for (size_t i = 0; i < mappings.size(); ++i) { if ( mappings[i].generated_position.file == pstate.file && mappings[i].generated_position.line == pstate.line && mappings[i].generated_position.column == pstate.column ) return ParserState(pstate.path, pstate.src, mappings[i].original_position, pstate.offset); } return ParserState(pstate.path, pstate.src, Position(-1, -1, -1), Offset(0, 0)); } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_IMAGE_DATA_HPP #define MAPNIK_IMAGE_DATA_HPP // mapnik #include <mapnik/global.hpp> #include <mapnik/config.hpp> // stl #include <cassert> #include <cstring> #include <stdexcept> namespace mapnik { template <typename T> class MAPNIK_DECL ImageData { public: using pixel_type = T; ImageData(int width, int height) : width_(static_cast<unsigned>(width)), height_(static_cast<unsigned>(height)), owns_data_(true) { if (width < 0) { throw std::runtime_error("negative width not allowed for image_data"); } if (height < 0) { throw std::runtime_error("negative height not allowed for image_data"); } pData_ = (width!=0 && height!=0)? static_cast<T*>(::operator new(sizeof(T)*width*height)):0; if (pData_) std::memset(pData_,0,sizeof(T)*width_*height_); } ImageData(int width, int height, T * data) : width_(static_cast<unsigned>(width)), height_(static_cast<unsigned>(height)), owns_data_(false), pData_(data) { if (width < 0) { throw std::runtime_error("negative width not allowed for image_data"); } if (height < 0) { throw std::runtime_error("negative height not allowed for image_data"); } } ImageData(ImageData<T> const& rhs) :width_(rhs.width_), height_(rhs.height_), owns_data_(true), pData_((rhs.width_!=0 && rhs.height_!=0)? static_cast<T*>(::operator new(sizeof(T)*rhs.width_*rhs.height_)) :0) { if (pData_) std::memcpy(pData_,rhs.pData_,sizeof(T)*rhs.width_* rhs.height_); } ImageData(ImageData<T> && rhs) noexcept : width_(rhs.width_), height_(rhs.height_), pData_(rhs.pData_) { rhs.width_ = 0; rhs.height_ = 0; rhs.pData_ = nullptr; } ImageData<T>& operator=(ImageData<T> rhs) { swap(rhs); return *this; } void swap(ImageData<T> & rhs) { std::swap(width_, rhs.width_); std::swap(height_, rhs.height_); std::swap(pData_, rhs.pData_); } inline T& operator() (unsigned i,unsigned j) { assert(i<width_ && j<height_); return pData_[j*width_+i]; } inline const T& operator() (unsigned i,unsigned j) const { assert(i<width_ && j<height_); return pData_[j*width_+i]; } inline unsigned width() const { return width_; } inline unsigned height() const { return height_; } inline void set(const T& t) { for (unsigned y = 0; y < height_; ++y) { T * row = getRow(y); for (unsigned x = 0; x < width_; ++x) { row[x] = t; } } } inline const T* getData() const { return pData_; } inline T* getData() { return pData_; } inline const unsigned char* getBytes() const { return (unsigned char*)pData_; } inline unsigned char* getBytes() { return (unsigned char*)pData_; } inline const T* getRow(unsigned row) const { return pData_+row*width_; } inline T* getRow(unsigned row) { return pData_+row*width_; } inline void setRow(unsigned row,const T* buf,unsigned size) { assert(row<height_); assert(size<=width_); std::memcpy(pData_+row*width_,buf,size*sizeof(T)); } inline void setRow(unsigned row,unsigned x0,unsigned x1,const T* buf) { std::memcpy(pData_+row*width_+x0,buf,(x1-x0)*sizeof(T)); } inline ~ImageData() { if (owns_data_) { ::operator delete(pData_),pData_=0; } } private: unsigned width_; unsigned height_; bool owns_data_; T *pData_; ImageData& operator=(ImageData const&); }; using image_data_32 = ImageData<unsigned>; using image_data_8 = ImageData<byte> ; } #endif // MAPNIK_IMAGE_DATA_HPP <commit_msg>remove redundant private copy assignment op<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_IMAGE_DATA_HPP #define MAPNIK_IMAGE_DATA_HPP // mapnik #include <mapnik/global.hpp> #include <mapnik/config.hpp> // stl #include <cassert> #include <cstring> #include <stdexcept> namespace mapnik { template <typename T> class MAPNIK_DECL ImageData { public: using pixel_type = T; ImageData(int width, int height) : width_(static_cast<unsigned>(width)), height_(static_cast<unsigned>(height)), owns_data_(true) { if (width < 0) { throw std::runtime_error("negative width not allowed for image_data"); } if (height < 0) { throw std::runtime_error("negative height not allowed for image_data"); } pData_ = (width!=0 && height!=0)? static_cast<T*>(::operator new(sizeof(T)*width*height)):0; if (pData_) std::memset(pData_,0,sizeof(T)*width_*height_); } ImageData(int width, int height, T * data) : width_(static_cast<unsigned>(width)), height_(static_cast<unsigned>(height)), owns_data_(false), pData_(data) { if (width < 0) { throw std::runtime_error("negative width not allowed for image_data"); } if (height < 0) { throw std::runtime_error("negative height not allowed for image_data"); } } ImageData(ImageData<T> const& rhs) :width_(rhs.width_), height_(rhs.height_), owns_data_(true), pData_((rhs.width_!=0 && rhs.height_!=0)? static_cast<T*>(::operator new(sizeof(T)*rhs.width_*rhs.height_)) :0) { if (pData_) std::memcpy(pData_,rhs.pData_,sizeof(T)*rhs.width_* rhs.height_); } ImageData(ImageData<T> && rhs) noexcept : width_(rhs.width_), height_(rhs.height_), pData_(rhs.pData_) { rhs.width_ = 0; rhs.height_ = 0; rhs.pData_ = nullptr; } ImageData<T>& operator=(ImageData<T> rhs) { swap(rhs); return *this; } void swap(ImageData<T> & rhs) { std::swap(width_, rhs.width_); std::swap(height_, rhs.height_); std::swap(pData_, rhs.pData_); } inline T& operator() (unsigned i,unsigned j) { assert(i<width_ && j<height_); return pData_[j*width_+i]; } inline const T& operator() (unsigned i,unsigned j) const { assert(i<width_ && j<height_); return pData_[j*width_+i]; } inline unsigned width() const { return width_; } inline unsigned height() const { return height_; } inline void set(const T& t) { for (unsigned y = 0; y < height_; ++y) { T * row = getRow(y); for (unsigned x = 0; x < width_; ++x) { row[x] = t; } } } inline const T* getData() const { return pData_; } inline T* getData() { return pData_; } inline const unsigned char* getBytes() const { return (unsigned char*)pData_; } inline unsigned char* getBytes() { return (unsigned char*)pData_; } inline const T* getRow(unsigned row) const { return pData_+row*width_; } inline T* getRow(unsigned row) { return pData_+row*width_; } inline void setRow(unsigned row,const T* buf,unsigned size) { assert(row<height_); assert(size<=width_); std::memcpy(pData_+row*width_,buf,size*sizeof(T)); } inline void setRow(unsigned row,unsigned x0,unsigned x1,const T* buf) { std::memcpy(pData_+row*width_+x0,buf,(x1-x0)*sizeof(T)); } inline ~ImageData() { if (owns_data_) { ::operator delete(pData_),pData_=0; } } private: unsigned width_; unsigned height_; bool owns_data_; T *pData_; }; using image_data_32 = ImageData<unsigned>; using image_data_8 = ImageData<byte> ; } #endif // MAPNIK_IMAGE_DATA_HPP <|endoftext|>
<commit_before>// Simple startrails composition program using OpenCV // Copyright 2018 Jarno Paananen <jarno.paananen@gmail.com> // Based on script by Thomas Jacquin // SPDX-License-Identifier: MIT using namespace std; #include <getopt.h> #include <glob.h> #include <sys/resource.h> #include <sys/time.h> #include <unistd.h> #include <algorithm> #include <cstdlib> #include <iostream> #include <mutex> #include <string> #include <thread> #include <vector> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" struct config_t { std::string img_src_dir, img_src_ext, dst_startrails; bool startrails_enabled; int num_threads; int nice_level; int img_width; int img_height; int verbose; double brightness_limit; } config; std::mutex stdio_mutex; void parse_args(int, char**, struct config_t*); void usage_and_exit(int); void startrail_worker(int, // thread num struct config_t*, // config glob_t*, // file list std::mutex*, // mutex cv::Mat*, // statistics cv::Mat* // accumulated ); void startrail_worker(int thread_num, struct config_t* cf, glob_t* files, std::mutex* mtx, cv::Mat* stats_ptr, cv::Mat* main_accumulator) { int start_num, end_num, batch_size, nchan = 0; unsigned long nfiles = files->gl_pathc; cv::Mat thread_accumulator; batch_size = nfiles / cf->num_threads; start_num = thread_num * batch_size; // last thread has more work to do if the number of images isn't multiple of // the number of threads if ((thread_num + 1) == cf->num_threads) end_num = nfiles - 1; else end_num = start_num + batch_size - 1; if (cf->verbose > 1) { stdio_mutex.lock(); fprintf(stderr, "thread %d/%d processing files %d-%d (%d/%lu)\n", thread_num + 1, cf->num_threads, start_num, end_num, end_num - start_num + 1, nfiles); stdio_mutex.unlock(); } for (int f = start_num; f <= end_num; f++) { char* filename = files->gl_pathv[f]; cv::Mat image = cv::imread(filename, cv::IMREAD_UNCHANGED); filename = basename(filename); if (!image.data) { stdio_mutex.lock(); fprintf(stderr, "Error reading file %s\n", filename); stdio_mutex.unlock(); continue; } if (cf->img_height && cf->img_width && (image.cols != cf->img_width || image.rows != cf->img_height)) { if (cf->verbose) { stdio_mutex.lock(); fprintf(stderr, "skip %s size %dx%d != %dx%d\n", filename, image.cols, image.cols, cf->img_width, cf->img_height); stdio_mutex.unlock(); } continue; } // first valid image sets the number of channels we expect if (nchan == 0 && image.channels()) nchan = image.channels(); cv::Scalar mean_scalar = cv::mean(image); double image_mean; switch (image.channels()) { default: // mono case image_mean = mean_scalar.val[0]; break; case 3: // for color choose maximum channel case 4: image_mean = cv::max(mean_scalar[0], cv::max(mean_scalar[1], mean_scalar[2])); break; } // Scale to 0-1 range switch (image.depth()) { case CV_8U: image_mean /= 255.0; break; case CV_16U: image_mean /= 65535.0; break; } if (cf->verbose > 1) { stdio_mutex.lock(); fprintf(stderr, "[%d/%lu] %s %.3f\n", f + 1, nfiles, filename, image_mean); stdio_mutex.unlock(); } // the matrix pointed to by stats_ptr has already been initialized to NAN // so we just update the entry once the image is successfully loaded stats_ptr->col(f) = image_mean; if (cf->startrails_enabled && image_mean <= cf->brightness_limit) { if (image.channels() != nchan) { if (cf->verbose) { stdio_mutex.lock(); fprintf(stderr, "repairing channel mismatch: %d != %d\n", image.channels(), nchan); stdio_mutex.unlock(); } if (image.channels() < nchan) cv::cvtColor(image, image, cv::COLOR_GRAY2BGR, nchan); else if (image.channels() > nchan) cv::cvtColor(image, image, cv::COLOR_BGR2GRAY, nchan); } if (thread_accumulator.empty()) { image.copyTo(thread_accumulator); } else { thread_accumulator = cv::max(thread_accumulator, image); } } } if (cf->startrails_enabled) { // skip unlucky threads that might have got only bad images if (!thread_accumulator.empty()) { mtx->lock(); if (main_accumulator->empty()) { thread_accumulator.copyTo(*main_accumulator); } else { *main_accumulator = cv::max(thread_accumulator, *main_accumulator); } mtx->unlock(); } } } void parse_args(int argc, char** argv, struct config_t* cf) { int c, tmp, ncpu = std::thread::hardware_concurrency(); cf->verbose = 0; cf->startrails_enabled = true; cf->img_height = cf->img_width = 0; cf->brightness_limit = 0.35; // not terrible in the city cf->nice_level = 10; cf->num_threads = ncpu; while (1) { // getopt loop int option_index = 0; static struct option long_options[] = { {"brightness", required_argument, 0, 'b'}, {"directory", required_argument, 0, 'd'}, {"extension", required_argument, 0, 'e'}, {"max-threads", required_argument, 0, 'm'}, {"nice-level", required_argument, 0, 'n'}, {"output", required_argument, 0, 'o'}, {"image-size", required_argument, 0, 's'}, {"statistics", no_argument, 0, 'S'}, {"verbose", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; c = getopt_long(argc, argv, "hvSb:d:e:m:n:o:s:", long_options, &option_index); if (c == -1) break; switch (c) { // option switch case 'h': usage_and_exit(0); // NOTREACHED break; case 'v': cf->verbose++; break; case 'S': cf->startrails_enabled = false; break; case 's': int height, width; sscanf(optarg, "%dx%d", &width, &height); // 122.8Mpx should be enough for anybody. if (height < 0 || height > 9600 || width < 0 || width > 12800) height = width = 0; cf->img_height = height; cf->img_width = width; break; case 'b': double b; b = atof(optarg); if (b >= 0 && b <= 1.0) cf->brightness_limit = b; break; case 'd': cf->img_src_dir = optarg; break; case 'e': cf->img_src_ext = optarg; break; case 'm': tmp = atoi(optarg); if ((tmp >= 1) && (tmp <= ncpu)) cf->num_threads = tmp; else fprintf(stderr, "invalid number of threads %d; using %d\n", tmp, cf->num_threads); break; case 'n': tmp = atoi(optarg); if (PRIO_MIN > tmp) { tmp = PRIO_MIN; fprintf(stderr, "clamping scheduler priority to PRIO_MIN\n"); } else if (PRIO_MAX < tmp) { fprintf(stderr, "clamping scheduler priority to PRIO_MAX\n"); tmp = PRIO_MAX; } cf->nice_level = atoi(optarg); break; case 'o': cf->dst_startrails = optarg; break; default: break; } // option switch } // getopt loop } void usage_and_exit(int x) { std::cout << "Usage: startrails [-v] -d <dir> -e <ext> [-b <brightness> -o " "<output> | -s] [-m <max-threads>] [-n <nice>]" << std::endl; if (x) { std::cout << KRED << "Source directory and file extension are always required." << std::endl; std::cout << "brightness threshold and output file are required to render " "startrails" << KNRM << std::endl; } std::cout << std::endl << "Arguments:" << std::endl; std::cout << "-h | --help : display this help, then exit" << std::endl; std::cout << "-v | --verbose : increase log verbosity" << std::endl; std::cout << "-S | --statistics : print image directory statistics without " "producing image." << std::endl; std::cout << "-d | --directory <str> : directory from which to read images" << std::endl; std::cout << "-e | --extension <str> : filter images to just this extension" << std::endl; std::cout << "-m | --max-threads <int> : limit maximum number of processing " "threads. (0 = nproc)" << std::endl; std::cout << "-n | --nice <int> : nice(2) level of processing threads (10)" << std::endl; std::cout << "-o | --output-file <str> : output image filename" << std::endl; std::cout << "-s | --image-size <int>x<int> : restrict processed images to " "this size" << std::endl; std::cout << "-b | --brightness-limit <float> : ranges from 0 (black) to 1 " "(white). Default 0.35" << std::endl; std::cout << "\tA moonless sky may be as low as 0.05 while full moon can be " "as high as 0.4" << std::endl; std::cout << std::endl << "ex: startrails -b 0.07 -d ../images/20180208/ -e jpg -o " "startrails.jpg" << std::endl; exit(x); } int main(int argc, char* argv[]) { int r; struct config_t config; int i; char* e; parse_args(argc, argv, &config); if (config.verbose < 1) if ((e = getenv("ALLSKY_DEBUG_LEVEL"))) if ((i = atoi(e)) > 0) config.verbose = i; if (config.img_src_dir.empty() || config.img_src_ext.empty()) usage_and_exit(3); if (!config.startrails_enabled) { config.brightness_limit = 0; config.dst_startrails = "/dev/null"; } if (!config.dst_startrails.empty() && config.brightness_limit < 0) usage_and_exit(3); r = setpriority(PRIO_PROCESS, 0, config.nice_level); if (r) { config.nice_level = getpriority(PRIO_PROCESS, 0); fprintf(stderr, "unable to set nice level: %s\n", strerror(errno)); } // Find files glob_t files; std::string wildcard = config.img_src_dir + "/*." + config.img_src_ext; glob(wildcard.c_str(), 0, NULL, &files); if (files.gl_pathc == 0) { globfree(&files); std::cout << "No images found, exiting." << std::endl; return 0; } std::mutex accumulated_mutex; cv::Mat accumulated; cv::Mat stats; stats.create(1, files.gl_pathc, CV_64F); // initialize stats to NAN because some images might legitimately be 100% // brightness if they're massively overexposed. They should be counted in // the summary statistics. It is not entirely accurate to signal invalid // images with 1.0 brightness since no image data was read. stats = NAN; std::vector<std::thread> threadpool; for (int tid = 0; tid < config.num_threads; tid++) threadpool.push_back(std::thread(startrail_worker, tid, &config, &files, &accumulated_mutex, &stats, &accumulated)); for (auto& t : threadpool) t.join(); // Calculate some descriptive statistics double ds_min, ds_max, ds_mean, ds_median; cv::Point min_loc; // Each thread will have updated stats with the brightness of the images // that were successfully processed. Invalid images will be left as NAN. // In OpenCV, NAN is unequal to everything including NAN which means we can // filter out bogus entries by checking stats for element-wise equality // with itself. cv::Mat nan_mask = cv::Mat(stats == stats); cv::Mat filtered_stats; stats.copyTo(filtered_stats, nan_mask); cv::minMaxLoc(stats, &ds_min, &ds_max, &min_loc); ds_mean = cv::mean(filtered_stats)[0]; // For median, do partial sort and take middle value std::vector<double> vec; filtered_stats.copyTo(vec); std::nth_element(vec.begin(), vec.begin() + (vec.size() / 2), vec.end()); ds_median = vec[vec.size() / 2]; std::cout << "Minimum: " << ds_min << " maximum: " << ds_max << " mean: " << ds_mean << " median: " << ds_median << std::endl; // If we still don't have an image (no images below threshold), copy the // minimum mean image so we see why if (config.startrails_enabled) { if (accumulated.empty()) { fprintf( stderr, "No images below threshold %.3f, writing the minimum image only\n", config.brightness_limit); accumulated = cv::imread(files.gl_pathv[min_loc.x], cv::IMREAD_UNCHANGED); } std::vector<int> compression_params; compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); compression_params.push_back(cv::IMWRITE_JPEG_QUALITY); compression_params.push_back(95); cv::imwrite(config.dst_startrails, accumulated, compression_params); } globfree(&files); return 0; } <commit_msg>clarify behavior of concurrency limit<commit_after>// Simple startrails composition program using OpenCV // Copyright 2018 Jarno Paananen <jarno.paananen@gmail.com> // Based on script by Thomas Jacquin // SPDX-License-Identifier: MIT using namespace std; #include <getopt.h> #include <glob.h> #include <sys/resource.h> #include <sys/time.h> #include <unistd.h> #include <algorithm> #include <cstdlib> #include <iostream> #include <mutex> #include <string> #include <thread> #include <vector> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" struct config_t { std::string img_src_dir, img_src_ext, dst_startrails; bool startrails_enabled; int num_threads; int nice_level; int img_width; int img_height; int verbose; double brightness_limit; } config; std::mutex stdio_mutex; void parse_args(int, char**, struct config_t*); void usage_and_exit(int); void startrail_worker(int, // thread num struct config_t*, // config glob_t*, // file list std::mutex*, // mutex cv::Mat*, // statistics cv::Mat* // accumulated ); void startrail_worker(int thread_num, struct config_t* cf, glob_t* files, std::mutex* mtx, cv::Mat* stats_ptr, cv::Mat* main_accumulator) { int start_num, end_num, batch_size, nchan = 0; unsigned long nfiles = files->gl_pathc; cv::Mat thread_accumulator; batch_size = nfiles / cf->num_threads; start_num = thread_num * batch_size; // last thread has more work to do if the number of images isn't multiple of // the number of threads if ((thread_num + 1) == cf->num_threads) end_num = nfiles - 1; else end_num = start_num + batch_size - 1; if (cf->verbose > 1) { stdio_mutex.lock(); fprintf(stderr, "thread %d/%d processing files %d-%d (%d/%lu)\n", thread_num + 1, cf->num_threads, start_num, end_num, end_num - start_num + 1, nfiles); stdio_mutex.unlock(); } for (int f = start_num; f <= end_num; f++) { char* filename = files->gl_pathv[f]; cv::Mat image = cv::imread(filename, cv::IMREAD_UNCHANGED); filename = basename(filename); if (!image.data) { stdio_mutex.lock(); fprintf(stderr, "Error reading file %s\n", filename); stdio_mutex.unlock(); continue; } if (cf->img_height && cf->img_width && (image.cols != cf->img_width || image.rows != cf->img_height)) { if (cf->verbose) { stdio_mutex.lock(); fprintf(stderr, "skip %s size %dx%d != %dx%d\n", filename, image.cols, image.cols, cf->img_width, cf->img_height); stdio_mutex.unlock(); } continue; } // first valid image sets the number of channels we expect if (nchan == 0 && image.channels()) nchan = image.channels(); cv::Scalar mean_scalar = cv::mean(image); double image_mean; switch (image.channels()) { default: // mono case image_mean = mean_scalar.val[0]; break; case 3: // for color choose maximum channel case 4: image_mean = cv::max(mean_scalar[0], cv::max(mean_scalar[1], mean_scalar[2])); break; } // Scale to 0-1 range switch (image.depth()) { case CV_8U: image_mean /= 255.0; break; case CV_16U: image_mean /= 65535.0; break; } if (cf->verbose > 1) { stdio_mutex.lock(); fprintf(stderr, "[%d/%lu] %s %.3f\n", f + 1, nfiles, filename, image_mean); stdio_mutex.unlock(); } // the matrix pointed to by stats_ptr has already been initialized to NAN // so we just update the entry once the image is successfully loaded stats_ptr->col(f) = image_mean; if (cf->startrails_enabled && image_mean <= cf->brightness_limit) { if (image.channels() != nchan) { if (cf->verbose) { stdio_mutex.lock(); fprintf(stderr, "repairing channel mismatch: %d != %d\n", image.channels(), nchan); stdio_mutex.unlock(); } if (image.channels() < nchan) cv::cvtColor(image, image, cv::COLOR_GRAY2BGR, nchan); else if (image.channels() > nchan) cv::cvtColor(image, image, cv::COLOR_BGR2GRAY, nchan); } if (thread_accumulator.empty()) { image.copyTo(thread_accumulator); } else { thread_accumulator = cv::max(thread_accumulator, image); } } } if (cf->startrails_enabled) { // skip unlucky threads that might have got only bad images if (!thread_accumulator.empty()) { mtx->lock(); if (main_accumulator->empty()) { thread_accumulator.copyTo(*main_accumulator); } else { *main_accumulator = cv::max(thread_accumulator, *main_accumulator); } mtx->unlock(); } } } void parse_args(int argc, char** argv, struct config_t* cf) { int c, tmp, ncpu = std::thread::hardware_concurrency(); cf->verbose = 0; cf->startrails_enabled = true; cf->img_height = cf->img_width = 0; cf->brightness_limit = 0.35; // not terrible in the city cf->nice_level = 10; cf->num_threads = ncpu; while (1) { // getopt loop int option_index = 0; static struct option long_options[] = { {"brightness", required_argument, 0, 'b'}, {"directory", required_argument, 0, 'd'}, {"extension", required_argument, 0, 'e'}, {"max-threads", required_argument, 0, 'm'}, {"nice-level", required_argument, 0, 'n'}, {"output", required_argument, 0, 'o'}, {"image-size", required_argument, 0, 's'}, {"statistics", no_argument, 0, 'S'}, {"verbose", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; c = getopt_long(argc, argv, "hvSb:d:e:m:n:o:s:", long_options, &option_index); if (c == -1) break; switch (c) { // option switch case 'h': usage_and_exit(0); // NOTREACHED break; case 'v': cf->verbose++; break; case 'S': cf->startrails_enabled = false; break; case 's': int height, width; sscanf(optarg, "%dx%d", &width, &height); // 122.8Mpx should be enough for anybody. if (height < 0 || height > 9600 || width < 0 || width > 12800) height = width = 0; cf->img_height = height; cf->img_width = width; break; case 'b': double b; b = atof(optarg); if (b >= 0 && b <= 1.0) cf->brightness_limit = b; break; case 'd': cf->img_src_dir = optarg; break; case 'e': cf->img_src_ext = optarg; break; case 'm': tmp = atoi(optarg); if ((tmp >= 1) && (tmp <= ncpu)) cf->num_threads = tmp; else fprintf(stderr, "invalid number of threads %d; using %d\n", tmp, cf->num_threads); break; case 'n': tmp = atoi(optarg); if (PRIO_MIN > tmp) { tmp = PRIO_MIN; fprintf(stderr, "clamping scheduler priority to PRIO_MIN\n"); } else if (PRIO_MAX < tmp) { fprintf(stderr, "clamping scheduler priority to PRIO_MAX\n"); tmp = PRIO_MAX; } cf->nice_level = atoi(optarg); break; case 'o': cf->dst_startrails = optarg; break; default: break; } // option switch } // getopt loop } void usage_and_exit(int x) { std::cout << "Usage: startrails [-v] -d <dir> -e <ext> [-b <brightness> -o " "<output> | -s] [-m <max-threads>] [-n <nice>]" << std::endl; if (x) { std::cout << KRED << "Source directory and file extension are always required." << std::endl; std::cout << "brightness threshold and output file are required to render " "startrails" << KNRM << std::endl; } std::cout << std::endl << "Arguments:" << std::endl; std::cout << "-h | --help : display this help, then exit" << std::endl; std::cout << "-v | --verbose : increase log verbosity" << std::endl; std::cout << "-S | --statistics : print image directory statistics without " "producing image." << std::endl; std::cout << "-d | --directory <str> : directory from which to read images" << std::endl; std::cout << "-e | --extension <str> : filter images to just this extension" << std::endl; std::cout << "-m | --max-threads <int> : limit maximum number of processing " "threads. (unspecified = use all cpus)" << std::endl; std::cout << "-n | --nice <int> : nice(2) level of processing threads (10)" << std::endl; std::cout << "-o | --output-file <str> : output image filename" << std::endl; std::cout << "-s | --image-size <int>x<int> : restrict processed images to " "this size" << std::endl; std::cout << "-b | --brightness-limit <float> : ranges from 0 (black) to 1 " "(white). Default 0.35" << std::endl; std::cout << "\tA moonless sky may be as low as 0.05 while full moon can be " "as high as 0.4" << std::endl; std::cout << std::endl << "ex: startrails -b 0.07 -d ../images/20180208/ -e jpg -o " "startrails.jpg" << std::endl; exit(x); } int main(int argc, char* argv[]) { int r; struct config_t config; int i; char* e; parse_args(argc, argv, &config); if (config.verbose < 1) if ((e = getenv("ALLSKY_DEBUG_LEVEL"))) if ((i = atoi(e)) > 0) config.verbose = i; if (config.img_src_dir.empty() || config.img_src_ext.empty()) usage_and_exit(3); if (!config.startrails_enabled) { config.brightness_limit = 0; config.dst_startrails = "/dev/null"; } if (!config.dst_startrails.empty() && config.brightness_limit < 0) usage_and_exit(3); r = setpriority(PRIO_PROCESS, 0, config.nice_level); if (r) { config.nice_level = getpriority(PRIO_PROCESS, 0); fprintf(stderr, "unable to set nice level: %s\n", strerror(errno)); } // Find files glob_t files; std::string wildcard = config.img_src_dir + "/*." + config.img_src_ext; glob(wildcard.c_str(), 0, NULL, &files); if (files.gl_pathc == 0) { globfree(&files); std::cout << "No images found, exiting." << std::endl; return 0; } std::mutex accumulated_mutex; cv::Mat accumulated; cv::Mat stats; stats.create(1, files.gl_pathc, CV_64F); // initialize stats to NAN because some images might legitimately be 100% // brightness if they're massively overexposed. They should be counted in // the summary statistics. It is not entirely accurate to signal invalid // images with 1.0 brightness since no image data was read. stats = NAN; std::vector<std::thread> threadpool; for (int tid = 0; tid < config.num_threads; tid++) threadpool.push_back(std::thread(startrail_worker, tid, &config, &files, &accumulated_mutex, &stats, &accumulated)); for (auto& t : threadpool) t.join(); // Calculate some descriptive statistics double ds_min, ds_max, ds_mean, ds_median; cv::Point min_loc; // Each thread will have updated stats with the brightness of the images // that were successfully processed. Invalid images will be left as NAN. // In OpenCV, NAN is unequal to everything including NAN which means we can // filter out bogus entries by checking stats for element-wise equality // with itself. cv::Mat nan_mask = cv::Mat(stats == stats); cv::Mat filtered_stats; stats.copyTo(filtered_stats, nan_mask); cv::minMaxLoc(stats, &ds_min, &ds_max, &min_loc); ds_mean = cv::mean(filtered_stats)[0]; // For median, do partial sort and take middle value std::vector<double> vec; filtered_stats.copyTo(vec); std::nth_element(vec.begin(), vec.begin() + (vec.size() / 2), vec.end()); ds_median = vec[vec.size() / 2]; std::cout << "Minimum: " << ds_min << " maximum: " << ds_max << " mean: " << ds_mean << " median: " << ds_median << std::endl; // If we still don't have an image (no images below threshold), copy the // minimum mean image so we see why if (config.startrails_enabled) { if (accumulated.empty()) { fprintf( stderr, "No images below threshold %.3f, writing the minimum image only\n", config.brightness_limit); accumulated = cv::imread(files.gl_pathv[min_loc.x], cv::IMREAD_UNCHANGED); } std::vector<int> compression_params; compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); compression_params.push_back(cv::IMWRITE_JPEG_QUALITY); compression_params.push_back(95); cv::imwrite(config.dst_startrails, accumulated, compression_params); } globfree(&files); return 0; } <|endoftext|>
<commit_before>#ifndef TELNETPP_TELNETPP_HPP_ #define TELNETPP_TELNETPP_HPP_ // routing_visitor pulls in all of the various routers, and thus all // of the various token types. #include "telnetpp/routing_visitor.hpp" // With the addition of the parser and generator, the client need then only // include the specific required options in order to have a complete Telnet // layer. #include "telnetpp/parser.hpp" #include "telnetpp/generator.hpp" #endif <commit_msg>Added protocol.hpp to convenience header.<commit_after>#ifndef TELNETPP_TELNETPP_HPP_ #define TELNETPP_TELNETPP_HPP_ // routing_visitor pulls in all of the various routers, and thus all // of the various token types. #include "telnetpp/routing_visitor.hpp" // For sending commands, it's necessary to know what the commands in the // protocol are. #include "telnetpp/protocol.hpp" // With the addition of the parser and generator, the client need then only // include the specific required options in order to have a complete Telnet // layer. #include "telnetpp/parser.hpp" #include "telnetpp/generator.hpp" #endif <|endoftext|>
<commit_before>#ifndef V_SMC_CORE_SAMPLER_HPP #define V_SMC_CORE_SAMPLER_HPP #include <iomanip> #include <iostream> #include <map> #include <set> #include <stdexcept> #include <string> #include <vector> #include <mkl_cblas.h> #include <boost/function.hpp> #include <vSMC/core/buffer.hpp> #include <vSMC/core/monitor.hpp> #include <vSMC/core/particle.hpp> #include <vSMC/core/path.hpp> namespace vSMC { template <typename T> class Sampler { public : /// The type of initialization functor typedef boost::function<std::size_t (Particle<T> &, void *)> init_type; /// The type of move functor typedef boost::function<std::size_t (std::size_t, Particle<T> &)> move_type; /// The type of importance sampling integral functor typedef boost::function<void (std::size_t, Particle<T> &, double *, void *)> integral_type; /// \brief Sampler does not have a default constructor /// /// \param N The number of particles /// \param init The functor used to initialize the particles /// \param move The functor used to move the particles and weights /// \param mcmc The functor used to perform MCMC move /// \param scheme The resampling scheme. See ResampleScheme /// \param threshold The threshold for performing resampling Sampler ( std::size_t N, const init_type &init, const move_type &move, const move_type &mcmc = NULL, ResampleScheme scheme = RESIDUAL, double threshold = 0.5, unsigned seed = V_SMC_RNG_SEED) : initialized_(false), init_(init), move_(move), mcmc_(mcmc), scheme_(scheme), threshold_(threshold * N), particle_(N, seed), iter_num_(0), show_progress_(false) {} /// \brief Size of the particle set /// /// \return The number of particles std::size_t size () const { return particle_.size(); } /// \brief Size of records /// /// \return The number of iterations recorded (including the /// initialization step) std::size_t iter_size () const { return ess_.size(); } /// \brief ESS /// /// \return The ESS value of the latest iteration double ess () const { return ess_.back(); } /// \brief ESS history /// /// \return A const reference to the history of ESS const std::vector<double> &ess_history () const { return ess_; } /// \brief ESS history /// /// \param first An iterator point to where writing starts template<typename OIter> void ess_history (OIter first) const { for (std::vector<double>::const_iterator iter = ess_.begin(); iter != ess_.end(); ++iter) *first++ = *iter; } /// \brief Indicator of resampling /// /// \return A bool value, \b true if the latest iteration was resampled bool resampled () const { return resampled_.back(); } /// \brief Resampling history /// /// \return A const reference to the history of resampling const std::vector<bool> &resampled_history () const { return resampled_; } /// \brief Resampling history /// /// \param first An iterator point to where writing starts template<typename OIter> void resampled_history (OIter first) const { for (std::vector<bool>::const_iterator iter = resampled_.begin(); iter != resampled_.end(); ++iter) *first++ = *iter; } /// \brief Accept count /// /// \return The accept count of the latest iteration std::size_t accept () const { return accept_.back(); } /// \brief Accept count history /// /// \return A const reference to the history of accept count const std::vector<std::size_t> &accept_history () const { return accept_; } /// \brief Accept count history /// /// \param first An iterator point to where writing starts template<typename OIter> void accept_history (OIter first) const { for (std::vector<std::size_t>::const_iterator iter = accept_.begin(); iter != accept_.end(); ++iter) *first++ = *iter; } /// \brief Read and write access to the particle set /// /// \return A reference to the latest particle set /// /// \note The Sampler class guarantee that during the life type of the /// object, the reference returned by this member will no be a dangle /// handler. Particle<T> &particle () { return particle_; } /// \brief Read only access to the particle set /// /// \return A const reference to the latest particle set. const Particle<T> &particle () const { return particle_; } /// \brief Initialize the particle set /// /// \param param Additional parameters passed to the initialization /// functor void initialize (void *param = NULL) { ess_.clear(); resampled_.clear(); accept_.clear(); path_.clear(); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) imap->second.clear(); iter_num_ = 0; accept_.push_back(init_(particle_, param)); post_move(); particle_.reset_zconst(); initialized_ = true; } /// \brief Perform iteration void iterate () { if (!initialized_) { throw std::runtime_error( "ERROR: vSMC::Sampler::iterate: " "Sampler has not been initialized yet"); } ++iter_num_; accept_.push_back(move_(iter_num_, particle_)); if (mcmc_) accept_.back() = mcmc_(iter_num_, particle_); post_move(); } /// \brief Perform iteration /// /// \param n The number of iterations to be performed void iterate (std::size_t n) { for (std::size_t i = 0; i != n; ++i) iterate(); } /// \brief Perform importance sampling integration /// /// \param integral The functor used to compute the integrands double integrate (typename Monitor<T>::integral_type integral) { buffer_.resize(size()); integral(iter_num_, particle_, buffer_); return cblas_ddot(size(), particle_.weight_ptr(), 1, buffer_, 1); } /// \brief Perform importance sampling integration /// /// \param integral The functor used to compute the integrands /// \param param Additional parameters passed to the integral functor double integrate (integral_type integral, void *param) const { buffer_.resize(size()); integral(iter_num_, particle_, buffer_, param); return cblas_ddot(size(), particle_.weight_ptr(), 1, buffer_, 1); } /// \brief Add a monitor, similar to \b monitor in \b BUGS /// /// \param name The name of the monitor /// \param integral The functor used to compute the integrands void monitor (const std::string &name, unsigned dim, const typename Monitor<T>::integral_type &integral) { monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral))); monitor_name_.insert(name); } /// \brief Read and write access to a named monitor through iterator /// /// \param name The name of the monitor /// \return An iterator point to the monitor for the given name typename std::map<std::string, Monitor<T> >::iterator monitor (const std::string &name) { return monitor_.find(name); } /// \brief Read only access to a named monitor through iterator /// /// \param name The name of the monitor /// \return An const_iterator point to the monitor for the given name typename std::map<std::string, Monitor<T> >::const_iterator monitor (const std::string &name) const { return monitor_.find(name); } /// \brief Read and write access to all monitors /// /// \return A reference to monitors std::map<std::string, Monitor<T> > &monitor () { return monitor_; } /// \brief Read only access to all monitors /// /// \return A const reference to monitors const std::map<std::string, Monitor<T> > &monitor () const { return monitor_; } /// \brief Erase a named monitor /// /// \param name The name of the monitor void erase_monitor (const std::string &name) { monitor_.erase(name); monitor_name_.erase(name); } /// \brief Erase (clear) all monitors void clear_monitor () { monitor_.clear(); monitor_name_.clear(); } /// \brief Read and write access to the Path sampling monitor /// /// \return A reference to the Path sampling monitor Path<T> &path () { return path_; } /// \brief Read only access to the Path sampling monitor /// /// \return A const reference to the Path sampling monitor const Path<T> &path () const { return path_; } /// \brief Set the path sampling integral /// /// \param integral The functor used to compute the integrands /// /// \note Set integral = NULL will stop path sampling recording void path_sampling (const typename Path<T>::integral_type &integral) { path_.integral(integral); } /// \brief Path sampling estimate of normalizing constant /// /// \return The log ratio of normalizing constants double path_sampling () const { return path_.zconst(); } /// \brief Toggle whether or not record SMC normalizing constant /// /// \param estimate_zconst Start estimating normalzing constant if true. void zconst (bool estimate_zconst) { particle_.zconst(estimate_zconst); } /// \brief SMC estimate of normalizing constant /// /// \return The SMC normalizng constant estimate double zconst () const { return particle_.zconst(); } /// \brief Print the history of the sampler /// /// \param output The ostream to which the contents are printed /// \param print_header Print header if \b true void print (std::ostream &output = std::cout, bool print_header = true) const { print(output, print_header, !path_.index().empty(), monitor_name_); } /// \brief Print the history of the sampler /// /// \param output The ostream to which the contents are printed /// \param print_path Print path sampling history if \b true /// \param print_monitor A set of monitor names to be printed /// \param print_header Print header if \b true void print (std::ostream &output, bool print_header, bool print_path, const std::set<std::string> &print_monitor) const { if (print_header) { output << "iter\tESS\tresample\taccept\t"; if (print_path) output << "path.integrand\tpath.width\tpath.grid\t"; } std::vector<std::size_t>::const_iterator iter_path_index = path_.index().begin(); std::vector<double>::const_iterator iter_path_integrand = path_.integrand().begin(); std::vector<double>::const_iterator iter_path_width = path_.width().begin(); std::vector<double>::const_iterator iter_path_grid = path_.grid().begin(); std::vector<bool> monitor_index_empty; std::vector<unsigned> monitor_dim; std::vector<std::vector<std::size_t>::const_iterator> iter_monitor_index; std::vector<std::vector<internal::Buffer<double> >::const_iterator> iter_monitor_record; for (typename std::map<std::string, Monitor<T> >::const_iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) { if (print_monitor.count(imap->first)) { monitor_index_empty.push_back(imap->second.index().empty()); monitor_dim.push_back(imap->second.dim()); iter_monitor_index.push_back(imap->second.index().begin()); iter_monitor_record.push_back(imap->second.record().begin()); if (print_header) { if (monitor_dim.back() > 1) { for (unsigned d = 0; d != monitor_dim.back(); ++d) output << imap->first << d + 1 << '\t'; } else { output << imap->first << '\t'; } } } } if (print_header) output << '\n'; for (std::size_t i = 0; i != iter_size(); ++i) { output << i << '\t' << ess_[i] / size() << '\t' << resampled_[i] << '\t' << static_cast<double>(accept_[i]) / size(); if (print_path) { if (!path_.index().empty() && *iter_path_index == i) { output << '\t' << *iter_path_integrand++ << '\t' << *iter_path_width++ << '\t' << *iter_path_grid++; ++iter_path_index; } else { output << '\t' << '.' << '\t' << '.' << '\t' << '.'; } } for (std::size_t m = 0; m != monitor_index_empty.size(); ++m) { if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) { for (unsigned d = 0; d != monitor_dim[m]; ++d) output << '\t' << (*iter_monitor_record[m])[d]; ++iter_monitor_index[m]; ++iter_monitor_record[m]; } else { for (unsigned d = 0; d != monitor_dim[m]; ++d) output << '\t' << '.'; } } output << '\n'; } } private : /// Initialization indicator bool initialized_; /// Initialization and movement init_type init_; move_type move_; move_type mcmc_; /// Resampling ResampleScheme scheme_; double threshold_; /// Particle sets Particle<T> particle_; std::size_t iter_num_; std::vector<double> ess_; std::vector<bool> resampled_; std::vector<std::size_t> accept_; /// Monte Carlo estimation by integration internal::Buffer<double> buffer_; std::map<std::string, Monitor<T> > monitor_; std::set<std::string> monitor_name_; /// Path sampling Path<T> path_; /// Whether to show prograss while iterating bool show_progress_; void post_move () { ess_.push_back(particle_.ess()); particle_.resampled(ess_.back() < threshold_); resampled_.push_back(particle_.resampled()); if (particle_.resampled()) particle_.resample(scheme_); if (!path_.empty()) path_.eval(iter_num_, particle_); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) { if (!imap->second.empty()) imap->second.eval(iter_num_, particle_); } if (show_progress_) { if (iter_num_) std::cerr << '.'; else std::cerr << '*'; std::cerr.flush(); } } }; // class Sampler } // namespace vSMC namespace std { template<typename T> std::ostream & operator<< (std::ostream &output, const vSMC::Sampler<T> &sampler) { sampler.print(output); return output; } } // namespace std #endif // V_SMC_CORE_SAMPLER_HPP <commit_msg>sampler allow multi dimension integration<commit_after>#ifndef V_SMC_CORE_SAMPLER_HPP #define V_SMC_CORE_SAMPLER_HPP #include <iomanip> #include <iostream> #include <map> #include <set> #include <stdexcept> #include <string> #include <vector> #include <mkl_cblas.h> #include <boost/function.hpp> #include <vSMC/core/buffer.hpp> #include <vSMC/core/monitor.hpp> #include <vSMC/core/particle.hpp> #include <vSMC/core/path.hpp> namespace vSMC { template <typename T> class Sampler { public : /// The type of initialization functor typedef boost::function<std::size_t (Particle<T> &, void *)> init_type; /// The type of move functor typedef boost::function<std::size_t (std::size_t, Particle<T> &)> move_type; /// The type of importance sampling integral functor typedef boost::function<void (std::size_t, Particle<T> &, double *, void *)> integral_type; /// \brief Sampler does not have a default constructor /// /// \param N The number of particles /// \param init The functor used to initialize the particles /// \param move The functor used to move the particles and weights /// \param mcmc The functor used to perform MCMC move /// \param scheme The resampling scheme. See ResampleScheme /// \param threshold The threshold for performing resampling Sampler ( std::size_t N, const init_type &init, const move_type &move, const move_type &mcmc = NULL, ResampleScheme scheme = RESIDUAL, double threshold = 0.5, unsigned seed = V_SMC_RNG_SEED) : initialized_(false), init_(init), move_(move), mcmc_(mcmc), scheme_(scheme), threshold_(threshold * N), particle_(N, seed), iter_num_(0), show_progress_(false) {} /// \brief Size of the particle set /// /// \return The number of particles std::size_t size () const { return particle_.size(); } /// \brief Size of records /// /// \return The number of iterations recorded (including the /// initialization step) std::size_t iter_size () const { return ess_.size(); } /// \brief ESS /// /// \return The ESS value of the latest iteration double ess () const { return ess_.back(); } /// \brief ESS history /// /// \return A const reference to the history of ESS const std::vector<double> &ess_history () const { return ess_; } /// \brief ESS history /// /// \param first An iterator point to where writing starts template<typename OIter> void ess_history (OIter first) const { for (std::vector<double>::const_iterator iter = ess_.begin(); iter != ess_.end(); ++iter) *first++ = *iter; } /// \brief Indicator of resampling /// /// \return A bool value, \b true if the latest iteration was resampled bool resampled () const { return resampled_.back(); } /// \brief Resampling history /// /// \return A const reference to the history of resampling const std::vector<bool> &resampled_history () const { return resampled_; } /// \brief Resampling history /// /// \param first An iterator point to where writing starts template<typename OIter> void resampled_history (OIter first) const { for (std::vector<bool>::const_iterator iter = resampled_.begin(); iter != resampled_.end(); ++iter) *first++ = *iter; } /// \brief Accept count /// /// \return The accept count of the latest iteration std::size_t accept () const { return accept_.back(); } /// \brief Accept count history /// /// \return A const reference to the history of accept count const std::vector<std::size_t> &accept_history () const { return accept_; } /// \brief Accept count history /// /// \param first An iterator point to where writing starts template<typename OIter> void accept_history (OIter first) const { for (std::vector<std::size_t>::const_iterator iter = accept_.begin(); iter != accept_.end(); ++iter) *first++ = *iter; } /// \brief Read and write access to the particle set /// /// \return A reference to the latest particle set /// /// \note The Sampler class guarantee that during the life type of the /// object, the reference returned by this member will no be a dangle /// handler. Particle<T> &particle () { return particle_; } /// \brief Read only access to the particle set /// /// \return A const reference to the latest particle set. const Particle<T> &particle () const { return particle_; } /// \brief Initialize the particle set /// /// \param param Additional parameters passed to the initialization /// functor void initialize (void *param = NULL) { ess_.clear(); resampled_.clear(); accept_.clear(); path_.clear(); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) imap->second.clear(); iter_num_ = 0; accept_.push_back(init_(particle_, param)); post_move(); particle_.reset_zconst(); initialized_ = true; } /// \brief Perform iteration void iterate () { if (!initialized_) { throw std::runtime_error( "ERROR: vSMC::Sampler::iterate: " "Sampler has not been initialized yet"); } ++iter_num_; accept_.push_back(move_(iter_num_, particle_)); if (mcmc_) accept_.back() = mcmc_(iter_num_, particle_); post_move(); } /// \brief Perform iteration /// /// \param n The number of iterations to be performed void iterate (std::size_t n) { for (std::size_t i = 0; i != n; ++i) iterate(); } /// \brief Perform importance sampling integration /// /// \param dim The dimension of the parameter /// \param integral The functor used to compute the integrands /// \param res The result, an array of length dim void integrate (unsigned dim, const typename Monitor<T>::integral_type &integral, double *res) { Monitor<T> m(dim, integral); m.eval(iter_num_, particle_); cblas_dcopy(dim, m.record().back().get(), 1, res, 1); } /// \brief Add a monitor, similar to \b monitor in \b BUGS /// /// \param name The name of the monitor /// \param integral The functor used to compute the integrands void monitor (const std::string &name, unsigned dim, const typename Monitor<T>::integral_type &integral) { monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral))); monitor_name_.insert(name); } /// \brief Read and write access to a named monitor through iterator /// /// \param name The name of the monitor /// \return An iterator point to the monitor for the given name typename std::map<std::string, Monitor<T> >::iterator monitor (const std::string &name) { return monitor_.find(name); } /// \brief Read only access to a named monitor through iterator /// /// \param name The name of the monitor /// \return An const_iterator point to the monitor for the given name typename std::map<std::string, Monitor<T> >::const_iterator monitor (const std::string &name) const { return monitor_.find(name); } /// \brief Read and write access to all monitors /// /// \return A reference to monitors std::map<std::string, Monitor<T> > &monitor () { return monitor_; } /// \brief Read only access to all monitors /// /// \return A const reference to monitors const std::map<std::string, Monitor<T> > &monitor () const { return monitor_; } /// \brief Erase a named monitor /// /// \param name The name of the monitor void erase_monitor (const std::string &name) { monitor_.erase(name); monitor_name_.erase(name); } /// \brief Erase (clear) all monitors void clear_monitor () { monitor_.clear(); monitor_name_.clear(); } /// \brief Read and write access to the Path sampling monitor /// /// \return A reference to the Path sampling monitor Path<T> &path () { return path_; } /// \brief Read only access to the Path sampling monitor /// /// \return A const reference to the Path sampling monitor const Path<T> &path () const { return path_; } /// \brief Set the path sampling integral /// /// \param integral The functor used to compute the integrands /// /// \note Set integral = NULL will stop path sampling recording void path_sampling (const typename Path<T>::integral_type &integral) { path_.integral(integral); } /// \brief Path sampling estimate of normalizing constant /// /// \return The log ratio of normalizing constants double path_sampling () const { return path_.zconst(); } /// \brief Toggle whether or not record SMC normalizing constant /// /// \param estimate_zconst Start estimating normalzing constant if true. void zconst (bool estimate_zconst) { particle_.zconst(estimate_zconst); } /// \brief SMC estimate of normalizing constant /// /// \return The SMC normalizng constant estimate double zconst () const { return particle_.zconst(); } /// \brief Print the history of the sampler /// /// \param output The ostream to which the contents are printed /// \param print_header Print header if \b true void print (std::ostream &output = std::cout, bool print_header = true) const { print(output, print_header, !path_.index().empty(), monitor_name_); } /// \brief Print the history of the sampler /// /// \param output The ostream to which the contents are printed /// \param print_path Print path sampling history if \b true /// \param print_monitor A set of monitor names to be printed /// \param print_header Print header if \b true void print (std::ostream &output, bool print_header, bool print_path, const std::set<std::string> &print_monitor) const { if (print_header) { output << "iter\tESS\tresample\taccept\t"; if (print_path) output << "path.integrand\tpath.width\tpath.grid\t"; } std::vector<std::size_t>::const_iterator iter_path_index = path_.index().begin(); std::vector<double>::const_iterator iter_path_integrand = path_.integrand().begin(); std::vector<double>::const_iterator iter_path_width = path_.width().begin(); std::vector<double>::const_iterator iter_path_grid = path_.grid().begin(); std::vector<bool> monitor_index_empty; std::vector<unsigned> monitor_dim; std::vector<std::vector<std::size_t>::const_iterator> iter_monitor_index; std::vector<std::vector<internal::Buffer<double> >::const_iterator> iter_monitor_record; for (typename std::map<std::string, Monitor<T> >::const_iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) { if (print_monitor.count(imap->first)) { monitor_index_empty.push_back(imap->second.index().empty()); monitor_dim.push_back(imap->second.dim()); iter_monitor_index.push_back(imap->second.index().begin()); iter_monitor_record.push_back(imap->second.record().begin()); if (print_header) { if (monitor_dim.back() > 1) { for (unsigned d = 0; d != monitor_dim.back(); ++d) output << imap->first << d + 1 << '\t'; } else { output << imap->first << '\t'; } } } } if (print_header) output << '\n'; for (std::size_t i = 0; i != iter_size(); ++i) { output << i << '\t' << ess_[i] / size() << '\t' << resampled_[i] << '\t' << static_cast<double>(accept_[i]) / size(); if (print_path) { if (!path_.index().empty() && *iter_path_index == i) { output << '\t' << *iter_path_integrand++ << '\t' << *iter_path_width++ << '\t' << *iter_path_grid++; ++iter_path_index; } else { output << '\t' << '.' << '\t' << '.' << '\t' << '.'; } } for (std::size_t m = 0; m != monitor_index_empty.size(); ++m) { if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) { for (unsigned d = 0; d != monitor_dim[m]; ++d) output << '\t' << (*iter_monitor_record[m])[d]; ++iter_monitor_index[m]; ++iter_monitor_record[m]; } else { for (unsigned d = 0; d != monitor_dim[m]; ++d) output << '\t' << '.'; } } output << '\n'; } } private : /// Initialization indicator bool initialized_; /// Initialization and movement init_type init_; move_type move_; move_type mcmc_; /// Resampling ResampleScheme scheme_; double threshold_; /// Particle sets Particle<T> particle_; std::size_t iter_num_; std::vector<double> ess_; std::vector<bool> resampled_; std::vector<std::size_t> accept_; /// Monte Carlo estimation by integration internal::Buffer<double> buffer_; std::map<std::string, Monitor<T> > monitor_; std::set<std::string> monitor_name_; /// Path sampling Path<T> path_; /// Whether to show prograss while iterating bool show_progress_; void post_move () { ess_.push_back(particle_.ess()); particle_.resampled(ess_.back() < threshold_); resampled_.push_back(particle_.resampled()); if (particle_.resampled()) particle_.resample(scheme_); if (!path_.empty()) path_.eval(iter_num_, particle_); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) { if (!imap->second.empty()) imap->second.eval(iter_num_, particle_); } if (show_progress_) { if (iter_num_) std::cerr << '.'; else std::cerr << '*'; std::cerr.flush(); } } }; // class Sampler } // namespace vSMC namespace std { template<typename T> std::ostream & operator<< (std::ostream &output, const vSMC::Sampler<T> &sampler) { sampler.print(output); return output; } } // namespace std #endif // V_SMC_CORE_SAMPLER_HPP <|endoftext|>
<commit_before>// Copyright (c) 2018 Benno Straub, licensed under the MIT license. (A copy can be found at the bottom of this file) // Utilities for 3d textures/voxel engines #pragma once #include <algorithm> #include <cmath> namespace stx { // == bitmap ================================================= /// Represents a subsection of bitmapped 2d array template<class T> struct bitmap { using u32 = unsigned; using i32 = int; T* data; u32 w, h; u32 elements_per_scanline; constexpr bitmap(T* data, u32 w, u32 h) noexcept; constexpr bitmap(T* data, u32 w, u32 h, u32 elements_per_scanline) noexcept; constexpr bitmap<T> subimage(u32 w, u32 h) noexcept; constexpr bitmap<T> subimage(i32 x, i32 y, u32 w, u32 h) noexcept; template<class Callback> void each(Callback&& callback) { T* scanline = data; for(u32 y = 0; y < h; y++) { for(u32 x = 0; x < w; x++) { callback(scanline[x]); } scanline += elements_per_scanline; } } constexpr i32 index(i32 x, i32 y) const noexcept { return x + y * elements_per_scanline; } constexpr T& operator()(i32 x, i32 y) const noexcept { return data[index(x, y)]; } constexpr u32 area() const noexcept { return w * h; } }; // == Blitting ================================================= /// Copies one bitmap to another // The destination bitmap should not overlap with the source bitmap! (use blit_in_place for that) template<class Src, class Dst, class Assigner = void(*)(Src&,Dst&)> void blit( bitmap<Src> src, bitmap<Dst> dst, Assigner assign = [](Src&a,Dst&b){b=std::move(a);}) noexcept; /// Copies one bitmap to another // The destination bitmap should not overlap with the source bitmap! (use blit_in_place for that) template<class Src, class Dst, class Assigner = void(*)(Src&,Dst&)> void blit_backwards( bitmap<Src> src, bitmap<Dst> dst, Assigner assign = [](Src&a,Dst&b){b=std::move(a);}) noexcept; /// Copies one bitmap to another /// The destination bitmap may overlap with the source bitmap /// If this is not needed use blit, because it has better memory access patterns template<class Src, class Dst, class Assigner = void(*)(Src&,Dst&)> void blit_in_place( bitmap<Src> src, bitmap<Dst> dst, Assigner assign = [](Src&a,Dst&b){b=std::move(a);}) noexcept; // == Sampling ================================================== template<class T> T sample_nearest(stx::bitmap<T> src, float x, float y) { unsigned ux = std::clamp<float>(std::round(x * (src.w - 1)), 0, src.w - 1); unsigned uy = std::clamp<float>(std::round(y * (src.h - 1)), 0, src.h - 1); return src(ux, uy); } } // namespace stx // ============================================================= // == Inline Implementation ============================================= // ============================================================= namespace stx { // -- bitmap ------------------------------------------------------- template<class T> constexpr bitmap<T>::bitmap(T* data, u32 w, u32 h) noexcept : data(data), w(w), h(h), elements_per_scanline(w) {} template<class T> constexpr bitmap<T>::bitmap( T* data, u32 w, u32 h, u32 elements_per_scanline) noexcept : data(data), w(w), h(h), elements_per_scanline(elements_per_scanline) {} template<class T> constexpr bitmap<T> bitmap<T>::subimage(u32 w, u32 h) noexcept { return bitmap<T>(data, w, h, elements_per_scanline); } template<class T> constexpr bitmap<T> bitmap<T>::subimage(i32 x, i32 y, u32 w, u32 h) noexcept { return bitmap<T>(data + index(x, y), w, h, elements_per_scanline); } // -- Blitting ------------------------------------------------------- template<class Src, class Dst, class Assigner> void blit(bitmap<Src> src, bitmap<Dst> dst, Assigner assign) noexcept { using u32 = unsigned; Src* src_scanline = src.data; Dst* dst_scanline = dst.data; for(u32 y=0;y<src.h;y++) { for(u32 x=0;x<src.w;x++) { assign(src_scanline[x], dst_scanline[x]); } src_scanline += src.elements_per_scanline; dst_scanline += dst.elements_per_scanline; } } template<class Src, class Dst, class Assigner> void blit_backwards(bitmap<Src> src, bitmap<Dst> dst, Assigner assign) noexcept { using i32 = int; Src* src_scanline = src.data; Dst* dst_scanline = dst.data; for(i32 y=src.h-1;y>=0;y--) { for(i32 x=src.w-1;x>=0;x--) { assign(src_scanline[x], dst_scanline[x]); } src_scanline += src.elements_per_scanline; dst_scanline += dst.elements_per_scanline; } } template<class Src, class Dst, class Assigner> void blit_in_place(bitmap<Src> src, bitmap<Dst> dst, Assigner assign) noexcept { if(src.data >= dst.data) { blit<Src, Dst, Assigner>(src, dst, assign); } else { blit_backwards<Src, Dst, Assigner>(src, dst, assign); } } } // namespace stx /* Copyright (c) 2018 Benno Straub 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. */ <commit_msg>stx/bitmap: nearest sampling now returns reference to pixel<commit_after>// Copyright (c) 2018 Benno Straub, licensed under the MIT license. (A copy can be found at the bottom of this file) // Utilities for 3d textures/voxel engines #pragma once #include <algorithm> #include <cmath> #include <cstddef> namespace stx { // == bitmap ================================================= /// Represents a subsection of bitmapped 2d array template<class T> struct bitmap { using u32 = unsigned; using i32 = int; T* data; u32 w, h; u32 elements_per_scanline; constexpr bitmap(T* data = nullptr, u32 w = 0, u32 h = 0) noexcept; constexpr bitmap(T* data, u32 w, u32 h, u32 elements_per_scanline) noexcept; constexpr bitmap<T> subimage(u32 w, u32 h) noexcept; constexpr bitmap<T> subimage(i32 x, i32 y, u32 w, u32 h) noexcept; template<class Callback> void each(Callback&& callback) { T* scanline = data; for(u32 y = 0; y < h; y++) { for(u32 x = 0; x < w; x++) { callback(scanline[x]); } scanline += elements_per_scanline; } } constexpr i32 index(i32 x, i32 y) const noexcept { return x + y * elements_per_scanline; } constexpr T& operator()(i32 x, i32 y) const noexcept { return data[index(x, y)]; } constexpr u32 area() const noexcept { return w * h; } }; // == Blitting ================================================= /// Copies one bitmap to another // The destination bitmap should not overlap with the source bitmap! (use blit_in_place for that) template<class Src, class Dst, class Assigner = void(*)(Src&,Dst&)> void blit( bitmap<Src> src, bitmap<Dst> dst, Assigner assign = [](Src&a,Dst&b){b=std::move(a);}) noexcept; /// Copies one bitmap to another // The destination bitmap should not overlap with the source bitmap! (use blit_in_place for that) template<class Src, class Dst, class Assigner = void(*)(Src&,Dst&)> void blit_backwards( bitmap<Src> src, bitmap<Dst> dst, Assigner assign = [](Src&a,Dst&b){b=std::move(a);}) noexcept; /// Copies one bitmap to another /// The destination bitmap may overlap with the source bitmap /// If this is not needed use blit, because it has better memory access patterns template<class Src, class Dst, class Assigner = void(*)(Src&,Dst&)> void blit_in_place( bitmap<Src> src, bitmap<Dst> dst, Assigner assign = [](Src&a,Dst&b){b=std::move(a);}) noexcept; // == Sampling ================================================== template<class T> T& sample_nearest(stx::bitmap<T> src, float x, float y) { unsigned ux = std::clamp<float>(std::round(x * (src.w - 1)), 0, src.w - 1); unsigned uy = std::clamp<float>(std::round(y * (src.h - 1)), 0, src.h - 1); return src(ux, uy); } } // namespace stx // ============================================================= // == Inline Implementation ============================================= // ============================================================= namespace stx { // -- bitmap ------------------------------------------------------- template<class T> constexpr bitmap<T>::bitmap(T* data, u32 w, u32 h) noexcept : data(data), w(w), h(h), elements_per_scanline(w) {} template<class T> constexpr bitmap<T>::bitmap( T* data, u32 w, u32 h, u32 elements_per_scanline) noexcept : data(data), w(w), h(h), elements_per_scanline(elements_per_scanline) {} template<class T> constexpr bitmap<T> bitmap<T>::subimage(u32 w, u32 h) noexcept { return bitmap<T>(data, w, h, elements_per_scanline); } template<class T> constexpr bitmap<T> bitmap<T>::subimage(i32 x, i32 y, u32 w, u32 h) noexcept { return bitmap<T>(data + index(x, y), w, h, elements_per_scanline); } // -- Blitting ------------------------------------------------------- template<class Src, class Dst, class Assigner> void blit(bitmap<Src> src, bitmap<Dst> dst, Assigner assign) noexcept { using u32 = unsigned; Src* src_scanline = src.data; Dst* dst_scanline = dst.data; for(u32 y=0;y<src.h;y++) { for(u32 x=0;x<src.w;x++) { assign(src_scanline[x], dst_scanline[x]); } src_scanline += src.elements_per_scanline; dst_scanline += dst.elements_per_scanline; } } template<class Src, class Dst, class Assigner> void blit_backwards(bitmap<Src> src, bitmap<Dst> dst, Assigner assign) noexcept { using i32 = int; Src* src_scanline = src.data; Dst* dst_scanline = dst.data; for(i32 y=src.h-1;y>=0;y--) { for(i32 x=src.w-1;x>=0;x--) { assign(src_scanline[x], dst_scanline[x]); } src_scanline += src.elements_per_scanline; dst_scanline += dst.elements_per_scanline; } } template<class Src, class Dst, class Assigner> void blit_in_place(bitmap<Src> src, bitmap<Dst> dst, Assigner assign) noexcept { if(src.data >= dst.data) { blit<Src, Dst, Assigner>(src, dst, assign); } else { blit_backwards<Src, Dst, Assigner>(src, dst, assign); } } } // namespace stx /* Copyright (c) 2018 Benno Straub 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. */ <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "InactivityMonitor.h" #include "ReadChecker.h" #include "WriteChecker.h" #include <activemq/threads/CompositeTask.h> #include <activemq/threads/CompositeTaskRunner.h> #include <activemq/commands/WireFormatInfo.h> #include <activemq/commands/KeepAliveInfo.h> #include <decaf/util/Timer.h> #include <decaf/util/concurrent/atomic/AtomicBoolean.h> #include <decaf/util/concurrent/atomic/AtomicInteger.h> #include <decaf/lang/Math.h> #include <decaf/lang/Thread.h> #include <decaf/lang/Runnable.h> #include <decaf/lang/Boolean.h> using namespace std; using namespace activemq; using namespace activemq::commands; using namespace activemq::threads; using namespace activemq::transport; using namespace activemq::transport::inactivity; using namespace activemq::exceptions; using namespace activemq::wireformat; using namespace decaf; using namespace decaf::io; using namespace decaf::util; using namespace decaf::util::concurrent; using namespace decaf::util::concurrent::atomic; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// namespace activemq{ namespace transport{ namespace inactivity{ class InactivityMonitorData { private: InactivityMonitorData(const InactivityMonitorData&); InactivityMonitorData operator=(const InactivityMonitorData&); public: // The configured WireFormat for the Transport Chain. Pointer<WireFormat> wireFormat; // Local and Remote WireFormat information. Pointer<WireFormatInfo> localWireFormatInfo; Pointer<WireFormatInfo> remoteWireFormatInfo; Pointer<ReadChecker> readCheckerTask; Pointer<WriteChecker> writeCheckerTask; Timer readCheckTimer; Timer writeCheckTimer; Pointer<CompositeTaskRunner> asyncTasks; Pointer<AsyncSignalReadErrorkTask> asyncReadTask; Pointer<AsyncWriteTask> asyncWriteTask; AtomicBoolean monitorStarted; AtomicBoolean commandSent; AtomicBoolean commandReceived; AtomicBoolean failed; AtomicBoolean inRead; AtomicBoolean inWrite; Mutex inWriteMutex; Mutex monitor; long long readCheckTime; long long writeCheckTime; long long initialDelayTime; bool keepAliveResponseRequired; InactivityMonitorData() : wireFormat(), localWireFormatInfo(), remoteWireFormatInfo(), readCheckerTask(), writeCheckerTask(), readCheckTimer("InactivityMonitor Read Check Timer"), writeCheckTimer("InactivityMonitor Write Check Timer"), asyncTasks(), asyncReadTask(), asyncWriteTask(), monitorStarted(), commandSent(), commandReceived(), failed(), inRead(), inWrite(), inWriteMutex(), monitor(), readCheckTime(0), writeCheckTime(0), initialDelayTime(0), keepAliveResponseRequired(false) { } }; // Task that fires when the TaskRunner is signaled by the ReadCheck Timer Task. class AsyncSignalReadErrorkTask : public CompositeTask { private: InactivityMonitor* parent; std::string remote; AtomicBoolean failed; private: AsyncSignalReadErrorkTask(const AsyncSignalReadErrorkTask&); AsyncSignalReadErrorkTask operator=(const AsyncSignalReadErrorkTask&); public: AsyncSignalReadErrorkTask(InactivityMonitor* parent, const std::string& remote) : parent(parent), remote(remote), failed() { } void setFailed(bool failed) { this->failed.set(failed); } virtual bool isPending() const { return this->failed.get(); } virtual bool iterate() { if (this->failed.compareAndSet(true, false)) { IOException ex(__FILE__, __LINE__, (std::string("Channel was inactive for too long: ") + remote).c_str()); this->parent->onException(ex); } return this->failed.get(); } }; // Task that fires when the TaskRunner is signaled by the WriteCheck Timer Task. class AsyncWriteTask : public CompositeTask { private: InactivityMonitor* parent; AtomicBoolean write; private: AsyncWriteTask(const AsyncWriteTask&); AsyncWriteTask operator=(const AsyncWriteTask&); public: AsyncWriteTask(InactivityMonitor* parent) : parent(parent), write() {} void setWrite( bool write ) { this->write.set( write ); } virtual bool isPending() const { return this->write.get(); } virtual bool iterate() { if (this->write.compareAndSet(true, false) && this->parent->members->monitorStarted.get()) { try { Pointer<KeepAliveInfo> info(new KeepAliveInfo()); info->setResponseRequired(this->parent->members->keepAliveResponseRequired); this->parent->oneway(info); } catch (IOException& e) { this->parent->onException(e); } } return this->write.get(); } }; }}} //////////////////////////////////////////////////////////////////////////////// InactivityMonitor::InactivityMonitor(const Pointer<Transport> next, const Pointer<WireFormat> wireFormat) : TransportFilter(next), members(new InactivityMonitorData()) { this->members->wireFormat = wireFormat; this->members->monitorStarted.set(false); this->members->commandSent.set(false); this->members->commandReceived.set(true); this->members->failed.set(false); this->members->inRead.set(false); this->members->inWrite.set(false); this->members->readCheckTime = 0; this->members->writeCheckTime = 0; this->members->initialDelayTime = 0; this->members->keepAliveResponseRequired = false; } //////////////////////////////////////////////////////////////////////////////// InactivityMonitor::InactivityMonitor(const Pointer<Transport> next, const decaf::util::Properties& properties, const Pointer<wireformat::WireFormat> wireFormat) : TransportFilter(next), members(new InactivityMonitorData()) { this->members->wireFormat = wireFormat; this->members->monitorStarted.set(false); this->members->commandSent.set(false); this->members->commandReceived.set(true); this->members->failed.set(false); this->members->inRead.set(false); this->members->inWrite.set(false); this->members->readCheckTime = 0; this->members->writeCheckTime = 0; this->members->initialDelayTime = 0; this->members->keepAliveResponseRequired = Boolean::parseBoolean(properties.getProperty("keepAliveResponseRequired", "false")); } //////////////////////////////////////////////////////////////////////////////// InactivityMonitor::~InactivityMonitor() { try { this->stopMonitorThreads(); } AMQ_CATCHALL_NOTHROW() try { delete this->members; } AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// long long InactivityMonitor::getReadCheckTime() const { return this->members->readCheckTime; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::setReadCheckTime(long long value) { this->members->readCheckTime = value; } //////////////////////////////////////////////////////////////////////////////// long long InactivityMonitor::getWriteCheckTime() const { return this->members->writeCheckTime; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::setWriteCheckTime(long long value) { this->members->writeCheckTime = value; } //////////////////////////////////////////////////////////////////////////////// long long InactivityMonitor::getInitialDelayTime() const { return this->members->initialDelayTime; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::setInitialDelayTime(long long value) const { this->members->initialDelayTime = value; } //////////////////////////////////////////////////////////////////////////////// bool InactivityMonitor::isKeepAliveResponseRequired() const { return this->members->keepAliveResponseRequired; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::setKeepAliveResponseRequired(bool value) { this->members->keepAliveResponseRequired = value; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::close() { try { setTransportListener(NULL); stopMonitorThreads(); TransportFilter::close(); } AMQ_CATCH_RETHROW(IOException) AMQ_CATCH_EXCEPTION_CONVERT(Exception, IOException) AMQ_CATCHALL_THROW(IOException) } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::onException(const decaf::lang::Exception& ex) { if (this->members->failed.compareAndSet(false, true)) { stopMonitorThreads(); TransportFilter::onException(ex); } } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::onCommand(const Pointer<Command> command) { this->members->commandReceived.set(true); this->members->inRead.set(true); try { if (command->isWireFormatInfo()) { synchronized(&this->members->monitor) { this->members->remoteWireFormatInfo = command.dynamicCast<WireFormatInfo>(); try { startMonitorThreads(); } catch (IOException& e) { onException(e); } } } TransportFilter::onCommand(command); this->members->inRead.set(false); } catch (Exception& ex) { this->members->inRead.set(false); ex.setMark(__FILE__, __LINE__); throw ex; } } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::oneway(const Pointer<Command> command) { try { // Disable inactivity monitoring while processing a command. Synchronize this // method - its not synchronized further down the transport stack and gets called // by more than one thread by this class synchronized(&this->members->inWriteMutex) { this->members->inWrite.set(true); try { if (this->members->failed.get()) { throw IOException(__FILE__, __LINE__, (std::string("Channel was inactive for too long: ") + next->getRemoteAddress()).c_str()); } if (command->isWireFormatInfo()) { synchronized( &this->members->monitor ) { this->members->localWireFormatInfo = command.dynamicCast<WireFormatInfo>(); startMonitorThreads(); } } this->next->oneway(command); this->members->commandSent.set(true); this->members->inWrite.set(false); } catch (Exception& ex) { this->members->commandSent.set(true); this->members->inWrite.set(false); ex.setMark(__FILE__, __LINE__); throw ex; } } } AMQ_CATCH_RETHROW(IOException) AMQ_CATCH_RETHROW(UnsupportedOperationException) AMQ_CATCH_EXCEPTION_CONVERT(Exception, IOException) AMQ_CATCHALL_THROW(IOException) } //////////////////////////////////////////////////////////////////////////////// bool InactivityMonitor::allowReadCheck(long long elapsed) { return elapsed > (this->members->readCheckTime * 9 / 10); } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::readCheck() { if (this->members->inRead.get() || this->members->wireFormat->inReceive()) { return; } if (!this->members->commandReceived.get()) { // Set the failed state on our async Read Failure Task and wakeup its runner. this->members->asyncReadTask->setFailed(true); this->members->asyncTasks->wakeup(); } this->members->commandReceived.set(false); } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::writeCheck() { if (this->members->inWrite.get()) { return; } if (!this->members->commandSent.get()) { this->members->asyncWriteTask->setWrite(true); this->members->asyncTasks->wakeup(); } this->members->commandSent.set(false); } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::startMonitorThreads() { synchronized( &this->members->monitor ) { if (this->members->monitorStarted.get()) { return; } if (this->members->localWireFormatInfo == NULL) { return; } if (this->members->remoteWireFormatInfo == NULL) { return; } this->members->asyncTasks.reset(new CompositeTaskRunner()); this->members->asyncReadTask.reset(new AsyncSignalReadErrorkTask(this, this->getRemoteAddress())); this->members->asyncWriteTask.reset(new AsyncWriteTask(this)); this->members->asyncTasks->addTask(this->members->asyncReadTask.get()); this->members->asyncTasks->addTask(this->members->asyncWriteTask.get()); this->members->readCheckTime = Math::min(this->members->localWireFormatInfo->getMaxInactivityDuration(), this->members->remoteWireFormatInfo->getMaxInactivityDuration()); this->members->initialDelayTime = Math::min(this->members->localWireFormatInfo->getMaxInactivityDurationInitalDelay(), this->members->remoteWireFormatInfo->getMaxInactivityDurationInitalDelay()); if (this->members->readCheckTime > 0) { this->members->monitorStarted.set(true); this->members->writeCheckerTask.reset(new WriteChecker(this)); this->members->readCheckerTask.reset(new ReadChecker(this)); this->members->writeCheckTime = this->members->readCheckTime > 3 ? this->members->readCheckTime / 3 : this->members->readCheckTime; this->members->writeCheckTimer.scheduleAtFixedRate(this->members->writeCheckerTask, this->members->initialDelayTime, this->members->writeCheckTime); this->members->readCheckTimer.scheduleAtFixedRate(this->members->readCheckerTask, this->members->initialDelayTime, this->members->readCheckTime); } } } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::stopMonitorThreads() { synchronized(&this->members->monitor) { if (this->members->monitorStarted.compareAndSet(true, false)) { this->members->readCheckerTask->cancel(); this->members->writeCheckerTask->cancel(); this->members->readCheckTimer.purge(); this->members->readCheckTimer.cancel(); this->members->writeCheckTimer.purge(); this->members->writeCheckTimer.cancel(); this->members->asyncTasks->shutdown(); } } } <commit_msg>https://issues.apache.org/jira/browse/AMQCPP-454<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "InactivityMonitor.h" #include "ReadChecker.h" #include "WriteChecker.h" #include <activemq/threads/CompositeTask.h> #include <activemq/threads/CompositeTaskRunner.h> #include <activemq/commands/WireFormatInfo.h> #include <activemq/commands/KeepAliveInfo.h> #include <decaf/util/Timer.h> #include <decaf/util/concurrent/atomic/AtomicBoolean.h> #include <decaf/util/concurrent/atomic/AtomicInteger.h> #include <decaf/lang/Math.h> #include <decaf/lang/Thread.h> #include <decaf/lang/Runnable.h> #include <decaf/lang/Boolean.h> using namespace std; using namespace activemq; using namespace activemq::commands; using namespace activemq::threads; using namespace activemq::transport; using namespace activemq::transport::inactivity; using namespace activemq::exceptions; using namespace activemq::wireformat; using namespace decaf; using namespace decaf::io; using namespace decaf::util; using namespace decaf::util::concurrent; using namespace decaf::util::concurrent::atomic; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// namespace activemq{ namespace transport{ namespace inactivity{ class InactivityMonitorData { private: InactivityMonitorData(const InactivityMonitorData&); InactivityMonitorData operator=(const InactivityMonitorData&); public: // The configured WireFormat for the Transport Chain. Pointer<WireFormat> wireFormat; // Local and Remote WireFormat information. Pointer<WireFormatInfo> localWireFormatInfo; Pointer<WireFormatInfo> remoteWireFormatInfo; Pointer<ReadChecker> readCheckerTask; Pointer<WriteChecker> writeCheckerTask; Timer readCheckTimer; Timer writeCheckTimer; Pointer<CompositeTaskRunner> asyncTasks; Pointer<AsyncSignalReadErrorkTask> asyncReadTask; Pointer<AsyncWriteTask> asyncWriteTask; AtomicBoolean monitorStarted; AtomicBoolean commandSent; AtomicBoolean commandReceived; AtomicBoolean failed; AtomicBoolean inRead; AtomicBoolean inWrite; Mutex inWriteMutex; Mutex monitor; long long readCheckTime; long long writeCheckTime; long long initialDelayTime; bool keepAliveResponseRequired; InactivityMonitorData() : wireFormat(), localWireFormatInfo(), remoteWireFormatInfo(), readCheckerTask(), writeCheckerTask(), readCheckTimer("InactivityMonitor Read Check Timer"), writeCheckTimer("InactivityMonitor Write Check Timer"), asyncTasks(), asyncReadTask(), asyncWriteTask(), monitorStarted(), commandSent(), commandReceived(), failed(), inRead(), inWrite(), inWriteMutex(), monitor(), readCheckTime(0), writeCheckTime(0), initialDelayTime(0), keepAliveResponseRequired(false) { } }; // Task that fires when the TaskRunner is signaled by the ReadCheck Timer Task. class AsyncSignalReadErrorkTask : public CompositeTask { private: InactivityMonitor* parent; std::string remote; AtomicBoolean failed; private: AsyncSignalReadErrorkTask(const AsyncSignalReadErrorkTask&); AsyncSignalReadErrorkTask operator=(const AsyncSignalReadErrorkTask&); public: AsyncSignalReadErrorkTask(InactivityMonitor* parent, const std::string& remote) : parent(parent), remote(remote), failed() { } void setFailed(bool failed) { this->failed.set(failed); } virtual bool isPending() const { return this->failed.get(); } virtual bool iterate() { if (this->failed.compareAndSet(true, false)) { IOException ex(__FILE__, __LINE__, (std::string("Channel was inactive for too long: ") + remote).c_str()); this->parent->onException(ex); } return this->failed.get(); } }; // Task that fires when the TaskRunner is signaled by the WriteCheck Timer Task. class AsyncWriteTask : public CompositeTask { private: InactivityMonitor* parent; AtomicBoolean write; private: AsyncWriteTask(const AsyncWriteTask&); AsyncWriteTask operator=(const AsyncWriteTask&); public: AsyncWriteTask(InactivityMonitor* parent) : parent(parent), write() {} void setWrite( bool write ) { this->write.set( write ); } virtual bool isPending() const { return this->write.get(); } virtual bool iterate() { if (this->write.compareAndSet(true, false) && this->parent->members->monitorStarted.get()) { try { Pointer<KeepAliveInfo> info(new KeepAliveInfo()); info->setResponseRequired(this->parent->members->keepAliveResponseRequired); this->parent->oneway(info); } catch (IOException& e) { this->parent->onException(e); } } return this->write.get(); } }; }}} //////////////////////////////////////////////////////////////////////////////// InactivityMonitor::InactivityMonitor(const Pointer<Transport> next, const Pointer<WireFormat> wireFormat) : TransportFilter(next), members(new InactivityMonitorData()) { this->members->wireFormat = wireFormat; this->members->monitorStarted.set(false); this->members->commandSent.set(false); this->members->commandReceived.set(true); this->members->failed.set(false); this->members->inRead.set(false); this->members->inWrite.set(false); this->members->readCheckTime = 0; this->members->writeCheckTime = 0; this->members->initialDelayTime = 0; this->members->keepAliveResponseRequired = false; } //////////////////////////////////////////////////////////////////////////////// InactivityMonitor::InactivityMonitor(const Pointer<Transport> next, const decaf::util::Properties& properties, const Pointer<wireformat::WireFormat> wireFormat) : TransportFilter(next), members(new InactivityMonitorData()) { this->members->wireFormat = wireFormat; this->members->monitorStarted.set(false); this->members->commandSent.set(false); this->members->commandReceived.set(true); this->members->failed.set(false); this->members->inRead.set(false); this->members->inWrite.set(false); this->members->readCheckTime = 0; this->members->writeCheckTime = 0; this->members->initialDelayTime = 0; this->members->keepAliveResponseRequired = Boolean::parseBoolean(properties.getProperty("keepAliveResponseRequired", "false")); } //////////////////////////////////////////////////////////////////////////////// InactivityMonitor::~InactivityMonitor() { try { this->stopMonitorThreads(); } AMQ_CATCHALL_NOTHROW() try { delete this->members; } AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// long long InactivityMonitor::getReadCheckTime() const { return this->members->readCheckTime; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::setReadCheckTime(long long value) { this->members->readCheckTime = value; } //////////////////////////////////////////////////////////////////////////////// long long InactivityMonitor::getWriteCheckTime() const { return this->members->writeCheckTime; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::setWriteCheckTime(long long value) { this->members->writeCheckTime = value; } //////////////////////////////////////////////////////////////////////////////// long long InactivityMonitor::getInitialDelayTime() const { return this->members->initialDelayTime; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::setInitialDelayTime(long long value) const { this->members->initialDelayTime = value; } //////////////////////////////////////////////////////////////////////////////// bool InactivityMonitor::isKeepAliveResponseRequired() const { return this->members->keepAliveResponseRequired; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::setKeepAliveResponseRequired(bool value) { this->members->keepAliveResponseRequired = value; } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::close() { try { setTransportListener(NULL); stopMonitorThreads(); TransportFilter::close(); } AMQ_CATCH_RETHROW(IOException) AMQ_CATCH_EXCEPTION_CONVERT(Exception, IOException) AMQ_CATCHALL_THROW(IOException) } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::onException(const decaf::lang::Exception& ex) { if (this->members->failed.compareAndSet(false, true)) { stopMonitorThreads(); TransportFilter::onException(ex); } } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::onCommand(const Pointer<Command> command) { this->members->commandReceived.set(true); this->members->inRead.set(true); try { if (command->isWireFormatInfo()) { synchronized(&this->members->monitor) { this->members->remoteWireFormatInfo = command.dynamicCast<WireFormatInfo>(); try { startMonitorThreads(); } catch (IOException& e) { onException(e); } } } TransportFilter::onCommand(command); this->members->inRead.set(false); } catch (Exception& ex) { this->members->inRead.set(false); ex.setMark(__FILE__, __LINE__); throw ex; } } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::oneway(const Pointer<Command> command) { try { // Disable inactivity monitoring while processing a command. Synchronize this // method - its not synchronized further down the transport stack and gets called // by more than one thread by this class synchronized(&this->members->inWriteMutex) { this->members->inWrite.set(true); try { if (this->members->failed.get()) { throw IOException(__FILE__, __LINE__, (std::string("Channel was inactive for too long: ") + next->getRemoteAddress()).c_str()); } if (command->isWireFormatInfo()) { synchronized( &this->members->monitor ) { this->members->localWireFormatInfo = command.dynamicCast<WireFormatInfo>(); startMonitorThreads(); } } this->next->oneway(command); this->members->commandSent.set(true); this->members->inWrite.set(false); } catch (Exception& ex) { this->members->commandSent.set(true); this->members->inWrite.set(false); ex.setMark(__FILE__, __LINE__); throw ex; } } } AMQ_CATCH_RETHROW(IOException) AMQ_CATCH_RETHROW(UnsupportedOperationException) AMQ_CATCH_EXCEPTION_CONVERT(Exception, IOException) AMQ_CATCHALL_THROW(IOException) } //////////////////////////////////////////////////////////////////////////////// bool InactivityMonitor::allowReadCheck(long long elapsed) { return elapsed > (this->members->readCheckTime * 9 / 10); } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::readCheck() { if (this->members->inRead.get() || this->members->wireFormat->inReceive()) { return; } if (!this->members->commandReceived.get()) { // Set the failed state on our async Read Failure Task and wakeup its runner. this->members->asyncReadTask->setFailed(true); this->members->asyncTasks->wakeup(); } this->members->commandReceived.set(false); } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::writeCheck() { if (this->members->inWrite.get()) { return; } if (!this->members->commandSent.get()) { this->members->asyncWriteTask->setWrite(true); this->members->asyncTasks->wakeup(); } this->members->commandSent.set(false); } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::startMonitorThreads() { synchronized( &this->members->monitor ) { if (this->members->monitorStarted.get()) { return; } if (this->members->localWireFormatInfo == NULL) { return; } if (this->members->remoteWireFormatInfo == NULL) { return; } this->members->asyncTasks.reset(new CompositeTaskRunner()); this->members->asyncReadTask.reset(new AsyncSignalReadErrorkTask(this, this->getRemoteAddress())); this->members->asyncWriteTask.reset(new AsyncWriteTask(this)); this->members->asyncTasks->addTask(this->members->asyncReadTask.get()); this->members->asyncTasks->addTask(this->members->asyncWriteTask.get()); this->members->readCheckTime = Math::min(this->members->localWireFormatInfo->getMaxInactivityDuration(), this->members->remoteWireFormatInfo->getMaxInactivityDuration()); this->members->initialDelayTime = Math::min(this->members->localWireFormatInfo->getMaxInactivityDurationInitalDelay(), this->members->remoteWireFormatInfo->getMaxInactivityDurationInitalDelay()); if (this->members->readCheckTime > 0) { this->members->monitorStarted.set(true); this->members->writeCheckerTask.reset(new WriteChecker(this)); this->members->readCheckerTask.reset(new ReadChecker(this)); this->members->writeCheckTime = this->members->readCheckTime > 3 ? this->members->readCheckTime / 3 : this->members->readCheckTime; this->members->writeCheckTimer.scheduleAtFixedRate(this->members->writeCheckerTask, this->members->initialDelayTime, this->members->writeCheckTime); this->members->readCheckTimer.scheduleAtFixedRate(this->members->readCheckerTask, this->members->initialDelayTime, this->members->readCheckTime); } } } //////////////////////////////////////////////////////////////////////////////// void InactivityMonitor::stopMonitorThreads() { if (this->members == NULL) { return; } synchronized(&this->members->monitor) { if (this->members->monitorStarted.compareAndSet(true, false)) { this->members->readCheckerTask->cancel(); this->members->writeCheckerTask->cancel(); this->members->readCheckTimer.purge(); this->members->readCheckTimer.cancel(); this->members->writeCheckTimer.purge(); this->members->writeCheckTimer.cancel(); this->members->asyncTasks->shutdown(); } } } <|endoftext|>
<commit_before>/** * @file LLSaleInfo_tut.cpp * @author Adroit * @date 2007-03 * @brief Test cases of llsaleinfo.h * * $LicenseInfo:firstyear=2007&license=viewergpl$ * * Copyright (c) 2007-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include <tut/tut.hpp> #include "linden_common.h" #include "lltut.h" #include "llsaleinfo.h" namespace tut { struct llsaleinfo_tut { }; typedef test_group<llsaleinfo_tut> llsaleinfo_tut_t; typedef llsaleinfo_tut_t::object llsaleinfo_test_t; tut::llsaleinfo_tut_t tut_llsaleinfo_test("llsaleinfo"); template<> template<> void llsaleinfo_test_t::test<1>() { //test case for getSaleType(), getSalePrice(), getCRC32() fn. //test case for setSaleType(), setSalePrice() fn. S32 sale_price = 10000; LLSaleInfo llsaleinfo(LLSaleInfo::FS_COPY, sale_price); char* sale= "copy"; LLSD llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); LLSaleInfo saleinfo1 = ll_sale_info_from_sd(llsd_obj1); ensure("1. The getSaleType() fn failed", LLSaleInfo::FS_COPY == llsaleinfo.getSaleType()); ensure("2. LLSaleInfo::isForSale() fn failed", TRUE == llsaleinfo.isForSale()); ensure("3. The getSalePrice() fn failed", sale_price == llsaleinfo.getSalePrice()); ensure("4. The getCRC32() fn failed", 235833404 == llsaleinfo.getCRC32()); ensure("5. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_COPY == llsaleinfo.lookup(sale)); ensure_equals("6. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("7. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); llsaleinfo.setSalePrice(10000000); llsaleinfo.setSaleType(LLSaleInfo::FS_ORIGINAL); sale = "cntn"; llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); saleinfo1 = ll_sale_info_from_sd(llsd_obj1); ensure("8. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_ORIGINAL == llsaleinfo.getSaleType()); ensure("9. LLSaleInfo::isForSale() fn failed", TRUE == llsaleinfo.isForSale()); ensure("10. The getSalePrice() fn failed", 10000000 == llsaleinfo.getSalePrice()); ensure("11. The getCRC32() fn failed", 127911702 == llsaleinfo.getCRC32()); ensure("12. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_CONTENTS == llsaleinfo.lookup(sale)); ensure_equals("13. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("14. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); llsaleinfo.setSalePrice(55000550); llsaleinfo.setSaleType(LLSaleInfo::FS_CONTENTS); sale = "orig"; llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); saleinfo1 = ll_sale_info_from_sd(llsd_obj1); ensure("15. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_CONTENTS == llsaleinfo.getSaleType()); ensure("16. LLSaleInfo::isForSale() fn failed", TRUE == llsaleinfo.isForSale()); ensure("17. The getSalePrice() fn failed", 55000550 == llsaleinfo.getSalePrice()); ensure("18. The getCRC32() fn failed", 408735656 == llsaleinfo.getCRC32()); ensure("19. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_ORIGINAL == llsaleinfo.lookup(sale)); ensure_equals("20. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("21. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); llsaleinfo.setSalePrice(-6432); llsaleinfo.setSaleType(LLSaleInfo::FS_NOT); sale = "not"; llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); saleinfo1 = ll_sale_info_from_sd(llsd_obj1); ensure("22. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_NOT == llsaleinfo.getSaleType()); ensure("23. LLSaleInfo::isForSale() fn failed", FALSE == llsaleinfo.isForSale()); ensure("24. The getSalePrice() fn failed", 0 == llsaleinfo.getSalePrice()); ensure("25. The getCRC32() fn failed", 0 == llsaleinfo.getCRC32()); ensure("26. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_NOT == llsaleinfo.lookup(sale)); ensure_equals("27. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("28. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); } template<> template<> void llsaleinfo_test_t::test<2>() { LLFILE* fp = LLFile::fopen("linden_file.dat","w+"); if(!fp) { llerrs << "file could not be opened\n" << llendl; return; } S32 sale_price = 43500; LLSaleInfo llsaleinfo(LLSaleInfo::FS_COPY, sale_price); llsaleinfo.exportFile(fp); fclose(fp); LLSaleInfo llsaleinfo1; U32 perm_mask; BOOL has_perm_mask; fp = LLFile::fopen("linden_file.dat","r"); if(!fp) { llerrs << "file coudnt be opened\n" << llendl; return; } llsaleinfo1.importFile(fp, has_perm_mask, perm_mask); fclose(fp); ensure("importFile() fn failed ", llsaleinfo.getSaleType() == llsaleinfo1.getSaleType() && llsaleinfo.getSalePrice() == llsaleinfo1.getSalePrice()); } template<> template<> void llsaleinfo_test_t::test<3>() { S32 sale_price = 525452; LLSaleInfo llsaleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); std::ostringstream ostream; llsaleinfo.exportLegacyStream(ostream); std::istringstream istream(ostream.str()); LLSaleInfo llsaleinfo1; U32 perm_mask = 0; BOOL has_perm_mask = FALSE; llsaleinfo1.importLegacyStream(istream, has_perm_mask, perm_mask); ensure("importLegacyStream() fn failed ", llsaleinfo.getSalePrice() == llsaleinfo1.getSalePrice() && llsaleinfo.getSaleType() == llsaleinfo1.getSaleType()); } template<> template<> void llsaleinfo_test_t::test<4>() { // LLXMLNode is teh suck. #if 0 S32 sale_price = 23445; LLSaleInfo saleinfo(LLSaleInfo::FS_CONTENTS, sale_price); LLXMLNode* x_node = saleinfo.exportFileXML(); LLSaleInfo saleinfo1(LLSaleInfo::FS_NOT, 0); saleinfo1.importXML(x_node); ensure_equals("1.importXML() fn failed", saleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("2.importXML() fn failed", saleinfo.getSaleType(), saleinfo1.getSaleType()); #endif } template<> template<> void llsaleinfo_test_t::test<5>() { S32 sale_price = 99000; LLSaleInfo saleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); LLSD sd_result = saleinfo.asLLSD(); U32 perm_mask = 0 ; BOOL has_perm_mask = FALSE; LLSaleInfo saleinfo1; saleinfo1.fromLLSD( sd_result, has_perm_mask, perm_mask); ensure_equals("asLLSD and fromLLSD failed", saleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("asLLSD and fromLLSD failed", saleinfo.getSaleType(), saleinfo1.getSaleType()); } //static EForSale lookup(const char* name) fn test template<> template<> void llsaleinfo_test_t::test<6>() { S32 sale_price = 233223; LLSaleInfo::EForSale ret_type = LLSaleInfo::lookup("orig"); ensure_equals("lookup(const char* name) fn failed", ret_type, LLSaleInfo::FS_ORIGINAL); LLSaleInfo saleinfo(LLSaleInfo::FS_COPY, sale_price); const char* result = LLSaleInfo::lookup(LLSaleInfo::FS_COPY); ensure("char* lookup(EForSale type) fn failed", 0 == strcmp("copy", result)); } //void LLSaleInfo::accumulate(const LLSaleInfo& sale_info) fn test template<> template<> void llsaleinfo_test_t::test<7>() { S32 sale_price = 20; LLSaleInfo saleinfo(LLSaleInfo::FS_COPY, sale_price); LLSaleInfo saleinfo1(LLSaleInfo::FS_COPY, sale_price); saleinfo1.accumulate(saleinfo); ensure_equals("LLSaleInfo::accumulate(const LLSaleInfo& sale_info) fn failed", saleinfo1.getSalePrice(), 40); } // test cases of bool operator==(const LLSaleInfo &rhs) fn // test case of bool operator!=(const LLSaleInfo &rhs) fn template<> template<> void llsaleinfo_test_t::test<8>() { S32 sale_price = 55000; LLSaleInfo saleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); LLSaleInfo saleinfoequal(LLSaleInfo::FS_ORIGINAL, sale_price); LLSaleInfo saleinfonotequal(LLSaleInfo::FS_ORIGINAL, sale_price*2); ensure("operator == fn. failed", true == (saleinfo == saleinfoequal)); ensure("operator != fn. failed", true == (saleinfo != saleinfonotequal)); } template<> template<> void llsaleinfo_test_t::test<9>() { //TBD: void LLSaleInfo::packMessage(LLMessageSystem* msg) const //TBD: void LLSaleInfo::unpackMessage(LLMessageSystem* msg, const char* block) //TBD: void LLSaleInfo::unpackMultiMessage(LLMessageSystem* msg, const char* block, S32 block_num) } } <commit_msg>More build fixes<commit_after>/** * @file LLSaleInfo_tut.cpp * @author Adroit * @date 2007-03 * @brief Test cases of llsaleinfo.h * * $LicenseInfo:firstyear=2007&license=viewergpl$ * * Copyright (c) 2007-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include <tut/tut.hpp> #include "linden_common.h" #include "lltut.h" #include "llsaleinfo.h" namespace tut { struct llsaleinfo_tut { }; typedef test_group<llsaleinfo_tut> llsaleinfo_tut_t; typedef llsaleinfo_tut_t::object llsaleinfo_test_t; tut::llsaleinfo_tut_t tut_llsaleinfo_test("llsaleinfo"); template<> template<> void llsaleinfo_test_t::test<1>() { //test case for getSaleType(), getSalePrice(), getCRC32() fn. //test case for setSaleType(), setSalePrice() fn. S32 sale_price = 10000; LLSaleInfo llsaleinfo(LLSaleInfo::FS_COPY, sale_price); const char* sale= "copy"; LLSD llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); LLSaleInfo saleinfo1 = ll_sale_info_from_sd(llsd_obj1); ensure("1. The getSaleType() fn failed", LLSaleInfo::FS_COPY == llsaleinfo.getSaleType()); ensure("2. LLSaleInfo::isForSale() fn failed", TRUE == llsaleinfo.isForSale()); ensure("3. The getSalePrice() fn failed", sale_price == llsaleinfo.getSalePrice()); ensure("4. The getCRC32() fn failed", 235833404 == llsaleinfo.getCRC32()); ensure("5. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_COPY == llsaleinfo.lookup(sale)); ensure_equals("6. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("7. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); llsaleinfo.setSalePrice(10000000); llsaleinfo.setSaleType(LLSaleInfo::FS_ORIGINAL); sale = "cntn"; llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); saleinfo1 = ll_sale_info_from_sd(llsd_obj1); ensure("8. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_ORIGINAL == llsaleinfo.getSaleType()); ensure("9. LLSaleInfo::isForSale() fn failed", TRUE == llsaleinfo.isForSale()); ensure("10. The getSalePrice() fn failed", 10000000 == llsaleinfo.getSalePrice()); ensure("11. The getCRC32() fn failed", 127911702 == llsaleinfo.getCRC32()); ensure("12. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_CONTENTS == llsaleinfo.lookup(sale)); ensure_equals("13. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("14. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); llsaleinfo.setSalePrice(55000550); llsaleinfo.setSaleType(LLSaleInfo::FS_CONTENTS); sale = "orig"; llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); saleinfo1 = ll_sale_info_from_sd(llsd_obj1); ensure("15. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_CONTENTS == llsaleinfo.getSaleType()); ensure("16. LLSaleInfo::isForSale() fn failed", TRUE == llsaleinfo.isForSale()); ensure("17. The getSalePrice() fn failed", 55000550 == llsaleinfo.getSalePrice()); ensure("18. The getCRC32() fn failed", 408735656 == llsaleinfo.getCRC32()); ensure("19. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_ORIGINAL == llsaleinfo.lookup(sale)); ensure_equals("20. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("21. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); llsaleinfo.setSalePrice(-6432); llsaleinfo.setSaleType(LLSaleInfo::FS_NOT); sale = "not"; llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); saleinfo1 = ll_sale_info_from_sd(llsd_obj1); ensure("22. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_NOT == llsaleinfo.getSaleType()); ensure("23. LLSaleInfo::isForSale() fn failed", FALSE == llsaleinfo.isForSale()); ensure("24. The getSalePrice() fn failed", 0 == llsaleinfo.getSalePrice()); ensure("25. The getCRC32() fn failed", 0 == llsaleinfo.getCRC32()); ensure("26. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_NOT == llsaleinfo.lookup(sale)); ensure_equals("27. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("28. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); } template<> template<> void llsaleinfo_test_t::test<2>() { LLFILE* fp = LLFile::fopen("linden_file.dat","w+"); if(!fp) { llerrs << "file could not be opened\n" << llendl; return; } S32 sale_price = 43500; LLSaleInfo llsaleinfo(LLSaleInfo::FS_COPY, sale_price); llsaleinfo.exportFile(fp); fclose(fp); LLSaleInfo llsaleinfo1; U32 perm_mask; BOOL has_perm_mask; fp = LLFile::fopen("linden_file.dat","r"); if(!fp) { llerrs << "file coudnt be opened\n" << llendl; return; } llsaleinfo1.importFile(fp, has_perm_mask, perm_mask); fclose(fp); ensure("importFile() fn failed ", llsaleinfo.getSaleType() == llsaleinfo1.getSaleType() && llsaleinfo.getSalePrice() == llsaleinfo1.getSalePrice()); } template<> template<> void llsaleinfo_test_t::test<3>() { S32 sale_price = 525452; LLSaleInfo llsaleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); std::ostringstream ostream; llsaleinfo.exportLegacyStream(ostream); std::istringstream istream(ostream.str()); LLSaleInfo llsaleinfo1; U32 perm_mask = 0; BOOL has_perm_mask = FALSE; llsaleinfo1.importLegacyStream(istream, has_perm_mask, perm_mask); ensure("importLegacyStream() fn failed ", llsaleinfo.getSalePrice() == llsaleinfo1.getSalePrice() && llsaleinfo.getSaleType() == llsaleinfo1.getSaleType()); } template<> template<> void llsaleinfo_test_t::test<4>() { // LLXMLNode is teh suck. #if 0 S32 sale_price = 23445; LLSaleInfo saleinfo(LLSaleInfo::FS_CONTENTS, sale_price); LLXMLNode* x_node = saleinfo.exportFileXML(); LLSaleInfo saleinfo1(LLSaleInfo::FS_NOT, 0); saleinfo1.importXML(x_node); ensure_equals("1.importXML() fn failed", saleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("2.importXML() fn failed", saleinfo.getSaleType(), saleinfo1.getSaleType()); #endif } template<> template<> void llsaleinfo_test_t::test<5>() { S32 sale_price = 99000; LLSaleInfo saleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); LLSD sd_result = saleinfo.asLLSD(); U32 perm_mask = 0 ; BOOL has_perm_mask = FALSE; LLSaleInfo saleinfo1; saleinfo1.fromLLSD( sd_result, has_perm_mask, perm_mask); ensure_equals("asLLSD and fromLLSD failed", saleinfo.getSalePrice(), saleinfo1.getSalePrice()); ensure_equals("asLLSD and fromLLSD failed", saleinfo.getSaleType(), saleinfo1.getSaleType()); } //static EForSale lookup(const char* name) fn test template<> template<> void llsaleinfo_test_t::test<6>() { S32 sale_price = 233223; LLSaleInfo::EForSale ret_type = LLSaleInfo::lookup("orig"); ensure_equals("lookup(const char* name) fn failed", ret_type, LLSaleInfo::FS_ORIGINAL); LLSaleInfo saleinfo(LLSaleInfo::FS_COPY, sale_price); const char* result = LLSaleInfo::lookup(LLSaleInfo::FS_COPY); ensure("char* lookup(EForSale type) fn failed", 0 == strcmp("copy", result)); } //void LLSaleInfo::accumulate(const LLSaleInfo& sale_info) fn test template<> template<> void llsaleinfo_test_t::test<7>() { S32 sale_price = 20; LLSaleInfo saleinfo(LLSaleInfo::FS_COPY, sale_price); LLSaleInfo saleinfo1(LLSaleInfo::FS_COPY, sale_price); saleinfo1.accumulate(saleinfo); ensure_equals("LLSaleInfo::accumulate(const LLSaleInfo& sale_info) fn failed", saleinfo1.getSalePrice(), 40); } // test cases of bool operator==(const LLSaleInfo &rhs) fn // test case of bool operator!=(const LLSaleInfo &rhs) fn template<> template<> void llsaleinfo_test_t::test<8>() { S32 sale_price = 55000; LLSaleInfo saleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); LLSaleInfo saleinfoequal(LLSaleInfo::FS_ORIGINAL, sale_price); LLSaleInfo saleinfonotequal(LLSaleInfo::FS_ORIGINAL, sale_price*2); ensure("operator == fn. failed", true == (saleinfo == saleinfoequal)); ensure("operator != fn. failed", true == (saleinfo != saleinfonotequal)); } template<> template<> void llsaleinfo_test_t::test<9>() { //TBD: void LLSaleInfo::packMessage(LLMessageSystem* msg) const //TBD: void LLSaleInfo::unpackMessage(LLMessageSystem* msg, const char* block) //TBD: void LLSaleInfo::unpackMultiMessage(LLMessageSystem* msg, const char* block, S32 block_num) } } <|endoftext|>
<commit_before>/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/test/unit_test.hpp> #include "Model.hpp" static Implementation::Model* createBaseModel() { Implementation::Model* model = Abstract::makeModel<Implementation::Model>( MIN_WIDTH, MIN_HEIGHT, 0, 1 ); return model; } BOOST_AUTO_TEST_CASE (height_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT); delete model; } BOOST_AUTO_TEST_CASE (width_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getWidth() == MIN_WIDTH); delete model; } BOOST_AUTO_TEST_CASE (kill_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates(0, 0); model->createNewByCoordinates( coordinates, DEFAULT_MASS, 0, 0, 0 ); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::BACTERIUM); model->killByCoordinates(coordinates); state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); delete model; } <commit_msg>Model tests: add default args of createBaseModel()<commit_after>/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/test/unit_test.hpp> #include "Model.hpp" static Implementation::Model* createBaseModel( int bacteria = 0, int teams = 1 ) { Implementation::Model* model = Abstract::makeModel<Implementation::Model>( MIN_WIDTH, MIN_HEIGHT, bacteria, teams ); return model; } BOOST_AUTO_TEST_CASE (height_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT); delete model; } BOOST_AUTO_TEST_CASE (width_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getWidth() == MIN_WIDTH); delete model; } BOOST_AUTO_TEST_CASE (kill_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates(0, 0); model->createNewByCoordinates( coordinates, DEFAULT_MASS, 0, 0, 0 ); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::BACTERIUM); model->killByCoordinates(coordinates); state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); delete model; } <|endoftext|>
<commit_before>/* * A job that shall be executed in a worker thread. * * author: Max Kellermann <mk@cm4all.com> */ #ifndef BENG_PROXY_THREAD_JOB_HXX #define BENG_PROXY_THREAD_JOB_HXX #include <boost/intrusive/list.hpp> class ThreadJob : public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { public: enum class State { /** * The job is not in any queue. */ INITIAL, /** * The job has been added to the queue, but is not being worked on * yet. */ WAITING, /** * The job is being performed via run(). */ BUSY, /** * The job has finished, but the done() method has not been * invoked yet. */ DONE, }; State state = State::INITIAL; /** * Shall this job be enqueued again instead of invoking its done() * method? */ bool again = false; virtual void Run() = 0; virtual void Done() = 0; }; #endif <commit_msg>thread_job: add method IsIdle()<commit_after>/* * A job that shall be executed in a worker thread. * * author: Max Kellermann <mk@cm4all.com> */ #ifndef BENG_PROXY_THREAD_JOB_HXX #define BENG_PROXY_THREAD_JOB_HXX #include <boost/intrusive/list.hpp> class ThreadJob : public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { public: enum class State { /** * The job is not in any queue. */ INITIAL, /** * The job has been added to the queue, but is not being worked on * yet. */ WAITING, /** * The job is being performed via run(). */ BUSY, /** * The job has finished, but the done() method has not been * invoked yet. */ DONE, }; State state = State::INITIAL; /** * Shall this job be enqueued again instead of invoking its done() * method? */ bool again = false; /** * Is this job currently idle, i.e. not being worked on by a * worker thread? This method may be called only from the main * thread. A "true" return value guarantees that no worker thread * is and will be working on it, and its internal data structures * may be accessed without mutex protection. Use this method with * caution. */ bool IsIdle() const { return state == State::INITIAL; } virtual void Run() = 0; virtual void Done() = 0; }; #endif <|endoftext|>
<commit_before>/* * Blink * Turns on an LED on for one second, * then off for one second, repeatedly. */ #include "Arduino.h" #ifndef LED_BUILTIN #define LED_BUILTIN 13 #endif void setup() { // initialize LED digital pin as an output. pinMode(LED_BUILTIN, OUTPUT); } void loop() { // turn the LED on (HIGH is the voltage level) digitalWrite(LED_BUILTIN, HIGH); // wait for a second delay(1000); // turn the LED off by making the voltage LOW digitalWrite(LED_BUILTIN, LOW); // wait for a second delay(1000); } <commit_msg>decorate header comment<commit_after>/**************************************** * Blink * * Turns on an LED on for one second, * * then off for one second, repeatedly. * ****************************************/ #include "Arduino.h" #ifndef LED_BUILTIN #define LED_BUILTIN 13 #endif void setup() { // initialize LED digital pin as an output. pinMode(LED_BUILTIN, OUTPUT); } void loop() { // turn the LED on (HIGH is the voltage level) digitalWrite(LED_BUILTIN, HIGH); // wait for a second delay(1000); // turn the LED off by making the voltage LOW digitalWrite(LED_BUILTIN, LOW); // wait for a second delay(1000); } <|endoftext|>
<commit_before>// // trajectory.cpp // EpiGenMCMC // // Created by Lucy Li on 13/04/2016. // Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved. // #include "trajectory.h" void Trajectory::initialise_file (std::string filename, int every) { std::ofstream file(filename); file << "state"; if (num_groups > 1) { for (int i=0; i<num_groups; ++i) { for (int t=0; t<num_time_steps; t+=every) { file << "\tT" << t << "Group" << i; } } } else { for (int t=0; t<num_time_steps; t+=every) { file << "\tIncT" << t; } for (int t=0; t<num_time_steps; t+=every) { file << "\tPrevT" << t; } } file << std::endl; file.close(); } Trajectory::Trajectory() { trajectory.resize(1); trajectory2.resize(1); trajectory3.resize(1); initial_states.resize(1); recoveries.resize(1); states.resize(1); } Trajectory::Trajectory(int numT, int numGroups) { num_time_steps = numT; num_groups = numGroups; trajectory.resize(numT*numGroups); trajectory2.resize(numT); trajectory3.resize(numT); recoveries.resize(numT); // initialise_file(filename); } void Trajectory::resize(int length) { if (trajectory.size() != length) { trajectory.resize(length); trajectory2.resize(length); trajectory3.resize(length); } fill(trajectory.begin(), trajectory.end(), 0.0); fill(trajectory2.begin(), trajectory2.end(), 0.0); fill(trajectory3.begin(), trajectory3.end(), 0.0); // num_time_steps = length; } void Trajectory::resize(int length, int groups) { if (trajectory.size() != length*groups) { trajectory.resize(length*groups); trajectory2.resize(length); trajectory3.resize(length); } fill(trajectory.begin(), trajectory.end(), 0.0); fill(trajectory2.begin(), trajectory2.end(), 0.0); fill(trajectory3.begin(), trajectory3.end(), 0.0); // num_time_steps = length; } void Trajectory::print_to_file(int iteration, std::string filename, int every, bool sum_across) { std::ofstream file(filename, std::ios::app); file << iteration; int total_steps = (int) trajectory.size(); if (num_groups > 1) { for (int i=0; i<num_groups; ++i) { for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, iteration-t); ++j) { count += trajectory[i*num_time_steps+t+j]; } } else { count = trajectory[i*num_time_steps+t]; } file << "\t" << count; } } } else { for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, total_steps-t); ++j) { count += trajectory[t+j]; } } else { count = trajectory[t]; } file << "\t" << count; } for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, total_steps-t); ++j) { count += trajectory2[t+j]; } count /= (double) std::min(every, total_steps-t); } else { count = trajectory2[t]; } file << "\t" << (int)count; } } file << std::endl; file.close(); } void Trajectory::print_to_file(std::string filename, int every, bool sum_across) { std::ofstream file(filename, std::ios::app); int total_steps = (int) trajectory.size(); if (num_groups > 1) { for (int i=0; i<num_groups; ++i) { for (int t=0; t<num_time_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, total_steps-t); ++j) { count += trajectory[i*num_time_steps+t+j]; } } else { count = trajectory[i*num_time_steps+t]; } file << "\t" << count; } } } else { for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, num_time_steps-t); ++j) { count += trajectory[t+j]; } } else { count = trajectory[t]; } file << "\t" << count; } for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, num_time_steps-t); ++j) { count += trajectory2[t+j]; } count /= (double) std::min(every, num_time_steps-t); } else { count = trajectory2[t]; } file << "\t" << (int)count; } } file << std::endl; file.close(); } void Trajectory::initialise_states(std::string filename) { std::ifstream file(filename); double num; while (file >> num) { initial_states.push_back(num); states.push_back(num); } file.close(); } void Trajectory::initialise_states(std::vector<double>input_vector) { for (int i=0; i!=input_vector.size(); ++i) { states[i] = input_vector[i]; initial_states[i] = input_vector[i]; } } void Trajectory::set_traj(int i, double value, int time) { if (i==0) trajectory[time] = value; else if (i==1) trajectory2[time] = value; else trajectory3[time] = value; } void Trajectory::set_traj(int i, double value, int time, int group) { trajectory[group*num_time_steps+time] = value; } //void Trajectory::set_traj2(double value, int time) { // trajectory2[time] = value; //} void Trajectory::set_state(double value, int time) { states[time] = value; } double Trajectory::get_traj(int i, int time_index) const { if (i==0) return(trajectory[time_index]); else if (i==1) return (trajectory2[time_index]); else return (trajectory3[time_index]); } double Trajectory::get_traj(int i, int time_index, int group_id) const { int index = num_time_steps*group_id+time_index; return (get_traj(i, index)); } // //double Trajectory::get_traj2(int time_index) const { // return(trajectory2[time_index]); //} void Trajectory::resize_recoveries(int total_times) { recoveries.resize(total_times); } void Trajectory::add_recovery_time(int new_recovery_time) { ++recoveries[new_recovery_time]; } void Trajectory::add_recovery_time(int new_recovery_time, int number) { recoveries[new_recovery_time] += number; } int Trajectory::num_recover_at(int time_to_find) { if (recoveries.size() < 1) return (0); return (recoveries[time_to_find]); } int Trajectory::num_recover_between(int time1, int time2) { if (recoveries.size() < 1) return (0); int total = 0; for (int i=time1; i!=time2; ++i) { total += recoveries[i]; } return (total); } int Trajectory::num_recover_after(int time_to_find) { if (recoveries.size() < 1) return (0); int total = 0; for (int i=time_to_find; i!=recoveries.size(); ++i) { total += recoveries[i]; } return (total); } void Trajectory::delete_recoveries_before(int time_to_find) { recoveries.erase(recoveries.begin(), recoveries.begin()+time_to_find); } std::vector <double> Trajectory::get_traj_range(int id, int start, int end) const { std::vector <double> output; if (num_groups > 1) { for (int group=0; group!=num_groups; ++group) { for (int i=start; i!=end; ++i) { if (id==0) output.push_back(trajectory[group*num_time_steps+i]); else if (id==1) output.push_back(trajectory2[group*num_time_steps+i]); else output.push_back(trajectory3[group*num_time_steps+i]); } } } else { for (int i=start; i!=end; ++i) { output.push_back(trajectory[i]); } } return(output); } std::vector <double> Trajectory::get_traj_range(int id, int start, int end, int group_id) const { std::vector <double> output; for (int i=start; i!=end; ++i) { if (id==0) output.push_back(trajectory[group_id*num_time_steps+i]); else if (id==1) output.push_back(trajectory2[group_id*num_time_steps+i]); else output.push_back(trajectory3[group_id*num_time_steps+i]); } return(output); } //std::vector <double> Trajectory::get_traj2_range(int start, int end) const { // std::vector <double> output; // for (int i=start; i!=end; ++i) { // output.push_back(trajectory2[i]); // } // return(output); //} std::vector<double>::iterator Trajectory::get_traj_ptr(int i, int index) { if (i==0) return(trajectory.begin()+index); else if (i==1) return(trajectory2.begin()+index); else return(trajectory3.begin()+index); } //std::vector<double>::iterator Trajectory::get_traj2_ptr(int index) { // return(trajectory2.begin()+index); //} double Trajectory::get_total_traj() const { double total_data = std::accumulate(trajectory.begin(), trajectory.end(), 0.0); return (total_data); } double* Trajectory::get_curr_states() { return (&states[0]); } double Trajectory::get_init_state(int index) const { return (states[index]); } double Trajectory::get_state(int index) const { return(states[index]); } int Trajectory::get_curr_states_size() const { return ((int)states.size()); } void Trajectory::reset() { // fill(trajectory.begin(), trajectory.end(), 0.0); // fill(trajectory2.begin(), trajectory2.end(), 0.0); states = initial_states; fill(recoveries.begin(), recoveries.end(), 0.0); } void Trajectory::replace(Trajectory * new_traj) { // for (int i=0; i!=new_traj->trajectory.size(); ++i) { // trajectory[i] = new_traj->trajectory[i]; // trajectory2[i] = new_traj->trajectory2[i]; // } states.clear(); states.insert(states.begin(), new_traj->states.begin(), new_traj->states.end()); initial_states.clear(); initial_states.insert(initial_states.begin(), new_traj->initial_states.begin(), new_traj->initial_states.end()); for (int i=0; i!=trajectory.size(); ++i) { trajectory[i] = new_traj->get_traj(1, i); } for (int i=0; i!=trajectory2.size(); ++i) { trajectory2[i] = new_traj->get_traj(2, i); } for (int i=0; i!=trajectory2.size(); ++i) { trajectory3[i] = new_traj->get_traj(3, i); } for (int i=0; i!=recoveries.size(); ++i) { recoveries[i] = new_traj->recoveries[i]; } num_time_steps = new_traj->num_time_steps; } <commit_msg>round the prevalence<commit_after>// // trajectory.cpp // EpiGenMCMC // // Created by Lucy Li on 13/04/2016. // Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved. // #include "trajectory.h" void Trajectory::initialise_file (std::string filename, int every) { std::ofstream file(filename); file << "state"; if (num_groups > 1) { for (int i=0; i<num_groups; ++i) { for (int t=0; t<num_time_steps; t+=every) { file << "\tT" << t << "Group" << i; } } } else { for (int t=0; t<num_time_steps; t+=every) { file << "\tIncT" << t; } for (int t=0; t<num_time_steps; t+=every) { file << "\tPrevT" << t; } } file << std::endl; file.close(); } Trajectory::Trajectory() { trajectory.resize(1); trajectory2.resize(1); trajectory3.resize(1); initial_states.resize(1); recoveries.resize(1); states.resize(1); } Trajectory::Trajectory(int numT, int numGroups) { num_time_steps = numT; num_groups = numGroups; trajectory.resize(numT*numGroups); trajectory2.resize(numT); trajectory3.resize(numT); recoveries.resize(numT); // initialise_file(filename); } void Trajectory::resize(int length) { if (trajectory.size() != length) { trajectory.resize(length); trajectory2.resize(length); trajectory3.resize(length); } fill(trajectory.begin(), trajectory.end(), 0.0); fill(trajectory2.begin(), trajectory2.end(), 0.0); fill(trajectory3.begin(), trajectory3.end(), 0.0); // num_time_steps = length; } void Trajectory::resize(int length, int groups) { if (trajectory.size() != length*groups) { trajectory.resize(length*groups); trajectory2.resize(length); trajectory3.resize(length); } fill(trajectory.begin(), trajectory.end(), 0.0); fill(trajectory2.begin(), trajectory2.end(), 0.0); fill(trajectory3.begin(), trajectory3.end(), 0.0); // num_time_steps = length; } void Trajectory::print_to_file(int iteration, std::string filename, int every, bool sum_across) { std::ofstream file(filename, std::ios::app); file << iteration; int total_steps = (int) trajectory.size(); if (num_groups > 1) { for (int i=0; i<num_groups; ++i) { for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, iteration-t); ++j) { count += trajectory[i*num_time_steps+t+j]; } } else { count = trajectory[i*num_time_steps+t]; } file << "\t" << count; } } } else { for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, total_steps-t); ++j) { count += trajectory[t+j]; } } else { count = trajectory[t]; } file << "\t" << count; } for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, total_steps-t); ++j) { count += trajectory2[t+j]; } count /= (double) std::min(every, total_steps-t); } else { count = trajectory2[t]; } file << "\t" << std::round(count); } } file << std::endl; file.close(); } void Trajectory::print_to_file(std::string filename, int every, bool sum_across) { std::ofstream file(filename, std::ios::app); int total_steps = (int) trajectory.size(); if (num_groups > 1) { for (int i=0; i<num_groups; ++i) { for (int t=0; t<num_time_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, total_steps-t); ++j) { count += trajectory[i*num_time_steps+t+j]; } } else { count = trajectory[i*num_time_steps+t]; } file << "\t" << count; } } } else { for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, num_time_steps-t); ++j) { count += trajectory[t+j]; } } else { count = trajectory[t]; } file << "\t" << count; } for (int t=0; t<total_steps; t+=every) { double count = 0.0; if (sum_across) { for (int j=0; j<std::min(every, num_time_steps-t); ++j) { count += trajectory2[t+j]; } count /= (double) std::min(every, num_time_steps-t); } else { count = trajectory2[t]; } file << "\t" << std::round(count); } } file << std::endl; file.close(); } void Trajectory::initialise_states(std::string filename) { std::ifstream file(filename); double num; while (file >> num) { initial_states.push_back(num); states.push_back(num); } file.close(); } void Trajectory::initialise_states(std::vector<double>input_vector) { for (int i=0; i!=input_vector.size(); ++i) { states[i] = input_vector[i]; initial_states[i] = input_vector[i]; } } void Trajectory::set_traj(int i, double value, int time) { if (i==0) trajectory[time] = value; else if (i==1) trajectory2[time] = value; else trajectory3[time] = value; } void Trajectory::set_traj(int i, double value, int time, int group) { trajectory[group*num_time_steps+time] = value; } //void Trajectory::set_traj2(double value, int time) { // trajectory2[time] = value; //} void Trajectory::set_state(double value, int time) { states[time] = value; } double Trajectory::get_traj(int i, int time_index) const { if (i==0) return(trajectory[time_index]); else if (i==1) return (trajectory2[time_index]); else return (trajectory3[time_index]); } double Trajectory::get_traj(int i, int time_index, int group_id) const { int index = num_time_steps*group_id+time_index; return (get_traj(i, index)); } // //double Trajectory::get_traj2(int time_index) const { // return(trajectory2[time_index]); //} void Trajectory::resize_recoveries(int total_times) { recoveries.resize(total_times); } void Trajectory::add_recovery_time(int new_recovery_time) { ++recoveries[new_recovery_time]; } void Trajectory::add_recovery_time(int new_recovery_time, int number) { recoveries[new_recovery_time] += number; } int Trajectory::num_recover_at(int time_to_find) { if (recoveries.size() < 1) return (0); return (recoveries[time_to_find]); } int Trajectory::num_recover_between(int time1, int time2) { if (recoveries.size() < 1) return (0); int total = 0; for (int i=time1; i!=time2; ++i) { total += recoveries[i]; } return (total); } int Trajectory::num_recover_after(int time_to_find) { if (recoveries.size() < 1) return (0); int total = 0; for (int i=time_to_find; i!=recoveries.size(); ++i) { total += recoveries[i]; } return (total); } void Trajectory::delete_recoveries_before(int time_to_find) { recoveries.erase(recoveries.begin(), recoveries.begin()+time_to_find); } std::vector <double> Trajectory::get_traj_range(int id, int start, int end) const { std::vector <double> output; if (num_groups > 1) { for (int group=0; group!=num_groups; ++group) { for (int i=start; i!=end; ++i) { if (id==0) output.push_back(trajectory[group*num_time_steps+i]); else if (id==1) output.push_back(trajectory2[group*num_time_steps+i]); else output.push_back(trajectory3[group*num_time_steps+i]); } } } else { for (int i=start; i!=end; ++i) { output.push_back(trajectory[i]); } } return(output); } std::vector <double> Trajectory::get_traj_range(int id, int start, int end, int group_id) const { std::vector <double> output; for (int i=start; i!=end; ++i) { if (id==0) output.push_back(trajectory[group_id*num_time_steps+i]); else if (id==1) output.push_back(trajectory2[group_id*num_time_steps+i]); else output.push_back(trajectory3[group_id*num_time_steps+i]); } return(output); } //std::vector <double> Trajectory::get_traj2_range(int start, int end) const { // std::vector <double> output; // for (int i=start; i!=end; ++i) { // output.push_back(trajectory2[i]); // } // return(output); //} std::vector<double>::iterator Trajectory::get_traj_ptr(int i, int index) { if (i==0) return(trajectory.begin()+index); else if (i==1) return(trajectory2.begin()+index); else return(trajectory3.begin()+index); } //std::vector<double>::iterator Trajectory::get_traj2_ptr(int index) { // return(trajectory2.begin()+index); //} double Trajectory::get_total_traj() const { double total_data = std::accumulate(trajectory.begin(), trajectory.end(), 0.0); return (total_data); } double* Trajectory::get_curr_states() { return (&states[0]); } double Trajectory::get_init_state(int index) const { return (states[index]); } double Trajectory::get_state(int index) const { return(states[index]); } int Trajectory::get_curr_states_size() const { return ((int)states.size()); } void Trajectory::reset() { // fill(trajectory.begin(), trajectory.end(), 0.0); // fill(trajectory2.begin(), trajectory2.end(), 0.0); states = initial_states; fill(recoveries.begin(), recoveries.end(), 0.0); } void Trajectory::replace(Trajectory * new_traj) { // for (int i=0; i!=new_traj->trajectory.size(); ++i) { // trajectory[i] = new_traj->trajectory[i]; // trajectory2[i] = new_traj->trajectory2[i]; // } states.clear(); states.insert(states.begin(), new_traj->states.begin(), new_traj->states.end()); initial_states.clear(); initial_states.insert(initial_states.begin(), new_traj->initial_states.begin(), new_traj->initial_states.end()); for (int i=0; i!=trajectory.size(); ++i) { trajectory[i] = new_traj->get_traj(1, i); } for (int i=0; i!=trajectory2.size(); ++i) { trajectory2[i] = new_traj->get_traj(2, i); } for (int i=0; i!=trajectory2.size(); ++i) { trajectory3[i] = new_traj->get_traj(3, i); } for (int i=0; i!=recoveries.size(); ++i) { recoveries[i] = new_traj->recoveries[i]; } num_time_steps = new_traj->num_time_steps; } <|endoftext|>