text
stringlengths
54
60.6k
<commit_before>#include "_mobs.hpp" #include "_player.hpp" #include <iostream> #include <cstdlib> #include <windows.h> player battle(pplayer account); player calcEXP(player account, classMob creature); player levelUp(player account); void death(); int main() { std::string name; int option1; std::cout<<"Welcome, please enter your name\n"; std::getline(std::cin, name); std::string location [4] = {"in a hole","in a cave","in the mountains","in a castle"}; std::cout<<"\nWelcome"<<account.getName()<<" you find yourself "<<account.getArea()<<" and you're not sure how you got there\n"; while (1) { std::this_thread::sleep_for(500); std::cout<<"Write 1 to walk forward, 2 to walk left and 3 to walk right \n"; std::getline(std::cin, option1); if (option1 == 1) { std::this_thread::sleep_for(50*(option1)); srand(time(NULL)); if (rand()%3 == option1-1){ account = battle(account); } } else{ std::cout<<"ERROR \n\nPlease enter a number between 1 and 3. \n\n"; std::cin.clear(); std::cin.ignore(); } } return 0; } player battle(plater account) { std::string option; std::string location[4] = {"in a hole", "in a cave", "in the mountains", "in a castle"}; std::string monsters[5][3] = {{"worm", "lizzard", "snake"},{"rat", "snake", "trolls"},{"Dragon", "Dragon", "Dragon"},{"Evil knight", "The Mad King", "Dark Prince"}}; std::this_thread::sleep_for(20); int ranM = (rand()%3); int ranD = (rand()%5)+1; classMob monster(monsters[account.getLevel()-1][ranM],account.getLevel(),account.getArea(),ranD); std::cout<<"Suddenly you meet a "<<monster.getName()<<", prepare for battle!\n"; std::this_thread::sleep_for(2000); do { std::cout<<"\n\n############################################# \n\n HP:"<<account.getHealth()<<"\n\n"; std::cout<<monster.getName()<<"HP: "<<monster.getHealth()<<" Level: "<<monster.getLevel()<<"\n"; std::cout<<"Select A for Attack or R for retreat"<<"\n"; std::cin>>option; srand(time(NULL)); if (option=="R" || option=="r") { if ((rand()%2) == 1){ std::cout<<"retreat sucessfull"<<"/n"; monster.setHealth(0); } else{ std::cout<<"You try to run, but it failed. \nThemonster attacks. You lose 5 health. \n"; account.setHealth(account.getHealth()-5); option = "A"; } } if (option == "A" || option =="a") { int attack = rand()%(account.getDamage()); srand(time(NULL)); int mobAttack = rand()%(monster.getDamage()); monster.setHealth(monster.getHealth()-attack); account.setHealth(account.getHealth()-mobAttack); std::cout<<"You attack the damage for "<<attack<<" damage.\n"; std::this_thread::sleep_for(500); std::cout<<"The monster attacks for "<< mobAttack<<" damage\n"; std::this_thread::sleep_for(500); } } while (monster.getHealth() > 0 && account.getHealth() > 0); std::cout<<"\n\n############################################# \n\n HP:"<<account.getHealth()<<"\n\n"; std::cout<<monster.getName()<<"HP: "<<monster.getHealth()<<" Level: "<<monster.getLevel()<<"\n"; if (account.getHealth() <= 0) { death(); exit(0); } account = calcEXP(account,monster); return account; } void death() { std::cout<< "You have died\n"; } player calcEXP(player account, classMob monster) { std::cout<<"#######\ncalculating EXP\n########\n"; std::this_thread::sleep_for(500); account.setEXP(account.getEXP() + monster.getEXP()); std::cout<<"EXP: " << account.getEXP()<<"/"<< account.getEXPReq()<<"\n"; if (account.getEXP()>=account.getEXPReq()) { levelUp(account); } return account; } player levelUp(player account) { account.setLevel(account.getLevel()+1); account.setEXPReq(); account.setMaxHealth(); account.setHealth(account.getMaxHealth()); std::cout<<"Level up! You are now level: "<<account.getLevel()<<"!\n"; return account; } <commit_msg>Update main.cpp<commit_after>#include "_mobs.h" #include "_player.h" #include <iostream> #include <cstdlib> #include <windows.h> player battle(pplayer account); player calcEXP(player account, classMob creature); player levelUp(player account); void death(); int main() { std::string name; int option1; std::cout<<"Welcome, please enter your name\n"; std::getline(std::cin, name); std::string location [4] = {"in a hole","in a cave","in the mountains","in a castle"}; std::cout<<"\nWelcome"<<account.getName()<<" you find yourself "<<account.getArea()<<" and you're not sure how you got there\n"; while (1) { std::this_thread::sleep_for(500); std::cout<<"Write 1 to walk forward, 2 to walk left and 3 to walk right \n"; std::getline(std::cin, option1); if (option1 == 1) { std::this_thread::sleep_for(50*(option1)); srand(time(NULL)); if (rand()%3 == option1-1){ account = battle(account); } } else{ std::cout<<"ERROR \n\nPlease enter a number between 1 and 3. \n\n"; std::cin.clear(); std::cin.ignore(); } } return 0; } player battle(plater account) { std::string option; std::string location[4] = {"in a hole", "in a cave", "in the mountains", "in a castle"}; std::string monsters[5][3] = {{"worm", "lizzard", "snake"},{"rat", "snake", "trolls"},{"Dragon", "Dragon", "Dragon"},{"Evil knight", "The Mad King", "Dark Prince"}}; std::this_thread::sleep_for(20); int ranM = (rand()%3); int ranD = (rand()%5)+1; classMob monster(monsters[account.getLevel()-1][ranM],account.getLevel(),account.getArea(),ranD); std::cout<<"Suddenly you meet a "<<monster.getName()<<", prepare for battle!\n"; std::this_thread::sleep_for(2000); do { std::cout<<"\n\n############################################# \n\n HP:"<<account.getHealth()<<"\n\n"; std::cout<<monster.getName()<<"HP: "<<monster.getHealth()<<" Level: "<<monster.getLevel()<<"\n"; std::cout<<"Select A for Attack or R for retreat"<<"\n"; std::cin>>option; srand(time(NULL)); if (option=="R" || option=="r") { if ((rand()%2) == 1){ std::cout<<"retreat sucessfull"<<"/n"; monster.setHealth(0); } else{ std::cout<<"You try to run, but it failed. \nThemonster attacks. You lose 5 health. \n"; account.setHealth(account.getHealth()-5); option = "A"; } } if (option == "A" || option =="a") { int attack = rand()%(account.getDamage()); srand(time(NULL)); int mobAttack = rand()%(monster.getDamage()); monster.setHealth(monster.getHealth()-attack); account.setHealth(account.getHealth()-mobAttack); std::cout<<"You attack the damage for "<<attack<<" damage.\n"; std::this_thread::sleep_for(500); std::cout<<"The monster attacks for "<< mobAttack<<" damage\n"; std::this_thread::sleep_for(500); } } while (monster.getHealth() > 0 && account.getHealth() > 0); std::cout<<"\n\n############################################# \n\n HP:"<<account.getHealth()<<"\n\n"; std::cout<<monster.getName()<<"HP: "<<monster.getHealth()<<" Level: "<<monster.getLevel()<<"\n"; if (account.getHealth() <= 0) { death(); exit(0); } account = calcEXP(account,monster); return account; } void death() { std::cout<< "You have died\n"; } player calcEXP(player account, classMob monster) { std::cout<<"#######\ncalculating EXP\n########\n"; std::this_thread::sleep_for(500); account.setEXP(account.getEXP() + monster.getEXP()); std::cout<<"EXP: " << account.getEXP()<<"/"<< account.getEXPReq()<<"\n"; if (account.getEXP()>=account.getEXPReq()) { levelUp(account); } return account; } player levelUp(player account) { account.setLevel(account.getLevel()+1); account.setEXPReq(); account.setMaxHealth(); account.setHealth(account.getMaxHealth()); std::cout<<"Level up! You are now level: "<<account.getLevel()<<"!\n"; return account; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <thread> #include <string> #include <map> #include <vector> #include <boost/program_options.hpp> #include "time_helper.h" #include "options.h" #include "pipeline_data.h" #include "array_prepare.h" #include "benchmark.h" #include "statistics.h" #include "test.h" #include "output.h" using namespace std; using namespace time_helper; namespace output = benchmark_output; int main(int argc, char* argv[]) { options opts = initialize_options(argc, argv); // benchmark map std::map<std::string, void(*)(pipeline_data& data)> benchmark_map; benchmark_map["bubble"] = benchmark_bubble; benchmark_map["insertion"] = benchmark_insertion; benchmark_map["selection"] = benchmark_selection; benchmark_map["merge"] = benchmark_merge; benchmark_map["count"] = benchmark_count; // checking if the user specified a valid algorithm for benchmarking auto benchmark = benchmark_map[opts.algorithm]; if (benchmark == nullptr) { cerr << "No such algorithm: " << opts.algorithm << endl; return 1; } // prepairing pipeline vector<void(*)(pipeline_data& data)> pipeline; pipeline.push_back(prepare_array); pipeline.push_back(benchmark); pipeline.push_back(aggregate_statistics); if (opts.test) pipeline.push_back(test); // printing greeting according to output mode and adding appropriate output method to the pipeline if (opts.output == "hs") { pipeline.push_back(output::human_sparse); output::human_sparse_greetings(opts); } else if (opts.output == "hv") { pipeline.push_back(output::human_verbose); output::human_verbose_greetings(opts); } else if (opts.output == "m") pipeline.push_back(output::machine); else { cout << "Unknown output mode: " << opts.output << endl; exit(2); } // preparing pipeline data pipeline_data data{}; data.array_size = opts.array_size; data.unsorted_array = new int[data.array_size]; data.sorted_array = new int[data.array_size]; data.iterations = opts.iterations; data.min_number = opts.arr_min_num; data.max_number = opts.arr_max_num; data.test = opts.test; // the pipeline itself for (unsigned int i = 0; i < opts.iterations; i++) { data.iteration = i; for (auto step : pipeline) step(data); } // presenting the report according to the set output tipe if (opts.output == "hs") output::human_sparse_report(data); else if (opts.output == "hv") output::human_verbose_report(data); // clearing data delete[] data.unsorted_array; delete[] data.sorted_array; }<commit_msg>Replaced an exit in main by return.<commit_after>#include <iostream> #include <iomanip> #include <thread> #include <string> #include <map> #include <vector> #include <boost/program_options.hpp> #include "time_helper.h" #include "options.h" #include "pipeline_data.h" #include "array_prepare.h" #include "benchmark.h" #include "statistics.h" #include "test.h" #include "output.h" using namespace std; using namespace time_helper; namespace output = benchmark_output; int main(int argc, char* argv[]) { options opts = initialize_options(argc, argv); // benchmark map std::map<std::string, void(*)(pipeline_data& data)> benchmark_map; benchmark_map["bubble"] = benchmark_bubble; benchmark_map["insertion"] = benchmark_insertion; benchmark_map["selection"] = benchmark_selection; benchmark_map["merge"] = benchmark_merge; benchmark_map["count"] = benchmark_count; // checking if the user specified a valid algorithm for benchmarking auto benchmark = benchmark_map[opts.algorithm]; if (benchmark == nullptr) { cerr << "No such algorithm: " << opts.algorithm << endl; return 1; } // prepairing pipeline vector<void(*)(pipeline_data& data)> pipeline; pipeline.push_back(prepare_array); pipeline.push_back(benchmark); pipeline.push_back(aggregate_statistics); if (opts.test) pipeline.push_back(test); // printing greeting according to output mode and adding appropriate output method to the pipeline if (opts.output == "hs") { pipeline.push_back(output::human_sparse); output::human_sparse_greetings(opts); } else if (opts.output == "hv") { pipeline.push_back(output::human_verbose); output::human_verbose_greetings(opts); } else if (opts.output == "m") pipeline.push_back(output::machine); else { cout << "Unknown output mode: " << opts.output << endl; return 2; } // preparing pipeline data pipeline_data data{}; data.array_size = opts.array_size; data.unsorted_array = new int[data.array_size]; data.sorted_array = new int[data.array_size]; data.iterations = opts.iterations; data.min_number = opts.arr_min_num; data.max_number = opts.arr_max_num; data.test = opts.test; // the pipeline itself for (unsigned int i = 0; i < opts.iterations; i++) { data.iteration = i; for (auto step : pipeline) step(data); } // presenting the report according to the set output tipe if (opts.output == "hs") output::human_sparse_report(data); else if (opts.output == "hv") output::human_verbose_report(data); // clearing data delete[] data.unsorted_array; delete[] data.sorted_array; } <|endoftext|>
<commit_before>// main.cpp #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "metasorter.h" #include <boost/foreach.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> void generate_skeleton_config(); using namespace std; using namespace boost::filesystem; int main(int argc, char* argv[]) { std::cout << "Metasort 1.4.5" << std::endl << std::endl; //std::cout << "Copyright 2013 Eric Griffin" << std::endl << std::endl; int err = 0; int ok_to_run = 0; int required_flags = 0; int config_num = 0; int input_file_process = 0; int input_file_num = 0; char input_file[255][255]; char config_file[255][255]; boost::property_tree::ptree pt[255]; if (argc > 1) { for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-g") == 0 ) { generate_skeleton_config(); exit(0); } if (strcmp(argv[i], "-?") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "/h") == 0) { std::cout << "Usage: metasort -c <config file> [-i <filename>] [-g]" << std::endl; std::cout << "-c <config file> -- specify configuration file to run" << std::endl; std::cout << "-i <filename> -- specify a single file to process (requires -c)" << std::endl; std::cout << "-g -- create a skeleton configuration file in the current directory" << std::endl; exit(0); } if (i + 1 != argc) { if (strcmp(argv[i], "-c") == 0) { strcpy(config_file[config_num], argv[i + 1]); config_num++; required_flags++; } if (strcmp(argv[i], "-i") == 0) { input_file_process = 1; strcpy(input_file[input_file_num], argv[i + 1]); input_file_num++; } } } if(required_flags > 0) { ok_to_run = 1; } } if(ok_to_run) { for(int q = 0; q < config_num; q++) { boost::property_tree::info_parser::read_info(config_file[q], pt[q]); // check for folders entry optional<const boost::property_tree::ptree&> pt_check_existence; pt_check_existence = pt[q].get_child_optional("folders"); if(input_file_process == 0) // if processing folders from config { if(pt_check_existence) { BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt[q].get_child("folders")) { int recurse = 0; std::cout << "Searching Root Folder: " << v.first.data() << std::endl; if(strcmp(v.second.data().c_str(), "R") == 0) { recurse = 1; } metasorter sorter((char*)v.first.data(), pt[q]); sorter.traverse_directory(recurse); sorter.tp.wait(); } std::cout << endl << "Finished." << std::endl; } else { cout << endl << "No folders defined in config file - aborting" << std::endl; exit(0); } } else // processing files from argv[] { for(int input_file_counter = 0; input_file_counter < input_file_num; input_file_counter++) { metasorter sorter(input_file[input_file_counter], pt[q]); sorter.process_file(); } std::cout << endl << "Finished." << std::endl; } } } else { std::cout << "Usage: metasort -c <config file> [-i <filename>] [-g]" << std::endl; } return err; } void generate_skeleton_config() { boost::filesystem::path working_path_raw(boost::filesystem::current_path()); std::string *config = new std::string(); std::string *working_path = new std::string(working_path_raw.string().c_str()); //change back-slashes to forward-slashes std::replace(working_path->begin(), working_path->end(), '\\', '/'); config->append("folders\n{\n\t;\""); config->append(working_path->c_str()); config->append("/\" R\n}\n\nextensions\n{\n"); config->append("\t[REGEX].*"); config->append("\n}\n\nconfig\n{\n"); config->append("\tlogfile \""); config->append(working_path->c_str()); config->append("/metasort.log\""); config->append("\n}\n\nrules\n{\n"); config->append("\tRule1_list \""); config->append(working_path->c_str()); config->append("/metasort_list.txt\"\n\t{\n"); config->append("\t\tGeneral_0\n\t\t{\n"); config->append("\t\t\tfile_size > 50\n\t\t}\n"); config->append("\n\t}\n}\n"); std::ofstream f; std::string *skeleton_config_file = new std::string(working_path_raw.string().c_str()); skeleton_config_file->append("\\metasort_config.ini"); std::cout << "Generating skeleton config file: " << skeleton_config_file->c_str() << std::endl; f.open(skeleton_config_file->c_str(), std::ios::out); f << config->c_str(); f.close(); } <commit_msg>portability fixes<commit_after>// main.cpp #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "metasorter.h" #include <boost/foreach.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> void generate_skeleton_config(); using namespace std; using namespace boost::filesystem; int main(int argc, char* argv[]) { std::cout << "Metasort 1.4.5" << std::endl << std::endl; //std::cout << "Copyright 2013 Eric Griffin" << std::endl << std::endl; int err = 0; int ok_to_run = 0; int required_flags = 0; int config_num = 0; int input_file_process = 0; int input_file_num = 0; char input_file[255][255]; char config_file[255][255]; boost::property_tree::ptree pt[255]; if (argc > 1) { for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-g") == 0 ) { generate_skeleton_config(); exit(0); } if (strcmp(argv[i], "-?") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "/h") == 0) { std::cout << "Usage: metasort -c <config file> [-i <filename>] [-g]" << std::endl; std::cout << "-c <config file> -- specify configuration file to run" << std::endl; std::cout << "-i <filename> -- specify a single file to process (requires -c)" << std::endl; std::cout << "-g -- create a skeleton configuration file in the current directory" << std::endl << std::endl; exit(0); } if (i + 1 != argc) { if (strcmp(argv[i], "-c") == 0) { strcpy(config_file[config_num], argv[i + 1]); config_num++; required_flags++; } if (strcmp(argv[i], "-i") == 0) { input_file_process = 1; strcpy(input_file[input_file_num], argv[i + 1]); input_file_num++; } } } if(required_flags > 0) { ok_to_run = 1; } } if(ok_to_run) { for(int q = 0; q < config_num; q++) { boost::property_tree::info_parser::read_info(config_file[q], pt[q]); // check for folders entry optional<const boost::property_tree::ptree&> pt_check_existence; pt_check_existence = pt[q].get_child_optional("folders"); if(input_file_process == 0) // if processing folders from config { if(pt_check_existence) { BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt[q].get_child("folders")) { int recurse = 0; std::cout << "Searching Root Folder: " << v.first.data() << std::endl; if(strcmp(v.second.data().c_str(), "R") == 0) { recurse = 1; } metasorter sorter((char*)v.first.data(), pt[q]); sorter.traverse_directory(recurse); sorter.tp.wait(); } std::cout << endl << "Finished." << std::endl; } else { cout << endl << "No folders defined in config file - aborting" << std::endl; exit(0); } } else // processing files from argv[] { for(int input_file_counter = 0; input_file_counter < input_file_num; input_file_counter++) { metasorter sorter(input_file[input_file_counter], pt[q]); sorter.process_file(); } std::cout << endl << "Finished." << std::endl; } } } else { std::cout << "Usage: metasort -c <config file> [-i <filename>] [-g]" << std::endl << std::endl; } return err; } void generate_skeleton_config() { boost::filesystem::path working_path_raw(boost::filesystem::current_path()); std::string *config = new std::string(); std::string *working_path = new std::string(working_path_raw.string().c_str()); //change back-slashes to forward-slashes std::replace(working_path->begin(), working_path->end(), '\\', '/'); config->append("folders\n{\n\t;\""); config->append(working_path->c_str()); config->append("/\" R\n}\n\nextensions\n{\n"); config->append("\t[REGEX].*"); config->append("\n}\n\nconfig\n{\n"); config->append("\tlogfile \""); config->append(working_path->c_str()); config->append("/metasort.log\""); config->append("\n}\n\nrules\n{\n"); config->append("\tRule1_list \""); config->append(working_path->c_str()); config->append("/metasort_list.txt\"\n\t{\n"); config->append("\t\tGeneral_0\n\t\t{\n"); config->append("\t\t\tfile_size > 50\n\t\t}\n"); config->append("\n\t}\n}\n"); std::ofstream f; std::string *skeleton_config_file = new std::string(working_path_raw.string().c_str()); skeleton_config_file->append("/metasort_config.ini"); std::cout << "Generating skeleton config file: " << skeleton_config_file->c_str() << std::endl << std::endl; f.open(skeleton_config_file->c_str(), std::ios::out); f << config->c_str(); f.close(); } <|endoftext|>
<commit_before>#include <iostream> #include "reader.hpp" #include "settings.hpp" #include "forest.hpp" using namespace std; using namespace ISUE::RelocForests; int main(int argc, char *argv[]) { if (argc < 2) { cout << "Usage: [train||test] ./relocforests <path_to_association_file>"; return 1; } // get path string data_path(argv[1]); Reader *reader = new Reader(); bool err = reader->Load(data_path); if (err) { return 1; } // Get data from reader Data *data = reader->GetData(); // settings for forest Settings *settings = new Settings(); settings->fx = 525.0f; settings->fy = 525.0f; settings->cx = 319.5f; settings->cy = 239.5f; Forest<ushort, cv::Vec3b> *forest = nullptr; bool train = false; if (train) { forest = new Forest<ushort, cv::Vec3b>(data, settings); forest->Train(); forest->Serialize("forest.rf"); cout << "Is forest valid:" << forest->IsValid() << endl; } else { // load forest forest = new Forest<ushort, cv::Vec3b>(data, settings, "forest.rf"); cout << "Is forest valid:" << forest->IsValid() << endl; // eval forest at frame std::clock_t start; double duration; start = std::clock(); Eigen::Affine3d pose = forest->Test(data->GetRGBImage(200), data->GetDepthImage(200)); duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; cout << "Train time: " << duration << " Seconds \n"; // compare pose to known value auto known_pose = data->GetPose(200); cout << "found pose:" << endl; cout << pose.rotation() << endl << endl; cout << pose.rotation().eulerAngles(0, 1, 2) * 180 / M_PI << endl; cout << pose.translation() << endl; cout << "known pose:" << endl; cout << known_pose.rotation << endl; cout << known_pose.rotation.eulerAngles(0, 1, 2) * 180 / M_PI << endl; cout << known_pose.position << endl; if ((known_pose.rotation - pose.rotation()).cwiseAbs().maxCoeff() > 1e-13 || (known_pose.position - pose.translation()).cwiseAbs().maxCoeff() > 1e-13) cout << "Pose could not be found\n"; else cout << "Pose was found!\n"; } cout << "Done.\n"; delete forest; delete reader; delete settings; return 0; } <commit_msg>Fixes command line interface.<commit_after>#include <iostream> #include "reader.hpp" #include "settings.hpp" #include "forest.hpp" using namespace std; using namespace ISUE::RelocForests; int main(int argc, char *argv[]) { if (argc < 2) { cout << "Usage: ./relocforests <path_to_association_file> (train|test) <forest_file_name>\n"; return 1; } // get path string data_path(argv[1]); Reader *reader = new Reader(); bool err = reader->Load(data_path); if (err) { return 1; } // train or test time string shouldTrain(argv[2]); bool train = (shouldTrain == "train"); // Get data from reader Data *data = reader->GetData(); // settings for forest Settings *settings = new Settings(640, 480, 5000, 525.0f, 525.0f, 319.5f, 239.5f); Forest<ushort, cv::Vec3b> *forest = nullptr; string forest_file_name; if (argv[3]) forest_file_name = string(argv[3]); else cout << "Train and Test time requires an output file name.\n"; if (shouldTrain) { forest = new Forest<ushort, cv::Vec3b>(data, settings); forest->Train(); forest->Serialize(forest_file_name); cout << "Is forest valid:" << forest->IsValid() << endl; } else { // load forest forest = new Forest<ushort, cv::Vec3b>(data, settings, "forest.rf"); cout << "Is forest valid:" << forest->IsValid() << endl; // eval forest at frame std::clock_t start; double duration; start = std::clock(); Eigen::Affine3d pose = forest->Test(data->GetRGBImage(200), data->GetDepthImage(200)); duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; cout << "Train time: " << duration << " Seconds \n"; // compare pose to known value auto known_pose = data->GetPose(200); cout << "found pose:" << endl; cout << pose.rotation() << endl << endl; cout << pose.rotation().eulerAngles(0, 1, 2) * 180 / M_PI << endl; cout << pose.translation() << endl; cout << "known pose:" << endl; cout << known_pose.rotation << endl; cout << known_pose.rotation.eulerAngles(0, 1, 2) * 180 / M_PI << endl; cout << known_pose.position << endl; } delete forest; delete reader; delete settings; return 0; } <|endoftext|>
<commit_before>#include <ctrcommon/app.hpp> #include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <stdio.h> #include <sstream> #include <iomanip> #include <sys/dirent.h> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "FBI v1.3.7" << "\n"; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; stream << "Y - Receive an app over the network" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; std::string batchInfo = ""; int prevProgress = -1; auto onProgress = [&](u64 pos, u64 totalSize) { u32 progress = (u32) ((pos * 100) / totalSize); if(prevProgress != (int) progress) { prevProgress = (int) progress; std::stringstream details; details << batchInfo; details << "Press B to cancel."; uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress); } inputPoll(); return !inputIsPressed(BUTTON_B); }; bool showNetworkPrompts = true; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { if(netInstall && !exit) { screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) { if(inputIsPressed(BUTTON_A)) { showNetworkPrompts = !showNetworkPrompts; } infoStream << "\n"; infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n"; infoStream << "Press A to toggle prompts." << "\n"; }); if(file.fd == NULL) { netInstall = false; continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); prevProgress = -1; if(showNetworkPrompts || ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } } fclose(file.fd); continue; } uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); u32 currItem = 0; for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { std::string displayFileName = (*it).name; if(displayFileName.length() > 40) { displayFileName.resize(40); displayFileName += "..."; } if(mode == INSTALL_CIA) { std::stringstream batchInstallStream; batchInstallStream << displayFileName << " (" << currItem << ")" << "\n"; batchInfo = batchInstallStream.str(); AppResult ret = appInstallFile(destination, path, onProgress); prevProgress = -1; batchInfo = ""; if(ret != APP_SUCCESS) { Error error = platformGetError(); platformSetError(error); std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << displayFileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); if(error.module != MODULE_AM || error.description != DESCRIPTION_ALREADY_EXISTS) { failed = true; break; } } } else { std::stringstream deleteStream; deleteStream << "Deleting CIA..." << "\n"; deleteStream << displayFileName << " (" << currItem << ")" << "\n"; uiDisplayMessage(TOP_SCREEN, deleteStream.str()); if(!fsDelete(path)) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << displayFileName << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } currItem++; } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); prevProgress = -1; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { uiDisplayMessage(TOP_SCREEN, "Deleting CIA..."); if(fsDelete(path)) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiDisplayMessage(BOTTOM_SCREEN, "Loading title list..."); uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(exit) { break; } } platformCleanup(); return 0; } <commit_msg>Switch from fsDelete to remove.<commit_after>#include <ctrcommon/app.hpp> #include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <sys/dirent.h> #include <sys/errno.h> #include <stdio.h> #include <string.h> #include <sstream> #include <iomanip> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "FBI v1.3.8" << "\n"; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; stream << "Y - Receive an app over the network" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; std::string batchInfo = ""; int prevProgress = -1; auto onProgress = [&](u64 pos, u64 totalSize) { u32 progress = (u32) ((pos * 100) / totalSize); if(prevProgress != (int) progress) { prevProgress = (int) progress; std::stringstream details; details << batchInfo; details << "Press B to cancel."; uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress); } inputPoll(); return !inputIsPressed(BUTTON_B); }; bool showNetworkPrompts = true; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { if(netInstall && !exit) { screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) { if(inputIsPressed(BUTTON_A)) { showNetworkPrompts = !showNetworkPrompts; } infoStream << "\n"; infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n"; infoStream << "Press A to toggle prompts." << "\n"; }); if(file.fd == NULL) { netInstall = false; continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); prevProgress = -1; if(showNetworkPrompts || ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } } fclose(file.fd); continue; } uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); u32 currItem = 0; for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { std::string displayFileName = (*it).name; if(displayFileName.length() > 40) { displayFileName.resize(40); displayFileName += "..."; } if(mode == INSTALL_CIA) { std::stringstream batchInstallStream; batchInstallStream << displayFileName << " (" << currItem << ")" << "\n"; batchInfo = batchInstallStream.str(); AppResult ret = appInstallFile(destination, path, onProgress); prevProgress = -1; batchInfo = ""; if(ret != APP_SUCCESS) { Error error = platformGetError(); platformSetError(error); std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << displayFileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); if(error.module != MODULE_AM || error.description != DESCRIPTION_ALREADY_EXISTS) { failed = true; break; } } } else { std::stringstream deleteStream; deleteStream << "Deleting CIA..." << "\n"; deleteStream << displayFileName << " (" << currItem << ")" << "\n"; uiDisplayMessage(TOP_SCREEN, deleteStream.str()); if(remove(path.c_str()) != 0) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << displayFileName << "\n"; resultMsg << strerror(errno) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } currItem++; } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); prevProgress = -1; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { uiDisplayMessage(TOP_SCREEN, "Deleting CIA..."); if(remove(path.c_str()) != 0) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << strerror(errno) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiDisplayMessage(BOTTOM_SCREEN, "Loading title list..."); uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(exit) { break; } } platformCleanup(); return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "mcc/cfg/cfg.h" #include "parser.h" #include "boost/graph/graphviz.hpp" namespace mcc { namespace cfg { TEST(Cfg, Cfg) { auto tree = parser::parse( R"( { int x=1; float y = 3.0; if(x > 0) { y = y * 1.5; } else { y = y + 2.0; } int a = 0; if( 1 <= 2) { a = 1; } else { a = 2; } })"); mcc::tac::Tac tac; tac.convertAst(tree); auto graph = std::make_shared<Cfg>(tac); std::string expected = R"(digraph G { 0; 1; 2; 3; 4; 5; 6; 0->1 ; 0->2 ; 1->3 ; 2->3 ; 3->4 ; 3->5 ; 4->6 ; 5->6 ; } )"; EXPECT_EQ(expected, graph->toDot()); } TEST(Cfg, Idom) { auto tree = parser::parse( R"( { int x=1; float y = 3.0; if(x > 0) { y = y * 1.5; } else { y = y + 2.0; } int a = 0; if( 1 <= 2) { a = 1; } else { a = 2; } })"); mcc::tac::Tac tac; tac.convertAst(tree); auto graph = std::make_shared<Cfg>(tac); auto index = tac.getBasicBlockIndex(); // TODO find reason why shared pointers as well as the results of get() are not equal EXPECT_EQ(graph->getIdom(index[0])->toString(), index[0]->toString()); EXPECT_EQ(graph->getIdom(index[1])->toString(), index[0]->toString()); EXPECT_EQ(graph->getIdom(index[2])->toString(), index[0]->toString()); EXPECT_EQ(graph->getIdom(index[3])->toString(), index[0]->toString()); EXPECT_EQ(graph->getIdom(index[4])->toString(), index[3]->toString()); EXPECT_EQ(graph->getIdom(index[5])->toString(), index[3]->toString()); EXPECT_EQ(graph->getIdom(index[6])->toString(), index[3]->toString()); EXPECT_EQ(graph->getIdom(0), 0); EXPECT_EQ(graph->getIdom(1), 0); EXPECT_EQ(graph->getIdom(2), 0); EXPECT_EQ(graph->getIdom(3), 0); EXPECT_EQ(graph->getIdom(4), 3); EXPECT_EQ(graph->getIdom(5), 3); EXPECT_EQ(graph->getIdom(6), 3); } /*TEST(Cfg, DomSetVertex) { auto tree = parser::parse( R"( { int x=1; float y = 3.0; if(x > 0) { y = y * 1.5; } else { y = y + 2.0; } int a = 0; if( 1 <= 2) { a = 1; } else { a = 2; } })"); mcc::tac::Tac tac; tac.convertAst(tree); auto graph = std::make_shared<Cfg>(tac); auto index = tac.getBasicBlockIndex(); std::vector<Vertex> set; set.push_back(index[0]); set.push_back(index[3]); auto dom0 = graph->getDomSet(index[0]).begin(); auto dom1 = graph->getDomSet(index[1]).begin(); auto dom2 = graph->getDomSet(index[2]).begin(); auto dom3 = graph->getDomSet(index[3]).begin(); auto dom4 = graph->getDomSet(index[4]).begin(); auto dom5 = graph->getDomSet(index[5]).begin(); auto dom6 = graph->getDomSet(index[6]).begin(); // TODO find reason why shared pointers as well as the results of get() are not equal EXPECT_EQ(dom0->get()->toString(), index[0]->toString()); EXPECT_EQ(dom1->get()->toString(), index[0]->toString()); EXPECT_EQ(dom2->get()->toString(), index[0]->toString()); EXPECT_EQ(dom3->get()->toString(), index[0]->toString()); EXPECT_EQ(dom4->get()->toString(), index[0]->toString()); EXPECT_EQ(dom5->get()->toString(), index[0]->toString()); EXPECT_EQ(dom6->get()->toString(), index[0]->toString()); EXPECT_EQ((++dom4)->get()->toString(), index[3]->toString()); EXPECT_EQ((++dom5)->get()->toString(), index[3]->toString()); EXPECT_EQ((++dom6)->get()->toString(), index[3]->toString()); }*/ TEST(Cfg, DomSet) { auto tree = parser::parse( R"( { int x=1; float y = 3.0; if(x > 0) { y = y * 1.5; } else { y = y + 2.0; } int a = 0; if( 1 <= 2) { a = 1; } else { a = 2; } })"); mcc::tac::Tac tac; tac.convertAst(tree); auto graph = std::make_shared<Cfg>(tac); std::vector<VertexDescriptor> set; set.push_back(0); set.push_back(3); auto dom0 = graph->getDomSet(0); auto dom1 = graph->getDomSet(1); auto dom2 = graph->getDomSet(2); auto dom3 = graph->getDomSet(3); auto dom4 = graph->getDomSet(4); auto dom5 = graph->getDomSet(5); auto dom6 = graph->getDomSet(6); EXPECT_NE(dom0.find(0), dom0.end()); EXPECT_NE(dom1.find(0), dom1.end()); EXPECT_NE(dom2.find(0), dom2.end()); EXPECT_NE(dom3.find(0), dom3.end()); for (auto e : set) { EXPECT_NE(dom4.find(e), dom4.end()); EXPECT_NE(dom5.find(e), dom5.end()); EXPECT_NE(dom6.find(e), dom6.end()); } } } } <commit_msg>Fixed cfg test segfault<commit_after>#include <gtest/gtest.h> #include "mcc/cfg/cfg.h" #include "parser.h" #include "boost/graph/graphviz.hpp" namespace mcc { namespace cfg { TEST(Cfg, Cfg) { auto tree = parser::parse( R"( { int x=1; float y = 3.0; if(x > 0) { y = y * 1.5; } else { y = y + 2.0; } int a = 0; if( 1 <= 2) { a = 1; } else { a = 2; } })"); mcc::tac::Tac tac; tac.convertAst(tree); auto graph = std::make_shared<Cfg>(tac); std::string expected = R"(digraph G { 0; 1; 2; 3; 4; 5; 6; 0->1 ; 0->2 ; 1->3 ; 2->3 ; 3->4 ; 3->5 ; 4->6 ; 5->6 ; } )"; EXPECT_EQ(expected, graph->toDot()); } TEST(Cfg, Idom) { auto tree = parser::parse( R"( { int x=1; float y = 3.0; if(x > 0) { y = y * 1.5; } else { y = y + 2.0; } int a = 0; if( 1 <= 2) { a = 1; } else { a = 2; } })"); mcc::tac::Tac tac; tac.convertAst(tree); auto graph = std::make_shared<Cfg>(tac); auto index = tac.getBasicBlockIndex(); // TODO find reason why shared pointers as well as the results of get() are not equal EXPECT_EQ(graph->getIdom(index[0])->toString(), index[0]->toString()); EXPECT_EQ(graph->getIdom(index[1])->toString(), index[0]->toString()); EXPECT_EQ(graph->getIdom(index[2])->toString(), index[0]->toString()); EXPECT_EQ(graph->getIdom(index[3])->toString(), index[0]->toString()); EXPECT_EQ(graph->getIdom(index[4])->toString(), index[3]->toString()); EXPECT_EQ(graph->getIdom(index[5])->toString(), index[3]->toString()); EXPECT_EQ(graph->getIdom(index[6])->toString(), index[3]->toString()); EXPECT_EQ(graph->getIdom(0), 0); EXPECT_EQ(graph->getIdom(1), 0); EXPECT_EQ(graph->getIdom(2), 0); EXPECT_EQ(graph->getIdom(3), 0); EXPECT_EQ(graph->getIdom(4), 3); EXPECT_EQ(graph->getIdom(5), 3); EXPECT_EQ(graph->getIdom(6), 3); } TEST(Cfg, DomSetVertex) { auto tree = parser::parse( R"( { int x=1; float y = 3.0; if(x > 0) { y = y * 1.5; } else { y = y + 2.0; } int a = 0; if( 1 <= 2) { a = 1; } else { a = 2; } })"); mcc::tac::Tac tac; tac.convertAst(tree); auto graph = std::make_shared<Cfg>(tac); auto index = tac.getBasicBlockIndex(); std::vector<Vertex> set; set.push_back(index[0]); set.push_back(index[3]); auto dom0 = graph->getDomSet(index[0]); auto dom1 = graph->getDomSet(index[1]); auto dom2 = graph->getDomSet(index[2]); auto dom3 = graph->getDomSet(index[3]); auto dom4 = graph->getDomSet(index[4]); auto dom5 = graph->getDomSet(index[5]); auto dom6 = graph->getDomSet(index[6]); // TODO find reason why shared pointers as well as the results of get() are not equal EXPECT_EQ(dom0.begin()->get()->toString(), index[0]->toString()); EXPECT_EQ(dom1.begin()->get()->toString(), index[0]->toString()); EXPECT_EQ(dom2.begin()->get()->toString(), index[0]->toString()); EXPECT_EQ(dom3.begin()->get()->toString(), index[0]->toString()); EXPECT_EQ(dom4.begin()->get()->toString(), index[3]->toString()); EXPECT_EQ(dom5.begin()->get()->toString(), index[3]->toString()); EXPECT_EQ(dom6.begin()->get()->toString(), index[3]->toString()); EXPECT_EQ((++dom4.begin())->get()->toString(), index[0]->toString()); EXPECT_EQ((++dom5.begin())->get()->toString(), index[0]->toString()); EXPECT_EQ((++dom6.begin())->get()->toString(), index[0]->toString()); } TEST(Cfg, DomSet) { auto tree = parser::parse( R"( { int x=1; float y = 3.0; if(x > 0) { y = y * 1.5; } else { y = y + 2.0; } int a = 0; if( 1 <= 2) { a = 1; } else { a = 2; } })"); mcc::tac::Tac tac; tac.convertAst(tree); auto graph = std::make_shared<Cfg>(tac); std::vector<VertexDescriptor> set; set.push_back(0); set.push_back(3); auto dom0 = graph->getDomSet(0); auto dom1 = graph->getDomSet(1); auto dom2 = graph->getDomSet(2); auto dom3 = graph->getDomSet(3); auto dom4 = graph->getDomSet(4); auto dom5 = graph->getDomSet(5); auto dom6 = graph->getDomSet(6); EXPECT_NE(dom0.find(0), dom0.end()); EXPECT_NE(dom1.find(0), dom1.end()); EXPECT_NE(dom2.find(0), dom2.end()); EXPECT_NE(dom3.find(0), dom3.end()); for (auto e : set) { EXPECT_NE(dom4.find(e), dom4.end()); EXPECT_NE(dom5.find(e), dom5.end()); EXPECT_NE(dom6.find(e), dom6.end()); } } } } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file CallTip.cxx ** Code for displaying call tips. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include "Platform.h" #include "Scintilla.h" #include "CallTip.h" CallTip::CallTip() { wCallTip = 0; inCallTipMode = false; posStartCallTip = 0; val = 0; xUp = -100; xDown = -100; lineHeight = 1; startHighlight = 0; endHighlight = 0; colourBG.desired = ColourDesired(0xff, 0xff, 0xff); colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80); colourSel.desired = ColourDesired(0, 0, 0x80); colourShade.desired = ColourDesired(0, 0, 0); colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0); } CallTip::~CallTip() { font.Release(); wCallTip.Destroy(); delete []val; val = 0; } const int widthArrow = 14; void CallTip::RefreshColourPalette(Palette &pal, bool want) { pal.WantFind(colourBG, want); pal.WantFind(colourUnSel, want); pal.WantFind(colourSel, want); pal.WantFind(colourShade, want); pal.WantFind(colourLight, want); } static bool IsArrowCharacter(char ch) { return (ch == 0) || (ch == '\001') || (ch == '\002'); } void CallTip::DrawChunk(Surface *surface, int &x, const char *s, int posStart, int posEnd, int ytext, PRectangle rcClient, bool highlight, bool draw) { s += posStart; int len = posEnd - posStart; int maxEnd = 0; int ends[10]; for (int i=0;i<len;i++) { if (IsArrowCharacter(s[i])) { if (i > 0) ends[maxEnd++] = i; ends[maxEnd++] = i+1; } } ends[maxEnd++] = len; int startSeg = 0; int xEnd; for (int seg = 0; seg<maxEnd; seg++) { int endSeg = ends[seg]; if (endSeg > startSeg) { if (IsArrowCharacter(s[startSeg])) { xEnd = x + widthArrow; offsetMain = xEnd; if (draw) { const int halfWidth = widthArrow / 2 - 3; const int centreX = x + widthArrow / 2 - 1; const int centreY = (rcClient.top + rcClient.bottom) / 2; rcClient.left = x; rcClient.right = xEnd; surface->FillRectangle(rcClient, colourBG.allocated); PRectangle rcClientInner(rcClient.left+1, rcClient.top+1, rcClient.right-2, rcClient.bottom-1); surface->FillRectangle(rcClientInner, colourUnSel.allocated); if (s[startSeg] == '\001') { // Up arrow Point pts[] = { Point(centreX - halfWidth, centreY + halfWidth / 2), Point(centreX + halfWidth, centreY + halfWidth / 2), Point(centreX, centreY - halfWidth + halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } else { // Down arrow Point pts[] = { Point(centreX - halfWidth, centreY - halfWidth / 2), Point(centreX + halfWidth, centreY - halfWidth / 2), Point(centreX, centreY + halfWidth - halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } } else { if (s[startSeg] == '\001') { xUp = x+1; } else { xDown = x+1; } } } else { xEnd = x + surface->WidthText(font, s+startSeg, endSeg - startSeg); if (draw) { rcClient.left = x; rcClient.right = xEnd; surface->DrawTextNoClip(rcClient, font, ytext, s+startSeg, endSeg - startSeg, highlight ? colourSel.allocated : colourUnSel.allocated, colourBG.allocated); } } x = xEnd; startSeg = endSeg; } } } int CallTip::PaintContents(Surface *surfaceWindow, bool draw) { PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); // To make a nice small call tip window, it is only sized to fit most normal characters without accents int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font); // For each line... // Draw the definition in three parts: before highlight, highlighted, after highlight int ytext = rcClient.top + ascent + 1; rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1; char *chunkVal = val; bool moreChunks = true; int maxWidth = 0; while (moreChunks) { char *chunkEnd = strchr(chunkVal, '\n'); if (chunkEnd == NULL) { chunkEnd = chunkVal + strlen(chunkVal); moreChunks = false; } int chunkOffset = chunkVal - val; int chunkLength = chunkEnd - chunkVal; int chunkEndOffset = chunkOffset + chunkLength; int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset); thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset); thisStartHighlight -= chunkOffset; int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset); thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset); thisEndHighlight -= chunkOffset; rcClient.top = ytext - ascent - 1; int x = 5; DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight, ytext, rcClient, false, draw); DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight, ytext, rcClient, true, draw); DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength, ytext, rcClient, false, draw); chunkVal = chunkEnd + 1; ytext += lineHeight; rcClient.bottom += lineHeight; maxWidth = Platform::Maximum(maxWidth, x); } return maxWidth; } void CallTip::PaintCT(Surface *surfaceWindow) { if (!val) return; PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->FillRectangle(rcClient, colourBG.allocated); offsetMain = 5; PaintContents(surfaceWindow, true); // Draw a raised border around the edges of the window surfaceWindow->MoveTo(0, rcClientSize.bottom - 1); surfaceWindow->PenColour(colourShade.allocated); surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->LineTo(rcClientSize.right - 1, 0); surfaceWindow->PenColour(colourLight.allocated); surfaceWindow->LineTo(0, 0); surfaceWindow->LineTo(0, rcClientSize.bottom - 1); } void CallTip::MouseClick(Point pt) { clickPlace = 0; if (pt.y < lineHeight) { if ((pt.x > xUp) && (pt.x < xUp + widthArrow - 2)) { clickPlace = 1; } else if ((pt.x > xDown) && (pt.x < xDown + widthArrow - 2)) { clickPlace = 2; } } } PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn, const char *faceName, int size, int codePage_, int characterSet, Window &wParent) { clickPlace = 0; if (val) delete []val; val = new char[strlen(defn) + 1]; if (!val) return PRectangle(); strcpy(val, defn); codePage = codePage_; Surface *surfaceMeasure = Surface::Allocate(); if (!surfaceMeasure) return PRectangle(); surfaceMeasure->Init(wParent.GetID()); surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage); surfaceMeasure->SetDBCSMode(codePage); startHighlight = 0; endHighlight = 0; inCallTipMode = true; posStartCallTip = pos; int deviceHeight = surfaceMeasure->DeviceHeightFont(size); font.Create(faceName, characterSet, deviceHeight, false, false); // Look for multiple lines in the text // Only support \n here - simply means container must avoid \r! int numLines = 1; const char *newline; const char *look = val; xUp = -100; xDown = -100; offsetMain = 5; int width = PaintContents(surfaceMeasure, false) + 5; while ((newline = strchr(look, '\n')) != NULL) { look = newline + 1; numLines++; } lineHeight = surfaceMeasure->Height(font); // Extra line for border and an empty line at top and bottom int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2; delete surfaceMeasure; return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height); } void CallTip::CallTipCancel() { inCallTipMode = false; if (wCallTip.Created()) { wCallTip.Destroy(); } } void CallTip::SetHighlight(int start, int end) { // Avoid flashing by checking something has really changed if ((start != startHighlight) || (end != endHighlight)) { startHighlight = start; endHighlight = end; if (wCallTip.Created()) { wCallTip.InvalidateAll(); } } } <commit_msg>Fixed up and down button handling so they work when not on first line of calltip.<commit_after>// Scintilla source code edit control /** @file CallTip.cxx ** Code for displaying call tips. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include "Platform.h" #include "Scintilla.h" #include "CallTip.h" CallTip::CallTip() { wCallTip = 0; inCallTipMode = false; posStartCallTip = 0; val = 0; rectUp = PRectangle(0,0,0,0); rectDown = PRectangle(0,0,0,0); lineHeight = 1; startHighlight = 0; endHighlight = 0; colourBG.desired = ColourDesired(0xff, 0xff, 0xff); colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80); colourSel.desired = ColourDesired(0, 0, 0x80); colourShade.desired = ColourDesired(0, 0, 0); colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0); } CallTip::~CallTip() { font.Release(); wCallTip.Destroy(); delete []val; val = 0; } const int widthArrow = 14; void CallTip::RefreshColourPalette(Palette &pal, bool want) { pal.WantFind(colourBG, want); pal.WantFind(colourUnSel, want); pal.WantFind(colourSel, want); pal.WantFind(colourShade, want); pal.WantFind(colourLight, want); } static bool IsArrowCharacter(char ch) { return (ch == 0) || (ch == '\001') || (ch == '\002'); } void CallTip::DrawChunk(Surface *surface, int &x, const char *s, int posStart, int posEnd, int ytext, PRectangle rcClient, bool highlight, bool draw) { s += posStart; int len = posEnd - posStart; int maxEnd = 0; int ends[10]; for (int i=0;i<len;i++) { if (IsArrowCharacter(s[i])) { if (i > 0) ends[maxEnd++] = i; ends[maxEnd++] = i+1; } } ends[maxEnd++] = len; int startSeg = 0; int xEnd; for (int seg = 0; seg<maxEnd; seg++) { int endSeg = ends[seg]; if (endSeg > startSeg) { if (IsArrowCharacter(s[startSeg])) { xEnd = x + widthArrow; offsetMain = xEnd; rcClient.left = x; rcClient.right = xEnd; if (draw) { const int halfWidth = widthArrow / 2 - 3; const int centreX = x + widthArrow / 2 - 1; const int centreY = (rcClient.top + rcClient.bottom) / 2; surface->FillRectangle(rcClient, colourBG.allocated); PRectangle rcClientInner(rcClient.left+1, rcClient.top+1, rcClient.right-2, rcClient.bottom-1); surface->FillRectangle(rcClientInner, colourUnSel.allocated); if (s[startSeg] == '\001') { // Up arrow Point pts[] = { Point(centreX - halfWidth, centreY + halfWidth / 2), Point(centreX + halfWidth, centreY + halfWidth / 2), Point(centreX, centreY - halfWidth + halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } else { // Down arrow Point pts[] = { Point(centreX - halfWidth, centreY - halfWidth / 2), Point(centreX + halfWidth, centreY - halfWidth / 2), Point(centreX, centreY + halfWidth - halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } } else { if (s[startSeg] == '\001') { rectUp = rcClient; } else { rectDown = rcClient; } } } else { xEnd = x + surface->WidthText(font, s+startSeg, endSeg - startSeg); if (draw) { rcClient.left = x; rcClient.right = xEnd; surface->DrawTextNoClip(rcClient, font, ytext, s+startSeg, endSeg - startSeg, highlight ? colourSel.allocated : colourUnSel.allocated, colourBG.allocated); } } x = xEnd; startSeg = endSeg; } } } int CallTip::PaintContents(Surface *surfaceWindow, bool draw) { PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); // To make a nice small call tip window, it is only sized to fit most normal characters without accents int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font); // For each line... // Draw the definition in three parts: before highlight, highlighted, after highlight int ytext = rcClient.top + ascent + 1; rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1; char *chunkVal = val; bool moreChunks = true; int maxWidth = 0; while (moreChunks) { char *chunkEnd = strchr(chunkVal, '\n'); if (chunkEnd == NULL) { chunkEnd = chunkVal + strlen(chunkVal); moreChunks = false; } int chunkOffset = chunkVal - val; int chunkLength = chunkEnd - chunkVal; int chunkEndOffset = chunkOffset + chunkLength; int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset); thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset); thisStartHighlight -= chunkOffset; int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset); thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset); thisEndHighlight -= chunkOffset; rcClient.top = ytext - ascent - 1; int x = 5; DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight, ytext, rcClient, false, draw); DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight, ytext, rcClient, true, draw); DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength, ytext, rcClient, false, draw); chunkVal = chunkEnd + 1; ytext += lineHeight; rcClient.bottom += lineHeight; maxWidth = Platform::Maximum(maxWidth, x); } return maxWidth; } void CallTip::PaintCT(Surface *surfaceWindow) { if (!val) return; PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->FillRectangle(rcClient, colourBG.allocated); offsetMain = 5; PaintContents(surfaceWindow, true); // Draw a raised border around the edges of the window surfaceWindow->MoveTo(0, rcClientSize.bottom - 1); surfaceWindow->PenColour(colourShade.allocated); surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->LineTo(rcClientSize.right - 1, 0); surfaceWindow->PenColour(colourLight.allocated); surfaceWindow->LineTo(0, 0); surfaceWindow->LineTo(0, rcClientSize.bottom - 1); } void CallTip::MouseClick(Point pt) { clickPlace = 0; if (rectUp.Contains(pt)) clickPlace = 1; if (rectDown.Contains(pt)) clickPlace = 2; } PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn, const char *faceName, int size, int codePage_, int characterSet, Window &wParent) { clickPlace = 0; if (val) delete []val; val = new char[strlen(defn) + 1]; if (!val) return PRectangle(); strcpy(val, defn); codePage = codePage_; Surface *surfaceMeasure = Surface::Allocate(); if (!surfaceMeasure) return PRectangle(); surfaceMeasure->Init(wParent.GetID()); surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage); surfaceMeasure->SetDBCSMode(codePage); startHighlight = 0; endHighlight = 0; inCallTipMode = true; posStartCallTip = pos; int deviceHeight = surfaceMeasure->DeviceHeightFont(size); font.Create(faceName, characterSet, deviceHeight, false, false); // Look for multiple lines in the text // Only support \n here - simply means container must avoid \r! int numLines = 1; const char *newline; const char *look = val; rectUp = PRectangle(0,0,0,0); rectDown = PRectangle(0,0,0,0); offsetMain = 5; int width = PaintContents(surfaceMeasure, false) + 5; while ((newline = strchr(look, '\n')) != NULL) { look = newline + 1; numLines++; } lineHeight = surfaceMeasure->Height(font); // Extra line for border and an empty line at top and bottom int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2; delete surfaceMeasure; return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height); } void CallTip::CallTipCancel() { inCallTipMode = false; if (wCallTip.Created()) { wCallTip.Destroy(); } } void CallTip::SetHighlight(int start, int end) { // Avoid flashing by checking something has really changed if ((start != startHighlight) || (end != endHighlight)) { startHighlight = start; endHighlight = end; if (wCallTip.Created()) { wCallTip.InvalidateAll(); } } } <|endoftext|>
<commit_before>#include "../include/Cluster.hpp" using namespace std; Cluster::Cluster(Options options) { int symmetric, format, offset; bool reduceZeroRows, transpose, printCooOrDense; #if 0 std::string path2matrix = options.path2data+"/testMat"+to_string(0)+".txt"; Matrix A; symmetric = 0; // 0-not, 1-lower tr., 2-upper tr. format = 1; // 0-coo, 1-csr, 2-dense offset = 0; printCooOrDense = true; A.readCooFromFile(path2matrix,symmetric,format,offset); A.printToFile("modif",0,printCooOrDense); A.CSR2COO(); A.printToFile("modif2",0,printCooOrDense); printCooOrDense = true; A.printToFile("modif3",0,printCooOrDense); return #endif const int nS = options.n_subdomOnCluster; K.resize(nS); K_reg.resize(nS); Lumped.resize(nS); R.resize(nS); rhs.resize(nS); Bc.resize(nS); Bf.resize(nS); Bc_dense.resize(nS); Fc.resize(nS); Gc.resize(nS); /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* READING DATA (TXT) */ /* matrices in coo format are one-based */ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ for (int i = 0 ; i < nS ; i++){ /* K - stiffness matrix */ string path2matrix = options.path2data+"/K"+to_string(i)+".txt"; symmetric = 2; format = 1; offset = 1; K[i].readCooFromFile(path2matrix,symmetric,format,offset); /* R - kernel matrix */ path2matrix = options.path2data+"/R1"+to_string(i)+".txt"; symmetric = 0; format = 2; offset = 1; R[i].readCooFromFile(path2matrix,symmetric,format,offset); /* rhs - right-hand-side vector */ path2matrix = options.path2data+"/f"+to_string(i)+".txt"; rhs[i].readCooFromFile(path2matrix,K[i].n_row); // /* Bf - constraints matrix */ path2matrix = options.path2data+"/B1"+to_string(i)+".txt"; symmetric = 0; format = 1; offset = 1; Bf[i].readCooFromFile(path2matrix,symmetric,format,offset); // /* Bc - constraints matrix */ path2matrix = options.path2data+"/B0"+to_string(i)+".txt"; symmetric = 0; format = 1; offset = 1; Bc[i].readCooFromFile(path2matrix,symmetric,format,offset); // /* Bc_dense - constraints matrix */ Bc_dense[i] = Bc[i]; reduceZeroRows = true; transpose = true; Bc_dense[i].CSRorCOO2DNS(reduceZeroRows,transpose); } for (int i_sub = 0; i_sub < nS; i_sub++){ Matrix Y; Y.zero_dense(K[i_sub].n_row_cmprs , R[i_sub].n_col); K[i_sub].mult(R[i_sub],Y,true); double normK = K[i_sub].norm2(); double normR = R[i_sub].norm2(); double normKR = Y.norm2(); printf("|K| = %.6e, ", normK); printf("|R| = %.6e, ", normR); printf("|KR|/(|K|*|R|) = %.6e \n", normKR / (normK*normR)); } printCooOrDense = true; for (int i = 0; i < nS ; i++ ){ K_reg[i] = K[i]; K_reg[i].factorization(); Matrix BcK_dense; BcK_dense = Matrix::CreateCopyFrom(Bc_dense[i]); BcK_dense.setZero(); K[i].mult(Bc_dense[i],BcK_dense,true); BcK_dense.printToFile("BcK_dense",i,printCooOrDense); Lumped[i].zero_dense(Bc[i].n_row_cmprs, Bc[i].n_row_cmprs); Bc[i].mult(BcK_dense,Lumped[i],true); Lumped[i].printToFile("Lumped",i,printCooOrDense); Matrix BcKplus_dense; BcKplus_dense = Matrix::CreateCopyFrom(Bc_dense[i]); BcKplus_dense.setZero(); K_reg[i].solve(Bc_dense[i],BcKplus_dense); BcKplus_dense.printToFile("BcKplus",i,printCooOrDense); Fc[i].zero_dense(Bc[i].n_row_cmprs, Bc[i].n_row_cmprs); Bc[i].mult(BcKplus_dense,Fc[i],true); Fc[i].printToFile("Fc",i,printCooOrDense); Fc[i].l2g_i_coo = Bc[i].l2g_i_coo; /* Gc - constraints matrix */ int n_rowGc = Bc[i].n_row_cmprs; int n_colGc = R[i].n_col; Gc[i].zero_dense(n_rowGc, n_colGc ); Bc[i].mult(R[i],Gc[i],true); K[i].printToFile("K",i,printCooOrDense); K_reg[i].printToFile("K_reg",i,printCooOrDense); R[i].printToFile("R",i,printCooOrDense); Bc[i].printToFile("Bc",i,printCooOrDense); Bc_dense[i].printToFile("Bc_dense",i,printCooOrDense); Bf[i].printToFile("Bf",i,printCooOrDense); Gc[i].printToFile("Gc",i,printCooOrDense); Gc[i].l2g_i_coo = Bc[i].l2g_i_coo; } // Matrix::testPardiso(); /* Fc_clust */ createFc_clust(); Fc_clust.printToFile("Fc_clust",0,printCooOrDense); createGc_clust(); Gc_clust.printToFile("Gc_clust",0,printCooOrDense); for (int i = 0 ; i < nS; i++){ K_reg[i].FinalizeSolve(i); } } void Cluster::createFc_clust(){ Matrix & A_clust = Fc_clust; vector <Matrix> & A_i = Fc; A_clust.symmetric = 2; bool remapCols = true; create_clust_object(A_clust, A_i, remapCols); } void Cluster::createGc_clust(){ Matrix & A_clust = Gc_clust; vector <Matrix> & A_i = Gc; A_clust.symmetric = 0; bool remapCols = false; create_clust_object(A_clust, A_i, remapCols); } void Cluster::create_clust_object(Matrix &A_clust, vector <Matrix> & A_i, bool remapCols){ const int nS = A_i.size(); int init_nnz = 0; for (int i = 0; i < nS; i++){ init_nnz += A_i[i].nnz; } A_clust.format = 0; vector < int_int_dbl > tmpVec; tmpVec.resize(init_nnz); A_clust.n_col = 0; /* Sorting [I, J, V] --------------------------------------------------------*/ int cnt = 0; int _i, _j; for (int d = 0; d < nS ; d++){ A_i[d].DNS2COO(); for (int i = 0; i < A_i[d].i_coo_cmpr.size();i++){ _i = A_i[d].l2g_i_coo[ A_i[d].i_coo_cmpr[i] ]; _j = A_i[d].j_col[i]; if (remapCols){ _j = A_i[d].l2g_i_coo[ _j ]; } else{ _j += A_clust.n_col; } if (A_clust.symmetric == 0 || (A_clust.symmetric == 1 && _j <= _i) || (A_clust.symmetric == 2 && _i <= _j) ){ tmpVec[cnt].I = _i; tmpVec[cnt].J = _j; tmpVec[cnt].V = A_i[d].val[i]; cnt++; } } A_clust.n_col += A_i[d].n_col; } A_clust.nnz = cnt; tmpVec.resize(A_clust.nnz); /* sort according to index I -------------------------------------------------*/ sort(tmpVec.begin(),tmpVec.end(),Matrix::cmp_int_int_I); /* partial sorting according to index J (per sets with same I)----------------*/ int startInd = 0, endInd = 1; int tmpVecIprev = tmpVec[0].I; for (int i = 1 ; i < tmpVec.size(); i ++){ if (tmpVec[i].I == tmpVecIprev){ endInd++; } if (tmpVec[i].I != tmpVecIprev || (tmpVec[i].I == tmpVecIprev && i == tmpVec.size() - 1)) { sort(tmpVec.begin() + startInd, tmpVec.begin() + (endInd ),Matrix::cmp_int_int_J); startInd = i; endInd = i + 1; } tmpVecIprev = tmpVec[i].I; } /* Cumulating duplicated A[I,J] elements--------------------------------------*/ int prevInd_I = -1; int prevInd_J = -1; int counter = 0; int cnt_j = -1; A_clust.l2g_i_coo.resize(tmpVec.size()); A_clust.i_coo_cmpr.resize(A_clust.nnz); A_clust.j_col.resize(A_clust.nnz); A_clust.val.resize(A_clust.nnz); for (int i = 0 ; i < tmpVec.size(); i++){ if (prevInd_I != tmpVec[i].I){ A_clust.l2g_i_coo[counter] = tmpVec[i].I; counter++; } if (prevInd_I == tmpVec[i].I && prevInd_J == tmpVec[i].J){ A_clust.val[cnt_j] += tmpVec[i].V; A_clust.nnz--; } else { cnt_j++; A_clust.i_coo_cmpr[cnt_j] = counter - 1; A_clust.j_col[cnt_j] = tmpVec[i].J; A_clust.val[cnt_j] = tmpVec[i].V; } prevInd_I = tmpVec[i].I; prevInd_J = tmpVec[i].J; } A_clust.l2g_i_coo.resize(counter ); A_clust.l2g_i_coo.shrink_to_fit(); A_clust.i_coo_cmpr.resize(A_clust.nnz); A_clust.i_coo_cmpr.shrink_to_fit(); A_clust.j_col.resize(A_clust.nnz); A_clust.j_col.shrink_to_fit(); A_clust.val.resize(A_clust.nnz); A_clust.val.shrink_to_fit(); A_clust.n_row_cmprs = counter; A_clust.n_row = counter; if (A_clust.symmetric > 0){ A_clust.n_col = A_clust.n_row_cmprs; } A_clust.COO2CSR(); tmpVec.clear(); tmpVec.shrink_to_fit(); } <commit_msg>src/Cluster.cpp: refactoring<commit_after>#include "../include/Cluster.hpp" using namespace std; Cluster::Cluster(Options options) { int symmetric, format, offset; bool reduceZeroRows, transpose, printCooOrDense; #if 0 std::string path2matrix = options.path2data+"/testMat"+to_string(0)+".txt"; Matrix A; symmetric = 0; // 0-not, 1-lower tr., 2-upper tr. format = 1; // 0-coo, 1-csr, 2-dense offset = 0; printCooOrDense = true; A.readCooFromFile(path2matrix,symmetric,format,offset); A.printToFile("modif",folder,0,printCooOrDense); A.CSR2COO(); A.printToFile("modif2",folder,0,printCooOrDense); printCooOrDense = true; A.printToFile("modif3",folder,0,printCooOrDense); return #endif const int nS = options.n_subdomOnCluster; string folder = options.path2data; K.resize(nS); K_reg.resize(nS); Lumped.resize(nS); R.resize(nS); rhs.resize(nS); Bc.resize(nS); Bf.resize(nS); Bc_dense.resize(nS); Fc.resize(nS); Gc.resize(nS); /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* READING DATA (TXT) */ /* matrices in coo format are one-based */ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ for (int i = 0 ; i < nS ; i++){ /* K - stiffness matrix */ string path2matrix = options.path2data+"/K"+to_string(i)+".txt"; symmetric = 2; format = 1; offset = 1; K[i].readCooFromFile(path2matrix,symmetric,format,offset); /* R - kernel matrix */ path2matrix = options.path2data+"/R1"+to_string(i)+".txt"; symmetric = 0; format = 2; offset = 1; R[i].readCooFromFile(path2matrix,symmetric,format,offset); /* rhs - right-hand-side vector */ path2matrix = options.path2data+"/f"+to_string(i)+".txt"; rhs[i].readCooFromFile(path2matrix,K[i].n_row); // /* Bf - constraints matrix */ path2matrix = options.path2data+"/B1"+to_string(i)+".txt"; symmetric = 0; format = 1; offset = 1; Bf[i].readCooFromFile(path2matrix,symmetric,format,offset); // /* Bc - constraints matrix */ path2matrix = options.path2data+"/B0"+to_string(i)+".txt"; symmetric = 0; format = 1; offset = 1; Bc[i].readCooFromFile(path2matrix,symmetric,format,offset); // /* Bc_dense - constraints matrix */ Bc_dense[i] = Bc[i]; reduceZeroRows = true; transpose = true; Bc_dense[i].CSRorCOO2DNS(reduceZeroRows,transpose); } #if 0 for (int i_sub = 0; i_sub < nS; i_sub++){ Matrix Y; Y.zero_dense(K[i_sub].n_row_cmprs , R[i_sub].n_col); K[i_sub].mult(R[i_sub],Y,true); double normK = K[i_sub].norm2(); double normR = R[i_sub].norm2(); double normKR = Y.norm2(); printf("|K| = %.6e, ", normK); printf("|R| = %.6e, ", normR); printf("|KR|/(|K|*|R|) = %.6e \n", normKR / (normK*normR)); } #endif printCooOrDense = true; for (int i = 0; i < nS ; i++ ){ vector <int > nullPivots; R[i].getNullPivots(nullPivots); // for (int i = 0 ; i < nullPivots.size(); i++){ // cout << nullPivots[i] << endl; // } K_reg[i] = K[i]; K_reg[i].factorization(nullPivots); Matrix BcK_dense; //BcK_dense = Matrix::CreateCopyFrom(Bc_dense[i]); BcK_dense = Bc_dense[i]; BcK_dense.setZero(); K[i].mult(Bc_dense[i],BcK_dense,true); BcK_dense.printToFile("BcK_dense",folder,i,printCooOrDense); Lumped[i].zero_dense(Bc[i].n_row_cmprs, Bc[i].n_row_cmprs); Bc[i].mult(BcK_dense,Lumped[i],true); Lumped[i].printToFile("Lumped",folder,i,printCooOrDense); Matrix BcKplus_dense; // BcKplus_dense = Matrix::CreateCopyFrom(Bc_dense[i]); BcKplus_dense = Bc_dense[i]; BcKplus_dense.setZero(); K_reg[i].solve(Bc_dense[i],BcKplus_dense); BcKplus_dense.printToFile("BcKplus",folder,i,printCooOrDense); Fc[i].zero_dense(Bc[i].n_row_cmprs, Bc[i].n_row_cmprs); Bc[i].mult(BcKplus_dense,Fc[i],true); Fc[i].printToFile("Fc",folder,i,printCooOrDense); Fc[i].l2g_i_coo = Bc[i].l2g_i_coo; /* Gc - constraints matrix */ int n_rowGc = Bc[i].n_row_cmprs; int n_colGc = R[i].n_col; Gc[i].zero_dense(n_rowGc, n_colGc ); Bc[i].mult(R[i],Gc[i],true); /* print */ /* K, R, etc.*/ cout << " ... printing matrices start ..."; K[i].printToFile("K",folder,i,printCooOrDense); K_reg[i].printToFile("K_reg",folder,i,printCooOrDense); R[i].printToFile("R",folder,i,printCooOrDense); Bc[i].printToFile("Bc",folder,i,printCooOrDense); Bc_dense[i].printToFile("Bc_dense",folder,i,printCooOrDense); Bf[i].printToFile("Bf",folder,i,printCooOrDense); Gc[i].printToFile("Gc",folder,i,printCooOrDense); Gc[i].l2g_i_coo = Bc[i].l2g_i_coo; cout << " " << i <<"/" << nS <<" ...\n"; } // Matrix::testPardiso(); /* Fc_clust */ create_Fc_clust(); Fc_clust.printToFile("Fc_clust",folder,0,printCooOrDense); create_Gc_clust(); Gc_clust.printToFile("Gc_clust",folder,0,printCooOrDense); for (int i = 0 ; i < nS; i++){ K_reg[i].FinalizeSolve(i); } } void Cluster::create_Fc_clust(){ Matrix & A_clust = Fc_clust; vector <Matrix> & A_i = Fc; A_clust.symmetric = 2; bool remapCols = true; create_clust_object(A_clust, A_i, remapCols); } void Cluster::create_Gc_clust(){ Matrix & A_clust = Gc_clust; vector <Matrix> & A_i = Gc; A_clust.symmetric = 0; bool remapCols = false; create_clust_object(A_clust, A_i, remapCols); } void Cluster::create_clust_object(Matrix &A_clust, vector <Matrix> & A_i, bool remapCols){ const int nS = A_i.size(); int init_nnz = 0; for (int i = 0; i < nS; i++){ init_nnz += A_i[i].nnz; } A_clust.format = 0; vector < int_int_dbl > tmpVec; tmpVec.resize(init_nnz); A_clust.n_col = 0; /* Sorting [I, J, V] --------------------------------------------------------*/ int cnt = 0; int _i, _j; for (int d = 0; d < nS ; d++){ A_i[d].DNS2COO(); for (int i = 0; i < A_i[d].i_coo_cmpr.size();i++){ _i = A_i[d].l2g_i_coo[ A_i[d].i_coo_cmpr[i] ]; _j = A_i[d].j_col[i]; if (remapCols){ _j = A_i[d].l2g_i_coo[ _j ]; } else{ _j += A_clust.n_col; } if (A_clust.symmetric == 0 || (A_clust.symmetric == 1 && _j <= _i) || (A_clust.symmetric == 2 && _i <= _j) ){ tmpVec[cnt].I = _i; tmpVec[cnt].J = _j; tmpVec[cnt].V = A_i[d].val[i]; cnt++; } } A_clust.n_col += A_i[d].n_col; } A_clust.nnz = cnt; tmpVec.resize(A_clust.nnz); /* sort according to index I -------------------------------------------------*/ sort(tmpVec.begin(),tmpVec.end(),Matrix::cmp_int_int_I); /* partial sorting according to index J (per sets with same I)----------------*/ int startInd = 0, endInd = 1; int tmpVecIprev = tmpVec[0].I; for (int i = 1 ; i < tmpVec.size(); i ++){ if (tmpVec[i].I == tmpVecIprev){ endInd++; } if (tmpVec[i].I != tmpVecIprev || (tmpVec[i].I == tmpVecIprev && i == tmpVec.size() - 1)) { sort(tmpVec.begin() + startInd, tmpVec.begin() + (endInd ),Matrix::cmp_int_int_J); startInd = i; endInd = i + 1; } tmpVecIprev = tmpVec[i].I; } /* Cumulating duplicated A[I,J] elements--------------------------------------*/ int prevInd_I = -1; int prevInd_J = -1; int counter = 0; int cnt_j = -1; A_clust.l2g_i_coo.resize(tmpVec.size()); A_clust.i_coo_cmpr.resize(A_clust.nnz); A_clust.j_col.resize(A_clust.nnz); A_clust.val.resize(A_clust.nnz); for (int i = 0 ; i < tmpVec.size(); i++){ if (prevInd_I != tmpVec[i].I){ A_clust.l2g_i_coo[counter] = tmpVec[i].I; counter++; } if (prevInd_I == tmpVec[i].I && prevInd_J == tmpVec[i].J){ A_clust.val[cnt_j] += tmpVec[i].V; A_clust.nnz--; } else { cnt_j++; A_clust.i_coo_cmpr[cnt_j] = counter - 1; A_clust.j_col[cnt_j] = tmpVec[i].J; A_clust.val[cnt_j] = tmpVec[i].V; } prevInd_I = tmpVec[i].I; prevInd_J = tmpVec[i].J; } A_clust.l2g_i_coo.resize(counter ); A_clust.l2g_i_coo.shrink_to_fit(); A_clust.i_coo_cmpr.resize(A_clust.nnz); A_clust.i_coo_cmpr.shrink_to_fit(); A_clust.j_col.resize(A_clust.nnz); A_clust.j_col.shrink_to_fit(); A_clust.val.resize(A_clust.nnz); A_clust.val.shrink_to_fit(); A_clust.n_row_cmprs = counter; A_clust.n_row = counter; if (A_clust.symmetric > 0){ A_clust.n_col = A_clust.n_row_cmprs; } A_clust.COO2CSR(); tmpVec.clear(); tmpVec.shrink_to_fit(); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <cassert> #include "CubeCmd.h" #include "HdfWriter.h" #include "TextWriter.h" #include "VtkWriter.h" #include "StringUtils.h" using namespace std; using namespace cigma; // --------------------------------------------------------------------------- cigma::CubeCmd::CubeCmd() { name = "cube"; L = M = N = 0; mesh = 0; writer = 0; } cigma::CubeCmd::~CubeCmd() { } // --------------------------------------------------------------------------- void cigma::CubeCmd::setupOptions(AnyOption *opt) { //cout << "Calling cigma::CubeCmd::setupOptions()" << endl; assert(opt != 0); /* setup usage */ opt->addUsage("Usage:"); opt->addUsage(" cigma cube [options]"); opt->addUsage(" -x Number of elements along x-dimension"); opt->addUsage(" -y Number of elements along y-dimension"); opt->addUsage(" -z Number of elements along z-dimension"); opt->addUsage(" --hex8 Create hexahedral partition (default)"); opt->addUsage(" --tet4 Create tetrahedral partition"); opt->addUsage(" --output Target output file"); opt->addUsage(" --coords-path Target path for coordinates (.h5 only)"); opt->addUsage(" --connect-path Target path for connectivity (.h5 only)"); /* setup flags and options */ opt->setFlag("help", 'h'); opt->setFlag("verbose", 'v'); opt->setFlag("hex8"); opt->setFlag("tet4"); opt->setOption('x'); opt->setOption('y'); opt->setOption('z'); opt->setOption("output", 'o'); opt->setOption("coords-path"); opt->setOption("connect-path"); } void cigma::CubeCmd::configure(AnyOption *opt) { //std::cout << "Calling cigma::CubeCmd::configure()" << std::endl; assert(opt != 0); if (!opt->hasOptions()) { //std::cerr << "No options?" << std::endl; opt->printUsage(); exit(1); } char *in; string inputstr; // read verbose flag verbose = opt->getFlag("verbose"); // read L in = opt->getValue('x'); if (in == 0) { cerr << "cube: Please specify the option -x" << endl; exit(1); } inputstr = in; string_to_int(inputstr, L); // read M in = opt->getValue('y'); if (in == 0) { cerr << "cube: Please specify the option -y" << endl; exit(1); } inputstr = in; string_to_int(inputstr, M); // read N in = opt->getValue('z'); if (in == 0) { cerr << "cube: Please specify the option -z" << endl; exit(1); } inputstr = in; string_to_int(inputstr, N); // read output file in = opt->getValue("output"); if (in == 0) { cerr << "cube: Please specify the option --output" << endl; exit(1); } output_filename = in; // determine the extension and instantiate appropriate writer object string root, ext; path_splitext(output_filename, root, ext); writer = NewWriter(ext.c_str()); if (writer == 0) { cerr << "cube: File with bad extension (" << ext << ")" << endl; exit(1); } // read target path for coordinates array in = opt->getValue("coords-path"); if (in == 0) { if (writer->getType() == Writer::HDF_WRITER) { coords_path = "/coordinates"; } } else { coords_path = in; } if ((coords_path != "") && (writer->getType() != Writer::HDF_WRITER)) { cerr << "cube: Can only use --coords-path " << "when writing to an HDF5 (.h5) file" << endl; exit(1); } // read target path for connectivity array in = opt->getValue("connect-path"); if (in == 0) { if (writer->getType() == Writer::HDF_WRITER) { connect_path = "/connectivity"; } } else { connect_path = in; } if ((connect_path != "") && (writer->getType() != Writer::HDF_WRITER)) { cerr << "cube: Can only use --connect-path " << "when writing to an HDF5 (.h5) file" << endl; exit(1); } // read tet/hex flags bool hexFlag = opt->getFlag("hex8"); bool tetFlag = opt->getFlag("tet4"); if (hexFlag && tetFlag) { std::cerr << "cube: Please specify only one of the flags " << "--hex8 or --tet8" << std::endl; exit(1); } if (!tetFlag) { hexFlag = true; } assert(hexFlag != tetFlag); // initialize mesh object mesh = new cigma::CubeMeshPart(); mesh->calc_coordinates(L,M,N); if (hexFlag) { mesh->calc_hex8_connectivity(); } if (tetFlag) { mesh->calc_tet4_connectivity(); } } int cigma::CubeCmd::run() { //std::cout << "Calling cigma::CubeCmd::run()" << std::endl; assert(mesh != 0); assert(writer != 0); if (verbose) { std::cout << "L, M, N = (" << L << ", " << M << ", " << N << ")" << std::endl; std::cout << "mesh->nno = " << mesh->nno << std::endl; std::cout << "mesh->nel = " << mesh->nel << std::endl; std::cout << "mesh->ndofs = " << mesh->ndofs << std::endl; } if (verbose) { int e = 0; double pts[2][3] = {{0.5, 0.5, 0.5}, {1.0, 1.0, 1.0}}; cout << "cube test: Looking for centroid..." << endl; bool found = mesh->find_cell(pts[0], &e); if (!found) { cerr << "cube test error: Could not find cell " << "containing centroid (0.5,0.5,0.5)" << endl; exit(1); } else { cout << "cube test: Found centroid in cell " << e << endl; } } int ierr; cout << "Creating file " << output_filename << endl; if (writer->getType() == Writer::HDF_WRITER) { HdfWriter *hdfWriter = static_cast<HdfWriter*>(writer); ierr = hdfWriter->open(output_filename.c_str()); if (ierr < 0) { cerr << "Error: Could not open (or create) the HDF5 file " << output_filename << endl; exit(1); } ierr = hdfWriter->write_coordinates(coords_path.c_str(), mesh->coords, mesh->nno, mesh->nsd); if (ierr < 0) { cerr << "Error: Could not write dataset " << coords_path << endl; exit(1); } ierr = hdfWriter->write_connectivity(connect_path.c_str(), mesh->connect, mesh->nel, mesh->ndofs); if (ierr < 0) { cerr << "Error: Could not write dataset " << connect_path << endl; exit(1); } hdfWriter->close(); } else if (writer->getType() == Writer::TEXT_WRITER) { TextWriter *textWriter = static_cast<TextWriter*>(writer); ierr = textWriter->open(output_filename.c_str()); if (ierr < 0) { cerr << "Error: Could not create output text file " << output_filename << endl; exit(1); } textWriter->write_coordinates(mesh->coords, mesh->nno, mesh->nsd); textWriter->write_connectivity(mesh->connect, mesh->nel, mesh->ndofs); textWriter->close(); } else if (writer->getType() == Writer::VTK_WRITER) { VtkWriter *vtkWriter = static_cast<VtkWriter*>(writer); ierr = vtkWriter->open(output_filename.c_str()); if (ierr < 0) { cerr << "Error: Could not create output VTK file " << output_filename << endl; exit(1); } vtkWriter->write_header(); vtkWriter->write_points(mesh->coords, mesh->nno, mesh->nsd); vtkWriter->write_cells(mesh->connect, mesh->nel, mesh->ndofs); vtkWriter->write_cell_types(mesh->nsd, mesh->nel, mesh->ndofs); vtkWriter->close(); } else { /* this should be unreachable */ cerr << "Fatal Error: Unsupported extension in output filename?" << endl; return 1; } if (writer != 0) { delete writer; } return 0; } // --------------------------------------------------------------------------- <commit_msg>Updated usage of TextWriter in CubeCmd<commit_after>#include <iostream> #include <string> #include <cassert> #include "CubeCmd.h" #include "HdfWriter.h" #include "TextWriter.h" #include "VtkWriter.h" #include "StringUtils.h" using namespace std; using namespace cigma; // --------------------------------------------------------------------------- cigma::CubeCmd::CubeCmd() { name = "cube"; L = M = N = 0; mesh = 0; writer = 0; } cigma::CubeCmd::~CubeCmd() { } // --------------------------------------------------------------------------- void cigma::CubeCmd::setupOptions(AnyOption *opt) { //cout << "Calling cigma::CubeCmd::setupOptions()" << endl; assert(opt != 0); /* setup usage */ opt->addUsage("Usage:"); opt->addUsage(" cigma cube [options]"); opt->addUsage(" -x Number of elements along x-dimension"); opt->addUsage(" -y Number of elements along y-dimension"); opt->addUsage(" -z Number of elements along z-dimension"); opt->addUsage(" --hex8 Create hexahedral partition (default)"); opt->addUsage(" --tet4 Create tetrahedral partition"); opt->addUsage(" --output Target output file"); opt->addUsage(" --coords-path Target path for coordinates (.h5 only)"); opt->addUsage(" --connect-path Target path for connectivity (.h5 only)"); /* setup flags and options */ opt->setFlag("help", 'h'); opt->setFlag("verbose", 'v'); opt->setFlag("hex8"); opt->setFlag("tet4"); opt->setOption('x'); opt->setOption('y'); opt->setOption('z'); opt->setOption("output", 'o'); opt->setOption("coords-path"); opt->setOption("connect-path"); } void cigma::CubeCmd::configure(AnyOption *opt) { //std::cout << "Calling cigma::CubeCmd::configure()" << std::endl; assert(opt != 0); if (!opt->hasOptions()) { //std::cerr << "No options?" << std::endl; opt->printUsage(); exit(1); } char *in; string inputstr; // read verbose flag verbose = opt->getFlag("verbose"); // read L in = opt->getValue('x'); if (in == 0) { cerr << "cube: Please specify the option -x" << endl; exit(1); } inputstr = in; string_to_int(inputstr, L); // read M in = opt->getValue('y'); if (in == 0) { cerr << "cube: Please specify the option -y" << endl; exit(1); } inputstr = in; string_to_int(inputstr, M); // read N in = opt->getValue('z'); if (in == 0) { cerr << "cube: Please specify the option -z" << endl; exit(1); } inputstr = in; string_to_int(inputstr, N); // read output file in = opt->getValue("output"); if (in == 0) { cerr << "cube: Please specify the option --output" << endl; exit(1); } output_filename = in; // determine the extension and instantiate appropriate writer object string root, ext; path_splitext(output_filename, root, ext); writer = NewWriter(ext.c_str()); if (writer == 0) { cerr << "cube: File with bad extension (" << ext << ")" << endl; exit(1); } // read target path for coordinates array in = opt->getValue("coords-path"); if (in == 0) { if (writer->getType() == Writer::HDF_WRITER) { coords_path = "/coordinates"; } } else { coords_path = in; } if ((coords_path != "") && (writer->getType() != Writer::HDF_WRITER)) { cerr << "cube: Can only use --coords-path " << "when writing to an HDF5 (.h5) file" << endl; exit(1); } // read target path for connectivity array in = opt->getValue("connect-path"); if (in == 0) { if (writer->getType() == Writer::HDF_WRITER) { connect_path = "/connectivity"; } } else { connect_path = in; } if ((connect_path != "") && (writer->getType() != Writer::HDF_WRITER)) { cerr << "cube: Can only use --connect-path " << "when writing to an HDF5 (.h5) file" << endl; exit(1); } // read tet/hex flags bool hexFlag = opt->getFlag("hex8"); bool tetFlag = opt->getFlag("tet4"); if (hexFlag && tetFlag) { std::cerr << "cube: Please specify only one of the flags " << "--hex8 or --tet8" << std::endl; exit(1); } if (!tetFlag) { hexFlag = true; } assert(hexFlag != tetFlag); // initialize mesh object mesh = new cigma::CubeMeshPart(); mesh->calc_coordinates(L,M,N); if (hexFlag) { mesh->calc_hex8_connectivity(); } if (tetFlag) { mesh->calc_tet4_connectivity(); } } int cigma::CubeCmd::run() { //std::cout << "Calling cigma::CubeCmd::run()" << std::endl; assert(mesh != 0); assert(writer != 0); if (verbose) { std::cout << "L, M, N = (" << L << ", " << M << ", " << N << ")" << std::endl; std::cout << "mesh->nno = " << mesh->nno << std::endl; std::cout << "mesh->nel = " << mesh->nel << std::endl; std::cout << "mesh->ndofs = " << mesh->ndofs << std::endl; } if (verbose) { int e = 0; double pts[2][3] = {{0.5, 0.5, 0.5}, {1.0, 1.0, 1.0}}; cout << "cube test: Looking for centroid..." << endl; bool found = mesh->find_cell(pts[0], &e); if (!found) { cerr << "cube test error: Could not find cell " << "containing centroid (0.5,0.5,0.5)" << endl; exit(1); } else { cout << "cube test: Found centroid in cell " << e << endl; } } int ierr; cout << "Creating file " << output_filename << endl; if (writer->getType() == Writer::HDF_WRITER) { HdfWriter *hdfWriter = static_cast<HdfWriter*>(writer); ierr = hdfWriter->open(output_filename.c_str()); if (ierr < 0) { cerr << "Error: Could not open (or create) the HDF5 file " << output_filename << endl; exit(1); } ierr = hdfWriter->write_coordinates(coords_path.c_str(), mesh->coords, mesh->nno, mesh->nsd); if (ierr < 0) { cerr << "Error: Could not write dataset " << coords_path << endl; exit(1); } ierr = hdfWriter->write_connectivity(connect_path.c_str(), mesh->connect, mesh->nel, mesh->ndofs); if (ierr < 0) { cerr << "Error: Could not write dataset " << connect_path << endl; exit(1); } hdfWriter->close(); } else if (writer->getType() == Writer::TEXT_WRITER) { TextWriter *textWriter = static_cast<TextWriter*>(writer); ierr = textWriter->open(output_filename.c_str()); if (ierr < 0) { cerr << "Error: Could not create output text file " << output_filename << endl; exit(1); } textWriter->write_coordinates(coords_path.c_str(), mesh->coords, mesh->nno, mesh->nsd); textWriter->write_connectivity(connect_path.c_str(), mesh->connect, mesh->nel, mesh->ndofs); textWriter->close(); } else if (writer->getType() == Writer::VTK_WRITER) { VtkWriter *vtkWriter = static_cast<VtkWriter*>(writer); ierr = vtkWriter->open(output_filename.c_str()); if (ierr < 0) { cerr << "Error: Could not create output VTK file " << output_filename << endl; exit(1); } //vtkWriter->write_header(); vtkWriter->write_points(mesh->coords, mesh->nno, mesh->nsd); vtkWriter->write_cells(mesh->connect, mesh->nel, mesh->ndofs); vtkWriter->write_cell_types(mesh->nsd, mesh->nel, mesh->ndofs); vtkWriter->close(); } else { /* this should be unreachable */ cerr << "Fatal Error: Unsupported extension in output filename?" << endl; return 1; } if (writer != 0) { delete writer; } return 0; } // --------------------------------------------------------------------------- <|endoftext|>
<commit_before> /* * Stream.cpp * sfeMovie project * * Copyright (C) 2010-2014 Lucas Soltic * lucas.soltic@orange.fr * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswscale/swscale.h> } #include "Demuxer.hpp" #include "VideoStream.hpp" #include "AudioStream.hpp" #include "SubtitleStream.hpp" #include "Threads.hpp" #include "Log.hpp" #include "Utilities.hpp" #include <iostream> #include <stdexcept> namespace sfe { std::list<Demuxer::DemuxerInfo> Demuxer::g_availableDemuxers; std::list<Demuxer::DecoderInfo> Demuxer::g_availableDecoders; static void loadFFmpeg(void) { ONCE(av_register_all()); ONCE(avcodec_register_all()); } static MediaType AVMediaTypeToMediaType(AVMediaType type) { switch (type) { case AVMEDIA_TYPE_AUDIO: return MEDIA_TYPE_AUDIO; case AVMEDIA_TYPE_SUBTITLE: return MEDIA_TYPE_SUBTITLE; case AVMEDIA_TYPE_VIDEO: return MEDIA_TYPE_VIDEO; default: return MEDIA_TYPE_UNKNOWN; } } const std::list<Demuxer::DemuxerInfo>& Demuxer::getAvailableDemuxers(void) { AVInputFormat* demuxer = NULL; loadFFmpeg(); if (g_availableDemuxers.empty()) { while (NULL != (demuxer = av_iformat_next(demuxer))) { DemuxerInfo info = { .name = std::string(demuxer->name), .description = std::string(demuxer->long_name) }; g_availableDemuxers.push_back(info); } } return g_availableDemuxers; } const std::list<Demuxer::DecoderInfo>& Demuxer::getAvailableDecoders(void) { AVCodecRef codec = NULL; loadFFmpeg(); if (g_availableDecoders.empty()) { while (NULL != (codec = av_codec_next(codec))) { DecoderInfo info = { .name = avcodec_get_name(codec->id), .description = codec->long_name, .type = AVMediaTypeToMediaType(codec->type) }; g_availableDecoders.push_back(info); } } return g_availableDecoders; } Demuxer::Demuxer(const std::string& sourceFile, Timer& timer) : m_avFormatCtx(NULL), m_eofReached(false), m_streams(), m_ignoredStreams(), m_synchronized(), m_timer(timer) { CHECK(sourceFile.size(), "Demuxer::Demuxer() - invalid argument: sourceFile"); int err = 0; // Load all the decoders loadFFmpeg(); // Open the movie file err = avformat_open_input(&m_avFormatCtx, sourceFile.c_str(), NULL, NULL); CHECK0(err, "Demuxer::Demuxer() - error while opening media: " + sourceFile); CHECK(m_avFormatCtx, "Demuxer() - inconsistency: media context cannot be null"); // Read the general movie informations err = avformat_find_stream_info(m_avFormatCtx, NULL); CHECK0(err, "Demuxer::Demuxer() - error while retreiving media information"); // Find all interesting streams for (int i = 0; i < m_avFormatCtx->nb_streams; i++) { AVStreamRef ffstream = m_avFormatCtx->streams[i]; try { switch (ffstream->codec->codec_type) { case AVMEDIA_TYPE_VIDEO: m_streams[ffstream->index] = new VideoStream(ffstream, *this, timer); sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " video stream"); break; case AVMEDIA_TYPE_AUDIO: m_streams[ffstream->index] = new AudioStream(ffstream, *this, timer); sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " audio stream"); break; /** TODO case AVMEDIA_TYPE_SUBTITLE: m_streams.push_back(new SubtitleStream(ffstream)); break; */ default: m_ignoredStreams[ffstream->index] = std::string(std::string(av_get_media_type_string(ffstream->codec->codec_type)) + "/" + avcodec_get_name(ffstream->codec->codec_id)); sfeLogWarning(m_ignoredStreams[ffstream->index] + "' stream ignored"); break; } } catch (std::runtime_error& e) { std::cerr << "Demuxer::Demuxer() - " << e.what() << std::endl; } } } Demuxer::~Demuxer(void) { if (m_timer.getStatus() != Timer::Stopped) m_timer.stop(); while (m_streams.size()) { delete m_streams.begin()->second; m_streams.erase(m_streams.begin()); } if (m_avFormatCtx) { avformat_close_input(&m_avFormatCtx); } } const std::map<int, Stream*>& Demuxer::getStreams(void) const { return m_streams; } std::set<Stream*> Demuxer::getStreamsOfType(MediaType type) const { std::set<Stream*> streamSet; std::map<int, Stream*>::const_iterator it; for (it = m_streams.begin(); it != m_streams.end(); it++) { if (it->second->getStreamKind() == type) streamSet.insert(it->second); } return streamSet; } void Demuxer::feedStream(Stream& stream) { sf::Lock l(m_synchronized); // sfeLogDebug(Threads::currentThreadName()); while (!didReachEndOfFile() && stream.needsMoreData()) { AVPacketRef pkt = readPacket(); if (!pkt) { m_eofReached = true; } else { if (!distributePacket(pkt)) { sfeLogWarning(m_ignoredStreams[pkt->stream_index] + " packet not handled and dropped"); av_free_packet(pkt); av_free(pkt); } } } } void Demuxer::updateVideoStreams(void) { std::set<Stream*> streams = getStreamsOfType(MEDIA_TYPE_VIDEO); std::set<Stream*>::iterator it; for (it = streams.begin();it != streams.end(); it++) { VideoStream* vStream = dynamic_cast<VideoStream*>(*it); CHECK(vStream, "Demuxer::updateVideoStreams() - got non video streams"); vStream->updateTexture(); } } bool Demuxer::didReachEndOfFile(void) const { return m_eofReached; } AVPacketRef Demuxer::readPacket(void) { sf::Lock l(m_synchronized); // sfeLogDebug(Threads::currentThreadName()); AVPacket *pkt = NULL; int err = 0; pkt = (AVPacket *)av_malloc(sizeof(*pkt)); CHECK(pkt, "Demuxer::readPacket() - out of memory"); av_init_packet(pkt); err = av_read_frame(m_avFormatCtx, pkt); if (err < 0) { av_free_packet(pkt); av_free(pkt); pkt = NULL; } return pkt; } bool Demuxer::distributePacket(AVPacketRef packet) { sf::Lock l(m_synchronized); CHECK(packet, "Demuxer::distributePacket() - invalid argument"); // sfeLogDebug(Threads::currentThreadName()); bool result = false; std::map<int, Stream*>::iterator it = m_streams.find(packet->stream_index); if (it != m_streams.end()) { it->second->pushEncodedData(packet); result = true; } return result; } void Demuxer::requestMoreData(Stream& starvingStream) { sf::Lock l(m_synchronized); // sfeLogDebug(Threads::currentThreadName()); feedStream(starvingStream); } } <commit_msg>#34 Removed dot struct notation<commit_after> /* * Stream.cpp * sfeMovie project * * Copyright (C) 2010-2014 Lucas Soltic * lucas.soltic@orange.fr * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswscale/swscale.h> } #include "Demuxer.hpp" #include "VideoStream.hpp" #include "AudioStream.hpp" #include "SubtitleStream.hpp" #include "Threads.hpp" #include "Log.hpp" #include "Utilities.hpp" #include <iostream> #include <stdexcept> namespace sfe { std::list<Demuxer::DemuxerInfo> Demuxer::g_availableDemuxers; std::list<Demuxer::DecoderInfo> Demuxer::g_availableDecoders; static void loadFFmpeg(void) { ONCE(av_register_all()); ONCE(avcodec_register_all()); } static MediaType AVMediaTypeToMediaType(AVMediaType type) { switch (type) { case AVMEDIA_TYPE_AUDIO: return MEDIA_TYPE_AUDIO; case AVMEDIA_TYPE_SUBTITLE: return MEDIA_TYPE_SUBTITLE; case AVMEDIA_TYPE_VIDEO: return MEDIA_TYPE_VIDEO; default: return MEDIA_TYPE_UNKNOWN; } } const std::list<Demuxer::DemuxerInfo>& Demuxer::getAvailableDemuxers(void) { AVInputFormat* demuxer = NULL; loadFFmpeg(); if (g_availableDemuxers.empty()) { while (NULL != (demuxer = av_iformat_next(demuxer))) { DemuxerInfo info = { std::string(demuxer->name), std::string(demuxer->long_name) }; g_availableDemuxers.push_back(info); } } return g_availableDemuxers; } const std::list<Demuxer::DecoderInfo>& Demuxer::getAvailableDecoders(void) { AVCodecRef codec = NULL; loadFFmpeg(); if (g_availableDecoders.empty()) { while (NULL != (codec = av_codec_next(codec))) { DecoderInfo info = { avcodec_get_name(codec->id), codec->long_name, AVMediaTypeToMediaType(codec->type) }; g_availableDecoders.push_back(info); } } return g_availableDecoders; } Demuxer::Demuxer(const std::string& sourceFile, Timer& timer) : m_avFormatCtx(NULL), m_eofReached(false), m_streams(), m_ignoredStreams(), m_synchronized(), m_timer(timer) { CHECK(sourceFile.size(), "Demuxer::Demuxer() - invalid argument: sourceFile"); int err = 0; // Load all the decoders loadFFmpeg(); // Open the movie file err = avformat_open_input(&m_avFormatCtx, sourceFile.c_str(), NULL, NULL); CHECK0(err, "Demuxer::Demuxer() - error while opening media: " + sourceFile); CHECK(m_avFormatCtx, "Demuxer() - inconsistency: media context cannot be null"); // Read the general movie informations err = avformat_find_stream_info(m_avFormatCtx, NULL); CHECK0(err, "Demuxer::Demuxer() - error while retreiving media information"); // Find all interesting streams for (int i = 0; i < m_avFormatCtx->nb_streams; i++) { AVStreamRef ffstream = m_avFormatCtx->streams[i]; try { switch (ffstream->codec->codec_type) { // case AVMEDIA_TYPE_VIDEO: // m_streams[ffstream->index] = new VideoStream(ffstream, *this, timer); // sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " video stream"); // break; case AVMEDIA_TYPE_AUDIO: m_streams[ffstream->index] = new AudioStream(ffstream, *this, timer); sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " audio stream"); break; /** TODO case AVMEDIA_TYPE_SUBTITLE: m_streams.push_back(new SubtitleStream(ffstream)); break; */ default: m_ignoredStreams[ffstream->index] = std::string(std::string(av_get_media_type_string(ffstream->codec->codec_type)) + "/" + avcodec_get_name(ffstream->codec->codec_id)); sfeLogWarning(m_ignoredStreams[ffstream->index] + "' stream ignored"); break; } } catch (std::runtime_error& e) { std::cerr << "Demuxer::Demuxer() - " << e.what() << std::endl; } } } Demuxer::~Demuxer(void) { if (m_timer.getStatus() != Timer::Stopped) m_timer.stop(); while (m_streams.size()) { delete m_streams.begin()->second; m_streams.erase(m_streams.begin()); } if (m_avFormatCtx) { avformat_close_input(&m_avFormatCtx); } } const std::map<int, Stream*>& Demuxer::getStreams(void) const { return m_streams; } std::set<Stream*> Demuxer::getStreamsOfType(MediaType type) const { std::set<Stream*> streamSet; std::map<int, Stream*>::const_iterator it; for (it = m_streams.begin(); it != m_streams.end(); it++) { if (it->second->getStreamKind() == type) streamSet.insert(it->second); } return streamSet; } void Demuxer::feedStream(Stream& stream) { sf::Lock l(m_synchronized); // sfeLogDebug(Threads::currentThreadName()); while (!didReachEndOfFile() && stream.needsMoreData()) { AVPacketRef pkt = readPacket(); if (!pkt) { m_eofReached = true; } else { if (!distributePacket(pkt)) { sfeLogWarning(m_ignoredStreams[pkt->stream_index] + " packet not handled and dropped"); av_free_packet(pkt); av_free(pkt); } } } } void Demuxer::updateVideoStreams(void) { std::set<Stream*> streams = getStreamsOfType(MEDIA_TYPE_VIDEO); std::set<Stream*>::iterator it; for (it = streams.begin();it != streams.end(); it++) { VideoStream* vStream = dynamic_cast<VideoStream*>(*it); CHECK(vStream, "Demuxer::updateVideoStreams() - got non video streams"); vStream->updateTexture(); } } bool Demuxer::didReachEndOfFile(void) const { return m_eofReached; } AVPacketRef Demuxer::readPacket(void) { sf::Lock l(m_synchronized); // sfeLogDebug(Threads::currentThreadName()); AVPacket *pkt = NULL; int err = 0; pkt = (AVPacket *)av_malloc(sizeof(*pkt)); CHECK(pkt, "Demuxer::readPacket() - out of memory"); av_init_packet(pkt); err = av_read_frame(m_avFormatCtx, pkt); if (err < 0) { av_free_packet(pkt); av_free(pkt); pkt = NULL; } return pkt; } bool Demuxer::distributePacket(AVPacketRef packet) { sf::Lock l(m_synchronized); CHECK(packet, "Demuxer::distributePacket() - invalid argument"); // sfeLogDebug(Threads::currentThreadName()); bool result = false; std::map<int, Stream*>::iterator it = m_streams.find(packet->stream_index); if (it != m_streams.end()) { it->second->pushEncodedData(packet); result = true; } return result; } void Demuxer::requestMoreData(Stream& starvingStream) { sf::Lock l(m_synchronized); // sfeLogDebug(Threads::currentThreadName()); feedStream(starvingStream); } } <|endoftext|>
<commit_before>// DibView.cpp : implementation file // #include "stdafx.h" #include "DibView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDibView CDibView::CDibView() : m_pDoc(NULL), m_pDib(NULL), m_pTransform(NULL), m_pInverseTransform(NULL), m_nDataSet(-1), m_nDraggingLandmark(-1), m_bDrawMarks(TRUE) { } CDibView::~CDibView() { } // sets the document that is being displayed by this CDibView void CDibView::SetDocument(CDocument *pDoc) { m_pDoc = pDoc; } // sets the DIB to be displayed void CDibView::SetDib(CDib *pDib) { m_pDib = pDib; } // sets the transform to be managed void CDibView::SetTransform(CTPSTransform *pForwardTransform, CTPSTransform *pInverseTransform, int nDataSet) { m_pTransform = pForwardTransform; m_pInverseTransform = pInverseTransform; m_nDataSet = nDataSet; } BEGIN_MESSAGE_MAP(CDibView, CWnd) //{{AFX_MSG_MAP(CDibView) ON_WM_PAINT() ON_WM_MOUSEMOVE() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDibView message handlers static COLORREF g_arrColors[] = { RGB(255, 128, 255), RGB(255, 0, 255), RGB(255, 255, 0), RGB( 0, 255, 255), RGB(255, 0, 0), RGB( 0, 255, 0), RGB( 0, 0, 255), RGB(128, 255, 128), }; void CDibView::OnPaint() { CPaintDC dc(this); // device context for painting if (m_pDib) { CRect rectSrc(0, 0, m_pDib->GetSize().cx, m_pDib->GetSize().cy); CRect rectDst = GetDstRect(); // draw the image m_pDib->Draw(dc, &rectDst, &rectSrc, FALSE, /*bUseDrawDib*/ NULL, FALSE /*bForeground*/ ); // draw the landmarks if (m_nDataSet >= 0 && m_bDrawMarks) { CBrush *pOldBrush = (CBrush *) dc.SelectStockObject(HOLLOW_BRUSH); for (int nAt = 0; nAt < m_pTransform->GetLandmarkCount(); nAt++) { int nColorCount = sizeof(g_arrColors) / sizeof(COLORREF); CPen pen(PS_SOLID, 1, g_arrColors[nAt % nColorCount]); CPen *pOldPen = (CPen *) dc.SelectObject(&pen); CPoint pt; switch (m_nDataSet) { case 0: pt = Image2Client(m_pTransform->GetLandmark<0>(nAt)); break; case 1: pt = Image2Client(m_pTransform->GetLandmark<1>(nAt)); break; default: throw invalid_argument("data set must be 0 or 1"); } // dc.Ellipse(pt.x - 5, pt.y - 5, pt.x + 6, pt.y + 6); dc.MoveTo(pt.x - 5, pt.y); dc.LineTo(pt.x + 6, pt.y); dc.MoveTo(pt.x, pt.y - 5); dc.LineTo(pt.x, pt.y + 6); dc.SelectObject(pOldPen); } dc.SelectObject(pOldBrush); } } // Do not call CWnd::OnPaint() for painting messages } void CDibView::OnLButtonDown(UINT nFlags, CPoint point) { if (NULL != m_pTransform) { // find the landmark that we are dragging for (int nAt = 0; nAt < m_pTransform->GetLandmarkCount(); nAt++) { CPoint ptLandmark; switch (m_nDataSet) { case 0: ptLandmark = Image2Client(m_pTransform->GetLandmark<0>(nAt)); break; case 1: ptLandmark = Image2Client(m_pTransform->GetLandmark<1>(nAt)); break; default: throw invalid_argument("data set must be 0 or 1"); } CSize size = point - ptLandmark; if (-5 < size.cx && size.cx < 5 && -5 < size.cy && size.cy < 5) { m_nDraggingLandmark = nAt; } } // create a new point if (-1 == m_nDraggingLandmark) { int nOldSize = m_pTransform->GetLandmarkCount(); m_nDraggingLandmark = m_pTransform->AddLandmark(Client2Image(point)); int nNewSize = m_pTransform->GetLandmarkCount(); ASSERT(nOldSize+1 == nNewSize); // add the inverse landmark int inverseLandmark = m_pInverseTransform->AddLandmark(Client2Image(point)); // check that the inverse landmark is at the same position ASSERT(m_nDraggingLandmark == inverseLandmark); // redraw the segment the warping Invalidate(FALSE); } // store the mouse point m_ptPrev = point; } CWnd::OnLButtonDown(nFlags, point); } void CDibView::OnMouseMove(UINT nFlags, CPoint point) { if (-1 != m_nDraggingLandmark) { Point_t forwardl0, forwardl1; std:tie(forwardl0, forwardl1) = m_pTransform->GetLandmarkTuple(m_nDraggingLandmark); Point_t reversel0, reversel1; std:tie(reversel0, reversel1) = m_pInverseTransform->GetLandmarkTuple(m_nDraggingLandmark); switch (m_nDataSet) { case 0: bg::add_point(reversel0, Client2Image(point).point()); bg::subtract_point(reversel0, Client2Image(m_ptPrev)); bg::add_point(forwardl1, Client2Image(point).point()); bg::subtract_point(forwardl1, Client2Image(m_ptPrev).point()); break; case 1: bg::add_point(forwardl0, Client2Image(point).point()); bg::subtract_point(forwardl0, Client2Image(m_ptPrev)); bg::add_point(reversel1, Client2Image(point).point()); bg::subtract_point(reversel1, Client2Image(m_ptPrev).point()); break; default: throw new invalid_argument("dataset must be 0 or 1"); } m_pTransform->SetLandmarkTuple(m_nDraggingLandmark, std::make_tuple(forwardl0, forwardl1)); m_pInverseTransform->SetLandmarkTuple(m_nDraggingLandmark, std::make_tuple(reversel0, reversel1)); Invalidate(FALSE); // store the mouse point m_ptPrev = point; } CWnd::OnMouseMove(nFlags, point); } BOOL CheckInverse(CTPSTransform* pForward, CTPSTransform* pInverse) { // now check to ensure the offsets at each landmark is correct for (int nAtLandmark = 0; nAtLandmark < pForward->GetLandmarkCount(); nAtLandmark++) { const CVectorD<3>& vL0 = pForward->GetLandmark<0>(nAtLandmark); const CVectorD<3>& vL0_other = pInverse->GetLandmark<1>(nAtLandmark); if (!vL0.IsApproxEqual(vL0_other)) return FALSE; const CVectorD<3>& vL1 = pForward->GetLandmark<1>(nAtLandmark); const CVectorD<3>& vL1_other = pInverse->GetLandmark<0>(nAtLandmark); if (!vL1.IsApproxEqual(vL1_other)) return FALSE; } return TRUE; } void CDibView::OnLButtonUp(UINT nFlags, CPoint point) { m_nDraggingLandmark = -1; // Check if both inverse and forward are consistent ASSERT(CheckInverse(m_pTransform, m_pInverseTransform)); ASSERT(CheckInverse(m_pInverseTransform, m_pTransform)); if (m_pDoc) { m_pDoc->UpdateAllViews(NULL); } CWnd::OnLButtonUp(nFlags, point); } CVectorD<3> CDibView::Client2Image(const CPoint &ptClient) { // source (DIB) image size CRect rectSrc(0, 0, m_pDib->GetSize().cx, m_pDib->GetSize().cy); // destination (window) image size CRect rectDst = GetDstRect(); // ratio of source / destination heights REAL ratio = (REAL) rectSrc.Height() / (REAL) rectDst.Height(); // offset to center and scale CVectorD<3> vImage(ptClient); vImage -= CVectorD<3>(rectDst.CenterPoint()); vImage[0] *= ratio; vImage[1] *= ratio; vImage[2] *= ratio; vImage += CVectorD<3>(rectSrc.CenterPoint()); return vImage; } CPoint CDibView::Image2Client(const CVectorD<3>&vImage) { // source (DIB) image size CRect rectSrc(0, 0, m_pDib->GetSize().cx, m_pDib->GetSize().cy); // destination (window) image size CRect rectDst = GetDstRect(); // ratio of destination / source heights REAL ratio = (REAL) rectDst.Height() / (REAL) rectSrc.Height(); // offset to center and scale CPoint ptClient(vImage - CVectorD<3>(rectSrc.CenterPoint())); ptClient.x = (int)(ratio * (REAL) ptClient.x); ptClient.y = (int)(ratio * (REAL) ptClient.y); ptClient += rectDst.CenterPoint(); return ptClient; } CRect CDibView::GetDstRect() { CRect rectDst; GetClientRect(&rectDst); CRect rectSrc(0, 0, m_pDib->GetSize().cx, m_pDib->GetSize().cy); // set the client rectangle to the same aspect ratio int nClientWidth = rectDst.Height() * rectSrc.Width() / rectSrc.Height(); CPoint ptCenter = rectDst.CenterPoint(); rectDst.left = ptCenter.x - nClientWidth / 2; rectDst.right = ptCenter.x + nClientWidth / 2; return rectDst; } <commit_msg>switch dib to bg::point from cvectord<commit_after>// DibView.cpp : implementation file // #include "stdafx.h" #include "DibView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDibView CDibView::CDibView() : m_pDoc(NULL), m_pDib(NULL), m_pTransform(NULL), m_pInverseTransform(NULL), m_nDataSet(-1), m_nDraggingLandmark(-1), m_bDrawMarks(TRUE) { } CDibView::~CDibView() { } // sets the document that is being displayed by this CDibView void CDibView::SetDocument(CDocument *pDoc) { m_pDoc = pDoc; } // sets the DIB to be displayed void CDibView::SetDib(CDib *pDib) { m_pDib = pDib; } // sets the transform to be managed void CDibView::SetTransform(CTPSTransform *pForwardTransform, CTPSTransform *pInverseTransform, int nDataSet) { m_pTransform = pForwardTransform; m_pInverseTransform = pInverseTransform; m_nDataSet = nDataSet; } BEGIN_MESSAGE_MAP(CDibView, CWnd) //{{AFX_MSG_MAP(CDibView) ON_WM_PAINT() ON_WM_MOUSEMOVE() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDibView message handlers static COLORREF g_arrColors[] = { RGB(255, 128, 255), RGB(255, 0, 255), RGB(255, 255, 0), RGB( 0, 255, 255), RGB(255, 0, 0), RGB( 0, 255, 0), RGB( 0, 0, 255), RGB(128, 255, 128), }; void CDibView::OnPaint() { CPaintDC dc(this); // device context for painting if (m_pDib) { CRect rectSrc(0, 0, m_pDib->GetSize().cx, m_pDib->GetSize().cy); CRect rectDst = GetDstRect(); // draw the image m_pDib->Draw(dc, &rectDst, &rectSrc, FALSE, /*bUseDrawDib*/ NULL, FALSE /*bForeground*/ ); // draw the landmarks if (m_nDataSet >= 0 && m_bDrawMarks) { CBrush *pOldBrush = (CBrush *) dc.SelectStockObject(HOLLOW_BRUSH); for (int nAt = 0; nAt < m_pTransform->GetLandmarkCount(); nAt++) { int nColorCount = sizeof(g_arrColors) / sizeof(COLORREF); CPen pen(PS_SOLID, 1, g_arrColors[nAt % nColorCount]); CPen *pOldPen = (CPen *) dc.SelectObject(&pen); CPoint pt; switch (m_nDataSet) { case 0: pt = Image2Client(m_pTransform->GetLandmark<0>(nAt)); break; case 1: pt = Image2Client(m_pTransform->GetLandmark<1>(nAt)); break; default: throw invalid_argument("data set must be 0 or 1"); } // dc.Ellipse(pt.x - 5, pt.y - 5, pt.x + 6, pt.y + 6); dc.MoveTo(pt.x - 5, pt.y); dc.LineTo(pt.x + 6, pt.y); dc.MoveTo(pt.x, pt.y - 5); dc.LineTo(pt.x, pt.y + 6); dc.SelectObject(pOldPen); } dc.SelectObject(pOldBrush); } } // Do not call CWnd::OnPaint() for painting messages } void CDibView::OnLButtonDown(UINT nFlags, CPoint point) { if (NULL != m_pTransform) { // find the landmark that we are dragging for (int nAt = 0; nAt < m_pTransform->GetLandmarkCount(); nAt++) { CPoint ptLandmark; switch (m_nDataSet) { case 0: ptLandmark = Image2Client(m_pTransform->GetLandmark<0>(nAt)); break; case 1: ptLandmark = Image2Client(m_pTransform->GetLandmark<1>(nAt)); break; default: throw invalid_argument("data set must be 0 or 1"); } CSize size = point - ptLandmark; if (-5 < size.cx && size.cx < 5 && -5 < size.cy && size.cy < 5) { m_nDraggingLandmark = nAt; } } // create a new point if (-1 == m_nDraggingLandmark) { int nOldSize = m_pTransform->GetLandmarkCount(); m_nDraggingLandmark = m_pTransform->AddLandmark(Client2Image(point)); int nNewSize = m_pTransform->GetLandmarkCount(); ASSERT(nOldSize+1 == nNewSize); // add the inverse landmark int inverseLandmark = m_pInverseTransform->AddLandmark(Client2Image(point)); // check that the inverse landmark is at the same position ASSERT(m_nDraggingLandmark == inverseLandmark); // redraw the segment the warping Invalidate(FALSE); } // store the mouse point m_ptPrev = point; } CWnd::OnLButtonDown(nFlags, point); } void CDibView::OnMouseMove(UINT nFlags, CPoint point) { if (-1 != m_nDraggingLandmark) { Point_t forwardl0, forwardl1; std::tie(forwardl0, forwardl1) = m_pTransform->GetLandmarkTuple(m_nDraggingLandmark); Point_t reversel0, reversel1; std::tie(reversel0, reversel1) = m_pInverseTransform->GetLandmarkTuple(m_nDraggingLandmark); switch (m_nDataSet) { case 0: bg::add_point(reversel0, Client2Image(point).point()); bg::subtract_point(reversel0, Client2Image(m_ptPrev)); bg::add_point(forwardl1, Client2Image(point).point()); bg::subtract_point(forwardl1, Client2Image(m_ptPrev).point()); break; case 1: bg::add_point(forwardl0, Client2Image(point).point()); bg::subtract_point(forwardl0, Client2Image(m_ptPrev)); bg::add_point(reversel1, Client2Image(point).point()); bg::subtract_point(reversel1, Client2Image(m_ptPrev).point()); break; default: throw new invalid_argument("dataset must be 0 or 1"); } m_pTransform->SetLandmarkTuple(m_nDraggingLandmark, std::make_tuple(forwardl0, forwardl1)); m_pInverseTransform->SetLandmarkTuple(m_nDraggingLandmark, std::make_tuple(reversel0, reversel1)); Invalidate(FALSE); // store the mouse point m_ptPrev = point; } CWnd::OnMouseMove(nFlags, point); } BOOL CheckInverse(CTPSTransform* pForward, CTPSTransform* pInverse) { // now check to ensure the offsets at each landmark is correct for (int nAtLandmark = 0; nAtLandmark < pForward->GetLandmarkCount(); nAtLandmark++) { const CVectorD<3>& vL0 = pForward->GetLandmark<0>(nAtLandmark); const CVectorD<3>& vL0_other = pInverse->GetLandmark<1>(nAtLandmark); if (!vL0.IsApproxEqual(vL0_other)) return FALSE; const CVectorD<3>& vL1 = pForward->GetLandmark<1>(nAtLandmark); const CVectorD<3>& vL1_other = pInverse->GetLandmark<0>(nAtLandmark); if (!vL1.IsApproxEqual(vL1_other)) return FALSE; } return TRUE; } void CDibView::OnLButtonUp(UINT nFlags, CPoint point) { m_nDraggingLandmark = -1; // Check if both inverse and forward are consistent ASSERT(CheckInverse(m_pTransform, m_pInverseTransform)); ASSERT(CheckInverse(m_pInverseTransform, m_pTransform)); if (m_pDoc) { m_pDoc->UpdateAllViews(NULL); } CWnd::OnLButtonUp(nFlags, point); } CVectorD<3> CDibView::Client2Image(const CPoint &ptClient) { // source (DIB) image size CRect rectSrc(0, 0, m_pDib->GetSize().cx, m_pDib->GetSize().cy); // destination (window) image size CRect rectDst = GetDstRect(); // ratio of source / destination heights REAL ratio = (REAL) rectSrc.Height() / (REAL) rectDst.Height(); // offset to center and scale CVectorD<3> vImage(ptClient); vImage -= CVectorD<3>(rectDst.CenterPoint()); vImage[0] *= ratio; vImage[1] *= ratio; vImage[2] *= ratio; vImage += CVectorD<3>(rectSrc.CenterPoint()); return vImage; } CPoint CDibView::Image2Client(const CVectorD<3>&vImage) { // source (DIB) image size CRect rectSrc(0, 0, m_pDib->GetSize().cx, m_pDib->GetSize().cy); // destination (window) image size CRect rectDst = GetDstRect(); // ratio of destination / source heights REAL ratio = (REAL) rectDst.Height() / (REAL) rectSrc.Height(); // offset to center and scale CPoint ptClient(vImage - CVectorD<3>(rectSrc.CenterPoint())); ptClient.x = (int)(ratio * (REAL) ptClient.x); ptClient.y = (int)(ratio * (REAL) ptClient.y); ptClient += rectDst.CenterPoint(); return ptClient; } CRect CDibView::GetDstRect() { CRect rectDst; GetClientRect(&rectDst); CRect rectSrc(0, 0, m_pDib->GetSize().cx, m_pDib->GetSize().cy); // set the client rectangle to the same aspect ratio int nClientWidth = rectDst.Height() * rectSrc.Width() / rectSrc.Height(); CPoint ptCenter = rectDst.CenterPoint(); rectDst.left = ptCenter.x - nClientWidth / 2; rectDst.right = ptCenter.x + nClientWidth / 2; return rectDst; } <|endoftext|>
<commit_before>/// /// @file EratBig.cpp /// @brief EratBig is a segmented sieve of Eratosthenes /// implementation optimized for big sieving primes. EratBig /// is a highly optimized implementation of Tomas Oliveira e /// Silva's cache-friendly bucket sieve algorithm: /// http://www.ieeta.pt/~tos/software/prime_sieve.html /// The idea is that for each segment we keep a list of buckets /// which contain the sieving primes that have a multiple /// occurrence in that segment. When we then cross off the /// multiples from the current segment we avoid processing /// sieving primes that do not have a multiple occurrence in /// the current segment. /// /// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/EratBig.hpp> #include <primesieve/Bucket.hpp> #include <primesieve/MemoryPool.hpp> #include <primesieve/pmath.hpp> #include <primesieve/primesieve_error.hpp> #include <primesieve/Wheel.hpp> #include <stdint.h> #include <cassert> #include <algorithm> #include <vector> namespace primesieve { /// @stop: Upper bound for sieving /// @sieveSize: Sieve size in bytes /// @maxPrime: Sieving primes <= maxPrime /// void EratBig::init(uint64_t stop, uint64_t sieveSize, uint64_t maxPrime) { // '>> log2SieveSize' requires power of 2 sieveSize if (!isPow2(sieveSize)) throw primesieve_error("EratBig: sieveSize is not a power of 2"); Wheel::init(stop, sieveSize); enabled_ = true; maxPrime_ = maxPrime; log2SieveSize_ = ilog2(sieveSize); moduloSieveSize_ = sieveSize - 1; uint64_t maxSievingPrime = maxPrime_ / 30; uint64_t maxNextMultiple = maxSievingPrime * getMaxFactor() + getMaxFactor(); uint64_t maxMultipleIndex = sieveSize - 1 + maxNextMultiple; uint64_t maxSegmentCount = maxMultipleIndex >> log2SieveSize_; uint64_t size = maxSegmentCount + 1; sievingPrimes_.resize(size, nullptr); } /// Add a new sieving prime void EratBig::storeSievingPrime(uint64_t prime, uint64_t multipleIndex, uint64_t wheelIndex) { assert(prime <= maxPrime_); uint64_t sievingPrime = prime / 30; uint64_t segment = multipleIndex >> log2SieveSize_; multipleIndex &= moduloSieveSize_; if (memoryPool_.isFullBucket(sievingPrimes_[segment])) memoryPool_.addBucket(sievingPrimes_[segment]); sievingPrimes_[segment]++->set(sievingPrime, multipleIndex, wheelIndex); } /// Iterate over the buckets related to the current segment /// and for each bucket execute crossOff() to remove /// the multiples of its sieving primes. /// void EratBig::crossOff(uint8_t* sieve) { while (sievingPrimes_[0]) { Bucket* bucket = memoryPool_.getBucket(sievingPrimes_[0]); bucket->setEnd(sievingPrimes_[0]); sievingPrimes_[0] = nullptr; while (bucket) { crossOff(sieve, bucket); Bucket* processed = bucket; bucket = bucket->next(); memoryPool_.freeBucket(processed); } } // Move the sieving primes related to the next segment to // the 1st position so that they will be used when // sieving the next segment. std::rotate(sievingPrimes_.begin(), sievingPrimes_.begin() + 1, sievingPrimes_.end()); } /// Segmented sieve of Eratosthenes with wheel factorization /// optimized for big sieving primes that have very few /// multiples per segment. Cross-off the next multiple of /// each sieving prime in the current bucket. /// void EratBig::crossOff(uint8_t* sieve, Bucket* bucket) { SievingPrime* prime = bucket->begin(); SievingPrime* end = bucket->end(); SievingPrime** sievingPrimes = &sievingPrimes_[0]; uint64_t moduloSieveSize = moduloSieveSize_; uint64_t log2SieveSize = log2SieveSize_; // Process 2 sieving primes per loop iteration to // increase instruction level parallelism. for (; prime <= end - 2; prime += 2) { uint64_t multipleIndex0 = prime[0].getMultipleIndex(); uint64_t wheelIndex0 = prime[0].getWheelIndex(); uint64_t sievingPrime0 = prime[0].getSievingPrime(); uint64_t multipleIndex1 = prime[1].getMultipleIndex(); uint64_t wheelIndex1 = prime[1].getWheelIndex(); uint64_t sievingPrime1 = prime[1].getSievingPrime(); // Cross-off the current multiple (unset bit) // and calculate the next multiple. unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0); unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1); uint64_t segment0 = multipleIndex0 >> log2SieveSize; uint64_t segment1 = multipleIndex1 >> log2SieveSize; multipleIndex0 &= moduloSieveSize; multipleIndex1 &= moduloSieveSize; if (memoryPool_.isFullBucket(sievingPrimes[segment0])) memoryPool_.addBucket(sievingPrimes[segment0]); // The next multiple of the sieving prime will // occur in segment0. Hence we move the // sieving prime to the list which corresponds // to that segment. sievingPrimes[segment0]++->set(sievingPrime0, multipleIndex0, wheelIndex0); if (memoryPool_.isFullBucket(sievingPrimes[segment1])) memoryPool_.addBucket(sievingPrimes[segment1]); sievingPrimes[segment1]++->set(sievingPrime1, multipleIndex1, wheelIndex1); } if (prime != end) { uint64_t multipleIndex = prime->getMultipleIndex(); uint64_t wheelIndex = prime->getWheelIndex(); uint64_t sievingPrime = prime->getSievingPrime(); unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex); uint64_t segment = multipleIndex >> log2SieveSize; multipleIndex &= moduloSieveSize; if (memoryPool_.isFullBucket(sievingPrimes[segment])) memoryPool_.addBucket(sievingPrimes[segment]); sievingPrimes[segment]++->set(sievingPrime, multipleIndex, wheelIndex); } } } // namespace <commit_msg>Refactor<commit_after>/// /// @file EratBig.cpp /// @brief EratBig is a segmented sieve of Eratosthenes /// implementation optimized for big sieving primes. EratBig /// is a highly optimized implementation of Tomas Oliveira e /// Silva's cache-friendly bucket sieve algorithm: /// http://www.ieeta.pt/~tos/software/prime_sieve.html /// The idea is that for each segment we keep a list of buckets /// which contain the sieving primes that have a multiple /// occurrence in that segment. When we then cross off the /// multiples from the current segment we avoid processing /// sieving primes that do not have a multiple occurrence in /// the current segment. /// /// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/EratBig.hpp> #include <primesieve/Bucket.hpp> #include <primesieve/MemoryPool.hpp> #include <primesieve/pmath.hpp> #include <primesieve/primesieve_error.hpp> #include <primesieve/Wheel.hpp> #include <stdint.h> #include <cassert> #include <algorithm> #include <vector> namespace primesieve { /// @stop: Upper bound for sieving /// @sieveSize: Sieve size in bytes /// @maxPrime: Sieving primes <= maxPrime /// void EratBig::init(uint64_t stop, uint64_t sieveSize, uint64_t maxPrime) { // '>> log2SieveSize' requires power of 2 sieveSize if (!isPow2(sieveSize)) throw primesieve_error("EratBig: sieveSize is not a power of 2"); Wheel::init(stop, sieveSize); enabled_ = true; maxPrime_ = maxPrime; log2SieveSize_ = ilog2(sieveSize); moduloSieveSize_ = sieveSize - 1; uint64_t maxSievingPrime = maxPrime_ / 30; uint64_t maxNextMultiple = maxSievingPrime * getMaxFactor() + getMaxFactor(); uint64_t maxMultipleIndex = sieveSize - 1 + maxNextMultiple; uint64_t maxSegmentCount = maxMultipleIndex >> log2SieveSize_; uint64_t size = maxSegmentCount + 1; sievingPrimes_.resize(size); } /// Add a new sieving prime void EratBig::storeSievingPrime(uint64_t prime, uint64_t multipleIndex, uint64_t wheelIndex) { assert(prime <= maxPrime_); uint64_t sievingPrime = prime / 30; uint64_t segment = multipleIndex >> log2SieveSize_; multipleIndex &= moduloSieveSize_; if (memoryPool_.isFullBucket(sievingPrimes_[segment])) memoryPool_.addBucket(sievingPrimes_[segment]); sievingPrimes_[segment]++->set(sievingPrime, multipleIndex, wheelIndex); } /// Iterate over the buckets related to the current segment /// and for each bucket execute crossOff() to remove /// the multiples of its sieving primes. /// void EratBig::crossOff(uint8_t* sieve) { while (sievingPrimes_[0]) { Bucket* bucket = memoryPool_.getBucket(sievingPrimes_[0]); bucket->setEnd(sievingPrimes_[0]); sievingPrimes_[0] = nullptr; while (bucket) { crossOff(sieve, bucket); Bucket* processed = bucket; bucket = bucket->next(); memoryPool_.freeBucket(processed); } } // Move the sieving primes related to the next segment to // the 1st position so that they will be used when // sieving the next segment. std::rotate(sievingPrimes_.begin(), sievingPrimes_.begin() + 1, sievingPrimes_.end()); } /// Segmented sieve of Eratosthenes with wheel factorization /// optimized for big sieving primes that have very few /// multiples per segment. Cross-off the next multiple of /// each sieving prime in the current bucket. /// void EratBig::crossOff(uint8_t* sieve, Bucket* bucket) { SievingPrime* prime = bucket->begin(); SievingPrime* end = bucket->end(); SievingPrime** sievingPrimes = &sievingPrimes_[0]; uint64_t moduloSieveSize = moduloSieveSize_; uint64_t log2SieveSize = log2SieveSize_; // Process 2 sieving primes per loop iteration to // increase instruction level parallelism. for (; prime <= end - 2; prime += 2) { uint64_t multipleIndex0 = prime[0].getMultipleIndex(); uint64_t wheelIndex0 = prime[0].getWheelIndex(); uint64_t sievingPrime0 = prime[0].getSievingPrime(); uint64_t multipleIndex1 = prime[1].getMultipleIndex(); uint64_t wheelIndex1 = prime[1].getWheelIndex(); uint64_t sievingPrime1 = prime[1].getSievingPrime(); // Cross-off the current multiple (unset bit) // and calculate the next multiple. unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0); unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1); uint64_t segment0 = multipleIndex0 >> log2SieveSize; uint64_t segment1 = multipleIndex1 >> log2SieveSize; multipleIndex0 &= moduloSieveSize; multipleIndex1 &= moduloSieveSize; if (memoryPool_.isFullBucket(sievingPrimes[segment0])) memoryPool_.addBucket(sievingPrimes[segment0]); // The next multiple of the sieving prime will // occur in segment0. Hence we move the // sieving prime to the list which corresponds // to that segment. sievingPrimes[segment0]++->set(sievingPrime0, multipleIndex0, wheelIndex0); if (memoryPool_.isFullBucket(sievingPrimes[segment1])) memoryPool_.addBucket(sievingPrimes[segment1]); sievingPrimes[segment1]++->set(sievingPrime1, multipleIndex1, wheelIndex1); } if (prime != end) { uint64_t multipleIndex = prime->getMultipleIndex(); uint64_t wheelIndex = prime->getWheelIndex(); uint64_t sievingPrime = prime->getSievingPrime(); unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex); uint64_t segment = multipleIndex >> log2SieveSize; multipleIndex &= moduloSieveSize; if (memoryPool_.isFullBucket(sievingPrimes[segment])) memoryPool_.addBucket(sievingPrimes[segment]); sievingPrimes[segment]++->set(sievingPrime, multipleIndex, wheelIndex); } } } // namespace <|endoftext|>
<commit_before>// App.hh // Copyright (c) 2002 Henrik Kinnunen (fluxgen at linuxmail.org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef FBTK_APP_HH #define FBTK_APP_HH #include <X11/Xlib.h> namespace FbTk { /// Main class for applications, every application must create an instance of this class /** * Usage: \n * App app; \n * ... \n * init some other stuff; \n * ... \n * main loop starts here: \n * app.eventLoop(); \n * * To end main loop you call App::instance()->end() */ class App { public: /// @return singleton instance of App static App *instance(); /// creates a display connection explicit App(const char *displayname=0); virtual ~App(); /// display connection Display *display() const { return m_display; } void sync(bool discard); /// starts event loop virtual void eventLoop(); /// forces an end to event loop void end(); bool done() const { return m_done; } private: static App *s_app; bool m_done; Display *m_display; }; } // end namespace FbTk #endif // FBTK_APP_HH <commit_msg>inline display<commit_after>// App.hh // Copyright (c) 2002 Henrik Kinnunen (fluxgen at linuxmail.org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef FBTK_APP_HH #define FBTK_APP_HH #include <X11/Xlib.h> namespace FbTk { /// Main class for applications, every application must create an instance of this class /** * Usage: \n * App app; \n * ... \n * init some other stuff; \n * ... \n * main loop starts here: \n * app.eventLoop(); \n * * To end main loop you call App::instance()->end() */ class App { public: /// @return singleton instance of App static App *instance(); /// creates a display connection explicit App(const char *displayname=0); virtual ~App(); /// display connection inline Display *display() const { return m_display; } void sync(bool discard); /// starts event loop virtual void eventLoop(); /// forces an end to event loop void end(); bool done() const { return m_done; } private: static App *s_app; bool m_done; Display *m_display; }; } // end namespace FbTk #endif // FBTK_APP_HH <|endoftext|>
<commit_before>/*================================================== Flexbar - flexible barcode and adapter removal Version 3.5.0 BSD 3-Clause License uses SeqAn library release 2.4.0 and TBB library 4.0 or later Developer: Johannes Roehr Former contributors: Matthias Dodt Benjamin Menkuec Sebastian Roskosch https://github.com/seqan/flexbar ===================================================*/ #include "Flexbar.h" int main(int argc, const char* argv[]){ using namespace std; using namespace seqan; const string version = "3.5 beta"; const string date = "October 2018"; ArgumentParser parser("flexbar"); defineOptions(parser, version, date); parseCmdLine(parser, version, argc, argv); Options o; initOptions(o, parser); loadOptions(o, parser); startComputation(o); return 0; } <commit_msg>Update date<commit_after>/*================================================== Flexbar - flexible barcode and adapter removal Version 3.5.0 BSD 3-Clause License uses SeqAn library release 2.4.0 and TBB library 4.0 or later Developer: Johannes Roehr Former contributors: Matthias Dodt Benjamin Menkuec Sebastian Roskosch https://github.com/seqan/flexbar ===================================================*/ #include "Flexbar.h" int main(int argc, const char* argv[]){ using namespace std; using namespace seqan; const string version = "3.5 beta"; const string date = "November 2018"; ArgumentParser parser("flexbar"); defineOptions(parser, version, date); parseCmdLine(parser, version, argc, argv); Options o; initOptions(o, parser); loadOptions(o, parser); startComputation(o); return 0; } <|endoftext|>
<commit_before>#include "General.h" #include "KBot.h" namespace KBot { using namespace BWAPI; General::General(KBot &kBot) : m_kBot(kBot) {} void General::update() { std::string squadSizes; for (auto &squad : m_squads) squadSizes += ", " + std::to_string(squad.size()); squadSizes = squadSizes.empty() ? "No squads" : squadSizes.substr(2); const auto enemiesNearBase = Broodwar->getUnitsInRadius(Position(Broodwar->self()->getStartLocation()), 1000, Filter::IsEnemy); // Display debug information Broodwar->drawTextScreen(2, 100, "General: -"); Broodwar->drawTextScreen(2, 110, "Squad sizes: %s", squadSizes.c_str()); Broodwar->drawTextScreen(2, 120, "Enemies near base: %d", enemiesNearBase.size()); // Remove empty squads decltype(m_squads)::const_iterator it; while ((it = std::find_if(m_squads.begin(), m_squads.end(), [](const Squad &squad) { return squad.empty(); })) != m_squads.end()) m_squads.erase(it); // Merge nearby and defensive squads bool merge = true; while (merge) { for (auto it = m_squads.begin(); it != m_squads.end(); ++it) { auto hit = std::find_if(it + 1, m_squads.end(), [it](const Squad &squad) { return (it->getPosition().getApproxDistance(squad.getPosition()) < 200) || (it->getPosition().getApproxDistance(squad.getPosition()) < 500 && it->getState() == SquadState::defend && squad.getState() == SquadState::defend); }); if (hit != m_squads.end()) { // Hold all units as some of them might have old, invalid orders. it->stop(); hit->stop(); // Merge squad *hit into *it. std::copy(hit->begin(), hit->end(), std::inserter(*it, it->end())); // Remove empty squad *hit. m_squads.erase(hit); // This invalidates all container iterators, so we have to start all over again! break; } } // No squads to merge left. merge = false; } // Update squads for (auto &squad : m_squads) squad.update(); } void General::transferOwnership(const Unit &unit) { Broodwar->registerEvent([unit](Game*) { Broodwar->drawTextMap(Position(unit->getPosition()), "General: %s", unit->getType().c_str()); }, [unit](Game*) { return unit->exists(); }, 250); for (auto &squad : m_squads) { if (unit->getPosition().getApproxDistance(squad.getPosition()) < 400) { // Join squad squad.insert(unit); return; } } // Create new squad Squad squad(m_kBot); squad.insert(unit); m_squads.push_back(squad); } void General::onUnitDestroy(const Unit &unit) { for (auto &squad : m_squads) squad.erase(unit); } } // namespace <commit_msg>Update squads (merge / delete) more rarely.<commit_after>#include "General.h" #include "KBot.h" namespace KBot { using namespace BWAPI; General::General(KBot &kBot) : m_kBot(kBot) {} void General::update() { std::string squadSizes; for (auto &squad : m_squads) squadSizes += ", " + std::to_string(squad.size()); squadSizes = squadSizes.empty() ? "No squads" : squadSizes.substr(2); const auto enemiesNearBase = Broodwar->getUnitsInRadius(Position(Broodwar->self()->getStartLocation()), 1000, Filter::IsEnemy); // Display debug information Broodwar->drawTextScreen(2, 100, "General: -"); Broodwar->drawTextScreen(2, 110, "Squad sizes: %s", squadSizes.c_str()); Broodwar->drawTextScreen(2, 120, "Enemies near base: %d", enemiesNearBase.size()); // Update squads for (auto &squad : m_squads) squad.update(); // Prevent spamming by only running our onFrame once every number of latency frames. // Latency frames are the number of frames before commands are processed. if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0) return; // Remove empty squads decltype(m_squads)::const_iterator it; while ((it = std::find_if(m_squads.begin(), m_squads.end(), [](const Squad &squad) { return squad.empty(); })) != m_squads.end()) m_squads.erase(it); // Merge nearby and defensive squads bool merge = true; while (merge) { for (auto it = m_squads.begin(); it != m_squads.end(); ++it) { auto hit = std::find_if(it + 1, m_squads.end(), [it](const Squad &squad) { return (it->getPosition().getApproxDistance(squad.getPosition()) < 200) || (it->getPosition().getApproxDistance(squad.getPosition()) < 500 && it->getState() == SquadState::defend && squad.getState() == SquadState::defend); }); if (hit != m_squads.end()) { // Hold all units as some of them might have old, invalid orders. it->stop(); hit->stop(); // Merge squad *hit into *it. std::copy(hit->begin(), hit->end(), std::inserter(*it, it->end())); // Remove empty squad *hit. m_squads.erase(hit); // This invalidates all container iterators, so we have to start all over again! break; } } // No squads to merge left. merge = false; } } void General::transferOwnership(const Unit &unit) { Broodwar->registerEvent([unit](Game*) { Broodwar->drawTextMap(Position(unit->getPosition()), "General: %s", unit->getType().c_str()); }, [unit](Game*) { return unit->exists(); }, 250); for (auto &squad : m_squads) { if (unit->getPosition().getApproxDistance(squad.getPosition()) < 400) { // Join squad squad.insert(unit); return; } } // Create new squad Squad squad(m_kBot); squad.insert(unit); m_squads.push_back(squad); } void General::onUnitDestroy(const Unit &unit) { for (auto &squad : m_squads) squad.erase(unit); } } // namespace <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------- Infomap software package for multi-level network clustering * Copyright (c) 2013. See LICENSE for more info. * For credits and origins, see AUTHORS or www.mapequation.org/about. ----------------------------------------------------------------------- */ #include <iostream> #include <sstream> #include <fstream> #include <stdexcept> #include "utils/Logger.h" #include "io/Config.h" #include "infomap/InfomapContext.h" #include "utils/Stopwatch.h" #include "io/ProgramInterface.h" #include "io/convert.h" #include "utils/FileURI.h" #include "utils/Date.h" #include <iomanip> void runInfomap(Config const& config) { InfomapContext context(config); context.getInfomap()->run(); } Config getConfig(int argc, char *argv[]) { Config conf; ProgramInterface api("Infomap", "Implementation of the Infomap clustering algorithm based on the Map Equation (see www.mapequation.org)", "0.9.2"); // --------------------- Input options --------------------- api.addNonOptionArgument(conf.networkFile, "network_file", "The file containing the network data. Accepted formats: Pajek (implied by .net) and link list (.txt)"); api.addOptionArgument(conf.inputFormat, 'i', "input-format", "Specify input format ('pajek' or 'link-list') to override format possibly implied by file extension.", "s"); api.addOptionArgument(conf.zeroBasedNodeNumbers, 'z', "zero-based-numbering", "Assume node numbers start from zero in the input file instead of one."); api.addOptionArgument(conf.includeSelfLinks, 'k', "include-self-links", "Include links with the same source and target node. (Ignored by default.)"); api.addOptionArgument(conf.nodeLimit, 'S', "node-limit", "Limit the number of nodes to read from the network. Ignore links connected to ignored nodes.", "n"); api.addOptionArgument(conf.clusterDataFile, 'c', "cluster-data", "Provide an initial two-level solution (.clu format).", "p"); // --------------------- Output options --------------------- // api.addOptionArgument(conf.printNodeRanks, 'p', "print-node-ranks", // "Print the calculated flow for each node to a file."); // // api.addOptionArgument(conf.printFlowNetwork, 'W', "print-flow-network", // "Print the network with calculated flow values."); //TODO: Add map container so that printing can be added like -Pranks -Pflow etc!! api.addOptionArgument(conf.noFileOutput, '0', "no-file-output", "Don't print any output to file."); // --------------------- Core algorithm options --------------------- api.addOptionArgument(conf.twoLevel, '2', "two-level", "Optimize a two-level partition of the network."); bool dummyUndirected; api.addOptionArgument(dummyUndirected, 'u', "undirected", "Assume undirected links (default)"); api.addOptionArgument(conf.directed, 'd', "directed", "Assume directed links"); api.addOptionArgument(conf.undirdir, 't', "undirdir", "Two-mode dynamics: Assume undirected links for calculating flow, but directed when minimizing codelength."); api.addOptionArgument(conf.rawdir, 'w', "rawdir", "Two-mode dynamics: Assume directed links and let the raw link weights be the flow."); api.addOptionArgument(conf.unrecordedTeleportation, 'e', "unrecorded-teleportation", "Assume teleportation when calculating flow (on directed network) but don't encode that flow."); api.addOptionArgument(conf.teleportToNodes, 'o', "to-nodes", "Teleport to nodes (like the PageRank algorithm) instead of to links."); api.addOptionArgument(conf.teleportationProbability, 'p', "teleportation-probability", "The probability of teleporting to a random node or link.", "f"); api.addOptionArgument(conf.seedToRandomNumberGenerator, 's', "seed", "A seed (integer) to the random number generator.", "n"); // --------------------- Performance and accuracy options --------------------- api.addOptionArgument(conf.numTrials, 'N', "num-trials", "The number of outer-most loops to run before picking the best solution.", "n"); api.addOptionArgument(conf.minimumCodelengthImprovement, 'm', "min-improvement", "Minimum codelength threshold for accepting a new solution.", "f"); api.addOptionArgument(conf.randomizeCoreLoopLimit, 'a', "random-loop-limit", "Randomize the core loop limit from 1 to 'core-loop-limit'"); api.addOptionArgument(conf.coreLoopLimit, 'M', "core-loop-limit", "Limit the number of loops that tries to move each node into the best possible module", "n"); api.addOptionArgument(conf.levelAggregationLimit, 'L', "core-level-limit", "Limit the number of times the core loops are reapplied on existing modular network to search bigger structures.", "n"); api.addOptionArgument(conf.tuneIterationLimit, 'T', "tune-iteration-limit", "Limit the number of main iterations in the two-level partition algorithm. 0 means no limit.", "n"); api.addOptionArgument(conf.minimumRelativeTuneIterationImprovement, 'U', "tune-iteration-threshold", "Set a codelength improvement threshold of each new tune iteration to 'f' times the initial two-level codelength.", "f"); api.addOptionArgument(conf.fastCoarseTunePartition, 'C', "fast-coarse-tune", "Try to find the quickest partition of each module when creating sub-modules for the coarse-tune part."); api.addOptionArgument(conf.alternateCoarseTuneLevel, 'A', "alternate-course-tune-level", "Try to find different levels of sub-modules to move in the coarse-tune part."); api.addOptionArgument(conf.coarseTuneLevel, 'S', "course-tune-level", "Set the recursion limit when searching for sub-modules. A level of 1 will find sub-sub-modules.", "n"); api.addIncrementalOptionArgument(conf.fastHierarchicalSolution, 'F', "fast-hierarchical-solution", "Find top modules fast. Use -FF to keep all fast levels. Use -FFF to skip recursive part."); api.addOptionArgument(conf.coarseTuneLevel, 'S', "course-tune-level", "Set the recursion limit when searching for sub-modules. A level of 1 will find sub-sub-modules.", "n"); // --------------------- Output options --------------------- api.addNonOptionArgument(conf.outDirectory, "out_directory", "The directory to write the results to"); api.addIncrementalOptionArgument(conf.verbosity, 'v', "verbose", "Verbose output on the console. Add additional 'v' flags to increase verbosity up to -vvv."); api.parseArgs(argc, argv); // Some checks if (*--conf.outDirectory.end() != '/') conf.outDirectory.append("/"); return conf; } void initBenchmark(const Config& conf, int argc, char * const argv[]) { std::string networkName = FileURI(conf.networkFile).getName(); std::string logFilename = io::Str() << conf.outDirectory << networkName << ".tsv"; Logger::setBenchmarkFilename(logFilename); std::ostringstream logInfo; logInfo << "#benchmark for"; for (int i = 0; i < argc; ++i) logInfo << " " << argv[i]; Logger::benchmark(logInfo.str(), 0, 0, 0, 0, true); Logger::benchmark("elapsedSeconds\ttag\tcodelength\tnumTopModules\tnumNonTrivialTopModules\ttreeDepth", 0, 0, 0, 0, true); // (todo: fix problem with initializing same static file from different functions to simplify above) std::cout << "(Writing benchmark log to '" << logFilename << "'...)\n"; } int main(int argc, char *argv[]) { Date startDate; Config conf; try { conf = getConfig(argc, argv); if (conf.benchmark) initBenchmark(conf, argc, argv); if (conf.verbosity == 0) conf.verboseNumberPrecision = 4; std::cout << std::setprecision(conf.verboseNumberPrecision); } catch (std::exception& e) { std::cerr << e.what() << std::endl; return 1; } std::cout << "===========================================\n"; std::cout << " Infomap starts at " << Date() << "\n"; std::cout << "===========================================\n"; runInfomap(conf); ASSERT(NodeBase::nodeCount() == 0); //TODO: Not working with OpenMP // if (NodeBase::nodeCount() != 0) // std::cout << "Warning: " << NodeBase::nodeCount() << " nodes not deleted!\n"; std::cout << "===========================================\n"; std::cout << " Infomap ends at " << Date() << "\n"; std::cout << " (Elapsed time: " << (Date() - startDate) << ")\n"; std::cout << "===========================================\n"; // ElapsedTime t1 = (Date() - startDate); // std::cout << "Elapsed time: " << t1 << " (" << // Stopwatch::getElapsedTimeSinceProgramStartInSec() << "s serial)." << std::endl; return 0; } <commit_msg>* Updated version<commit_after>/* ----------------------------------------------------------------------- Infomap software package for multi-level network clustering * Copyright (c) 2013. See LICENSE for more info. * For credits and origins, see AUTHORS or www.mapequation.org/about. ----------------------------------------------------------------------- */ #include <iostream> #include <sstream> #include <fstream> #include <stdexcept> #include "utils/Logger.h" #include "io/Config.h" #include "infomap/InfomapContext.h" #include "utils/Stopwatch.h" #include "io/ProgramInterface.h" #include "io/convert.h" #include "utils/FileURI.h" #include "utils/Date.h" #include <iomanip> void runInfomap(Config const& config) { InfomapContext context(config); context.getInfomap()->run(); } Config getConfig(int argc, char *argv[]) { Config conf; ProgramInterface api("Infomap", "Implementation of the Infomap clustering algorithm based on the Map Equation (see www.mapequation.org)", "0.10.1"); // --------------------- Input options --------------------- api.addNonOptionArgument(conf.networkFile, "network_file", "The file containing the network data. Accepted formats: Pajek (implied by .net) and link list (.txt)"); api.addOptionArgument(conf.inputFormat, 'i', "input-format", "Specify input format ('pajek' or 'link-list') to override format possibly implied by file extension.", "s"); api.addOptionArgument(conf.zeroBasedNodeNumbers, 'z', "zero-based-numbering", "Assume node numbers start from zero in the input file instead of one."); api.addOptionArgument(conf.includeSelfLinks, 'k', "include-self-links", "Include links with the same source and target node. (Ignored by default.)"); api.addOptionArgument(conf.nodeLimit, 'S', "node-limit", "Limit the number of nodes to read from the network. Ignore links connected to ignored nodes.", "n"); api.addOptionArgument(conf.clusterDataFile, 'c', "cluster-data", "Provide an initial two-level solution (.clu format).", "p"); // --------------------- Output options --------------------- // api.addOptionArgument(conf.printNodeRanks, 'p', "print-node-ranks", // "Print the calculated flow for each node to a file."); // // api.addOptionArgument(conf.printFlowNetwork, 'W', "print-flow-network", // "Print the network with calculated flow values."); //TODO: Add map container so that printing can be added like -Pranks -Pflow etc!! api.addOptionArgument(conf.noFileOutput, '0', "no-file-output", "Don't print any output to file."); // --------------------- Core algorithm options --------------------- api.addOptionArgument(conf.twoLevel, '2', "two-level", "Optimize a two-level partition of the network."); bool dummyUndirected; api.addOptionArgument(dummyUndirected, 'u', "undirected", "Assume undirected links (default)"); api.addOptionArgument(conf.directed, 'd', "directed", "Assume directed links"); api.addOptionArgument(conf.undirdir, 't', "undirdir", "Two-mode dynamics: Assume undirected links for calculating flow, but directed when minimizing codelength."); api.addOptionArgument(conf.rawdir, 'w', "rawdir", "Two-mode dynamics: Assume directed links and let the raw link weights be the flow."); api.addOptionArgument(conf.unrecordedTeleportation, 'e', "unrecorded-teleportation", "Assume teleportation when calculating flow (on directed network) but don't encode that flow."); api.addOptionArgument(conf.teleportToNodes, 'o', "to-nodes", "Teleport to nodes (like the PageRank algorithm) instead of to links."); api.addOptionArgument(conf.teleportationProbability, 'p', "teleportation-probability", "The probability of teleporting to a random node or link.", "f"); api.addOptionArgument(conf.seedToRandomNumberGenerator, 's', "seed", "A seed (integer) to the random number generator.", "n"); // --------------------- Performance and accuracy options --------------------- api.addOptionArgument(conf.numTrials, 'N', "num-trials", "The number of outer-most loops to run before picking the best solution.", "n"); api.addOptionArgument(conf.minimumCodelengthImprovement, 'm', "min-improvement", "Minimum codelength threshold for accepting a new solution.", "f"); api.addOptionArgument(conf.randomizeCoreLoopLimit, 'a', "random-loop-limit", "Randomize the core loop limit from 1 to 'core-loop-limit'"); api.addOptionArgument(conf.coreLoopLimit, 'M', "core-loop-limit", "Limit the number of loops that tries to move each node into the best possible module", "n"); api.addOptionArgument(conf.levelAggregationLimit, 'L', "core-level-limit", "Limit the number of times the core loops are reapplied on existing modular network to search bigger structures.", "n"); api.addOptionArgument(conf.tuneIterationLimit, 'T', "tune-iteration-limit", "Limit the number of main iterations in the two-level partition algorithm. 0 means no limit.", "n"); api.addOptionArgument(conf.minimumRelativeTuneIterationImprovement, 'U', "tune-iteration-threshold", "Set a codelength improvement threshold of each new tune iteration to 'f' times the initial two-level codelength.", "f"); api.addOptionArgument(conf.fastCoarseTunePartition, 'C', "fast-coarse-tune", "Try to find the quickest partition of each module when creating sub-modules for the coarse-tune part."); api.addOptionArgument(conf.alternateCoarseTuneLevel, 'A', "alternate-course-tune-level", "Try to find different levels of sub-modules to move in the coarse-tune part."); api.addOptionArgument(conf.coarseTuneLevel, 'S', "course-tune-level", "Set the recursion limit when searching for sub-modules. A level of 1 will find sub-sub-modules.", "n"); api.addIncrementalOptionArgument(conf.fastHierarchicalSolution, 'F', "fast-hierarchical-solution", "Find top modules fast. Use -FF to keep all fast levels. Use -FFF to skip recursive part."); api.addOptionArgument(conf.coarseTuneLevel, 'S', "course-tune-level", "Set the recursion limit when searching for sub-modules. A level of 1 will find sub-sub-modules.", "n"); // --------------------- Output options --------------------- api.addNonOptionArgument(conf.outDirectory, "out_directory", "The directory to write the results to"); api.addIncrementalOptionArgument(conf.verbosity, 'v', "verbose", "Verbose output on the console. Add additional 'v' flags to increase verbosity up to -vvv."); api.parseArgs(argc, argv); // Some checks if (*--conf.outDirectory.end() != '/') conf.outDirectory.append("/"); return conf; } void initBenchmark(const Config& conf, int argc, char * const argv[]) { std::string networkName = FileURI(conf.networkFile).getName(); std::string logFilename = io::Str() << conf.outDirectory << networkName << ".tsv"; Logger::setBenchmarkFilename(logFilename); std::ostringstream logInfo; logInfo << "#benchmark for"; for (int i = 0; i < argc; ++i) logInfo << " " << argv[i]; Logger::benchmark(logInfo.str(), 0, 0, 0, 0, true); Logger::benchmark("elapsedSeconds\ttag\tcodelength\tnumTopModules\tnumNonTrivialTopModules\ttreeDepth", 0, 0, 0, 0, true); // (todo: fix problem with initializing same static file from different functions to simplify above) std::cout << "(Writing benchmark log to '" << logFilename << "'...)\n"; } int main(int argc, char *argv[]) { Date startDate; Config conf; try { conf = getConfig(argc, argv); if (conf.benchmark) initBenchmark(conf, argc, argv); if (conf.verbosity == 0) conf.verboseNumberPrecision = 4; std::cout << std::setprecision(conf.verboseNumberPrecision); } catch (std::exception& e) { std::cerr << e.what() << std::endl; return 1; } std::cout << "===========================================\n"; std::cout << " Infomap starts at " << Date() << "\n"; std::cout << "===========================================\n"; runInfomap(conf); ASSERT(NodeBase::nodeCount() == 0); //TODO: Not working with OpenMP // if (NodeBase::nodeCount() != 0) // std::cout << "Warning: " << NodeBase::nodeCount() << " nodes not deleted!\n"; std::cout << "===========================================\n"; std::cout << " Infomap ends at " << Date() << "\n"; std::cout << " (Elapsed time: " << (Date() - startDate) << ")\n"; std::cout << "===========================================\n"; // ElapsedTime t1 = (Date() - startDate); // std::cout << "Elapsed time: " << t1 << " (" << // Stopwatch::getElapsedTimeSinceProgramStartInSec() << "s serial)." << std::endl; return 0; } <|endoftext|>
<commit_before>// The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. #include "llvm/IR/DataLayout.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/IR/Type.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" using namespace llvm; namespace { class Prepare : public ModulePass { public: static char ID; Prepare() : ModulePass(ID) {} virtual bool runOnModule(Module &M); }; } static RegisterPass<Prepare> PRP("prepare", "Prepare the code for svcomp"); char Prepare::ID; bool Prepare::runOnModule(Module &M) { static const char *del_body[] = { "__VERIFIER_assume", "__VERIFIER_error", "__VERIFIER_nondet_pointer", "__VERIFIER_nondet_pchar", "__VERIFIER_nondet_char", "__VERIFIER_nondet_short", "__VERIFIER_nondet_int", "__VERIFIER_nondet_long", "__VERIFIER_nondet_uchar", "__VERIFIER_nondet_ushort", "__VERIFIER_nondet_uint", "__VERIFIER_nondet_ulong", "__VERIFIER_nondet_unsigned", "__VERIFIER_nondet_u32", "__VERIFIER_nondet_float", "__VERIFIER_nondet_double", "__VERIFIER_nondet_bool", "__VERIFIER_nondet__Bool", "__VERIFIER_nondet_size_t", nullptr }; for (const char **curr = del_body; *curr; curr++) { Function *toDel = M.getFunction(*curr); if (toDel && !toDel->empty()) { errs() << "deleting " << toDel->getName() << '\n'; toDel->deleteBody(); } } // prevent __VERIFIER_assert from inlining, it introduces // a weakness in our control dependence algorithm in some cases if (Function *F = M.getFunction("__VERIFIER_assert")) F->addFnAttr(Attribute::NoInline); return true; } <commit_msg>Prepare.cpp Set private linkage to malloc, calloc, realloc<commit_after>// The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. #include "llvm/IR/DataLayout.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/IR/Type.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" using namespace llvm; namespace { class Prepare : public ModulePass { public: static char ID; Prepare() : ModulePass(ID) {} virtual bool runOnModule(Module &M); }; } static RegisterPass<Prepare> PRP("prepare", "Prepare the code for svcomp"); char Prepare::ID; bool Prepare::runOnModule(Module &M) { static const char *del_body[] = { "__VERIFIER_assume", "__VERIFIER_error", "__VERIFIER_nondet_pointer", "__VERIFIER_nondet_pchar", "__VERIFIER_nondet_char", "__VERIFIER_nondet_short", "__VERIFIER_nondet_int", "__VERIFIER_nondet_long", "__VERIFIER_nondet_uchar", "__VERIFIER_nondet_ushort", "__VERIFIER_nondet_uint", "__VERIFIER_nondet_ulong", "__VERIFIER_nondet_unsigned", "__VERIFIER_nondet_u32", "__VERIFIER_nondet_float", "__VERIFIER_nondet_double", "__VERIFIER_nondet_bool", "__VERIFIER_nondet__Bool", "__VERIFIER_nondet_size_t", nullptr }; for (const char **curr = del_body; *curr; curr++) { Function *toDel = M.getFunction(*curr); if (toDel && !toDel->empty()) { errs() << "deleting " << toDel->getName() << '\n'; toDel->deleteBody(); } } // prevent __VERIFIER_assert from inlining, it introduces // a weakness in our control dependence algorithm in some cases if (Function *F = M.getFunction("__VERIFIER_assert")) F->addFnAttr(Attribute::NoInline); static const char *set_linkage[] = { "malloc", "calloc", "realloc", nullptr }; // we want to use our definiton of malloc for (const char **curr = set_linkage; *curr; curr++) { Function *F = M.getFunction(*curr); if (F && !F->empty()) { errs() << "Making " << F->getName() << " private\n"; F->setLinkage(GlobalValue::PrivateLinkage); } } return true; } <|endoftext|>
<commit_before>/*============================================================================= Copyright (c) 2016-2017 Joel de Guzman Distributed under the MIT License (https://opensource.org/licenses/MIT) =============================================================================*/ #include "view_impl.hpp" #include <cairo.h> namespace photon { /////////////////////////////////////////////////////////////////////////// // Main view creation callback std::function<std::unique_ptr<base_view>(host_view* h)> new_view; struct platform_access { inline static host_view* get_host_view(base_view& main_view) { return main_view.h; } }; namespace { inline base_view& get(gpointer user_data) { return *reinterpret_cast<base_view*>(user_data); } gboolean on_draw(GtkWidget* widget, cairo_t* cr, gpointer user_data) { auto& main_view = get(user_data); platform_access::get_host_view(main_view)->cr = cr; // Note that cr (cairo_t) is already clipped to only draw the // exposed areas of the widget. double left, top, right, bottom; cairo_clip_extents(cr, &left, &top, &right, &bottom); main_view.draw(rect{ float(left), float(top), float(right), float(bottom) }); return false; } // void draw(base_view& main_view) // { // platform_access::get_host_view(main_view)->cr = cr; // // Note that cr (cairo_t) is already clipped to only draw the // // exposed areas of the widget. // double left, top, right, bottom; // cairo_clip_extents(cr, &left, &top, &right, &bottom); // main_view.draw(rect{ float(left), float(top), float(right), float(bottom) }); // } template <typename Event> bool get_mouse(Event* event, mouse_button& btn, host_view* view) { btn.modifiers = 0; if (event->state & GDK_SHIFT_MASK) btn.modifiers |= mod_shift; if (event->state & GDK_CONTROL_MASK) btn.modifiers |= mod_control; if (event->state & GDK_MOD1_MASK) btn.modifiers |= mod_alt; if (event->state & GDK_SUPER_MASK) btn.modifiers |= mod_super; btn.num_clicks = view->click_count; btn.pos = { float(event->x), float(event->y) }; return true; } bool get_button(GdkEventButton* event, mouse_button& btn, host_view* view) { if (event->button > 4) return false; static constexpr auto _250ms = 250; switch (event->type) { case GDK_BUTTON_PRESS: btn.down = true; if ((event->time - view->click_time) < _250ms) ++view->click_count; else view->click_count = 1; view->click_time = event->time; break; case GDK_BUTTON_RELEASE: btn.down = false; view->click_count = 0; break; default: return false; } if (!get_mouse(event, btn, view)) return false; return true; } static gboolean on_button(GtkWidget* widget, GdkEventButton* event, gpointer user_data) { auto& main_view = get(user_data); mouse_button btn; if (get_button(event, btn, platform_access::get_host_view(main_view))) main_view.click(btn); return TRUE; } static gboolean on_motion(GtkWidget* widget, GdkEventMotion* event, gpointer user_data) { auto& main_view = get(user_data); mouse_button btn; if (get_mouse(event, btn, platform_access::get_host_view(main_view))) { if (event->state & GDK_BUTTON1_MASK) { btn.down = true; btn.state = mouse_button::left; } else if (event->state & GDK_BUTTON2_MASK) { btn.down = true; btn.state = mouse_button::middle; } else if (event->state & GDK_BUTTON3_MASK) { btn.down = true; btn.state = mouse_button::right; } else { btn.down = false; } if (btn.down) main_view.drag(btn); } return TRUE; } static gboolean on_scroll(GtkWidget* widget, GdkEventScroll* event, gpointer user_data) { auto& main_view = get(user_data); auto* host_view = platform_access::get_host_view(main_view); auto elapsed = event->time - host_view->scroll_time; static constexpr float _1s = 1000; host_view->scroll_time = event->time; float dx = 0; float dy = 0; float step = _1s / elapsed; switch (event->direction) { case GDK_SCROLL_UP: dy = step; break; case GDK_SCROLL_DOWN: dy = -step; break; case GDK_SCROLL_LEFT: dx = step; break; case GDK_SCROLL_RIGHT: dy = -step; break; case GDK_SCROLL_SMOOTH: dx = event->delta_x; dy = event->delta_y; break; default: break; } main_view.scroll( { dx, dy }, { float(event->x), float(event->y) } ); return TRUE; } } void make_main_window(base_view& main_view, GtkWidget* window) { auto* drawing_area = gtk_drawing_area_new(); gtk_container_add(GTK_CONTAINER(window), drawing_area); g_signal_connect(G_OBJECT(drawing_area), "draw", G_CALLBACK(on_draw), &main_view); //gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window), 400, 300); g_signal_connect(drawing_area, "button-press-event", G_CALLBACK(on_button), &main_view); g_signal_connect (drawing_area, "button-release-event", G_CALLBACK(on_button), &main_view); g_signal_connect(drawing_area, "motion-notify-event", G_CALLBACK(on_motion), &main_view); g_signal_connect(drawing_area, "scroll-event", G_CALLBACK(on_scroll), &main_view); // Ask to receive events the drawing area doesn't normally // subscribe to. In particular, we need to ask for the // button press and motion notify events that want to handle. gtk_widget_set_events (drawing_area, gtk_widget_get_events(drawing_area) | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK ); } point base_view::cursor_pos() const { return {}; } point base_view::size() const { auto x = gtk_widget_get_allocated_width(h->window); auto y = gtk_widget_get_allocated_height(h->window); return { float(x), float(y) }; } void base_view::size(point p) { } void base_view::refresh() { auto x = gtk_widget_get_allocated_width(h->window); auto y = gtk_widget_get_allocated_height(h->window); refresh({ 0, 0, float(x), float(y) }); } void base_view::refresh(rect area) { gtk_widget_queue_draw_area(h->window, area.left, area.top, area.width(), area.height()); } void base_view::limits(view_limits limits_, bool maintain_aspect) { } bool base_view::is_focus() const { return false; } cairo_t* base_view::begin_drawing() { // GTK already does this for us return h->cr; } void base_view::end_drawing(cairo_t* ctx) { // GTK will do this for us } std::string clipboard() { return ""; } void clipboard(std::string const& text) { } void set_cursor(cursor_type type) { switch (type) { case cursor_type::arrow: break; case cursor_type::ibeam: break; case cursor_type::cross_hair: break; case cursor_type::hand: break; case cursor_type::h_resize: break; case cursor_type::v_resize: break; } } } <commit_msg>bug: wrong coordinate<commit_after>/*============================================================================= Copyright (c) 2016-2017 Joel de Guzman Distributed under the MIT License (https://opensource.org/licenses/MIT) =============================================================================*/ #include "view_impl.hpp" #include <cairo.h> namespace photon { /////////////////////////////////////////////////////////////////////////// // Main view creation callback std::function<std::unique_ptr<base_view>(host_view* h)> new_view; struct platform_access { inline static host_view* get_host_view(base_view& main_view) { return main_view.h; } }; namespace { inline base_view& get(gpointer user_data) { return *reinterpret_cast<base_view*>(user_data); } gboolean on_draw(GtkWidget* widget, cairo_t* cr, gpointer user_data) { auto& main_view = get(user_data); platform_access::get_host_view(main_view)->cr = cr; // Note that cr (cairo_t) is already clipped to only draw the // exposed areas of the widget. double left, top, right, bottom; cairo_clip_extents(cr, &left, &top, &right, &bottom); main_view.draw(rect{ float(left), float(top), float(right), float(bottom) }); return false; } // void draw(base_view& main_view) // { // platform_access::get_host_view(main_view)->cr = cr; // // Note that cr (cairo_t) is already clipped to only draw the // // exposed areas of the widget. // double left, top, right, bottom; // cairo_clip_extents(cr, &left, &top, &right, &bottom); // main_view.draw(rect{ float(left), float(top), float(right), float(bottom) }); // } template <typename Event> bool get_mouse(Event* event, mouse_button& btn, host_view* view) { btn.modifiers = 0; if (event->state & GDK_SHIFT_MASK) btn.modifiers |= mod_shift; if (event->state & GDK_CONTROL_MASK) btn.modifiers |= mod_control; if (event->state & GDK_MOD1_MASK) btn.modifiers |= mod_alt; if (event->state & GDK_SUPER_MASK) btn.modifiers |= mod_super; btn.num_clicks = view->click_count; btn.pos = { float(event->x), float(event->y) }; return true; } bool get_button(GdkEventButton* event, mouse_button& btn, host_view* view) { if (event->button > 4) return false; static constexpr auto _250ms = 250; switch (event->type) { case GDK_BUTTON_PRESS: btn.down = true; if ((event->time - view->click_time) < _250ms) ++view->click_count; else view->click_count = 1; view->click_time = event->time; break; case GDK_BUTTON_RELEASE: btn.down = false; view->click_count = 0; break; default: return false; } if (!get_mouse(event, btn, view)) return false; return true; } static gboolean on_button(GtkWidget* widget, GdkEventButton* event, gpointer user_data) { auto& main_view = get(user_data); mouse_button btn; if (get_button(event, btn, platform_access::get_host_view(main_view))) main_view.click(btn); return TRUE; } static gboolean on_motion(GtkWidget* widget, GdkEventMotion* event, gpointer user_data) { auto& main_view = get(user_data); mouse_button btn; if (get_mouse(event, btn, platform_access::get_host_view(main_view))) { if (event->state & GDK_BUTTON1_MASK) { btn.down = true; btn.state = mouse_button::left; } else if (event->state & GDK_BUTTON2_MASK) { btn.down = true; btn.state = mouse_button::middle; } else if (event->state & GDK_BUTTON3_MASK) { btn.down = true; btn.state = mouse_button::right; } else { btn.down = false; } if (btn.down) main_view.drag(btn); } return TRUE; } static gboolean on_scroll(GtkWidget* widget, GdkEventScroll* event, gpointer user_data) { auto& main_view = get(user_data); auto* host_view = platform_access::get_host_view(main_view); auto elapsed = event->time - host_view->scroll_time; static constexpr float _1s = 1000; host_view->scroll_time = event->time; float dx = 0; float dy = 0; float step = _1s / elapsed; switch (event->direction) { case GDK_SCROLL_UP: dy = step; break; case GDK_SCROLL_DOWN: dy = -step; break; case GDK_SCROLL_LEFT: dx = step; break; case GDK_SCROLL_RIGHT: dx = -step; break; case GDK_SCROLL_SMOOTH: dx = event->delta_x; dy = event->delta_y; break; default: break; } main_view.scroll( { dx, dy }, { float(event->x), float(event->y) } ); return TRUE; } } void make_main_window(base_view& main_view, GtkWidget* window) { auto* drawing_area = gtk_drawing_area_new(); gtk_container_add(GTK_CONTAINER(window), drawing_area); g_signal_connect(G_OBJECT(drawing_area), "draw", G_CALLBACK(on_draw), &main_view); //gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window), 400, 300); g_signal_connect(drawing_area, "button-press-event", G_CALLBACK(on_button), &main_view); g_signal_connect (drawing_area, "button-release-event", G_CALLBACK(on_button), &main_view); g_signal_connect(drawing_area, "motion-notify-event", G_CALLBACK(on_motion), &main_view); g_signal_connect(drawing_area, "scroll-event", G_CALLBACK(on_scroll), &main_view); // Ask to receive events the drawing area doesn't normally // subscribe to. In particular, we need to ask for the // button press and motion notify events that want to handle. gtk_widget_set_events (drawing_area, gtk_widget_get_events(drawing_area) | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK ); } point base_view::cursor_pos() const { return {}; } point base_view::size() const { auto x = gtk_widget_get_allocated_width(h->window); auto y = gtk_widget_get_allocated_height(h->window); return { float(x), float(y) }; } void base_view::size(point p) { } void base_view::refresh() { auto x = gtk_widget_get_allocated_width(h->window); auto y = gtk_widget_get_allocated_height(h->window); refresh({ 0, 0, float(x), float(y) }); } void base_view::refresh(rect area) { gtk_widget_queue_draw_area(h->window, area.left, area.top, area.width(), area.height()); } void base_view::limits(view_limits limits_, bool maintain_aspect) { } bool base_view::is_focus() const { return false; } cairo_t* base_view::begin_drawing() { // GTK already does this for us return h->cr; } void base_view::end_drawing(cairo_t* ctx) { // GTK will do this for us } std::string clipboard() { return ""; } void clipboard(std::string const& text) { } void set_cursor(cursor_type type) { switch (type) { case cursor_type::arrow: break; case cursor_type::ibeam: break; case cursor_type::cross_hair: break; case cursor_type::hand: break; case cursor_type::h_resize: break; case cursor_type::v_resize: break; } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * 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. * */ #include "QXmppUtils.h" #include "QXmppIq.h" #include <QDomElement> #include <QXmlStreamWriter> /// Constructs a QXmppIq with the specified \a type. /// /// \param type QXmppIq::QXmppIq(QXmppIq::Type type) : QXmppStanza(), m_type(type) { generateAndSetNextId(); } /// Returns the IQ's type. /// QXmppIq::Type QXmppIq::type() const { return m_type; } /// Sets the IQ's type. /// /// \param type void QXmppIq::setType(QXmppIq::Type type) { m_type = type; } void QXmppIq::parse(const QDomElement &element) { QXmppStanza::parse(element); setTypeFromStr(element.attribute("type")); parseElementFromChild(element); } void QXmppIq::parseElementFromChild(const QDomElement &element) { QXmppElementList extensions; QDomElement itemElement = element.firstChildElement(); while (!itemElement.isNull()) { extensions.append(QXmppElement(itemElement)); itemElement = itemElement.nextSiblingElement(); } setExtensions(extensions); } void QXmppIq::toXml( QXmlStreamWriter *xmlWriter ) const { xmlWriter->writeStartElement("iq"); helperToXmlAddAttribute(xmlWriter, "id", id()); helperToXmlAddAttribute(xmlWriter, "to", to()); helperToXmlAddAttribute(xmlWriter, "from", from()); if(getTypeStr().isEmpty()) helperToXmlAddAttribute(xmlWriter, "type", "get"); else helperToXmlAddAttribute(xmlWriter, "type", getTypeStr()); toXmlElementFromChild(xmlWriter); error().toXml(xmlWriter); xmlWriter->writeEndElement(); } void QXmppIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const { foreach (const QXmppElement &extension, extensions()) extension.toXml(writer); } QString QXmppIq::getTypeStr() const { switch(m_type) { case QXmppIq::Error: return "error"; case QXmppIq::Get: return "get"; case QXmppIq::Set: return "set"; case QXmppIq::Result: return "result"; default: qWarning("QXmppIq::getTypeStr() invalid type %d", (int)m_type); return ""; } } void QXmppIq::setTypeFromStr(const QString& str) { if(str == "error") { setType(QXmppIq::Error); return; } else if(str == "get") { setType(QXmppIq::Get); return; } else if(str == "set") { setType(QXmppIq::Set); return; } else if(str == "result") { setType(QXmppIq::Result); return; } else { setType(static_cast<QXmppIq::Type>(-1)); qWarning("QXmppIq::setTypeFromStr() invalid input string type: %s", qPrintable(str)); return; } } // deprecated QXmppIq::Type QXmppIq::getType() const { return m_type; } <commit_msg>doc improvement<commit_after>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * 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. * */ #include "QXmppUtils.h" #include "QXmppIq.h" #include <QDomElement> #include <QXmlStreamWriter> /// Constructs a QXmppIq with the specified \a type. /// /// \param type QXmppIq::QXmppIq(QXmppIq::Type type) : QXmppStanza(), m_type(type) { generateAndSetNextId(); } /// Returns the IQ's type. /// /// \return QXmppIq::Type QXmppIq::Type QXmppIq::type() const { return m_type; } /// Sets the IQ's type. /// /// \param type as QXmppIq::Type void QXmppIq::setType(QXmppIq::Type type) { m_type = type; } void QXmppIq::parse(const QDomElement &element) { QXmppStanza::parse(element); setTypeFromStr(element.attribute("type")); parseElementFromChild(element); } void QXmppIq::parseElementFromChild(const QDomElement &element) { QXmppElementList extensions; QDomElement itemElement = element.firstChildElement(); while (!itemElement.isNull()) { extensions.append(QXmppElement(itemElement)); itemElement = itemElement.nextSiblingElement(); } setExtensions(extensions); } void QXmppIq::toXml( QXmlStreamWriter *xmlWriter ) const { xmlWriter->writeStartElement("iq"); helperToXmlAddAttribute(xmlWriter, "id", id()); helperToXmlAddAttribute(xmlWriter, "to", to()); helperToXmlAddAttribute(xmlWriter, "from", from()); if(getTypeStr().isEmpty()) helperToXmlAddAttribute(xmlWriter, "type", "get"); else helperToXmlAddAttribute(xmlWriter, "type", getTypeStr()); toXmlElementFromChild(xmlWriter); error().toXml(xmlWriter); xmlWriter->writeEndElement(); } void QXmppIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const { foreach (const QXmppElement &extension, extensions()) extension.toXml(writer); } QString QXmppIq::getTypeStr() const { switch(m_type) { case QXmppIq::Error: return "error"; case QXmppIq::Get: return "get"; case QXmppIq::Set: return "set"; case QXmppIq::Result: return "result"; default: qWarning("QXmppIq::getTypeStr() invalid type %d", (int)m_type); return ""; } } void QXmppIq::setTypeFromStr(const QString& str) { if(str == "error") { setType(QXmppIq::Error); return; } else if(str == "get") { setType(QXmppIq::Get); return; } else if(str == "set") { setType(QXmppIq::Set); return; } else if(str == "result") { setType(QXmppIq::Result); return; } else { setType(static_cast<QXmppIq::Type>(-1)); qWarning("QXmppIq::setTypeFromStr() invalid input string type: %s", qPrintable(str)); return; } } // deprecated QXmppIq::Type QXmppIq::getType() const { return m_type; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <boost/program_options.hpp> #include <boost/format.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> int constexpr hsplit_default = 16; int constexpr vsplit_default = 16; int constexpr selectable_default = 16; int constexpr select_cost_default = 1; int constexpr change_cost_default = 1; std::string const ext = ".ppm"; int main(int argc, char* argv[]) { std::vector<std::string> input_filenames; std::string output_filename_base; int hsplit, vsplit; int selectable; int select_cost, change_cost; // コマンドラインオプションの定義 boost::program_options::options_description options(argv[0]); options.add_options() ("input,i", boost::program_options::value<std::vector<std::string>>(&input_filenames) ->multitoken() ->required(), "入力ファイル名") ("output,o", boost::program_options::value<std::string>(&output_filename_base), "出力ファイル名") ("hsplit,h", boost::program_options::value<int>(&hsplit) ->default_value(hsplit_default), "横分割数") ("vsplit,v", boost::program_options::value<int>(&vsplit) ->default_value(vsplit_default), "縦分割数") ("selectable,n", boost::program_options::value<int>(&selectable) ->default_value(selectable_default), "選択可能回数") ("select_cost,s", boost::program_options::value<int>(&select_cost) ->default_value(select_cost_default), "選択コスト変換レート") ("change_cost,c", boost::program_options::value<int>(&change_cost) ->default_value(change_cost_default), "交換コスト変換レート") ; // コマンドラインオプションのチェック boost::program_options::variables_map options_map; try { boost::program_options::store(boost::program_options::parse_command_line(argc, argv, options), options_map); boost::program_options::notify(options_map); } catch (boost::program_options::error_with_option_name const& e) { std::cout << e.what() << std::endl; std::cout << options << std::endl; return -1; } // 入力ファイル名でループ cv::Mat input_image; std::vector<uchar> output_buffer; std::string header; std::string output_filename; int count = 0; for (std::string const& input_filename : input_filenames) { // 出力ファイル名の設定 if (output_filename_base.size() == 0) { output_filename = input_filename; } else { output_filename = output_filename_base; } auto dotpos = output_filename.find_last_of('.'); if (dotpos != std::string::npos) { output_filename.resize(dotpos); } output_filename += (boost::format("_%1$02d") % count).str(); output_filename += ext; // ヘッダ文字列の設定 header.erase(); header += (boost::format("# %1% %2%\n") % hsplit % vsplit).str(); header += (boost::format("# %1%\n") % selectable).str(); header += (boost::format("# %1% %2%\n") % select_cost % change_cost).str(); // 画像読み込み input_image = cv::imread(input_filename); if (input_image.data == nullptr) { std::cout << "Fatal: " << input_filename << " を読み込めませんでした。" << std::endl; return -1; } // バッファへ書き込み cv::imencode(ext, input_image, output_buffer, std::vector<int>(CV_IMWRITE_PXM_BINARY)); // ヘッダ流し込み output_buffer.insert(output_buffer.begin() + 3, header.begin(), header.end()); // ファイル書き出し std::ofstream output_file(output_filename, std::ofstream::binary); if (!output_file) { std::cout << "Fatal: " << output_filename << " へ書き込めませんでした。" << std::endl; return -1; } std::copy(output_buffer.begin(), output_buffer.end(), std::ostream_iterator<uchar>(output_file)); } return 0; } <commit_msg>エラー処理には例外を使うようにした<commit_after>#include <iostream> #include <fstream> #include <boost/program_options.hpp> #include <boost/format.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> int constexpr hsplit_default = 16; int constexpr vsplit_default = 16; int constexpr selectable_default = 16; int constexpr select_cost_default = 1; int constexpr change_cost_default = 1; std::string const ext = ".ppm"; int main(int argc, char* argv[]) { std::vector<std::string> input_filenames; std::string output_filename_base; int hsplit, vsplit; int selectable; int select_cost, change_cost; // コマンドラインオプションの定義 boost::program_options::options_description options(argv[0]); options.add_options() ("input,i", boost::program_options::value<std::vector<std::string>>(&input_filenames) ->multitoken() ->required(), "入力ファイル名") ("output,o", boost::program_options::value<std::string>(&output_filename_base), "出力ファイル名") ("hsplit,h", boost::program_options::value<int>(&hsplit) ->default_value(hsplit_default), "横分割数") ("vsplit,v", boost::program_options::value<int>(&vsplit) ->default_value(vsplit_default), "縦分割数") ("selectable,n", boost::program_options::value<int>(&selectable) ->default_value(selectable_default), "選択可能回数") ("select_cost,s", boost::program_options::value<int>(&select_cost) ->default_value(select_cost_default), "選択コスト変換レート") ("change_cost,c", boost::program_options::value<int>(&change_cost) ->default_value(change_cost_default), "交換コスト変換レート") ; // コマンドラインオプションのチェック boost::program_options::variables_map options_map; try { boost::program_options::store(boost::program_options::parse_command_line(argc, argv, options), options_map); boost::program_options::notify(options_map); } catch (boost::program_options::error_with_option_name const& e) { std::cout << e.what() << std::endl; std::cout << options << std::endl; return -1; } // 入力ファイル名でループ cv::Mat input_image; std::string header; std::vector<uchar> output_buffer; std::string output_filename; std::ofstream output_file; output_file.exceptions(std::ofstream::eofbit | std::ofstream::failbit | std::ofstream::badbit); for (std::string const& input_filename : input_filenames) { // 出力ファイル名の設定 if (output_filename_base.size() == 0) { output_filename = input_filename; } else { output_filename = output_filename_base; } auto dotpos = output_filename.find_last_of('.'); if (dotpos != std::string::npos) { output_filename.resize(dotpos); } output_filename += ext; // ヘッダ文字列の設定 header.erase(); header += (boost::format("# %1% %2%\n") % hsplit % vsplit).str(); header += (boost::format("# %1%\n") % selectable).str(); header += (boost::format("# %1% %2%\n") % select_cost % change_cost).str(); // 画像読み込み input_image = cv::imread(input_filename); if (input_image.data == nullptr) { std::cerr << "Fatal: " << input_filename << " を読み込めませんでした" << std::endl; return -1; } // バッファへ書き込み cv::imencode(ext, input_image, output_buffer, std::vector<int>(CV_IMWRITE_PXM_BINARY)); // ヘッダ流し込み // 先頭の "P6\n" の後にヘッダ文字列を挿入する output_buffer.insert(output_buffer.begin() + 3, header.begin(), header.end()); // ファイル書き出し try { output_file.open(output_filename, std::ofstream::binary); std::copy(output_buffer.begin(), output_buffer.end(), std::ostream_iterator<uchar>(output_file)); output_file.close(); } catch (std::ofstream::failure e) { std::cerr << "Fatal: " << output_filename << " へ書き込めません"; if (output_file.bad()) { std::cerr << " (bad)"; } else if (output_file.fail()) { std::cerr << " (fail)"; } else { std::cerr << " (eof)"; } std::cerr << std::endl; return -1; } } return 0; } <|endoftext|>
<commit_before>//************************************************************/ // // Plot Implementation // // Implements the SPXPlot class, which connects all of the // other non-configuration classes (non-steering/options) and // manages the plotting, drawing, and ROOT objects // // @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS // @Date: 13.10.2014 // @Email: gibsjose@mail.gvsu.edu // //************************************************************/ #include <sstream> #include "SPXPlot.h" #include "SPXUtilities.h" const std::string cn = "SPXPlot::"; //Must define the static debug variable in the implementation bool SPXPlot::debug; //Initialize all plots void SPXPlot::Initialize(void) { try { InitializeData(); InitializeCrossSections(); NormalizeCrossSections(); } catch(const SPXException &e) { throw; } } void SPXPlot::Plot(void) { std::string mn = "Plot:: "; SPXPlotConfiguration &pc = steeringFile->GetPlotConfiguration(id); std::ostringstream oss; oss << "canvas" << id; std::string canvasID = oss.str(); //@TODO Where should these come from? Or are they just initial values that are set later? int wtopx = 200; //Window top x int wtopy = 10; //Window top y int ww = 700; //Window width int wh = 500; //Window height canvas = new TCanvas(canvasID.c_str(), pc.GetDescription().c_str(), wtopx, wtopy, ww, wh); canvas->SetFillColor(0); canvas->SetGrid(); if(debug) { std::cout << cn << mn << "Canvas (" << canvasID << ") created for Plot ID " << id << " with dimensions: " << ww << " x " << wh << " and title: " << pc.GetDescription() << std::endl; } //@TODO Where should these come from? double xMin; // = 0; double xMax; // = 3000; double yMin; // = 0; double yMax; // = 0.003; //Determine frame bounds by calculating the xmin, xmax, ymin, ymax from ALL graphs being drawn std::vector<TGraphAsymmErrors *> graphs; { //Data graphs for(int i = 0; i < data.size(); i++) { graphs.push_back(data[i].GetStatisticalErrorGraph()); graphs.push_back(data[i].GetSystematicErrorGraph()); } //Cross sections for(int i = 0; i < crossSections.size(); i++) { graphs.push_back(crossSections[i].GetPDFBandResults()); } xMin = SPXGraphUtilities::GetXMin(graphs); xMax = SPXGraphUtilities::GetXMax(graphs); yMin = SPXGraphUtilities::GetYMin(graphs); yMax = SPXGraphUtilities::GetYMax(graphs); //Sanity check if(xMin > xMax) { throw SPXGraphException("xMin calculated to be larger than xMax"); } if(yMin > yMax) { throw SPXGraphException("yMin calculated to be larger than yMax"); } } //Draw the frame (xmin, ymin, xmax, ymax) canvas->DrawFrame(xMin, yMin, xMax, yMax); if(debug) { std::cout << cn << mn << "Canvas (" << canvasID << ") frame drawn with dimensions: " << std::endl; std::cout << "\t xMin = " << xMin << std::endl; std::cout << "\t xMax = " << xMax << std::endl; std::cout << "\t yMin = " << yMin << std::endl; std::cout << "\t yMax = " << yMax << std::endl; } //Draw data graphs for(int i = 0; i < data.size(); i++) { data[i].GetSystematicErrorGraph()->Draw("P"); data[i].GetStatisticalErrorGraph()->Draw("||"); } //Draw cross sections for(int i = 0; i < crossSections.size(); i++) { crossSections[i].GetPDFBandResults()->Draw("P"); } //Update canvas canvas->Update(); } //@TODO Where do I normalize cross section??? void SPXPlot::InitializeCrossSections(void) { std::string mn = "InitializeCrossSections: "; //Create cross sections for each configuration instance (and each PDF) for(int i = 0; i < steeringFile->GetNumberOfConfigurationInstances(id); i++) { for(int j = 0; j < steeringFile->GetNumberOfPDFSteeringFiles(); j++) { SPXPDFSteeringFile &psf = steeringFile->GetPDFSteeringFile(j); SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i); SPXCrossSection crossSectionInstance = SPXCrossSection(&psf, &pci); try { crossSectionInstance.Create(); crossSections.push_back(crossSectionInstance); } catch(const SPXException &e) { throw; } } } } void SPXPlot::NormalizeCrossSections(void) { std::string mn = "NormalizeCrossSections: "; for(int i = 0; i < crossSections.size(); i++) { try { if(debug) std::cout << cn << mn << "Normalizing Cross Section at index " << i << std::endl; SPXPDFSteeringFile *psf = crossSections[i].GetPDFSteeringFile(); SPXPlotConfigurationInstance *pci = crossSections[i].GetPlotConfigurationInstance(); std::string masterXUnits = pci->dataSteeringFile.GetXUnits(); std::string slaveXUnits = pci->gridSteeringFile.GetXUnits(); std::string masterYUnits = pci->dataSteeringFile.GetYUnits(); std::string slaveYUnits = pci->gridSteeringFile.GetYUnits(); //Determine the scale from the unit difference between data and grid double xScale = SPXGraphUtilities::GetXUnitsScale(masterXUnits, slaveXUnits); double yScale = SPXGraphUtilities::GetYUnitsScale(masterYUnits, slaveYUnits); if(debug) { std::cout << cn << mn << "Scales determined from data/grid unit differential: " << std::endl; std::cout << "\t Data X Units: " << masterXUnits << std::endl; std::cout << "\t Grid X Units: " << slaveXUnits << std::endl << std::endl; std::cout << "\t Data Y Units: " << masterYUnits << std::endl; std::cout << "\t Grid Y Units: " << slaveYUnits << std::endl << std::endl; std::cout << "\t ---> X Unit Scale Determined: " << xScale << std::endl; std::cout << "\t ---> Y Unit Scale Determined: " << yScale << std::endl << std::endl; } //Also scale by the artificial scale from the plot configuration instance xScale *= pci->xScale; yScale *= pci->yScale; SPXGraphUtilities::Scale(crossSections[i].GetPDFBandResults(), xScale, yScale); if(debug) { std::cout << cn << mn << "Additional artificial scale for Cross Section: " << std::endl; std::cout << "\t X Scale: " << pci->xScale << std::endl; std::cout << "\t Y Scale: " << pci->yScale << std::endl << std::endl; } //Normalized to total sigma from the DATA steering file bool normalizeToTotalSigma = pci->dataSteeringFile.IsNormalizedToTotalSigma(); bool dataDividedByBinWidth = pci->dataSteeringFile.IsDividedByBinWidth(); bool gridDividedByBinWidth = pci->gridSteeringFile.IsDividedByBinWidth(); bool divideByBinWidth = false; if(dataDividedByBinWidth && !gridDividedByBinWidth) { if(debug) std::cout << cn << mn << "Data IS divided by bin width but the grid IS NOT. Will call Normalize with divideByBinWidth = true" << std::endl; divideByBinWidth = true; } double yBinWidthScale = 1.0; //If the data is divided by the bin width, then set the yBinWidthScale, which is the scaling of the Data's Y Bin Width Units to the Data's X Units if(dataDividedByBinWidth) { yBinWidthScale = SPXGraphUtilities::GetYBinWidthUnitsScale(pci->dataSteeringFile.GetXUnits(), pci->dataSteeringFile.GetYBinWidthUnits()); } if(debug) std::cout << cn << mn << "Y Bin Width Scale = " << yBinWidthScale << std::endl; if(debug) std::cout << cn << mn << "Normalize to Total Sigma is " << (normalizeToTotalSigma ? "ON" : "OFF") << std::endl; if(debug) std::cout << cn << mn << "Divide by Bin Width is " << (divideByBinWidth ? "ON" : "OFF") << std::endl; //Normalize the cross section SPXGraphUtilities::Normalize(crossSections[i].GetPDFBandResults(), yBinWidthScale, normalizeToTotalSigma, divideByBinWidth); if(debug) std::cout << cn << mn << "Sucessfully normalized Cross Section " << i << std::endl; } catch(const SPXException &e) { std::cerr << e.what() << std::endl; throw SPXGraphException("SPXPlot::NormalizeCrossSections: Unable to obtain X/Y Scale based on Data/Grid Units"); } } } void SPXPlot::InitializeData(void) { std::string mn = "InitializeData: "; //Create data objects for each configuration instance of this plot and add them to vector for(int i = 0; i < steeringFile->GetNumberOfConfigurationInstances(id); i++) { SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i); SPXData dataInstance = SPXData(pci); try { dataInstance.Parse(); dataInstance.Print(); data.push_back(dataInstance); } catch(const SPXException &e) { throw; } } //Go through data objects and create graphs, modify settings, etc. for(int i = 0; i < data.size(); i++) { //Create graphs: once this function is called, it is safe to manipulate graphs data[i].CreateGraphs(); //Obtain the graphs TGraphAsymmErrors *statGraph = data[i].GetStatisticalErrorGraph(); TGraphAsymmErrors *systGraph = data[i].GetSystematicErrorGraph(); //Get settings SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i); //Normalize the graphs based on the settings double xScale = pci.xScale; double yScale = pci.yScale; if(debug) { std::cout << cn << mn << "Scaling Data with: " << std::endl; std::cout << "\t X Scale = " << xScale << std::endl; std::cout << "\t Y Scale = " << yScale << std::endl; } SPXGraphUtilities::Scale(statGraph, xScale, yScale); SPXGraphUtilities::Scale(systGraph, xScale, yScale); //Modify Data Graph styles statGraph->SetMarkerStyle(pci.markerStyle); systGraph->SetMarkerStyle(pci.markerStyle); statGraph->SetMarkerColor(pci.markerColor); systGraph->SetMarkerColor(pci.markerColor); statGraph->SetMarkerSize(1.0); systGraph->SetMarkerSize(1.0); statGraph->SetLineColor(4); systGraph->SetLineColor(1); statGraph->SetLineWidth(1); systGraph->SetLineWidth(1); } }<commit_msg>Modified divideByBinWidth: NORMALIZATION ACTUALLY TAKES DIVIDED<------ the past participle, not the imperative verb form...<commit_after>//************************************************************/ // // Plot Implementation // // Implements the SPXPlot class, which connects all of the // other non-configuration classes (non-steering/options) and // manages the plotting, drawing, and ROOT objects // // @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS // @Date: 13.10.2014 // @Email: gibsjose@mail.gvsu.edu // //************************************************************/ #include <sstream> #include "SPXPlot.h" #include "SPXUtilities.h" const std::string cn = "SPXPlot::"; //Must define the static debug variable in the implementation bool SPXPlot::debug; //Initialize all plots void SPXPlot::Initialize(void) { try { InitializeData(); InitializeCrossSections(); NormalizeCrossSections(); } catch(const SPXException &e) { throw; } } void SPXPlot::Plot(void) { std::string mn = "Plot:: "; SPXPlotConfiguration &pc = steeringFile->GetPlotConfiguration(id); std::ostringstream oss; oss << "canvas" << id; std::string canvasID = oss.str(); //@TODO Where should these come from? Or are they just initial values that are set later? int wtopx = 200; //Window top x int wtopy = 10; //Window top y int ww = 700; //Window width int wh = 500; //Window height canvas = new TCanvas(canvasID.c_str(), pc.GetDescription().c_str(), wtopx, wtopy, ww, wh); canvas->SetFillColor(0); canvas->SetGrid(); if(debug) { std::cout << cn << mn << "Canvas (" << canvasID << ") created for Plot ID " << id << " with dimensions: " << ww << " x " << wh << " and title: " << pc.GetDescription() << std::endl; } //@TODO Where should these come from? double xMin; // = 0; double xMax; // = 3000; double yMin; // = 0; double yMax; // = 0.003; //Determine frame bounds by calculating the xmin, xmax, ymin, ymax from ALL graphs being drawn std::vector<TGraphAsymmErrors *> graphs; { //Data graphs for(int i = 0; i < data.size(); i++) { graphs.push_back(data[i].GetStatisticalErrorGraph()); graphs.push_back(data[i].GetSystematicErrorGraph()); } //Cross sections for(int i = 0; i < crossSections.size(); i++) { graphs.push_back(crossSections[i].GetPDFBandResults()); } xMin = SPXGraphUtilities::GetXMin(graphs); xMax = SPXGraphUtilities::GetXMax(graphs); yMin = SPXGraphUtilities::GetYMin(graphs); yMax = SPXGraphUtilities::GetYMax(graphs); //Sanity check if(xMin > xMax) { throw SPXGraphException("xMin calculated to be larger than xMax"); } if(yMin > yMax) { throw SPXGraphException("yMin calculated to be larger than yMax"); } } //Draw the frame (xmin, ymin, xmax, ymax) canvas->DrawFrame(xMin, yMin, xMax, yMax); if(debug) { std::cout << cn << mn << "Canvas (" << canvasID << ") frame drawn with dimensions: " << std::endl; std::cout << "\t xMin = " << xMin << std::endl; std::cout << "\t xMax = " << xMax << std::endl; std::cout << "\t yMin = " << yMin << std::endl; std::cout << "\t yMax = " << yMax << std::endl; } //Draw data graphs for(int i = 0; i < data.size(); i++) { data[i].GetSystematicErrorGraph()->Draw("P"); data[i].GetStatisticalErrorGraph()->Draw("||"); } //Draw cross sections for(int i = 0; i < crossSections.size(); i++) { crossSections[i].GetPDFBandResults()->Draw("P"); } //Update canvas canvas->Update(); } //@TODO Where do I normalize cross section??? void SPXPlot::InitializeCrossSections(void) { std::string mn = "InitializeCrossSections: "; //Create cross sections for each configuration instance (and each PDF) for(int i = 0; i < steeringFile->GetNumberOfConfigurationInstances(id); i++) { for(int j = 0; j < steeringFile->GetNumberOfPDFSteeringFiles(); j++) { SPXPDFSteeringFile &psf = steeringFile->GetPDFSteeringFile(j); SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i); SPXCrossSection crossSectionInstance = SPXCrossSection(&psf, &pci); try { crossSectionInstance.Create(); crossSections.push_back(crossSectionInstance); } catch(const SPXException &e) { throw; } } } } void SPXPlot::NormalizeCrossSections(void) { std::string mn = "NormalizeCrossSections: "; for(int i = 0; i < crossSections.size(); i++) { try { if(debug) std::cout << cn << mn << "Normalizing Cross Section at index " << i << std::endl; SPXPDFSteeringFile *psf = crossSections[i].GetPDFSteeringFile(); SPXPlotConfigurationInstance *pci = crossSections[i].GetPlotConfigurationInstance(); std::string masterXUnits = pci->dataSteeringFile.GetXUnits(); std::string slaveXUnits = pci->gridSteeringFile.GetXUnits(); std::string masterYUnits = pci->dataSteeringFile.GetYUnits(); std::string slaveYUnits = pci->gridSteeringFile.GetYUnits(); //Determine the scale from the unit difference between data and grid double xScale = SPXGraphUtilities::GetXUnitsScale(masterXUnits, slaveXUnits); double yScale = SPXGraphUtilities::GetYUnitsScale(masterYUnits, slaveYUnits); if(debug) { std::cout << cn << mn << "Scales determined from data/grid unit differential: " << std::endl; std::cout << "\t Data X Units: " << masterXUnits << std::endl; std::cout << "\t Grid X Units: " << slaveXUnits << std::endl << std::endl; std::cout << "\t Data Y Units: " << masterYUnits << std::endl; std::cout << "\t Grid Y Units: " << slaveYUnits << std::endl << std::endl; std::cout << "\t ---> X Unit Scale Determined: " << xScale << std::endl; std::cout << "\t ---> Y Unit Scale Determined: " << yScale << std::endl << std::endl; } //Also scale by the artificial scale from the plot configuration instance xScale *= pci->xScale; yScale *= pci->yScale; SPXGraphUtilities::Scale(crossSections[i].GetPDFBandResults(), xScale, yScale); if(debug) { std::cout << cn << mn << "Additional artificial scale for Cross Section: " << std::endl; std::cout << "\t X Scale: " << pci->xScale << std::endl; std::cout << "\t Y Scale: " << pci->yScale << std::endl << std::endl; } //Normalized to total sigma from the DATA steering file bool normalizeToTotalSigma = pci->dataSteeringFile.IsNormalizedToTotalSigma(); bool dataDividedByBinWidth = pci->dataSteeringFile.IsDividedByBinWidth(); bool gridDividedByBinWidth = pci->gridSteeringFile.IsDividedByBinWidth(); //@TODO Change back to being initialized as false bool divideByBinWidth = true; if(dataDividedByBinWidth && !gridDividedByBinWidth) { if(debug) std::cout << cn << mn << "Data IS divided by bin width but the grid IS NOT. Will call Normalize with divideByBinWidth = true" << std::endl; divideByBinWidth = true; } double yBinWidthScale = 1.0; //If the data is divided by the bin width, then set the yBinWidthScale, which is the scaling of the Data's Y Bin Width Units to the Data's X Units if(dataDividedByBinWidth) { yBinWidthScale = SPXGraphUtilities::GetYBinWidthUnitsScale(pci->dataSteeringFile.GetXUnits(), pci->dataSteeringFile.GetYBinWidthUnits()); } if(debug) std::cout << cn << mn << "Y Bin Width Scale = " << yBinWidthScale << std::endl; if(debug) std::cout << cn << mn << "Normalize to Total Sigma is " << (normalizeToTotalSigma ? "ON" : "OFF") << std::endl; if(debug) std::cout << cn << mn << "Divide by Bin Width is " << (divideByBinWidth ? "ON" : "OFF") << std::endl; //Normalize the cross section SPXGraphUtilities::Normalize(crossSections[i].GetPDFBandResults(), yBinWidthScale, normalizeToTotalSigma, divideByBinWidth); if(debug) std::cout << cn << mn << "Sucessfully normalized Cross Section " << i << std::endl; } catch(const SPXException &e) { std::cerr << e.what() << std::endl; throw SPXGraphException("SPXPlot::NormalizeCrossSections: Unable to obtain X/Y Scale based on Data/Grid Units"); } } } void SPXPlot::InitializeData(void) { std::string mn = "InitializeData: "; //Create data objects for each configuration instance of this plot and add them to vector for(int i = 0; i < steeringFile->GetNumberOfConfigurationInstances(id); i++) { SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i); SPXData dataInstance = SPXData(pci); try { dataInstance.Parse(); dataInstance.Print(); data.push_back(dataInstance); } catch(const SPXException &e) { throw; } } //Go through data objects and create graphs, modify settings, etc. for(int i = 0; i < data.size(); i++) { //Create graphs: once this function is called, it is safe to manipulate graphs data[i].CreateGraphs(); //Obtain the graphs TGraphAsymmErrors *statGraph = data[i].GetStatisticalErrorGraph(); TGraphAsymmErrors *systGraph = data[i].GetSystematicErrorGraph(); //Get settings SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i); //Normalize the graphs based on the settings double xScale = pci.xScale; double yScale = pci.yScale; if(debug) { std::cout << cn << mn << "Scaling Data with: " << std::endl; std::cout << "\t X Scale = " << xScale << std::endl; std::cout << "\t Y Scale = " << yScale << std::endl; } SPXGraphUtilities::Scale(statGraph, xScale, yScale); SPXGraphUtilities::Scale(systGraph, xScale, yScale); //Modify Data Graph styles statGraph->SetMarkerStyle(pci.markerStyle); systGraph->SetMarkerStyle(pci.markerStyle); statGraph->SetMarkerColor(pci.markerColor); systGraph->SetMarkerColor(pci.markerColor); statGraph->SetMarkerSize(1.0); systGraph->SetMarkerSize(1.0); statGraph->SetLineColor(4); systGraph->SetLineColor(1); statGraph->SetLineWidth(1); systGraph->SetLineWidth(1); } }<|endoftext|>
<commit_before>/* * Seek camera interface * Author: Maarten Vandersteegen */ #include "SeekCam.h" #include "SeekLogging.h" #include <iomanip> using namespace LibSeek; SeekCam::SeekCam(int vendor_id, int product_id, uint16_t* buffer, size_t raw_height, size_t raw_width, size_t request_size, cv::Rect roi, std::string ffc_filename) : m_offset(0x4000), m_ffc_filename(ffc_filename), m_is_opened(false), m_dev(vendor_id, product_id), m_raw_data(buffer), m_raw_data_size(raw_height * raw_width), m_raw_frame(raw_height, raw_width, CV_16UC1, buffer, cv::Mat::AUTO_STEP), m_request_size(request_size), m_flat_field_calibration_frame(), m_additional_ffc(), m_dead_pixel_mask() { /* set ROI to exclude metadata frame regions */ m_raw_frame = m_raw_frame(roi); } SeekCam::~SeekCam() { close(); } bool SeekCam::open() { if (m_ffc_filename != std::string()) { m_additional_ffc = cv::imread(m_ffc_filename, -1); if (m_additional_ffc.type() != m_raw_frame.type()) { error("Error: '%s' not found or it has the wrong type: %d\n", m_ffc_filename.c_str(), m_additional_ffc.type()); return false; } if (m_additional_ffc.size() != m_raw_frame.size()) { error("Error: expected '%s' to have size [%d,%d], got [%d,%d]\n", m_ffc_filename.c_str(), m_raw_frame.cols, m_raw_frame.rows, m_additional_ffc.cols, m_additional_ffc.rows); return false; } } return open_cam(); } void SeekCam::close() { if (m_dev.isOpened()) { std::vector<uint8_t> data = { 0x00, 0x00 }; m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); } m_is_opened = false; } bool SeekCam::isOpened() { return m_is_opened; } bool SeekCam::grab() { int i; for (i=0; i<40; i++) { if(!get_frame()) { error("Error: frame acquisition failed\n"); return false; } if (frame_id() == 3) { return true; } else if (frame_id() == 1) { m_raw_frame.copyTo(m_flat_field_calibration_frame); } } return false; } void SeekCam::retrieve(cv::Mat& dst) { /* apply flat field calibration */ m_raw_frame += m_offset - m_flat_field_calibration_frame; /* filter out dead pixels */ apply_dead_pixel_filter(m_raw_frame, dst); /* apply additional flat field calibration for degradient */ if (!m_additional_ffc.empty()) dst += m_offset - m_additional_ffc; } bool SeekCam::read(cv::Mat& dst) { if (!grab()) return false; retrieve(dst); return true; } void SeekCam::convertToGreyScale(cv::Mat& src, cv::Mat& dst) { double tmin, tmax, rsize; double rnint = 0; double rnstart = 0; size_t n; size_t num_of_pixels = src.rows * src.cols; cv::minMaxLoc(src, &tmin, &tmax); rsize = (tmax - tmin) / 10.0; for (n=0; n<10; n++) { double min = tmin + n * rsize; cv::Mat mask; cv::Mat temp; rnstart += rnint; cv::inRange(src, cv::Scalar(min), cv::Scalar(min + rsize), mask); /* num_of_pixels_in_range / total_num_of_pixels * 256 */ rnint = (cv::countNonZero(mask) << 8) / num_of_pixels; temp = ((src - min) * rnint) / rsize + rnstart; temp.copyTo(dst, mask); } dst.convertTo(dst, CV_8UC1); } bool SeekCam::open_cam() { int i; if (!m_dev.open()) { error("Error: open failed\n"); return false; } /* init retry loop: sometimes cam skips first 512 bytes of first frame (needed for dead pixel filter) */ for (i=0; i<3; i++) { /* cam specific configuration */ if (!init_cam()) { error("Error: init_cam failed\n"); return false; } if (!get_frame()) { error("Error: first frame acquisition failed, retry attempt %d\n", i+1); continue; } if (frame_id() != 4) { error("Error: expected first frame to have id 4\n"); return false; } create_dead_pixel_list(m_raw_frame, m_dead_pixel_mask, m_dead_pixel_list); if (!grab()) { error("Error: first grab failed\n"); return false; } m_is_opened = true; return true; } error("Error: max init retry count exceeded\n"); return false; } bool SeekCam::get_frame() { /* request new frame */ uint8_t* s = reinterpret_cast<uint8_t*>(&m_raw_data_size); std::vector<uint8_t> data = { s[0], s[1], s[2], s[3] }; if (!m_dev.request_set(DeviceCommand::START_GET_IMAGE_TRANSFER, data)) return false; /* store frame data */ if (!m_dev.fetch_frame(m_raw_data, m_raw_data_size, m_request_size)) return false; return true; } void SeekCam::print_usb_data(std::vector<uint8_t>& data) { std::stringstream ss; std::string out; ss << "Response:"; for (size_t i = 0; i < data.size(); i++) { ss << " " << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(data[i]); } out = ss.str(); debug("%s\n", out.c_str()); } void SeekCam::create_dead_pixel_list(cv::Mat frame, cv::Mat& dead_pixel_mask, std::vector<cv::Point>& dead_pixel_list) { int x, y; bool has_unlisted_pixels; double max_value; cv::Point hist_max_value; cv::Mat tmp, hist; int channels[] = {0}; int histSize[] = {0x4000}; float range[] = {0, 0x4000}; const float* ranges[] = { range }; /* calculate optimal threshold to determine what pixels are dead pixels */ frame.convertTo(tmp, CV_32FC1); cv::minMaxLoc(tmp, nullptr, &max_value); cv::calcHist(&tmp, 1, channels, cv::Mat(), hist, 1, histSize, ranges, true, /* the histogram is uniform */ false); hist.at<float>(0, 0) = 0; /* suppres 0th bin since its usual the highest, but we don't want this one */ cv::minMaxLoc(hist, nullptr, nullptr, nullptr, &hist_max_value); const double threshold = hist_max_value.y - (max_value - hist_max_value.y); /* calculate the dead pixels mask */ cv::threshold(tmp, tmp, threshold, 255, cv::THRESH_BINARY); tmp.convertTo(dead_pixel_mask, CV_8UC1); /* build dead pixel list in a certain order to assure that every dead pixel value * gets an estimated value in the filter stage */ dead_pixel_mask.convertTo(tmp, CV_16UC1); dead_pixel_list.clear(); do { has_unlisted_pixels = false; for (y=0; y<tmp.rows; y++) { for (x=0; x<tmp.cols; x++) { const cv::Point p(x, y); if (tmp.at<uint16_t>(y, x) != 0) continue; /* not a dead pixel */ /* only add pixel to the list if we can estimate its value * directly from its neighbor pixels */ if (calc_mean_value(tmp, p, 0) != 0) { dead_pixel_list.push_back(p); tmp.at<uint16_t>(y, x) = 255; } else has_unlisted_pixels = true; } } } while (has_unlisted_pixels); } void SeekCam::apply_dead_pixel_filter(cv::Mat& src, cv::Mat& dst) { size_t i; const size_t size = m_dead_pixel_list.size(); const uint32_t dead_pixel_marker = 0xffff; dst.create(src.rows, src.cols, src.type()); /* ensure dst is properly allocated */ dst.setTo(dead_pixel_marker); /* value to identify dead pixels */ src.copyTo(dst, m_dead_pixel_mask); /* only copy non dead pixel values */ /* replace dead pixel values (0xffff) with the mean of its non dead surrounding pixels */ for (i=0; i<size; i++) { cv::Point p = m_dead_pixel_list[i]; dst.at<uint16_t>(p) = calc_mean_value(dst, p, dead_pixel_marker); } } uint16_t SeekCam::calc_mean_value(cv::Mat& img, cv::Point p, uint32_t dead_pixel_marker) { uint32_t value = 0, temp; uint32_t div = 0; const int right_border = img.cols - 1; const int lower_border = img.rows - 1; if (p.x != 0) { /* if not on the left border of the image */ temp = img.at<uint16_t>(p.y, p.x-1); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.x != right_border) { /* if not on the right border of the image */ temp = img.at<uint16_t>(p.y, p.x+1); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.y != 0) { /* upper */ temp = img.at<uint16_t>(p.y-1, p.x); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.y != lower_border) { /* lower */ temp = img.at<uint16_t>(p.y+1, p.x); if (temp != dead_pixel_marker) { value += temp; div++; } } if (div) return (value / div); return 0; } <commit_msg>Fix warning (wrong initialization order) (#53)<commit_after>/* * Seek camera interface * Author: Maarten Vandersteegen */ #include "SeekCam.h" #include "SeekLogging.h" #include <iomanip> using namespace LibSeek; SeekCam::SeekCam(int vendor_id, int product_id, uint16_t* buffer, size_t raw_height, size_t raw_width, size_t request_size, cv::Rect roi, std::string ffc_filename) : m_offset(0x4000), m_ffc_filename(ffc_filename), m_is_opened(false), m_dev(vendor_id, product_id), m_raw_data(buffer), m_raw_data_size(raw_height * raw_width), m_request_size(request_size), m_raw_frame(raw_height, raw_width, CV_16UC1, buffer, cv::Mat::AUTO_STEP), m_flat_field_calibration_frame(), m_additional_ffc(), m_dead_pixel_mask() { /* set ROI to exclude metadata frame regions */ m_raw_frame = m_raw_frame(roi); } SeekCam::~SeekCam() { close(); } bool SeekCam::open() { if (m_ffc_filename != std::string()) { m_additional_ffc = cv::imread(m_ffc_filename, -1); if (m_additional_ffc.type() != m_raw_frame.type()) { error("Error: '%s' not found or it has the wrong type: %d\n", m_ffc_filename.c_str(), m_additional_ffc.type()); return false; } if (m_additional_ffc.size() != m_raw_frame.size()) { error("Error: expected '%s' to have size [%d,%d], got [%d,%d]\n", m_ffc_filename.c_str(), m_raw_frame.cols, m_raw_frame.rows, m_additional_ffc.cols, m_additional_ffc.rows); return false; } } return open_cam(); } void SeekCam::close() { if (m_dev.isOpened()) { std::vector<uint8_t> data = { 0x00, 0x00 }; m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); } m_is_opened = false; } bool SeekCam::isOpened() { return m_is_opened; } bool SeekCam::grab() { int i; for (i=0; i<40; i++) { if(!get_frame()) { error("Error: frame acquisition failed\n"); return false; } if (frame_id() == 3) { return true; } else if (frame_id() == 1) { m_raw_frame.copyTo(m_flat_field_calibration_frame); } } return false; } void SeekCam::retrieve(cv::Mat& dst) { /* apply flat field calibration */ m_raw_frame += m_offset - m_flat_field_calibration_frame; /* filter out dead pixels */ apply_dead_pixel_filter(m_raw_frame, dst); /* apply additional flat field calibration for degradient */ if (!m_additional_ffc.empty()) dst += m_offset - m_additional_ffc; } bool SeekCam::read(cv::Mat& dst) { if (!grab()) return false; retrieve(dst); return true; } void SeekCam::convertToGreyScale(cv::Mat& src, cv::Mat& dst) { double tmin, tmax, rsize; double rnint = 0; double rnstart = 0; size_t n; size_t num_of_pixels = src.rows * src.cols; cv::minMaxLoc(src, &tmin, &tmax); rsize = (tmax - tmin) / 10.0; for (n=0; n<10; n++) { double min = tmin + n * rsize; cv::Mat mask; cv::Mat temp; rnstart += rnint; cv::inRange(src, cv::Scalar(min), cv::Scalar(min + rsize), mask); /* num_of_pixels_in_range / total_num_of_pixels * 256 */ rnint = (cv::countNonZero(mask) << 8) / num_of_pixels; temp = ((src - min) * rnint) / rsize + rnstart; temp.copyTo(dst, mask); } dst.convertTo(dst, CV_8UC1); } bool SeekCam::open_cam() { int i; if (!m_dev.open()) { error("Error: open failed\n"); return false; } /* init retry loop: sometimes cam skips first 512 bytes of first frame (needed for dead pixel filter) */ for (i=0; i<3; i++) { /* cam specific configuration */ if (!init_cam()) { error("Error: init_cam failed\n"); return false; } if (!get_frame()) { error("Error: first frame acquisition failed, retry attempt %d\n", i+1); continue; } if (frame_id() != 4) { error("Error: expected first frame to have id 4\n"); return false; } create_dead_pixel_list(m_raw_frame, m_dead_pixel_mask, m_dead_pixel_list); if (!grab()) { error("Error: first grab failed\n"); return false; } m_is_opened = true; return true; } error("Error: max init retry count exceeded\n"); return false; } bool SeekCam::get_frame() { /* request new frame */ uint8_t* s = reinterpret_cast<uint8_t*>(&m_raw_data_size); std::vector<uint8_t> data = { s[0], s[1], s[2], s[3] }; if (!m_dev.request_set(DeviceCommand::START_GET_IMAGE_TRANSFER, data)) return false; /* store frame data */ if (!m_dev.fetch_frame(m_raw_data, m_raw_data_size, m_request_size)) return false; return true; } void SeekCam::print_usb_data(std::vector<uint8_t>& data) { std::stringstream ss; std::string out; ss << "Response:"; for (size_t i = 0; i < data.size(); i++) { ss << " " << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(data[i]); } out = ss.str(); debug("%s\n", out.c_str()); } void SeekCam::create_dead_pixel_list(cv::Mat frame, cv::Mat& dead_pixel_mask, std::vector<cv::Point>& dead_pixel_list) { int x, y; bool has_unlisted_pixels; double max_value; cv::Point hist_max_value; cv::Mat tmp, hist; int channels[] = {0}; int histSize[] = {0x4000}; float range[] = {0, 0x4000}; const float* ranges[] = { range }; /* calculate optimal threshold to determine what pixels are dead pixels */ frame.convertTo(tmp, CV_32FC1); cv::minMaxLoc(tmp, nullptr, &max_value); cv::calcHist(&tmp, 1, channels, cv::Mat(), hist, 1, histSize, ranges, true, /* the histogram is uniform */ false); hist.at<float>(0, 0) = 0; /* suppres 0th bin since its usual the highest, but we don't want this one */ cv::minMaxLoc(hist, nullptr, nullptr, nullptr, &hist_max_value); const double threshold = hist_max_value.y - (max_value - hist_max_value.y); /* calculate the dead pixels mask */ cv::threshold(tmp, tmp, threshold, 255, cv::THRESH_BINARY); tmp.convertTo(dead_pixel_mask, CV_8UC1); /* build dead pixel list in a certain order to assure that every dead pixel value * gets an estimated value in the filter stage */ dead_pixel_mask.convertTo(tmp, CV_16UC1); dead_pixel_list.clear(); do { has_unlisted_pixels = false; for (y=0; y<tmp.rows; y++) { for (x=0; x<tmp.cols; x++) { const cv::Point p(x, y); if (tmp.at<uint16_t>(y, x) != 0) continue; /* not a dead pixel */ /* only add pixel to the list if we can estimate its value * directly from its neighbor pixels */ if (calc_mean_value(tmp, p, 0) != 0) { dead_pixel_list.push_back(p); tmp.at<uint16_t>(y, x) = 255; } else has_unlisted_pixels = true; } } } while (has_unlisted_pixels); } void SeekCam::apply_dead_pixel_filter(cv::Mat& src, cv::Mat& dst) { size_t i; const size_t size = m_dead_pixel_list.size(); const uint32_t dead_pixel_marker = 0xffff; dst.create(src.rows, src.cols, src.type()); /* ensure dst is properly allocated */ dst.setTo(dead_pixel_marker); /* value to identify dead pixels */ src.copyTo(dst, m_dead_pixel_mask); /* only copy non dead pixel values */ /* replace dead pixel values (0xffff) with the mean of its non dead surrounding pixels */ for (i=0; i<size; i++) { cv::Point p = m_dead_pixel_list[i]; dst.at<uint16_t>(p) = calc_mean_value(dst, p, dead_pixel_marker); } } uint16_t SeekCam::calc_mean_value(cv::Mat& img, cv::Point p, uint32_t dead_pixel_marker) { uint32_t value = 0, temp; uint32_t div = 0; const int right_border = img.cols - 1; const int lower_border = img.rows - 1; if (p.x != 0) { /* if not on the left border of the image */ temp = img.at<uint16_t>(p.y, p.x-1); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.x != right_border) { /* if not on the right border of the image */ temp = img.at<uint16_t>(p.y, p.x+1); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.y != 0) { /* upper */ temp = img.at<uint16_t>(p.y-1, p.x); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.y != lower_border) { /* lower */ temp = img.at<uint16_t>(p.y+1, p.x); if (temp != dead_pixel_marker) { value += temp; div++; } } if (div) return (value / div); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 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 <numeric> #include <vector> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/array_view.h" #include "webrtc/base/random.h" #include "webrtc/modules/audio_processing/audio_buffer.h" #include "webrtc/modules/audio_processing/include/audio_processing.h" #include "webrtc/modules/audio_processing/level_controller/level_controller.h" #include "webrtc/modules/audio_processing/test/audio_buffer_tools.h" #include "webrtc/modules/audio_processing/test/bitexactness_tools.h" #include "webrtc/system_wrappers/include/clock.h" #include "webrtc/test/testsupport/perf_test.h" namespace webrtc { namespace { const size_t kNumFramesToProcess = 100; struct SimulatorBuffers { SimulatorBuffers(int render_input_sample_rate_hz, int capture_input_sample_rate_hz, int render_output_sample_rate_hz, int capture_output_sample_rate_hz, size_t num_render_input_channels, size_t num_capture_input_channels, size_t num_render_output_channels, size_t num_capture_output_channels) { Random rand_gen(42); CreateConfigAndBuffer(render_input_sample_rate_hz, num_render_input_channels, &rand_gen, &render_input_buffer, &render_input_config, &render_input, &render_input_samples); CreateConfigAndBuffer(render_output_sample_rate_hz, num_render_output_channels, &rand_gen, &render_output_buffer, &render_output_config, &render_output, &render_output_samples); CreateConfigAndBuffer(capture_input_sample_rate_hz, num_capture_input_channels, &rand_gen, &capture_input_buffer, &capture_input_config, &capture_input, &capture_input_samples); CreateConfigAndBuffer(capture_output_sample_rate_hz, num_capture_output_channels, &rand_gen, &capture_output_buffer, &capture_output_config, &capture_output, &capture_output_samples); UpdateInputBuffers(); } void CreateConfigAndBuffer(int sample_rate_hz, size_t num_channels, Random* rand_gen, std::unique_ptr<AudioBuffer>* buffer, StreamConfig* config, std::vector<float*>* buffer_data, std::vector<float>* buffer_data_samples) { int samples_per_channel = rtc::CheckedDivExact(sample_rate_hz, 100); *config = StreamConfig(sample_rate_hz, num_channels, false); buffer->reset(new AudioBuffer(config->num_frames(), config->num_channels(), config->num_frames(), config->num_channels(), config->num_frames())); buffer_data_samples->resize(samples_per_channel * num_channels); for (auto& v : *buffer_data_samples) { v = rand_gen->Rand<float>(); } buffer_data->resize(num_channels); for (size_t ch = 0; ch < num_channels; ++ch) { (*buffer_data)[ch] = &(*buffer_data_samples)[ch * samples_per_channel]; } } void UpdateInputBuffers() { test::CopyVectorToAudioBuffer(capture_input_config, capture_input_samples, capture_input_buffer.get()); test::CopyVectorToAudioBuffer(render_input_config, render_input_samples, render_input_buffer.get()); } std::unique_ptr<AudioBuffer> render_input_buffer; std::unique_ptr<AudioBuffer> capture_input_buffer; std::unique_ptr<AudioBuffer> render_output_buffer; std::unique_ptr<AudioBuffer> capture_output_buffer; StreamConfig render_input_config; StreamConfig capture_input_config; StreamConfig render_output_config; StreamConfig capture_output_config; std::vector<float*> render_input; std::vector<float> render_input_samples; std::vector<float*> capture_input; std::vector<float> capture_input_samples; std::vector<float*> render_output; std::vector<float> render_output_samples; std::vector<float*> capture_output; std::vector<float> capture_output_samples; }; class SubmodulePerformanceTimer { public: SubmodulePerformanceTimer() : clock_(webrtc::Clock::GetRealTimeClock()) { timestamps_us_.reserve(kNumFramesToProcess); } void StartTimer() { start_timestamp_us_ = rtc::Optional<int64_t>(clock_->TimeInMicroseconds()); } void StopTimer() { RTC_DCHECK(start_timestamp_us_); timestamps_us_.push_back(clock_->TimeInMicroseconds() - *start_timestamp_us_); } double GetDurationAverage() const { RTC_DCHECK(!timestamps_us_.empty()); return static_cast<double>(std::accumulate(timestamps_us_.begin(), timestamps_us_.end(), 0)) / timestamps_us_.size(); } double GetDurationStandardDeviation() const { RTC_DCHECK(!timestamps_us_.empty()); double average_duration = GetDurationAverage(); int64_t variance = std::accumulate(timestamps_us_.begin(), timestamps_us_.end(), 0, [average_duration](const int64_t& a, const int64_t& b) { return a + (b - average_duration); }); return sqrt(variance / timestamps_us_.size()); } private: webrtc::Clock* clock_; rtc::Optional<int64_t> start_timestamp_us_; std::vector<int64_t> timestamps_us_; }; std::string FormPerformanceMeasureString( const SubmodulePerformanceTimer& timer) { std::string s = std::to_string(timer.GetDurationAverage()); s += ", "; s += std::to_string(timer.GetDurationStandardDeviation()); return s; } void RunStandaloneSubmodule(int sample_rate_hz, size_t num_channels) { SimulatorBuffers buffers(sample_rate_hz, sample_rate_hz, sample_rate_hz, sample_rate_hz, num_channels, num_channels, num_channels, num_channels); SubmodulePerformanceTimer timer; LevelController level_controller; level_controller.Initialize(sample_rate_hz); for (size_t frame_no = 0; frame_no < kNumFramesToProcess; ++frame_no) { buffers.UpdateInputBuffers(); timer.StartTimer(); level_controller.Process(buffers.capture_input_buffer.get()); timer.StopTimer(); } webrtc::test::PrintResultMeanAndError( "level_controller_call_durations", "_" + std::to_string(sample_rate_hz) + "Hz_" + std::to_string(num_channels) + "_channels", "StandaloneLevelControl", FormPerformanceMeasureString(timer), "us", false); } void RunTogetherWithApm(std::string test_description, int render_input_sample_rate_hz, int render_output_sample_rate_hz, int capture_input_sample_rate_hz, int capture_output_sample_rate_hz, size_t num_channels, bool use_mobile_aec, bool include_default_apm_processing) { SimulatorBuffers buffers( render_input_sample_rate_hz, capture_input_sample_rate_hz, render_output_sample_rate_hz, capture_output_sample_rate_hz, num_channels, num_channels, num_channels, num_channels); SubmodulePerformanceTimer render_timer; SubmodulePerformanceTimer capture_timer; SubmodulePerformanceTimer total_timer; Config config; if (include_default_apm_processing) { config.Set<DelayAgnostic>(new DelayAgnostic(true)); config.Set<ExtendedFilter>(new ExtendedFilter(true)); } config.Set<LevelControl>(new LevelControl(true)); std::unique_ptr<AudioProcessing> apm; apm.reset(AudioProcessing::Create(config)); ASSERT_TRUE(apm.get()); ASSERT_EQ(AudioProcessing::kNoError, apm->gain_control()->Enable(include_default_apm_processing)); if (use_mobile_aec) { ASSERT_EQ(AudioProcessing::kNoError, apm->echo_cancellation()->Enable(false)); ASSERT_EQ(AudioProcessing::kNoError, apm->echo_control_mobile()->Enable( include_default_apm_processing)); } else { ASSERT_EQ(AudioProcessing::kNoError, apm->echo_cancellation()->Enable(include_default_apm_processing)); ASSERT_EQ(AudioProcessing::kNoError, apm->echo_control_mobile()->Enable(false)); } ASSERT_EQ(AudioProcessing::kNoError, apm->high_pass_filter()->Enable(include_default_apm_processing)); ASSERT_EQ(AudioProcessing::kNoError, apm->noise_suppression()->Enable(include_default_apm_processing)); ASSERT_EQ(AudioProcessing::kNoError, apm->voice_detection()->Enable(include_default_apm_processing)); ASSERT_EQ(AudioProcessing::kNoError, apm->level_estimator()->Enable(include_default_apm_processing)); StreamConfig render_input_config(render_input_sample_rate_hz, num_channels, false); StreamConfig render_output_config(render_output_sample_rate_hz, num_channels, false); StreamConfig capture_input_config(capture_input_sample_rate_hz, num_channels, false); StreamConfig capture_output_config(capture_output_sample_rate_hz, num_channels, false); for (size_t frame_no = 0; frame_no < kNumFramesToProcess; ++frame_no) { buffers.UpdateInputBuffers(); total_timer.StartTimer(); render_timer.StartTimer(); ASSERT_EQ(AudioProcessing::kNoError, apm->ProcessReverseStream( &buffers.render_input[0], render_input_config, render_output_config, &buffers.render_output[0])); render_timer.StopTimer(); capture_timer.StartTimer(); ASSERT_EQ(AudioProcessing::kNoError, apm->set_stream_delay_ms(0)); ASSERT_EQ( AudioProcessing::kNoError, apm->ProcessStream(&buffers.capture_input[0], capture_input_config, capture_output_config, &buffers.capture_output[0])); capture_timer.StopTimer(); total_timer.StopTimer(); } webrtc::test::PrintResultMeanAndError( "level_controller_call_durations", "_" + std::to_string(render_input_sample_rate_hz) + "_" + std::to_string(render_output_sample_rate_hz) + "_" + std::to_string(capture_input_sample_rate_hz) + "_" + std::to_string(capture_output_sample_rate_hz) + "Hz_" + std::to_string(num_channels) + "_channels" + "_render", test_description, FormPerformanceMeasureString(render_timer), "us", false); webrtc::test::PrintResultMeanAndError( "level_controller_call_durations", "_" + std::to_string(render_input_sample_rate_hz) + "_" + std::to_string(render_output_sample_rate_hz) + "_" + std::to_string(capture_input_sample_rate_hz) + "_" + std::to_string(capture_output_sample_rate_hz) + "Hz_" + std::to_string(num_channels) + "_channels" + "_capture", test_description, FormPerformanceMeasureString(capture_timer), "us", false); webrtc::test::PrintResultMeanAndError( "level_controller_call_durations", "_" + std::to_string(render_input_sample_rate_hz) + "_" + std::to_string(render_output_sample_rate_hz) + "_" + std::to_string(capture_input_sample_rate_hz) + "_" + std::to_string(capture_output_sample_rate_hz) + "Hz_" + std::to_string(num_channels) + "_channels" + "_total", test_description, FormPerformanceMeasureString(total_timer), "us", false); } } // namespace TEST(LevelControllerPerformanceTest, StandaloneProcessing) { int sample_rates_to_test[] = { AudioProcessing::kSampleRate8kHz, AudioProcessing::kSampleRate16kHz, AudioProcessing::kSampleRate32kHz, AudioProcessing::kSampleRate48kHz}; for (auto sample_rate : sample_rates_to_test) { for (size_t num_channels = 1; num_channels <= 2; ++num_channels) { RunStandaloneSubmodule(sample_rate, num_channels); } } } TEST(LevelControllerPerformanceTest, ProcessingViaApm) { int sample_rates_to_test[] = {AudioProcessing::kSampleRate8kHz, AudioProcessing::kSampleRate16kHz, AudioProcessing::kSampleRate32kHz, AudioProcessing::kSampleRate48kHz, 44100}; for (auto capture_input_sample_rate_hz : sample_rates_to_test) { for (auto capture_output_sample_rate_hz : sample_rates_to_test) { for (size_t num_channels = 1; num_channels <= 2; ++num_channels) { RunTogetherWithApm("SimpleLevelControlViaApm", 48000, 48000, capture_input_sample_rate_hz, capture_output_sample_rate_hz, num_channels, false, false); } } } } TEST(LevelControllerPerformanceTest, InteractionWithDefaultApm) { int sample_rates_to_test[] = {AudioProcessing::kSampleRate8kHz, AudioProcessing::kSampleRate16kHz, AudioProcessing::kSampleRate32kHz, AudioProcessing::kSampleRate48kHz, 44100}; for (auto capture_input_sample_rate_hz : sample_rates_to_test) { for (auto capture_output_sample_rate_hz : sample_rates_to_test) { for (size_t num_channels = 1; num_channels <= 2; ++num_channels) { RunTogetherWithApm("LevelControlAndDefaultDesktopApm", 48000, 48000, capture_input_sample_rate_hz, capture_output_sample_rate_hz, num_channels, false, true); RunTogetherWithApm("LevelControlAndDefaultMobileApm", 48000, 48000, capture_input_sample_rate_hz, capture_output_sample_rate_hz, num_channels, true, true); } } } } } // namespace webrtc <commit_msg>Disabling the performance unittests on Android for the level controller.<commit_after>/* * Copyright (c) 2016 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 <numeric> #include <vector> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/array_view.h" #include "webrtc/base/random.h" #include "webrtc/modules/audio_processing/audio_buffer.h" #include "webrtc/modules/audio_processing/include/audio_processing.h" #include "webrtc/modules/audio_processing/level_controller/level_controller.h" #include "webrtc/modules/audio_processing/test/audio_buffer_tools.h" #include "webrtc/modules/audio_processing/test/bitexactness_tools.h" #include "webrtc/system_wrappers/include/clock.h" #include "webrtc/test/testsupport/perf_test.h" namespace webrtc { namespace { const size_t kNumFramesToProcess = 100; struct SimulatorBuffers { SimulatorBuffers(int render_input_sample_rate_hz, int capture_input_sample_rate_hz, int render_output_sample_rate_hz, int capture_output_sample_rate_hz, size_t num_render_input_channels, size_t num_capture_input_channels, size_t num_render_output_channels, size_t num_capture_output_channels) { Random rand_gen(42); CreateConfigAndBuffer(render_input_sample_rate_hz, num_render_input_channels, &rand_gen, &render_input_buffer, &render_input_config, &render_input, &render_input_samples); CreateConfigAndBuffer(render_output_sample_rate_hz, num_render_output_channels, &rand_gen, &render_output_buffer, &render_output_config, &render_output, &render_output_samples); CreateConfigAndBuffer(capture_input_sample_rate_hz, num_capture_input_channels, &rand_gen, &capture_input_buffer, &capture_input_config, &capture_input, &capture_input_samples); CreateConfigAndBuffer(capture_output_sample_rate_hz, num_capture_output_channels, &rand_gen, &capture_output_buffer, &capture_output_config, &capture_output, &capture_output_samples); UpdateInputBuffers(); } void CreateConfigAndBuffer(int sample_rate_hz, size_t num_channels, Random* rand_gen, std::unique_ptr<AudioBuffer>* buffer, StreamConfig* config, std::vector<float*>* buffer_data, std::vector<float>* buffer_data_samples) { int samples_per_channel = rtc::CheckedDivExact(sample_rate_hz, 100); *config = StreamConfig(sample_rate_hz, num_channels, false); buffer->reset(new AudioBuffer(config->num_frames(), config->num_channels(), config->num_frames(), config->num_channels(), config->num_frames())); buffer_data_samples->resize(samples_per_channel * num_channels); for (auto& v : *buffer_data_samples) { v = rand_gen->Rand<float>(); } buffer_data->resize(num_channels); for (size_t ch = 0; ch < num_channels; ++ch) { (*buffer_data)[ch] = &(*buffer_data_samples)[ch * samples_per_channel]; } } void UpdateInputBuffers() { test::CopyVectorToAudioBuffer(capture_input_config, capture_input_samples, capture_input_buffer.get()); test::CopyVectorToAudioBuffer(render_input_config, render_input_samples, render_input_buffer.get()); } std::unique_ptr<AudioBuffer> render_input_buffer; std::unique_ptr<AudioBuffer> capture_input_buffer; std::unique_ptr<AudioBuffer> render_output_buffer; std::unique_ptr<AudioBuffer> capture_output_buffer; StreamConfig render_input_config; StreamConfig capture_input_config; StreamConfig render_output_config; StreamConfig capture_output_config; std::vector<float*> render_input; std::vector<float> render_input_samples; std::vector<float*> capture_input; std::vector<float> capture_input_samples; std::vector<float*> render_output; std::vector<float> render_output_samples; std::vector<float*> capture_output; std::vector<float> capture_output_samples; }; class SubmodulePerformanceTimer { public: SubmodulePerformanceTimer() : clock_(webrtc::Clock::GetRealTimeClock()) { timestamps_us_.reserve(kNumFramesToProcess); } void StartTimer() { start_timestamp_us_ = rtc::Optional<int64_t>(clock_->TimeInMicroseconds()); } void StopTimer() { RTC_DCHECK(start_timestamp_us_); timestamps_us_.push_back(clock_->TimeInMicroseconds() - *start_timestamp_us_); } double GetDurationAverage() const { RTC_DCHECK(!timestamps_us_.empty()); return static_cast<double>(std::accumulate(timestamps_us_.begin(), timestamps_us_.end(), 0)) / timestamps_us_.size(); } double GetDurationStandardDeviation() const { RTC_DCHECK(!timestamps_us_.empty()); double average_duration = GetDurationAverage(); int64_t variance = std::accumulate(timestamps_us_.begin(), timestamps_us_.end(), 0, [average_duration](const int64_t& a, const int64_t& b) { return a + (b - average_duration); }); return sqrt(variance / timestamps_us_.size()); } private: webrtc::Clock* clock_; rtc::Optional<int64_t> start_timestamp_us_; std::vector<int64_t> timestamps_us_; }; std::string FormPerformanceMeasureString( const SubmodulePerformanceTimer& timer) { std::string s = std::to_string(timer.GetDurationAverage()); s += ", "; s += std::to_string(timer.GetDurationStandardDeviation()); return s; } void RunStandaloneSubmodule(int sample_rate_hz, size_t num_channels) { SimulatorBuffers buffers(sample_rate_hz, sample_rate_hz, sample_rate_hz, sample_rate_hz, num_channels, num_channels, num_channels, num_channels); SubmodulePerformanceTimer timer; LevelController level_controller; level_controller.Initialize(sample_rate_hz); for (size_t frame_no = 0; frame_no < kNumFramesToProcess; ++frame_no) { buffers.UpdateInputBuffers(); timer.StartTimer(); level_controller.Process(buffers.capture_input_buffer.get()); timer.StopTimer(); } webrtc::test::PrintResultMeanAndError( "level_controller_call_durations", "_" + std::to_string(sample_rate_hz) + "Hz_" + std::to_string(num_channels) + "_channels", "StandaloneLevelControl", FormPerformanceMeasureString(timer), "us", false); } void RunTogetherWithApm(std::string test_description, int render_input_sample_rate_hz, int render_output_sample_rate_hz, int capture_input_sample_rate_hz, int capture_output_sample_rate_hz, size_t num_channels, bool use_mobile_aec, bool include_default_apm_processing) { SimulatorBuffers buffers( render_input_sample_rate_hz, capture_input_sample_rate_hz, render_output_sample_rate_hz, capture_output_sample_rate_hz, num_channels, num_channels, num_channels, num_channels); SubmodulePerformanceTimer render_timer; SubmodulePerformanceTimer capture_timer; SubmodulePerformanceTimer total_timer; Config config; if (include_default_apm_processing) { config.Set<DelayAgnostic>(new DelayAgnostic(true)); config.Set<ExtendedFilter>(new ExtendedFilter(true)); } config.Set<LevelControl>(new LevelControl(true)); std::unique_ptr<AudioProcessing> apm; apm.reset(AudioProcessing::Create(config)); ASSERT_TRUE(apm.get()); ASSERT_EQ(AudioProcessing::kNoError, apm->gain_control()->Enable(include_default_apm_processing)); if (use_mobile_aec) { ASSERT_EQ(AudioProcessing::kNoError, apm->echo_cancellation()->Enable(false)); ASSERT_EQ(AudioProcessing::kNoError, apm->echo_control_mobile()->Enable( include_default_apm_processing)); } else { ASSERT_EQ(AudioProcessing::kNoError, apm->echo_cancellation()->Enable(include_default_apm_processing)); ASSERT_EQ(AudioProcessing::kNoError, apm->echo_control_mobile()->Enable(false)); } ASSERT_EQ(AudioProcessing::kNoError, apm->high_pass_filter()->Enable(include_default_apm_processing)); ASSERT_EQ(AudioProcessing::kNoError, apm->noise_suppression()->Enable(include_default_apm_processing)); ASSERT_EQ(AudioProcessing::kNoError, apm->voice_detection()->Enable(include_default_apm_processing)); ASSERT_EQ(AudioProcessing::kNoError, apm->level_estimator()->Enable(include_default_apm_processing)); StreamConfig render_input_config(render_input_sample_rate_hz, num_channels, false); StreamConfig render_output_config(render_output_sample_rate_hz, num_channels, false); StreamConfig capture_input_config(capture_input_sample_rate_hz, num_channels, false); StreamConfig capture_output_config(capture_output_sample_rate_hz, num_channels, false); for (size_t frame_no = 0; frame_no < kNumFramesToProcess; ++frame_no) { buffers.UpdateInputBuffers(); total_timer.StartTimer(); render_timer.StartTimer(); ASSERT_EQ(AudioProcessing::kNoError, apm->ProcessReverseStream( &buffers.render_input[0], render_input_config, render_output_config, &buffers.render_output[0])); render_timer.StopTimer(); capture_timer.StartTimer(); ASSERT_EQ(AudioProcessing::kNoError, apm->set_stream_delay_ms(0)); ASSERT_EQ( AudioProcessing::kNoError, apm->ProcessStream(&buffers.capture_input[0], capture_input_config, capture_output_config, &buffers.capture_output[0])); capture_timer.StopTimer(); total_timer.StopTimer(); } webrtc::test::PrintResultMeanAndError( "level_controller_call_durations", "_" + std::to_string(render_input_sample_rate_hz) + "_" + std::to_string(render_output_sample_rate_hz) + "_" + std::to_string(capture_input_sample_rate_hz) + "_" + std::to_string(capture_output_sample_rate_hz) + "Hz_" + std::to_string(num_channels) + "_channels" + "_render", test_description, FormPerformanceMeasureString(render_timer), "us", false); webrtc::test::PrintResultMeanAndError( "level_controller_call_durations", "_" + std::to_string(render_input_sample_rate_hz) + "_" + std::to_string(render_output_sample_rate_hz) + "_" + std::to_string(capture_input_sample_rate_hz) + "_" + std::to_string(capture_output_sample_rate_hz) + "Hz_" + std::to_string(num_channels) + "_channels" + "_capture", test_description, FormPerformanceMeasureString(capture_timer), "us", false); webrtc::test::PrintResultMeanAndError( "level_controller_call_durations", "_" + std::to_string(render_input_sample_rate_hz) + "_" + std::to_string(render_output_sample_rate_hz) + "_" + std::to_string(capture_input_sample_rate_hz) + "_" + std::to_string(capture_output_sample_rate_hz) + "Hz_" + std::to_string(num_channels) + "_channels" + "_total", test_description, FormPerformanceMeasureString(total_timer), "us", false); } } // namespace TEST(LevelControllerPerformanceTest, StandaloneProcessing) { int sample_rates_to_test[] = { AudioProcessing::kSampleRate8kHz, AudioProcessing::kSampleRate16kHz, AudioProcessing::kSampleRate32kHz, AudioProcessing::kSampleRate48kHz}; for (auto sample_rate : sample_rates_to_test) { for (size_t num_channels = 1; num_channels <= 2; ++num_channels) { RunStandaloneSubmodule(sample_rate, num_channels); } } } #if !defined(WEBRTC_ANDROID) TEST(LevelControllerPerformanceTest, ProcessingViaApm) { #else TEST(LevelControllerPerformanceTest, DISABLED_ProcessingViaApm) { #endif int sample_rates_to_test[] = {AudioProcessing::kSampleRate8kHz, AudioProcessing::kSampleRate16kHz, AudioProcessing::kSampleRate32kHz, AudioProcessing::kSampleRate48kHz, 44100}; for (auto capture_input_sample_rate_hz : sample_rates_to_test) { for (auto capture_output_sample_rate_hz : sample_rates_to_test) { for (size_t num_channels = 1; num_channels <= 2; ++num_channels) { RunTogetherWithApm("SimpleLevelControlViaApm", 48000, 48000, capture_input_sample_rate_hz, capture_output_sample_rate_hz, num_channels, false, false); } } } } #if !defined(WEBRTC_ANDROID) TEST(LevelControllerPerformanceTest, InteractionWithDefaultApm) { #else TEST(LevelControllerPerformanceTest, DISABLED_InteractionWithDefaultApm) { #endif int sample_rates_to_test[] = {AudioProcessing::kSampleRate8kHz, AudioProcessing::kSampleRate16kHz, AudioProcessing::kSampleRate32kHz, AudioProcessing::kSampleRate48kHz, 44100}; for (auto capture_input_sample_rate_hz : sample_rates_to_test) { for (auto capture_output_sample_rate_hz : sample_rates_to_test) { for (size_t num_channels = 1; num_channels <= 2; ++num_channels) { RunTogetherWithApm("LevelControlAndDefaultDesktopApm", 48000, 48000, capture_input_sample_rate_hz, capture_output_sample_rate_hz, num_channels, false, true); RunTogetherWithApm("LevelControlAndDefaultMobileApm", 48000, 48000, capture_input_sample_rate_hz, capture_output_sample_rate_hz, num_channels, true, true); } } } } } // namespace webrtc <|endoftext|>
<commit_before>// NCMLContainer.cc // -*- mode: c++; c-basic-offset:4 -*- // This file is part of ncml_module, A C++ module that can be loaded in to // the OPeNDAP Back-End Server (BES) and is able to handle ncml requests. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: Patrick West <pwest@ucar.edu> // // 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 Street, Fifth Floor, Boston, MA 02110-1301 USA // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. // (c) COPYRIGHT URI/MIT 1994-1999 // Please read the full copyright statement in the file COPYRIGHT_URI. // // Authors: // pcw Patrick West <pwest@ucar.edu> #include <fstream> #include <cerrno> #include <cstdlib> #include <cstring> using std::ofstream ; using std::endl ; using std::ios_base ; #include "NCMLContainer.h" #include "NCMLContainerStorage.h" #include <BESSyntaxUserError.h> #include <BESInternalError.h> #include <BESDebug.h> /** @brief Creates an instances of NCMLContainer with the symbolic name * and the xml document string. * * The xml document is contained within the DHI, so must be passed in * here. * * The type of the container is ncml. This way we know to use the ncml * handler for this container. * * @param sym_name symbolic name representing this NCML container * @param ncml_doc string of the xml document * @see NCMLGatewayUtils */ NCMLContainer::NCMLContainer( const string &sym_name, const string &xml_doc ) : BESContainer( sym_name, "", "ncml" ), _xml_doc( xml_doc ), _accessed( false ) { } NCMLContainer::NCMLContainer( const NCMLContainer &copy_from ) : BESContainer( copy_from ), _xml_doc( copy_from._xml_doc ), _accessed( copy_from._accessed ) { // we can not make a copy of this container once the NCML document has // been written to the temporary file if( _accessed ) { string err = (string)"The Container has already been accessed, " + "can not create a copy of this container." ; throw BESInternalError( err, __FILE__, __LINE__ ) ; } } void NCMLContainer::_duplicate( NCMLContainer &copy_to ) { if( copy_to._accessed ) { string err = (string)"The Container has already been accessed, " + "can not duplicate this resource." ; throw BESInternalError( err, __FILE__, __LINE__ ) ; } copy_to._xml_doc = _xml_doc ; copy_to._accessed = false ; BESContainer::_duplicate( copy_to ) ; } BESContainer * NCMLContainer::ptr_duplicate( ) { NCMLContainer *container = new NCMLContainer ; _duplicate( *container ) ; return container ; } NCMLContainer::~NCMLContainer() { if( _accessed ) { release() ; } } /** @brief access the NCML target response by making the NCML request * * @return full path to the NCML request response data file * @throws BESError if there is a problem making the NCML request */ string NCMLContainer::access() { BESDEBUG( "ncml", "accessing " << _xml_doc << endl ); if( !_accessed ) { // save the xml document to a temporary file, open it, unlink // it. In release, close the file. This will remove the file if // it is no longer open. string tempfile_template = "ncml_module_XXXXXX" ; #if defined(WIN32) || defined(TEST_WIN32_TEMPS) char *tempfile_c = _mktemp( (char *)tempfile_template.c_str() ) ; #else char *tempfile_c = mktemp( (char *)tempfile_template.c_str() ) ; #endif string tempfile ; if( tempfile_c ) { tempfile = tempfile_c ; } else { string err = (string)"Unable to create temporary ncml document " + _tmp_file_name ; throw BESInternalError( err, __FILE__, __LINE__ ) ; } _tmp_file_name = NCMLContainerStorage::NCML_TempDir + "/" + tempfile + ".ncml" ; ofstream ostrm ; int my_errno = 0 ; ostrm.open( _tmp_file_name.c_str(), ios_base::out ) ; my_errno = errno ; if( !ostrm ) { string err = (string)"Unable to write out the ncml document " + _tmp_file_name ; if( my_errno ) { char *str = strerror( my_errno ) ; if( str ) err += (string)" " + str ; } throw BESInternalError( err, __FILE__, __LINE__ ) ; } // write out <?xml version="1.0" encoding="UTF-8"?> ostrm << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl ; // then write out the r_name as the ncml document (no validation) ostrm << _xml_doc << endl ; ostrm.close() ; _accessed = true ; } return _tmp_file_name ; } /** @brief release the NCML cached resources * * Release the resource * * @return true if the resource is released successfully and false otherwise */ bool NCMLContainer::release() { if( _accessed && !_tmp_file_name.empty() ) { unlink( _tmp_file_name.c_str() ) ; _tmp_file_name = "" ; } _accessed = false ; return true ; } /** @brief dumps information about this object * * Displays the pointer value of this instance along with information about * this container. * * @param strm C++ i/o stream to dump the information to */ void NCMLContainer::dump( ostream &strm ) const { strm << BESIndent::LMarg << "NCMLContainer::dump - (" << (void *)this << ")" << endl ; BESIndent::Indent() ; if( _accessed ) { strm << BESIndent::LMarg << "temporary file: " << _tmp_file_name << endl ; } else { strm << BESIndent::LMarg << "temporary file: not open" << endl ; } BESContainer::dump( strm ) ; BESIndent::UnIndent() ; } <commit_msg>Added unistd.h for osx 10.9<commit_after>// NCMLContainer.cc // -*- mode: c++; c-basic-offset:4 -*- // This file is part of ncml_module, A C++ module that can be loaded in to // the OPeNDAP Back-End Server (BES) and is able to handle ncml requests. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: Patrick West <pwest@ucar.edu> // // 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 Street, Fifth Floor, Boston, MA 02110-1301 USA // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. // (c) COPYRIGHT URI/MIT 1994-1999 // Please read the full copyright statement in the file COPYRIGHT_URI. // // Authors: // pcw Patrick West <pwest@ucar.edu> #include "config.h" #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <fstream> #include <cerrno> #include <cstdlib> #include <cstring> using std::ofstream ; using std::endl ; using std::ios_base ; #include "NCMLContainer.h" #include "NCMLContainerStorage.h" #include <BESSyntaxUserError.h> #include <BESInternalError.h> #include <BESDebug.h> /** @brief Creates an instances of NCMLContainer with the symbolic name * and the xml document string. * * The xml document is contained within the DHI, so must be passed in * here. * * The type of the container is ncml. This way we know to use the ncml * handler for this container. * * @param sym_name symbolic name representing this NCML container * @param ncml_doc string of the xml document * @see NCMLGatewayUtils */ NCMLContainer::NCMLContainer( const string &sym_name, const string &xml_doc ) : BESContainer( sym_name, "", "ncml" ), _xml_doc( xml_doc ), _accessed( false ) { } NCMLContainer::NCMLContainer( const NCMLContainer &copy_from ) : BESContainer( copy_from ), _xml_doc( copy_from._xml_doc ), _accessed( copy_from._accessed ) { // we can not make a copy of this container once the NCML document has // been written to the temporary file if( _accessed ) { string err = (string)"The Container has already been accessed, " + "can not create a copy of this container." ; throw BESInternalError( err, __FILE__, __LINE__ ) ; } } void NCMLContainer::_duplicate( NCMLContainer &copy_to ) { if( copy_to._accessed ) { string err = (string)"The Container has already been accessed, " + "can not duplicate this resource." ; throw BESInternalError( err, __FILE__, __LINE__ ) ; } copy_to._xml_doc = _xml_doc ; copy_to._accessed = false ; BESContainer::_duplicate( copy_to ) ; } BESContainer * NCMLContainer::ptr_duplicate( ) { NCMLContainer *container = new NCMLContainer ; _duplicate( *container ) ; return container ; } NCMLContainer::~NCMLContainer() { if( _accessed ) { release() ; } } /** @brief access the NCML target response by making the NCML request * * @return full path to the NCML request response data file * @throws BESError if there is a problem making the NCML request */ string NCMLContainer::access() { BESDEBUG( "ncml", "accessing " << _xml_doc << endl ); if( !_accessed ) { // save the xml document to a temporary file, open it, unlink // it. In release, close the file. This will remove the file if // it is no longer open. string tempfile_template = "ncml_module_XXXXXX" ; #if defined(WIN32) || defined(TEST_WIN32_TEMPS) char *tempfile_c = _mktemp( (char *)tempfile_template.c_str() ) ; #else char *tempfile_c = mktemp( (char *)tempfile_template.c_str() ) ; #endif string tempfile ; if( tempfile_c ) { tempfile = tempfile_c ; } else { string err = (string)"Unable to create temporary ncml document " + _tmp_file_name ; throw BESInternalError( err, __FILE__, __LINE__ ) ; } _tmp_file_name = NCMLContainerStorage::NCML_TempDir + "/" + tempfile + ".ncml" ; ofstream ostrm ; int my_errno = 0 ; ostrm.open( _tmp_file_name.c_str(), ios_base::out ) ; my_errno = errno ; if( !ostrm ) { string err = (string)"Unable to write out the ncml document " + _tmp_file_name ; if( my_errno ) { char *str = strerror( my_errno ) ; if( str ) err += (string)" " + str ; } throw BESInternalError( err, __FILE__, __LINE__ ) ; } // write out <?xml version="1.0" encoding="UTF-8"?> ostrm << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl ; // then write out the r_name as the ncml document (no validation) ostrm << _xml_doc << endl ; ostrm.close() ; _accessed = true ; } return _tmp_file_name ; } /** @brief release the NCML cached resources * * Release the resource * * @return true if the resource is released successfully and false otherwise */ bool NCMLContainer::release() { if( _accessed && !_tmp_file_name.empty() ) { unlink( _tmp_file_name.c_str() ) ; _tmp_file_name = "" ; } _accessed = false ; return true ; } /** @brief dumps information about this object * * Displays the pointer value of this instance along with information about * this container. * * @param strm C++ i/o stream to dump the information to */ void NCMLContainer::dump( ostream &strm ) const { strm << BESIndent::LMarg << "NCMLContainer::dump - (" << (void *)this << ")" << endl ; BESIndent::Indent() ; if( _accessed ) { strm << BESIndent::LMarg << "temporary file: " << _tmp_file_name << endl ; } else { strm << BESIndent::LMarg << "temporary file: not open" << endl ; } BESContainer::dump( strm ) ; BESIndent::UnIndent() ; } <|endoftext|>
<commit_before>#include "window.h" #include "logging.h" Window::Window() : window_box_(Gtk::ORIENTATION_VERTICAL), main_config_(), keybindings_(main_config_.keybindings_cfg()), terminal_(main_config_.terminal_cfg()), notebook_(this,keybindings(), main_config_.source_cfg(), main_config_.dir_cfg()), menu_(keybindings()), api_(menu_, notebook_) { INFO("Create Window"); set_title("juCi++"); set_default_size(600, 400); add(window_box_); keybindings_.action_group_menu()->add(Gtk::Action::create("FileQuit", "Quit juCi++"), Gtk::AccelKey(keybindings_.config_ .key_map()["quit"]), [this]() { OnWindowHide(); }); keybindings_.action_group_menu()->add(Gtk::Action::create("FileOpenFile", "Open file"), Gtk::AccelKey(keybindings_.config_ .key_map()["open_file"]), [this]() { OnOpenFile(); }); keybindings_.action_group_menu()->add(Gtk::Action::create("FileOpenFolder", "Open folder"), Gtk::AccelKey(keybindings_.config_ .key_map()["open_folder"]), [this]() { OnFileOpenFolder(); }); keybindings_. action_group_menu()-> add(Gtk::Action::create("FileSaveAs", "Save as"), Gtk::AccelKey(keybindings_.config_ .key_map()["save_as"]), [this]() { SaveFileAs(); }); keybindings_. action_group_menu()-> add(Gtk::Action::create("FileSave", "Save"), Gtk::AccelKey(keybindings_.config_ .key_map()["save"]), [this]() { SaveFile(); }); keybindings_. action_group_menu()-> add(Gtk::Action::create("ProjectCompileAndRun", "Compile And Run"), Gtk::AccelKey(keybindings_.config_ .key_map()["compile_and_run"]), [this]() { SaveFile(); if (running.try_lock()) { std::thread execute([=]() { std::string path = notebook_.CurrentPagePath(); int pos = path.find_last_of("/\\"); if(pos != std::string::npos) { path.erase(path.begin()+pos,path.end()); terminal_.SetFolderCommand(path); } terminal_.Compile(); std::string executable = notebook_.directories(). GetCmakeVarValue(path,"add_executable"); terminal_.Run(executable); }); execute.detach(); running.unlock(); } }); keybindings_. action_group_menu()-> add(Gtk::Action::create("ProjectCompile", "Compile"), Gtk::AccelKey(keybindings_.config_ .key_map()["compile"]), [this]() { SaveFile(); if (running.try_lock()) { std::thread execute([=]() { std::string path = notebook_.CurrentPagePath(); int pos = path.find_last_of("/\\"); if(pos != std::string::npos){ path.erase(path.begin()+pos,path.end()); terminal_.SetFolderCommand(path); } terminal_.Compile(); }); execute.detach(); running.unlock(); } }); this->signal_button_release_event(). connect(sigc::mem_fun(*this,&Window::OnMouseRelease),false); terminal_.Terminal().signal_button_release_event(). connect(sigc::mem_fun(*this,&Window::OnMouseRelease),false); add_accel_group(keybindings_.ui_manager_menu()->get_accel_group()); add_accel_group(keybindings_.ui_manager_hidden()->get_accel_group()); keybindings_.BuildMenu(); window_box_.pack_start(menu_.view(), Gtk::PACK_SHRINK); window_box_.pack_start(notebook_.entry_view(), Gtk::PACK_SHRINK); paned_.set_position(300); paned_.pack1(notebook_.view(), true, false); paned_.pack2(terminal_.view(), true, true); window_box_.pack_end(paned_); show_all_children(); INFO("Window created"); } // Window constructor void Window::OnWindowHide() { hide(); } void Window::OnFileOpenFolder() { Gtk::FileChooserDialog dialog("Please choose a folder", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER); dialog.set_transient_for(*this); //Add response buttons the the dialog: dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL); dialog.add_button("Select", Gtk::RESPONSE_OK); int result = dialog.run(); //Handle the response: switch(result) { case(Gtk::RESPONSE_OK): { std::cout << "Folder selected: " << dialog.get_filename() << std::endl; notebook_.directories().open_folder(dialog.get_filename()); std::cout << dialog.get_filename()<< std::endl; break; } case(Gtk::RESPONSE_CANCEL): { std::cout << "Cancel clicked." << std::endl; break; } default: { std::cout << "Unexpected button clicked." << std::endl; break; } } } void Window::OnOpenFile() { Gtk::FileChooserDialog dialog("Please choose a file", Gtk::FILE_CHOOSER_ACTION_OPEN); dialog.set_transient_for(*this); dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ALWAYS); //Add response buttons the the dialog: dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL); dialog.add_button("_Open", Gtk::RESPONSE_OK); //Add filters, so that only certain file types can be selected: Glib::RefPtr<Gtk::FileFilter> filter_text = Gtk::FileFilter::create(); filter_text->set_name("Text files"); filter_text->add_mime_type("text/plain"); dialog.add_filter(filter_text); Glib::RefPtr<Gtk::FileFilter> filter_cpp = Gtk::FileFilter::create(); filter_cpp->set_name("C/C++ files"); filter_cpp->add_mime_type("text/x-c"); filter_cpp->add_mime_type("text/x-c++"); filter_cpp->add_mime_type("text/x-c-header"); dialog.add_filter(filter_cpp); Glib::RefPtr<Gtk::FileFilter> filter_any = Gtk::FileFilter::create(); filter_any->set_name("Any files"); filter_any->add_pattern("*"); dialog.add_filter(filter_any); int result = dialog.run(); switch (result) { case(Gtk::RESPONSE_OK): { std::cout << "Open clicked." << std::endl; std::string path = dialog.get_filename(); std::cout << "File selected: " << path << std::endl; notebook_.OnOpenFile(path); break; } case(Gtk::RESPONSE_CANCEL): { std::cout << "Cancel clicked." << std::endl; break; } default: { std::cout << "Unexpected button clicked." << std::endl; break; } } } bool Window::OnMouseRelease(GdkEventButton *button){ return notebook_.OnMouseRelease(button); } bool Window::SaveFile() { if(notebook_.OnSaveFile()) { terminal_.PrintMessage("File saved to: " + notebook_.CurrentPagePath()+"\n"); return true; } terminal_.PrintMessage("File not saved"); return false; } bool Window::SaveFileAs() { if(notebook_.OnSaveFile(notebook_.OnSaveFileAs())){ terminal_.PrintMessage("File saved to: " + notebook_.CurrentPagePath()+"\n"); return true; } terminal_.PrintMessage("File not saved"); return false; } <commit_msg>move lock<commit_after>#include "window.h" #include "logging.h" Window::Window() : window_box_(Gtk::ORIENTATION_VERTICAL), main_config_(), keybindings_(main_config_.keybindings_cfg()), terminal_(main_config_.terminal_cfg()), notebook_(this,keybindings(), main_config_.source_cfg(), main_config_.dir_cfg()), menu_(keybindings()), api_(menu_, notebook_) { INFO("Create Window"); set_title("juCi++"); set_default_size(600, 400); add(window_box_); keybindings_.action_group_menu()->add(Gtk::Action::create("FileQuit", "Quit juCi++"), Gtk::AccelKey(keybindings_.config_ .key_map()["quit"]), [this]() { OnWindowHide(); }); keybindings_.action_group_menu()->add(Gtk::Action::create("FileOpenFile", "Open file"), Gtk::AccelKey(keybindings_.config_ .key_map()["open_file"]), [this]() { OnOpenFile(); }); keybindings_.action_group_menu()->add(Gtk::Action::create("FileOpenFolder", "Open folder"), Gtk::AccelKey(keybindings_.config_ .key_map()["open_folder"]), [this]() { OnFileOpenFolder(); }); keybindings_. action_group_menu()-> add(Gtk::Action::create("FileSaveAs", "Save as"), Gtk::AccelKey(keybindings_.config_ .key_map()["save_as"]), [this]() { SaveFileAs(); }); keybindings_. action_group_menu()-> add(Gtk::Action::create("FileSave", "Save"), Gtk::AccelKey(keybindings_.config_ .key_map()["save"]), [this]() { SaveFile(); }); keybindings_. action_group_menu()-> add(Gtk::Action::create("ProjectCompileAndRun", "Compile And Run"), Gtk::AccelKey(keybindings_.config_ .key_map()["compile_and_run"]), [this]() { SaveFile(); if (running.try_lock()) { std::thread execute([=]() { std::string path = notebook_.CurrentPagePath(); int pos = path.find_last_of("/\\"); if(pos != std::string::npos) { path.erase(path.begin()+pos,path.end()); terminal_.SetFolderCommand(path); } terminal_.Compile(); std::string executable = notebook_.directories(). GetCmakeVarValue(path,"add_executable"); terminal_.Run(executable); running.unlock(); }); execute.detach(); } }); keybindings_. action_group_menu()-> add(Gtk::Action::create("ProjectCompile", "Compile"), Gtk::AccelKey(keybindings_.config_ .key_map()["compile"]), [this]() { SaveFile(); if (running.try_lock()) { std::thread execute([=]() { std::string path = notebook_.CurrentPagePath(); int pos = path.find_last_of("/\\"); if(pos != std::string::npos){ path.erase(path.begin()+pos,path.end()); terminal_.SetFolderCommand(path); } terminal_.Compile(); running.unlock(); }); execute.detach(); } }); this->signal_button_release_event(). connect(sigc::mem_fun(*this,&Window::OnMouseRelease),false); terminal_.Terminal().signal_button_release_event(). connect(sigc::mem_fun(*this,&Window::OnMouseRelease),false); add_accel_group(keybindings_.ui_manager_menu()->get_accel_group()); add_accel_group(keybindings_.ui_manager_hidden()->get_accel_group()); keybindings_.BuildMenu(); window_box_.pack_start(menu_.view(), Gtk::PACK_SHRINK); window_box_.pack_start(notebook_.entry_view(), Gtk::PACK_SHRINK); paned_.set_position(300); paned_.pack1(notebook_.view(), true, false); paned_.pack2(terminal_.view(), true, true); window_box_.pack_end(paned_); show_all_children(); INFO("Window created"); } // Window constructor void Window::OnWindowHide() { hide(); } void Window::OnFileOpenFolder() { Gtk::FileChooserDialog dialog("Please choose a folder", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER); dialog.set_transient_for(*this); //Add response buttons the the dialog: dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL); dialog.add_button("Select", Gtk::RESPONSE_OK); int result = dialog.run(); //Handle the response: switch(result) { case(Gtk::RESPONSE_OK): { std::cout << "Folder selected: " << dialog.get_filename() << std::endl; notebook_.directories().open_folder(dialog.get_filename()); std::cout << dialog.get_filename()<< std::endl; break; } case(Gtk::RESPONSE_CANCEL): { std::cout << "Cancel clicked." << std::endl; break; } default: { std::cout << "Unexpected button clicked." << std::endl; break; } } } void Window::OnOpenFile() { Gtk::FileChooserDialog dialog("Please choose a file", Gtk::FILE_CHOOSER_ACTION_OPEN); dialog.set_transient_for(*this); dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ALWAYS); //Add response buttons the the dialog: dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL); dialog.add_button("_Open", Gtk::RESPONSE_OK); //Add filters, so that only certain file types can be selected: Glib::RefPtr<Gtk::FileFilter> filter_text = Gtk::FileFilter::create(); filter_text->set_name("Text files"); filter_text->add_mime_type("text/plain"); dialog.add_filter(filter_text); Glib::RefPtr<Gtk::FileFilter> filter_cpp = Gtk::FileFilter::create(); filter_cpp->set_name("C/C++ files"); filter_cpp->add_mime_type("text/x-c"); filter_cpp->add_mime_type("text/x-c++"); filter_cpp->add_mime_type("text/x-c-header"); dialog.add_filter(filter_cpp); Glib::RefPtr<Gtk::FileFilter> filter_any = Gtk::FileFilter::create(); filter_any->set_name("Any files"); filter_any->add_pattern("*"); dialog.add_filter(filter_any); int result = dialog.run(); switch (result) { case(Gtk::RESPONSE_OK): { std::cout << "Open clicked." << std::endl; std::string path = dialog.get_filename(); std::cout << "File selected: " << path << std::endl; notebook_.OnOpenFile(path); break; } case(Gtk::RESPONSE_CANCEL): { std::cout << "Cancel clicked." << std::endl; break; } default: { std::cout << "Unexpected button clicked." << std::endl; break; } } } bool Window::OnMouseRelease(GdkEventButton *button){ return notebook_.OnMouseRelease(button); } bool Window::SaveFile() { if(notebook_.OnSaveFile()) { terminal_.PrintMessage("File saved to: " + notebook_.CurrentPagePath()+"\n"); return true; } terminal_.PrintMessage("File not saved"); return false; } bool Window::SaveFileAs() { if(notebook_.OnSaveFile(notebook_.OnSaveFileAs())){ terminal_.PrintMessage("File saved to: " + notebook_.CurrentPagePath()+"\n"); return true; } terminal_.PrintMessage("File not saved"); return false; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/host_resolver_proc.h" #include "build/build_config.h" #if defined(OS_WIN) #include <ws2tcpip.h> #include <wspiapi.h> // Needed for Win2k compat. #elif defined(OS_POSIX) #include <netdb.h> #include <sys/socket.h> #endif #if defined(OS_LINUX) #include <resolv.h> #endif #include "base/logging.h" #include "base/time.h" #include "net/base/address_list.h" #include "net/base/net_errors.h" #if defined(OS_LINUX) #include "base/singleton.h" #include "base/thread_local_storage.h" #endif namespace net { HostResolverProc* HostResolverProc::default_proc_ = NULL; HostResolverProc::HostResolverProc(HostResolverProc* previous) { set_previous_proc(previous); // Implicitly fall-back to the global default procedure. if (!previous) set_previous_proc(default_proc_); } // static HostResolverProc* HostResolverProc::SetDefault(HostResolverProc* proc) { HostResolverProc* old = default_proc_; default_proc_ = proc; return old; } // static HostResolverProc* HostResolverProc::GetDefault() { return default_proc_; } int HostResolverProc::ResolveUsingPrevious(const std::string& host, AddressFamily address_family, AddressList* addrlist) { if (previous_proc_) return previous_proc_->Resolve(host, address_family, addrlist); // Final fallback is the system resolver. return SystemHostResolverProc(host, address_family, addrlist); } #if defined(OS_LINUX) // On Linux changes to /etc/resolv.conf can go unnoticed thus resulting in // DNS queries failing either because nameservers are unknown on startup // or because nameserver info has changed as a result of e.g. connecting to // a new network. Some distributions patch glibc to stat /etc/resolv.conf // to try to automatically detect such changes but these patches are not // universal and even patched systems such as Jaunty appear to need calls // to res_ninit to reload the nameserver information in different threads. // // We adopt the Mozilla solution here which is to call res_ninit when // lookups fail and to rate limit the reloading to once per second per // thread. // Keep a timer per calling thread to rate limit the calling of res_ninit. class DnsReloadTimer { public: // Check if the timer for the calling thread has expired. When no // timer exists for the calling thread, create one. bool Expired() { const base::TimeDelta kRetryTime = base::TimeDelta::FromSeconds(1); base::TimeTicks now = base::TimeTicks::Now(); base::TimeTicks* timer_ptr = static_cast<base::TimeTicks*>(tls_index_.Get()); if (!timer_ptr) { timer_ptr = new base::TimeTicks(); *timer_ptr = base::TimeTicks::Now(); tls_index_.Set(timer_ptr); // Return true to reload dns info on the first call for each thread. return true; } else if (now - *timer_ptr > kRetryTime) { *timer_ptr = now; return true; } else { return false; } } // Free the allocated timer. static void SlotReturnFunction(void* data) { base::TimeTicks* tls_data = static_cast<base::TimeTicks*>(data); delete tls_data; } private: friend struct DefaultSingletonTraits<DnsReloadTimer>; DnsReloadTimer() { tls_index_.Initialize(SlotReturnFunction); } ~DnsReloadTimer() { tls_index_.Free(); } // We use thread local storage to identify which base::TimeTicks to // interact with. static ThreadLocalStorage::Slot tls_index_ ; DISALLOW_COPY_AND_ASSIGN(DnsReloadTimer); }; // A TLS slot to the TimeTicks for the current thread. // static ThreadLocalStorage::Slot DnsReloadTimer::tls_index_(base::LINKER_INITIALIZED); #endif // defined(OS_LINUX) int SystemHostResolverProc(const std::string& host, AddressFamily address_family, AddressList* addrlist) { // The result of |getaddrinfo| for empty hosts is inconsistent across systems. // On Windows it gives the default interface's address, whereas on Linux it // gives an error. We will make it fail on all platforms for consistency. if (host.empty()) return ERR_NAME_NOT_RESOLVED; struct addrinfo* ai = NULL; struct addrinfo hints = {0}; switch (address_family) { case ADDRESS_FAMILY_IPV4: hints.ai_family = AF_INET; break; case ADDRESS_FAMILY_IPV6: hints.ai_family = AF_INET6; break; case ADDRESS_FAMILY_UNSPECIFIED: hints.ai_family = AF_UNSPEC; break; default: NOTREACHED(); hints.ai_family = AF_UNSPEC; } #if defined(OS_WIN) // DO NOT USE AI_ADDRCONFIG ON WINDOWS. // // The following comment in <winsock2.h> is the best documentation I found // on AI_ADDRCONFIG for Windows: // Flags used in "hints" argument to getaddrinfo() // - AI_ADDRCONFIG is supported starting with Vista // - default is AI_ADDRCONFIG ON whether the flag is set or not // because the performance penalty in not having ADDRCONFIG in // the multi-protocol stack environment is severe; // this defaulting may be disabled by specifying the AI_ALL flag, // in that case AI_ADDRCONFIG must be EXPLICITLY specified to // enable ADDRCONFIG behavior // // Not only is AI_ADDRCONFIG unnecessary, but it can be harmful. If the // computer is not connected to a network, AI_ADDRCONFIG causes getaddrinfo // to fail with WSANO_DATA (11004) for "localhost", probably because of the // following note on AI_ADDRCONFIG in the MSDN getaddrinfo page: // The IPv4 or IPv6 loopback address is not considered a valid global // address. // See http://crbug.com/5234. hints.ai_flags = 0; #else hints.ai_flags = AI_ADDRCONFIG; #endif // Restrict result set to only this socket type to avoid duplicates. hints.ai_socktype = SOCK_STREAM; int err = getaddrinfo(host.c_str(), NULL, &hints, &ai); #if defined(OS_LINUX) net::DnsReloadTimer* dns_timer = Singleton<net::DnsReloadTimer>::get(); // If we fail, re-initialise the resolver just in case there have been any // changes to /etc/resolv.conf and retry. See http://crbug.com/11380 for info. if (err && dns_timer->Expired()) { res_nclose(&_res); if (!res_ninit(&_res)) err = getaddrinfo(host.c_str(), NULL, &hints, &ai); } #endif if (err) return ERR_NAME_NOT_RESOLVED; addrlist->Adopt(ai); return OK; } } // namespace net <commit_msg>Fix a memory leak in DnsReloadTimer<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/host_resolver_proc.h" #include "build/build_config.h" #if defined(OS_WIN) #include <ws2tcpip.h> #include <wspiapi.h> // Needed for Win2k compat. #elif defined(OS_POSIX) #include <netdb.h> #include <sys/socket.h> #endif #if defined(OS_LINUX) #include <resolv.h> #endif #include "base/logging.h" #include "base/time.h" #include "net/base/address_list.h" #include "net/base/net_errors.h" #if defined(OS_LINUX) #include "base/singleton.h" #include "base/thread_local_storage.h" #endif namespace net { HostResolverProc* HostResolverProc::default_proc_ = NULL; HostResolverProc::HostResolverProc(HostResolverProc* previous) { set_previous_proc(previous); // Implicitly fall-back to the global default procedure. if (!previous) set_previous_proc(default_proc_); } // static HostResolverProc* HostResolverProc::SetDefault(HostResolverProc* proc) { HostResolverProc* old = default_proc_; default_proc_ = proc; return old; } // static HostResolverProc* HostResolverProc::GetDefault() { return default_proc_; } int HostResolverProc::ResolveUsingPrevious(const std::string& host, AddressFamily address_family, AddressList* addrlist) { if (previous_proc_) return previous_proc_->Resolve(host, address_family, addrlist); // Final fallback is the system resolver. return SystemHostResolverProc(host, address_family, addrlist); } #if defined(OS_LINUX) // On Linux changes to /etc/resolv.conf can go unnoticed thus resulting in // DNS queries failing either because nameservers are unknown on startup // or because nameserver info has changed as a result of e.g. connecting to // a new network. Some distributions patch glibc to stat /etc/resolv.conf // to try to automatically detect such changes but these patches are not // universal and even patched systems such as Jaunty appear to need calls // to res_ninit to reload the nameserver information in different threads. // // We adopt the Mozilla solution here which is to call res_ninit when // lookups fail and to rate limit the reloading to once per second per // thread. // Keep a timer per calling thread to rate limit the calling of res_ninit. class DnsReloadTimer { public: // Check if the timer for the calling thread has expired. When no // timer exists for the calling thread, create one. bool Expired() { const base::TimeDelta kRetryTime = base::TimeDelta::FromSeconds(1); base::TimeTicks now = base::TimeTicks::Now(); base::TimeTicks* timer_ptr = static_cast<base::TimeTicks*>(tls_index_.Get()); if (!timer_ptr) { timer_ptr = new base::TimeTicks(); *timer_ptr = base::TimeTicks::Now(); tls_index_.Set(timer_ptr); // Return true to reload dns info on the first call for each thread. return true; } else if (now - *timer_ptr > kRetryTime) { *timer_ptr = now; return true; } else { return false; } } // Free the allocated timer. static void SlotReturnFunction(void* data) { base::TimeTicks* tls_data = static_cast<base::TimeTicks*>(data); delete tls_data; } private: friend struct DefaultSingletonTraits<DnsReloadTimer>; DnsReloadTimer() { tls_index_.Initialize(SlotReturnFunction); } ~DnsReloadTimer() { SlotReturnFunction(tls_index_.Get()); tls_index_.Free(); } // We use thread local storage to identify which base::TimeTicks to // interact with. static ThreadLocalStorage::Slot tls_index_ ; DISALLOW_COPY_AND_ASSIGN(DnsReloadTimer); }; // A TLS slot to the TimeTicks for the current thread. // static ThreadLocalStorage::Slot DnsReloadTimer::tls_index_(base::LINKER_INITIALIZED); #endif // defined(OS_LINUX) int SystemHostResolverProc(const std::string& host, AddressFamily address_family, AddressList* addrlist) { // The result of |getaddrinfo| for empty hosts is inconsistent across systems. // On Windows it gives the default interface's address, whereas on Linux it // gives an error. We will make it fail on all platforms for consistency. if (host.empty()) return ERR_NAME_NOT_RESOLVED; struct addrinfo* ai = NULL; struct addrinfo hints = {0}; switch (address_family) { case ADDRESS_FAMILY_IPV4: hints.ai_family = AF_INET; break; case ADDRESS_FAMILY_IPV6: hints.ai_family = AF_INET6; break; case ADDRESS_FAMILY_UNSPECIFIED: hints.ai_family = AF_UNSPEC; break; default: NOTREACHED(); hints.ai_family = AF_UNSPEC; } #if defined(OS_WIN) // DO NOT USE AI_ADDRCONFIG ON WINDOWS. // // The following comment in <winsock2.h> is the best documentation I found // on AI_ADDRCONFIG for Windows: // Flags used in "hints" argument to getaddrinfo() // - AI_ADDRCONFIG is supported starting with Vista // - default is AI_ADDRCONFIG ON whether the flag is set or not // because the performance penalty in not having ADDRCONFIG in // the multi-protocol stack environment is severe; // this defaulting may be disabled by specifying the AI_ALL flag, // in that case AI_ADDRCONFIG must be EXPLICITLY specified to // enable ADDRCONFIG behavior // // Not only is AI_ADDRCONFIG unnecessary, but it can be harmful. If the // computer is not connected to a network, AI_ADDRCONFIG causes getaddrinfo // to fail with WSANO_DATA (11004) for "localhost", probably because of the // following note on AI_ADDRCONFIG in the MSDN getaddrinfo page: // The IPv4 or IPv6 loopback address is not considered a valid global // address. // See http://crbug.com/5234. hints.ai_flags = 0; #else hints.ai_flags = AI_ADDRCONFIG; #endif // Restrict result set to only this socket type to avoid duplicates. hints.ai_socktype = SOCK_STREAM; int err = getaddrinfo(host.c_str(), NULL, &hints, &ai); #if defined(OS_LINUX) net::DnsReloadTimer* dns_timer = Singleton<net::DnsReloadTimer>::get(); // If we fail, re-initialise the resolver just in case there have been any // changes to /etc/resolv.conf and retry. See http://crbug.com/11380 for info. if (err && dns_timer->Expired()) { res_nclose(&_res); if (!res_ninit(&_res)) err = getaddrinfo(host.c_str(), NULL, &hints, &ai); } #endif if (err) return ERR_NAME_NOT_RESOLVED; addrlist->Adopt(ai); return OK; } } // namespace net <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/strings/string_split.h" #include "base/utf_string_conversions.h" #include "net/base/mime_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { TEST(MimeUtilTest, ExtensionTest) { const struct { const base::FilePath::CharType* extension; const char* mime_type; bool valid; } tests[] = { { FILE_PATH_LITERAL("png"), "image/png", true }, { FILE_PATH_LITERAL("css"), "text/css", true }, { FILE_PATH_LITERAL("pjp"), "image/jpeg", true }, { FILE_PATH_LITERAL("pjpeg"), "image/jpeg", true }, { FILE_PATH_LITERAL("not an extension / for sure"), "", false }, }; std::string mime_type; bool rv; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { rv = GetMimeTypeFromExtension(tests[i].extension, &mime_type); EXPECT_EQ(tests[i].valid, rv); if (rv) EXPECT_EQ(tests[i].mime_type, mime_type); } } TEST(MimeUtilTest, FileTest) { const struct { const base::FilePath::CharType* file_path; const char* mime_type; bool valid; } tests[] = { { FILE_PATH_LITERAL("c:\\foo\\bar.css"), "text/css", true }, { FILE_PATH_LITERAL("c:\\blah"), "", false }, { FILE_PATH_LITERAL("/usr/local/bin/mplayer"), "", false }, { FILE_PATH_LITERAL("/home/foo/bar.css"), "text/css", true }, { FILE_PATH_LITERAL("/blah."), "", false }, { FILE_PATH_LITERAL("c:\\blah."), "", false }, }; std::string mime_type; bool rv; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { rv = GetMimeTypeFromFile(base::FilePath(tests[i].file_path), &mime_type); EXPECT_EQ(tests[i].valid, rv); if (rv) EXPECT_EQ(tests[i].mime_type, mime_type); } } TEST(MimeUtilTest, LookupTypes) { EXPECT_FALSE(IsUnsupportedTextMimeType("text/banana")); EXPECT_TRUE(IsUnsupportedTextMimeType("text/vcard")); EXPECT_TRUE(IsSupportedImageMimeType("image/jpeg")); EXPECT_FALSE(IsSupportedImageMimeType("image/lolcat")); EXPECT_TRUE(IsSupportedNonImageMimeType("text/html")); EXPECT_TRUE(IsSupportedNonImageMimeType("text/banana")); EXPECT_FALSE(IsSupportedNonImageMimeType("text/vcard")); EXPECT_FALSE(IsSupportedNonImageMimeType("application/virus")); EXPECT_TRUE(IsSupportedNonImageMimeType("application/x-x509-user-cert")); #if defined(OS_ANDROID) EXPECT_TRUE(IsSupportedNonImageMimeType("application/x-x509-ca-cert")); EXPECT_TRUE(IsSupportedNonImageMimeType("application/x-pkcs12")); #endif EXPECT_TRUE(IsSupportedMimeType("image/jpeg")); EXPECT_FALSE(IsSupportedMimeType("image/lolcat")); EXPECT_TRUE(IsSupportedMimeType("text/html")); EXPECT_TRUE(IsSupportedMimeType("text/banana")); EXPECT_FALSE(IsSupportedMimeType("text/vcard")); EXPECT_FALSE(IsSupportedMimeType("application/virus")); } TEST(MimeUtilTest, MatchesMimeType) { EXPECT_TRUE(MatchesMimeType("*", "video/x-mpeg")); EXPECT_TRUE(MatchesMimeType("video/*", "video/x-mpeg")); EXPECT_TRUE(MatchesMimeType("video/*", "video/*")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg", "video/x-mpeg")); EXPECT_TRUE(MatchesMimeType("application/*+xml", "application/html+xml")); EXPECT_TRUE(MatchesMimeType("application/*+xml", "application/+xml")); EXPECT_TRUE(MatchesMimeType("aaa*aaa", "aaaaaa")); EXPECT_TRUE(MatchesMimeType("*", std::string())); EXPECT_FALSE(MatchesMimeType("video/", "video/x-mpeg")); EXPECT_FALSE(MatchesMimeType(std::string(), "video/x-mpeg")); EXPECT_FALSE(MatchesMimeType(std::string(), std::string())); EXPECT_FALSE(MatchesMimeType("video/x-mpeg", std::string())); EXPECT_FALSE(MatchesMimeType("application/*+xml", "application/xml")); EXPECT_FALSE(MatchesMimeType("application/*+xml", "application/html+xmlz")); EXPECT_FALSE(MatchesMimeType("application/*+xml", "applcation/html+xml")); EXPECT_FALSE(MatchesMimeType("aaa*aaa", "aaaaa")); EXPECT_TRUE(MatchesMimeType("*", "video/x-mpeg;param=val")); EXPECT_TRUE(MatchesMimeType("video/*", "video/x-mpeg;param=val")); EXPECT_FALSE(MatchesMimeType("video/*;param=val", "video/mpeg")); EXPECT_FALSE(MatchesMimeType("video/*;param=val", "video/mpeg;param=other")); EXPECT_TRUE(MatchesMimeType("video/*;param=val", "video/mpeg;param=val")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg", "video/x-mpeg;param=val")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param=val", "video/x-mpeg;param=val")); EXPECT_FALSE(MatchesMimeType("video/x-mpeg;param2=val2", "video/x-mpeg;param=val")); EXPECT_FALSE(MatchesMimeType("video/x-mpeg;param2=val2", "video/x-mpeg;param2=val")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param=val", "video/x-mpeg;param=val;param2=val2")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param=val;param2=val2", "video/x-mpeg;param=val;param2=val2")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param2=val2;param=val", "video/x-mpeg;param=val;param2=val2")); EXPECT_FALSE(MatchesMimeType("video/x-mpeg;param3=val3;param=val", "video/x-mpeg;param=val;param2=val2")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param=val ;param2=val2 ", "video/x-mpeg;param=val;param2=val2")); EXPECT_TRUE(MatchesMimeType("*/*;param=val", "video/x-mpeg;param=val")); EXPECT_FALSE(MatchesMimeType("*/*;param=val", "video/x-mpeg;param=val2")); EXPECT_TRUE(MatchesMimeType("*", "*")); EXPECT_TRUE(MatchesMimeType("*", "*/*")); EXPECT_TRUE(MatchesMimeType("*/*", "*/*")); EXPECT_TRUE(MatchesMimeType("*/*", "*")); EXPECT_TRUE(MatchesMimeType("video/*", "video/*")); EXPECT_FALSE(MatchesMimeType("video/*", "*/*")); EXPECT_FALSE(MatchesMimeType("video/*;param=val", "video/*")); EXPECT_TRUE(MatchesMimeType("video/*;param=val", "video/*;param=val")); EXPECT_FALSE(MatchesMimeType("video/*;param=val", "video/*;param=val2")); EXPECT_TRUE(MatchesMimeType("ab*cd", "abxxxcd")); EXPECT_TRUE(MatchesMimeType("ab*cd", "abx/xcd")); EXPECT_TRUE(MatchesMimeType("ab/*cd", "ab/xxxcd")); } // Note: codecs should only be a list of 2 or fewer; hence the restriction of // results' length to 2. TEST(MimeUtilTest, ParseCodecString) { const struct { const char* original; size_t expected_size; const char* results[2]; } tests[] = { { "\"bogus\"", 1, { "bogus" } }, { "0", 1, { "0" } }, { "avc1.42E01E, mp4a.40.2", 2, { "avc1", "mp4a" } }, { "\"mp4v.20.240, mp4a.40.2\"", 2, { "mp4v", "mp4a" } }, { "mp4v.20.8, samr", 2, { "mp4v", "samr" } }, { "\"theora, vorbis\"", 2, { "theora", "vorbis" } }, { "", 0, { } }, { "\"\"", 0, { } }, { "\" \"", 0, { } }, { ",", 2, { "", "" } }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { std::vector<std::string> codecs_out; ParseCodecString(tests[i].original, &codecs_out, true); ASSERT_EQ(tests[i].expected_size, codecs_out.size()); for (size_t j = 0; j < tests[i].expected_size; ++j) EXPECT_EQ(tests[i].results[j], codecs_out[j]); } // Test without stripping the codec type. std::vector<std::string> codecs_out; ParseCodecString("avc1.42E01E, mp4a.40.2", &codecs_out, false); ASSERT_EQ(2u, codecs_out.size()); EXPECT_EQ("avc1.42E01E", codecs_out[0]); EXPECT_EQ("mp4a.40.2", codecs_out[1]); } TEST(MimeUtilTest, TestIsMimeType) { std::string nonAscii("application/nonutf8"); EXPECT_TRUE(IsMimeType(nonAscii)); #if defined(OS_WIN) nonAscii.append(WideToUTF8(std::wstring(L"\u2603"))); #else nonAscii.append("\u2603"); // unicode snowman #endif EXPECT_FALSE(IsMimeType(nonAscii)); EXPECT_TRUE(IsMimeType("application/mime")); EXPECT_TRUE(IsMimeType("audio/mime")); EXPECT_TRUE(IsMimeType("example/mime")); EXPECT_TRUE(IsMimeType("image/mime")); EXPECT_TRUE(IsMimeType("message/mime")); EXPECT_TRUE(IsMimeType("model/mime")); EXPECT_TRUE(IsMimeType("multipart/mime")); EXPECT_TRUE(IsMimeType("text/mime")); EXPECT_TRUE(IsMimeType("TEXT/mime")); EXPECT_TRUE(IsMimeType("Text/mime")); EXPECT_TRUE(IsMimeType("TeXt/mime")); EXPECT_TRUE(IsMimeType("video/mime")); EXPECT_TRUE(IsMimeType("video/mime;parameter")); EXPECT_TRUE(IsMimeType("*/*")); EXPECT_TRUE(IsMimeType("*")); EXPECT_TRUE(IsMimeType("x-video/mime")); EXPECT_TRUE(IsMimeType("X-Video/mime")); EXPECT_FALSE(IsMimeType("x-video/")); EXPECT_FALSE(IsMimeType("x-/mime")); EXPECT_FALSE(IsMimeType("mime/looking")); EXPECT_FALSE(IsMimeType("text/")); } TEST(MimeUtilTest, TestToIANAMediaType) { EXPECT_EQ("", GetIANAMediaType("texting/driving")); EXPECT_EQ("", GetIANAMediaType("ham/sandwich")); EXPECT_EQ("", GetIANAMediaType(std::string())); EXPECT_EQ("", GetIANAMediaType("/application/hamsandwich")); EXPECT_EQ("application", GetIANAMediaType("application/poodle-wrestler")); EXPECT_EQ("audio", GetIANAMediaType("audio/mpeg")); EXPECT_EQ("example", GetIANAMediaType("example/yomomma")); EXPECT_EQ("image", GetIANAMediaType("image/png")); EXPECT_EQ("message", GetIANAMediaType("message/sipfrag")); EXPECT_EQ("model", GetIANAMediaType("model/vrml")); EXPECT_EQ("multipart", GetIANAMediaType("multipart/mixed")); EXPECT_EQ("text", GetIANAMediaType("text/plain")); EXPECT_EQ("video", GetIANAMediaType("video/H261")); } TEST(MimeUtilTest, TestGetExtensionsForMimeType) { const struct { const char* mime_type; size_t min_expected_size; const char* contained_result; } tests[] = { { "text/plain", 2, "txt" }, { "*", 0, NULL }, { "message/*", 1, "eml" }, { "MeSsAge/*", 1, "eml" }, { "image/bmp", 1, "bmp" }, { "video/*", 6, "mp4" }, #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_IOS) { "video/*", 6, "mpg" }, #else { "video/*", 6, "mpeg" }, #endif { "audio/*", 6, "oga" }, { "aUDIo/*", 6, "wav" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { std::vector<base::FilePath::StringType> extensions; GetExtensionsForMimeType(tests[i].mime_type, &extensions); ASSERT_TRUE(tests[i].min_expected_size <= extensions.size()); if (!tests[i].contained_result) continue; bool found = false; for (size_t j = 0; !found && j < extensions.size(); ++j) { #if defined(OS_WIN) if (extensions[j] == UTF8ToWide(tests[i].contained_result)) found = true; #else if (extensions[j] == tests[i].contained_result) found = true; #endif } ASSERT_TRUE(found) << "Must find at least the contained result within " << tests[i].mime_type; } } TEST(MimeUtilTest, TestGetCertificateMimeTypeForMimeType) { EXPECT_EQ(CERTIFICATE_MIME_TYPE_X509_USER_CERT, GetCertificateMimeTypeForMimeType("application/x-x509-user-cert")); #if defined(OS_ANDROID) // Only Android supports CA Certs and PKCS12 archives. EXPECT_EQ(CERTIFICATE_MIME_TYPE_X509_CA_CERT, GetCertificateMimeTypeForMimeType("application/x-x509-ca-cert")); EXPECT_EQ(CERTIFICATE_MIME_TYPE_PKCS12_ARCHIVE, GetCertificateMimeTypeForMimeType("application/x-pkcs12")); #else EXPECT_EQ(CERTIFICATE_MIME_TYPE_UNKNOWN, GetCertificateMimeTypeForMimeType("application/x-x509-ca-cert")); EXPECT_EQ(CERTIFICATE_MIME_TYPE_UNKNOWN, GetCertificateMimeTypeForMimeType("application/x-pkcs12")); #endif EXPECT_EQ(CERTIFICATE_MIME_TYPE_UNKNOWN, GetCertificateMimeTypeForMimeType("text/plain")); } } // namespace net <commit_msg>Adding unit test for two new functions in mime_util.h/cc.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/strings/string_split.h" #include "base/utf_string_conversions.h" #include "net/base/mime_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { TEST(MimeUtilTest, ExtensionTest) { const struct { const base::FilePath::CharType* extension; const char* mime_type; bool valid; } tests[] = { { FILE_PATH_LITERAL("png"), "image/png", true }, { FILE_PATH_LITERAL("css"), "text/css", true }, { FILE_PATH_LITERAL("pjp"), "image/jpeg", true }, { FILE_PATH_LITERAL("pjpeg"), "image/jpeg", true }, { FILE_PATH_LITERAL("not an extension / for sure"), "", false }, }; std::string mime_type; bool rv; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { rv = GetMimeTypeFromExtension(tests[i].extension, &mime_type); EXPECT_EQ(tests[i].valid, rv); if (rv) EXPECT_EQ(tests[i].mime_type, mime_type); } } TEST(MimeUtilTest, FileTest) { const struct { const base::FilePath::CharType* file_path; const char* mime_type; bool valid; } tests[] = { { FILE_PATH_LITERAL("c:\\foo\\bar.css"), "text/css", true }, { FILE_PATH_LITERAL("c:\\blah"), "", false }, { FILE_PATH_LITERAL("/usr/local/bin/mplayer"), "", false }, { FILE_PATH_LITERAL("/home/foo/bar.css"), "text/css", true }, { FILE_PATH_LITERAL("/blah."), "", false }, { FILE_PATH_LITERAL("c:\\blah."), "", false }, }; std::string mime_type; bool rv; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { rv = GetMimeTypeFromFile(base::FilePath(tests[i].file_path), &mime_type); EXPECT_EQ(tests[i].valid, rv); if (rv) EXPECT_EQ(tests[i].mime_type, mime_type); } } TEST(MimeUtilTest, LookupTypes) { EXPECT_FALSE(IsUnsupportedTextMimeType("text/banana")); EXPECT_TRUE(IsUnsupportedTextMimeType("text/vcard")); EXPECT_TRUE(IsSupportedImageMimeType("image/jpeg")); EXPECT_FALSE(IsSupportedImageMimeType("image/lolcat")); EXPECT_TRUE(IsSupportedNonImageMimeType("text/html")); EXPECT_TRUE(IsSupportedNonImageMimeType("text/banana")); EXPECT_FALSE(IsSupportedNonImageMimeType("text/vcard")); EXPECT_FALSE(IsSupportedNonImageMimeType("application/virus")); EXPECT_TRUE(IsSupportedNonImageMimeType("application/x-x509-user-cert")); #if defined(OS_ANDROID) EXPECT_TRUE(IsSupportedNonImageMimeType("application/x-x509-ca-cert")); EXPECT_TRUE(IsSupportedNonImageMimeType("application/x-pkcs12")); #endif EXPECT_TRUE(IsSupportedMimeType("image/jpeg")); EXPECT_FALSE(IsSupportedMimeType("image/lolcat")); EXPECT_TRUE(IsSupportedMimeType("text/html")); EXPECT_TRUE(IsSupportedMimeType("text/banana")); EXPECT_FALSE(IsSupportedMimeType("text/vcard")); EXPECT_FALSE(IsSupportedMimeType("application/virus")); } TEST(MimeUtilTest, MatchesMimeType) { EXPECT_TRUE(MatchesMimeType("*", "video/x-mpeg")); EXPECT_TRUE(MatchesMimeType("video/*", "video/x-mpeg")); EXPECT_TRUE(MatchesMimeType("video/*", "video/*")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg", "video/x-mpeg")); EXPECT_TRUE(MatchesMimeType("application/*+xml", "application/html+xml")); EXPECT_TRUE(MatchesMimeType("application/*+xml", "application/+xml")); EXPECT_TRUE(MatchesMimeType("aaa*aaa", "aaaaaa")); EXPECT_TRUE(MatchesMimeType("*", std::string())); EXPECT_FALSE(MatchesMimeType("video/", "video/x-mpeg")); EXPECT_FALSE(MatchesMimeType(std::string(), "video/x-mpeg")); EXPECT_FALSE(MatchesMimeType(std::string(), std::string())); EXPECT_FALSE(MatchesMimeType("video/x-mpeg", std::string())); EXPECT_FALSE(MatchesMimeType("application/*+xml", "application/xml")); EXPECT_FALSE(MatchesMimeType("application/*+xml", "application/html+xmlz")); EXPECT_FALSE(MatchesMimeType("application/*+xml", "applcation/html+xml")); EXPECT_FALSE(MatchesMimeType("aaa*aaa", "aaaaa")); EXPECT_TRUE(MatchesMimeType("*", "video/x-mpeg;param=val")); EXPECT_TRUE(MatchesMimeType("video/*", "video/x-mpeg;param=val")); EXPECT_FALSE(MatchesMimeType("video/*;param=val", "video/mpeg")); EXPECT_FALSE(MatchesMimeType("video/*;param=val", "video/mpeg;param=other")); EXPECT_TRUE(MatchesMimeType("video/*;param=val", "video/mpeg;param=val")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg", "video/x-mpeg;param=val")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param=val", "video/x-mpeg;param=val")); EXPECT_FALSE(MatchesMimeType("video/x-mpeg;param2=val2", "video/x-mpeg;param=val")); EXPECT_FALSE(MatchesMimeType("video/x-mpeg;param2=val2", "video/x-mpeg;param2=val")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param=val", "video/x-mpeg;param=val;param2=val2")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param=val;param2=val2", "video/x-mpeg;param=val;param2=val2")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param2=val2;param=val", "video/x-mpeg;param=val;param2=val2")); EXPECT_FALSE(MatchesMimeType("video/x-mpeg;param3=val3;param=val", "video/x-mpeg;param=val;param2=val2")); EXPECT_TRUE(MatchesMimeType("video/x-mpeg;param=val ;param2=val2 ", "video/x-mpeg;param=val;param2=val2")); EXPECT_TRUE(MatchesMimeType("*/*;param=val", "video/x-mpeg;param=val")); EXPECT_FALSE(MatchesMimeType("*/*;param=val", "video/x-mpeg;param=val2")); EXPECT_TRUE(MatchesMimeType("*", "*")); EXPECT_TRUE(MatchesMimeType("*", "*/*")); EXPECT_TRUE(MatchesMimeType("*/*", "*/*")); EXPECT_TRUE(MatchesMimeType("*/*", "*")); EXPECT_TRUE(MatchesMimeType("video/*", "video/*")); EXPECT_FALSE(MatchesMimeType("video/*", "*/*")); EXPECT_FALSE(MatchesMimeType("video/*;param=val", "video/*")); EXPECT_TRUE(MatchesMimeType("video/*;param=val", "video/*;param=val")); EXPECT_FALSE(MatchesMimeType("video/*;param=val", "video/*;param=val2")); EXPECT_TRUE(MatchesMimeType("ab*cd", "abxxxcd")); EXPECT_TRUE(MatchesMimeType("ab*cd", "abx/xcd")); EXPECT_TRUE(MatchesMimeType("ab/*cd", "ab/xxxcd")); } // Note: codecs should only be a list of 2 or fewer; hence the restriction of // results' length to 2. TEST(MimeUtilTest, ParseCodecString) { const struct { const char* original; size_t expected_size; const char* results[2]; } tests[] = { { "\"bogus\"", 1, { "bogus" } }, { "0", 1, { "0" } }, { "avc1.42E01E, mp4a.40.2", 2, { "avc1", "mp4a" } }, { "\"mp4v.20.240, mp4a.40.2\"", 2, { "mp4v", "mp4a" } }, { "mp4v.20.8, samr", 2, { "mp4v", "samr" } }, { "\"theora, vorbis\"", 2, { "theora", "vorbis" } }, { "", 0, { } }, { "\"\"", 0, { } }, { "\" \"", 0, { } }, { ",", 2, { "", "" } }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { std::vector<std::string> codecs_out; ParseCodecString(tests[i].original, &codecs_out, true); ASSERT_EQ(tests[i].expected_size, codecs_out.size()); for (size_t j = 0; j < tests[i].expected_size; ++j) EXPECT_EQ(tests[i].results[j], codecs_out[j]); } // Test without stripping the codec type. std::vector<std::string> codecs_out; ParseCodecString("avc1.42E01E, mp4a.40.2", &codecs_out, false); ASSERT_EQ(2u, codecs_out.size()); EXPECT_EQ("avc1.42E01E", codecs_out[0]); EXPECT_EQ("mp4a.40.2", codecs_out[1]); } TEST(MimeUtilTest, TestIsMimeType) { std::string nonAscii("application/nonutf8"); EXPECT_TRUE(IsMimeType(nonAscii)); #if defined(OS_WIN) nonAscii.append(WideToUTF8(std::wstring(L"\u2603"))); #else nonAscii.append("\u2603"); // unicode snowman #endif EXPECT_FALSE(IsMimeType(nonAscii)); EXPECT_TRUE(IsMimeType("application/mime")); EXPECT_TRUE(IsMimeType("audio/mime")); EXPECT_TRUE(IsMimeType("example/mime")); EXPECT_TRUE(IsMimeType("image/mime")); EXPECT_TRUE(IsMimeType("message/mime")); EXPECT_TRUE(IsMimeType("model/mime")); EXPECT_TRUE(IsMimeType("multipart/mime")); EXPECT_TRUE(IsMimeType("text/mime")); EXPECT_TRUE(IsMimeType("TEXT/mime")); EXPECT_TRUE(IsMimeType("Text/mime")); EXPECT_TRUE(IsMimeType("TeXt/mime")); EXPECT_TRUE(IsMimeType("video/mime")); EXPECT_TRUE(IsMimeType("video/mime;parameter")); EXPECT_TRUE(IsMimeType("*/*")); EXPECT_TRUE(IsMimeType("*")); EXPECT_TRUE(IsMimeType("x-video/mime")); EXPECT_TRUE(IsMimeType("X-Video/mime")); EXPECT_FALSE(IsMimeType("x-video/")); EXPECT_FALSE(IsMimeType("x-/mime")); EXPECT_FALSE(IsMimeType("mime/looking")); EXPECT_FALSE(IsMimeType("text/")); } TEST(MimeUtilTest, TestToIANAMediaType) { EXPECT_EQ("", GetIANAMediaType("texting/driving")); EXPECT_EQ("", GetIANAMediaType("ham/sandwich")); EXPECT_EQ("", GetIANAMediaType(std::string())); EXPECT_EQ("", GetIANAMediaType("/application/hamsandwich")); EXPECT_EQ("application", GetIANAMediaType("application/poodle-wrestler")); EXPECT_EQ("audio", GetIANAMediaType("audio/mpeg")); EXPECT_EQ("example", GetIANAMediaType("example/yomomma")); EXPECT_EQ("image", GetIANAMediaType("image/png")); EXPECT_EQ("message", GetIANAMediaType("message/sipfrag")); EXPECT_EQ("model", GetIANAMediaType("model/vrml")); EXPECT_EQ("multipart", GetIANAMediaType("multipart/mixed")); EXPECT_EQ("text", GetIANAMediaType("text/plain")); EXPECT_EQ("video", GetIANAMediaType("video/H261")); } TEST(MimeUtilTest, TestGetExtensionsForMimeType) { const struct { const char* mime_type; size_t min_expected_size; const char* contained_result; } tests[] = { { "text/plain", 2, "txt" }, { "*", 0, NULL }, { "message/*", 1, "eml" }, { "MeSsAge/*", 1, "eml" }, { "image/bmp", 1, "bmp" }, { "video/*", 6, "mp4" }, #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_IOS) { "video/*", 6, "mpg" }, #else { "video/*", 6, "mpeg" }, #endif { "audio/*", 6, "oga" }, { "aUDIo/*", 6, "wav" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { std::vector<base::FilePath::StringType> extensions; GetExtensionsForMimeType(tests[i].mime_type, &extensions); ASSERT_TRUE(tests[i].min_expected_size <= extensions.size()); if (!tests[i].contained_result) continue; bool found = false; for (size_t j = 0; !found && j < extensions.size(); ++j) { #if defined(OS_WIN) if (extensions[j] == UTF8ToWide(tests[i].contained_result)) found = true; #else if (extensions[j] == tests[i].contained_result) found = true; #endif } ASSERT_TRUE(found) << "Must find at least the contained result within " << tests[i].mime_type; } } TEST(MimeUtilTest, TestGetCertificateMimeTypeForMimeType) { EXPECT_EQ(CERTIFICATE_MIME_TYPE_X509_USER_CERT, GetCertificateMimeTypeForMimeType("application/x-x509-user-cert")); #if defined(OS_ANDROID) // Only Android supports CA Certs and PKCS12 archives. EXPECT_EQ(CERTIFICATE_MIME_TYPE_X509_CA_CERT, GetCertificateMimeTypeForMimeType("application/x-x509-ca-cert")); EXPECT_EQ(CERTIFICATE_MIME_TYPE_PKCS12_ARCHIVE, GetCertificateMimeTypeForMimeType("application/x-pkcs12")); #else EXPECT_EQ(CERTIFICATE_MIME_TYPE_UNKNOWN, GetCertificateMimeTypeForMimeType("application/x-x509-ca-cert")); EXPECT_EQ(CERTIFICATE_MIME_TYPE_UNKNOWN, GetCertificateMimeTypeForMimeType("application/x-pkcs12")); #endif EXPECT_EQ(CERTIFICATE_MIME_TYPE_UNKNOWN, GetCertificateMimeTypeForMimeType("text/plain")); } TEST(MimeUtilTest, TestAddMultipartValueForUpload) { const char* ref_output = "--boundary\r\nContent-Disposition: form-data;" " name=\"value name\"\r\nContent-Type: content type" "\r\n\r\nvalue\r\n" "--boundary\r\nContent-Disposition: form-data;" " name=\"value name\"\r\n\r\nvalue\r\n" "--boundary--\r\n"; std::string post_data; AddMultipartValueForUpload("value name", "value", "boundary", "content type", &post_data); AddMultipartValueForUpload("value name", "value", "boundary", "", &post_data); AddMultipartFinalDelimiterForUpload("boundary", &post_data); EXPECT_STREQ(ref_output, post_data.c_str()); } } // namespace net <|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 "net/http/http_network_layer.h" #include "base/field_trial.h" #include "base/logging.h" #include "base/string_util.h" #include "net/http/http_network_session.h" #include "net/http/http_network_transaction.h" #include "net/socket/client_socket_factory.h" #include "net/spdy/spdy_framer.h" #include "net/spdy/spdy_network_transaction.h" #include "net/spdy/spdy_session.h" #include "net/spdy/spdy_session_pool.h" namespace net { //----------------------------------------------------------------------------- // static HttpTransactionFactory* HttpNetworkLayer::CreateFactory( HostResolver* host_resolver, ProxyService* proxy_service, SSLConfigService* ssl_config_service, HttpAuthHandlerFactory* http_auth_handler_factory, HttpNetworkDelegate* network_delegate, NetLog* net_log) { DCHECK(proxy_service); return new HttpNetworkLayer(ClientSocketFactory::GetDefaultFactory(), host_resolver, proxy_service, ssl_config_service, http_auth_handler_factory, network_delegate, net_log); } // static HttpTransactionFactory* HttpNetworkLayer::CreateFactory( HttpNetworkSession* session) { DCHECK(session); return new HttpNetworkLayer(session); } //----------------------------------------------------------------------------- bool HttpNetworkLayer::force_spdy_ = false; HttpNetworkLayer::HttpNetworkLayer( ClientSocketFactory* socket_factory, HostResolver* host_resolver, ProxyService* proxy_service, SSLConfigService* ssl_config_service, HttpAuthHandlerFactory* http_auth_handler_factory, HttpNetworkDelegate* network_delegate, NetLog* net_log) : socket_factory_(socket_factory), host_resolver_(host_resolver), proxy_service_(proxy_service), ssl_config_service_(ssl_config_service), session_(NULL), spdy_session_pool_(NULL), http_auth_handler_factory_(http_auth_handler_factory), network_delegate_(network_delegate), net_log_(net_log), suspended_(false) { DCHECK(proxy_service_); DCHECK(ssl_config_service_.get()); } HttpNetworkLayer::HttpNetworkLayer(HttpNetworkSession* session) : socket_factory_(ClientSocketFactory::GetDefaultFactory()), ssl_config_service_(NULL), session_(session), spdy_session_pool_(session->spdy_session_pool()), http_auth_handler_factory_(NULL), network_delegate_(NULL), net_log_(NULL), suspended_(false) { DCHECK(session_.get()); } HttpNetworkLayer::~HttpNetworkLayer() { } int HttpNetworkLayer::CreateTransaction(scoped_ptr<HttpTransaction>* trans) { if (suspended_) return ERR_NETWORK_IO_SUSPENDED; if (force_spdy_) trans->reset(new SpdyNetworkTransaction(GetSession())); else trans->reset(new HttpNetworkTransaction(GetSession())); return OK; } HttpCache* HttpNetworkLayer::GetCache() { return NULL; } void HttpNetworkLayer::Suspend(bool suspend) { suspended_ = suspend; if (suspend && session_) session_->tcp_socket_pool()->CloseIdleSockets(); } HttpNetworkSession* HttpNetworkLayer::GetSession() { if (!session_) { DCHECK(proxy_service_); SpdySessionPool* spdy_pool = new SpdySessionPool(); session_ = new HttpNetworkSession(host_resolver_, proxy_service_, socket_factory_, ssl_config_service_, spdy_pool, http_auth_handler_factory_, network_delegate_, net_log_); // These were just temps for lazy-initializing HttpNetworkSession. host_resolver_ = NULL; proxy_service_ = NULL; socket_factory_ = NULL; http_auth_handler_factory_ = NULL; net_log_ = NULL; network_delegate_ = NULL; } return session_; } // static void HttpNetworkLayer::EnableSpdy(const std::string& mode) { static const char kDisableSSL[] = "no-ssl"; static const char kDisableCompression[] = "no-compress"; // We want an A/B experiment between SPDY enabled and SPDY disabled, // but only for pages where SPDY *could have been* negotiated. To do // this, we use NPN, but prevent it from negotiating SPDY. If the // server negotiates HTTP, rather than SPDY, today that will only happen // on servers that installed NPN (and could have done SPDY). But this is // a bit of a hack, as this correlation between NPN and SPDY is not // really guaranteed. static const char kEnableNPN[] = "npn"; static const char kEnableNpnHttpOnly[] = "npn-http"; // Except for the first element, the order is irrelevant. First element // specifies the fallback in case nothing matches // (SSLClientSocket::kNextProtoNoOverlap). Otherwise, the SSL library // will choose the first overlapping protocol in the server's list, since // it presumedly has a better understanding of which protocol we should // use, therefore the rest of the ordering here is not important. static const char kNpnProtosFull[] = "\x08http/1.1\x07http1.1\x06spdy/1\x04spdy"; // No spdy specified. static const char kNpnProtosHttpOnly[] = "\x08http/1.1\x07http1.1"; std::vector<std::string> spdy_options; SplitString(mode, ',', &spdy_options); // Force spdy mode (use SpdyNetworkTransaction for all http requests). force_spdy_ = true; for (std::vector<std::string>::iterator it = spdy_options.begin(); it != spdy_options.end(); ++it) { const std::string& option = *it; if (option == kDisableSSL) { SpdySession::SetSSLMode(false); // Disable SSL } else if (option == kDisableCompression) { spdy::SpdyFramer::set_enable_compression_default(false); } else if (option == kEnableNPN) { HttpNetworkTransaction::SetUseAlternateProtocols(true); HttpNetworkTransaction::SetNextProtos(kNpnProtosFull); force_spdy_ = false; } else if (option == kEnableNpnHttpOnly) { HttpNetworkTransaction::SetUseAlternateProtocols(true); HttpNetworkTransaction::SetNextProtos(kNpnProtosHttpOnly); force_spdy_ = false; } else if (option.empty() && it == spdy_options.begin()) { continue; } else { LOG(DFATAL) << "Unrecognized spdy option: " << option; } } } } // namespace net <commit_msg>Add back a flag to disable Alternate-Protocol processing. Specifically, provide a no-alt-protocols option to the --use-spdy flag.<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 "net/http/http_network_layer.h" #include "base/field_trial.h" #include "base/logging.h" #include "base/string_util.h" #include "net/http/http_network_session.h" #include "net/http/http_network_transaction.h" #include "net/socket/client_socket_factory.h" #include "net/spdy/spdy_framer.h" #include "net/spdy/spdy_network_transaction.h" #include "net/spdy/spdy_session.h" #include "net/spdy/spdy_session_pool.h" namespace net { //----------------------------------------------------------------------------- // static HttpTransactionFactory* HttpNetworkLayer::CreateFactory( HostResolver* host_resolver, ProxyService* proxy_service, SSLConfigService* ssl_config_service, HttpAuthHandlerFactory* http_auth_handler_factory, HttpNetworkDelegate* network_delegate, NetLog* net_log) { DCHECK(proxy_service); return new HttpNetworkLayer(ClientSocketFactory::GetDefaultFactory(), host_resolver, proxy_service, ssl_config_service, http_auth_handler_factory, network_delegate, net_log); } // static HttpTransactionFactory* HttpNetworkLayer::CreateFactory( HttpNetworkSession* session) { DCHECK(session); return new HttpNetworkLayer(session); } //----------------------------------------------------------------------------- bool HttpNetworkLayer::force_spdy_ = false; HttpNetworkLayer::HttpNetworkLayer( ClientSocketFactory* socket_factory, HostResolver* host_resolver, ProxyService* proxy_service, SSLConfigService* ssl_config_service, HttpAuthHandlerFactory* http_auth_handler_factory, HttpNetworkDelegate* network_delegate, NetLog* net_log) : socket_factory_(socket_factory), host_resolver_(host_resolver), proxy_service_(proxy_service), ssl_config_service_(ssl_config_service), session_(NULL), spdy_session_pool_(NULL), http_auth_handler_factory_(http_auth_handler_factory), network_delegate_(network_delegate), net_log_(net_log), suspended_(false) { DCHECK(proxy_service_); DCHECK(ssl_config_service_.get()); } HttpNetworkLayer::HttpNetworkLayer(HttpNetworkSession* session) : socket_factory_(ClientSocketFactory::GetDefaultFactory()), ssl_config_service_(NULL), session_(session), spdy_session_pool_(session->spdy_session_pool()), http_auth_handler_factory_(NULL), network_delegate_(NULL), net_log_(NULL), suspended_(false) { DCHECK(session_.get()); } HttpNetworkLayer::~HttpNetworkLayer() { } int HttpNetworkLayer::CreateTransaction(scoped_ptr<HttpTransaction>* trans) { if (suspended_) return ERR_NETWORK_IO_SUSPENDED; if (force_spdy_) trans->reset(new SpdyNetworkTransaction(GetSession())); else trans->reset(new HttpNetworkTransaction(GetSession())); return OK; } HttpCache* HttpNetworkLayer::GetCache() { return NULL; } void HttpNetworkLayer::Suspend(bool suspend) { suspended_ = suspend; if (suspend && session_) session_->tcp_socket_pool()->CloseIdleSockets(); } HttpNetworkSession* HttpNetworkLayer::GetSession() { if (!session_) { DCHECK(proxy_service_); SpdySessionPool* spdy_pool = new SpdySessionPool(); session_ = new HttpNetworkSession(host_resolver_, proxy_service_, socket_factory_, ssl_config_service_, spdy_pool, http_auth_handler_factory_, network_delegate_, net_log_); // These were just temps for lazy-initializing HttpNetworkSession. host_resolver_ = NULL; proxy_service_ = NULL; socket_factory_ = NULL; http_auth_handler_factory_ = NULL; net_log_ = NULL; network_delegate_ = NULL; } return session_; } // static void HttpNetworkLayer::EnableSpdy(const std::string& mode) { static const char kDisableSSL[] = "no-ssl"; static const char kDisableCompression[] = "no-compress"; static const char kDisableAltProtocols[] = "no-alt-protocols"; // We want an A/B experiment between SPDY enabled and SPDY disabled, // but only for pages where SPDY *could have been* negotiated. To do // this, we use NPN, but prevent it from negotiating SPDY. If the // server negotiates HTTP, rather than SPDY, today that will only happen // on servers that installed NPN (and could have done SPDY). But this is // a bit of a hack, as this correlation between NPN and SPDY is not // really guaranteed. static const char kEnableNPN[] = "npn"; static const char kEnableNpnHttpOnly[] = "npn-http"; // Except for the first element, the order is irrelevant. First element // specifies the fallback in case nothing matches // (SSLClientSocket::kNextProtoNoOverlap). Otherwise, the SSL library // will choose the first overlapping protocol in the server's list, since // it presumedly has a better understanding of which protocol we should // use, therefore the rest of the ordering here is not important. static const char kNpnProtosFull[] = "\x08http/1.1\x07http1.1\x06spdy/1\x04spdy"; // No spdy specified. static const char kNpnProtosHttpOnly[] = "\x08http/1.1\x07http1.1"; std::vector<std::string> spdy_options; SplitString(mode, ',', &spdy_options); // Force spdy mode (use SpdyNetworkTransaction for all http requests). force_spdy_ = true; bool use_alt_protocols = true; for (std::vector<std::string>::iterator it = spdy_options.begin(); it != spdy_options.end(); ++it) { const std::string& option = *it; if (option == kDisableSSL) { SpdySession::SetSSLMode(false); // Disable SSL } else if (option == kDisableCompression) { spdy::SpdyFramer::set_enable_compression_default(false); } else if (option == kEnableNPN) { HttpNetworkTransaction::SetUseAlternateProtocols(use_alt_protocols); HttpNetworkTransaction::SetNextProtos(kNpnProtosFull); force_spdy_ = false; } else if (option == kEnableNpnHttpOnly) { HttpNetworkTransaction::SetUseAlternateProtocols(use_alt_protocols); HttpNetworkTransaction::SetNextProtos(kNpnProtosHttpOnly); force_spdy_ = false; } else if (option == kDisableAltProtocols) { use_alt_protocols = false; HttpNetworkTransaction::SetUseAlternateProtocols(false); } else if (option.empty() && it == spdy_options.begin()) { continue; } else { LOG(DFATAL) << "Unrecognized spdy option: " << option; } } } } // namespace net <|endoftext|>
<commit_before>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef TOKDEF # define TOKDEF(k, s) #endif #ifndef TOKEN # define TOKEN(k, s) TOKDEF(TK_##k, s) #endif #ifndef PUNCTUATOR # define PUNCTUATOR(k, s) TOKEN(k, s) #endif #ifndef KEYWORD # define KEYWORD(k, s) TOKDEF(KW_##k, s) #endif PUNCTUATOR(LPAREN, "(") PUNCTUATOR(RPAREN, ")") PUNCTUATOR(LBRACKET, "[") PUNCTUATOR(RBRACKET, "]") PUNCTUATOR(LBRACE, "{") PUNCTUATOR(RBRACE, "}") PUNCTUATOR(COLON, ":") PUNCTUATOR(DOT, ".") PUNCTUATOR(COMMA, ",") PUNCTUATOR(STAR, "*") PUNCTUATOR(SLASH, "/") PUNCTUATOR(PERCENT, "%") PUNCTUATOR(PLUS, "+") PUNCTUATOR(MINUS, "-") PUNCTUATOR(PIPE, "|") PUNCTUATOR(AMP, "&") PUNCTUATOR(BANG, "!") PUNCTUATOR(EQ, "=") PUNCTUATOR(LT, "<") PUNCTUATOR(GT, ">") PUNCTUATOR(LTEQ, "<=") PUNCTUATOR(GTEQ, ">=") PUNCTUATOR(EQEQ, "==") PUNCTUATOR(BANGEQ, "!=") KEYWORD(CLASS, "class") KEYWORD(META, "meta") KEYWORD(VAR, "var") TOKEN(EMBED, "embed") TOKEN(IDENTIFIER, "identifier") TOKEN(NUMERIC, "numeric") TOKEN(STRING, "string") TOKEN(NL, "new-line") TOKEN(ERROR, "error") TOKEN(EOF, "eof") #undef KEYWORD #undef PUNCTUATOR #undef TOKEN #undef TOKDEF <commit_msg>:construction: chore(kinds): updated the kinds definitions<commit_after>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef TOKDEF # define TOKDEF(k, s) #endif #ifndef TOKEN # define TOKEN(k, s) TOKDEF(TK_##k, s) #endif #ifndef PUNCTUATOR # define PUNCTUATOR(k, s) TOKEN(k, s) #endif #ifndef KEYWORD # define KEYWORD(k, s) TOKDEF(KW_##k, s) #endif PUNCTUATOR(LPAREN, "(") PUNCTUATOR(RPAREN, ")") PUNCTUATOR(LBRACKET, "[") PUNCTUATOR(RBRACKET, "]") PUNCTUATOR(LBRACE, "{") PUNCTUATOR(RBRACE, "}") PUNCTUATOR(COLON, ":") PUNCTUATOR(DOT, ".") PUNCTUATOR(COMMA, ",") PUNCTUATOR(STAR, "*") PUNCTUATOR(SLASH, "/") PUNCTUATOR(PERCENT, "%") PUNCTUATOR(PLUS, "+") PUNCTUATOR(MINUS, "-") PUNCTUATOR(PIPE, "|") PUNCTUATOR(AMP, "&") PUNCTUATOR(BANG, "!") PUNCTUATOR(EQ, "=") PUNCTUATOR(LT, "<") PUNCTUATOR(GT, ">") PUNCTUATOR(LTEQ, "<=") PUNCTUATOR(GTEQ, ">=") PUNCTUATOR(EQEQ, "==") PUNCTUATOR(BANGEQ, "!=") KEYWORD(CLASS, "class") KEYWORD(META, "meta") KEYWORD(VAR, "var") TOKEN(IDENTIFIER, "identifier") TOKEN(NUMERIC, "numeric") TOKEN(STRING, "string") TOKEN(NL, "new-line") TOKEN(ERROR, "error") TOKEN(EOF, "eof") #undef KEYWORD #undef PUNCTUATOR #undef TOKEN #undef TOKDEF <|endoftext|>
<commit_before>#include <config.h> #include <assert.h> #include <boost/assert.hpp> #include <dune/common/exceptions.hh> #include <dune/common/timer.hh> #include <dune/multiscale/common/righthandside_assembler.hh> #include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh> #include <dune/multiscale/msfem/msfem_grid_specifier.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/parameter/configcontainer.hh> #include <dune/stuff/common/profiler.hh> #include <dune/stuff/discretefunction/projection/heterogenous.hh> #include <sstream> #include "dune/multiscale/common/dirichletconstraints.hh" #include "dune/multiscale/common/traits.hh" #include "dune/multiscale/msfem/msfem_traits.hh" #include "msfem_solver.hh" namespace Dune { namespace Multiscale { namespace MsFEM { Elliptic_MsFEM_Solver::Elliptic_MsFEM_Solver(const DiscreteFunctionSpace& discreteFunctionSpace) : discreteFunctionSpace_(discreteFunctionSpace) {} void Elliptic_MsFEM_Solver::subgrid_to_hostrid_projection(const SubgridDiscreteFunctionType& sub_func, DiscreteFunctionType& host_func) const { host_func.clear(); Stuff::HeterogenousProjection<>::project(sub_func, host_func); } // subgrid_to_hostrid_projection void Elliptic_MsFEM_Solver::identify_fine_scale_part(MacroMicroGridSpecifier& specifier, MsFEMTraits::LocalGridListType& subgrid_list, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& fine_scale_part) const { fine_scale_part.clear(); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); DSC_LOG_INFO << "Indentifying fine scale part of the MsFEM solution... "; // traverse coarse space for (auto& coarseCell : coarse_space) { LocalSolutionManager localSolManager(coarseCell, subgrid_list, specifier); localSolManager.loadLocalSolutions(); auto& localSolutions = localSolManager.getLocalSolutions(); auto coarseSolutionLF = coarse_msfem_solution.localFunction(coarseCell); if ((DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 3) || specifier.simplexCoarseGrid()) { BOOST_ASSERT_MSG(localSolutions.size() == Dune::GridSelector::dimgrid, "We should have dim local solutions per coarse element on triangular meshes!"); JacobianRangeType grad_coarse_msfem_on_entity; // We only need the gradient of the coarse scale part on the element, which is a constant. coarseSolutionLF.jacobian(coarseCell.geometry().center(), grad_coarse_msfem_on_entity); // get the coarse gradient on T, multiply it with the local correctors and sum it up. for (int spaceDimension = 0; spaceDimension < Dune::GridSelector::dimgrid; ++spaceDimension) { *localSolutions[spaceDimension] *= grad_coarse_msfem_on_entity[0][spaceDimension]; if (spaceDimension > 0) *localSolutions[0] += *localSolutions[spaceDimension]; } } else { //! @warning At this point, we assume to have the same types of elements in the coarse and fine grid! BOOST_ASSERT_MSG( static_cast<long long>(localSolutions.size() - localSolManager.numBoundaryCorrectors()) == static_cast<long long>(coarseSolutionLF.numDofs()), "The current implementation relies on having thesame types of elements on coarse and fine level!"); for (int dof = 0; dof < coarseSolutionLF.numDofs(); ++dof) { *localSolutions[dof] *= coarseSolutionLF[dof]; if (dof > 0) *localSolutions[0] += *localSolutions[dof]; } // add dirichlet corrector DiscreteFunctionType boundaryCorrector("Boundary Corrector", discreteFunctionSpace_); DMM::MsFEMTraits::LocalGridDiscreteFunctionType& ff = *localSolutions[coarseSolutionLF.numDofs() + 1]; subgrid_to_hostrid_projection(ff, boundaryCorrector); fine_scale_part += boundaryCorrector; // substract neumann corrector subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()], boundaryCorrector); fine_scale_part -= boundaryCorrector; } // oversampling strategy 3: just sum up the local correctors: if ((DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 3)) { DiscreteFunctionType correction_on_U_T("correction_on_U_T", discreteFunctionSpace_); subgrid_to_hostrid_projection(*localSolutions[0], correction_on_U_T); fine_scale_part += correction_on_U_T; } // oversampling strategy 1 or 2: restrict the local correctors to the element T, sum them up and apply a conforming // projection: if ((DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 1) || (DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 2)) { // DUNE_THROW(NotImplemented, "pretty sure this is bs. there's no sum of local correctors. restriction also no longer works"); // for (auto& local_entity : localSolManager.getLocalDiscreteFunctionSpace()) { // if (subgrid_list.covers(coarseCell, local_entity)) { // const auto sub_loc_value = localSolutions[0]->localFunction(local_entity); // assert(localSolutions.size() == coarseSolutionLF.numDofs() + localSolManager.numBoundaryCorrectors()); // auto host_loc_value = fine_scale_part.localFunction(local_entity); // const auto number_of_nodes_entity = local_entity.count<LocalGrid::dimension>(); // for (auto i : DSC::valueRange(number_of_nodes_entity)) { // const auto node = local_entity.subEntity<LocalGrid::dimension>(i); // const auto global_index_node = gridPart.indexSet().index(*node); // // devide the value by the number of fine elements sharing the node (will be // // added numEntitiesSharingNode times) // const auto numEntitiesSharingNode = nodeToEntityMap[global_index_node].size(); // host_loc_value[i] += (sub_loc_value[i] / numEntitiesSharingNode); // } // } // } } } DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::solve_dirichlet_zero( const CommonTraits::DiffusionType& diffusion_op, const CommonTraits::FirstSourceType& f, // number of layers per coarse grid entity T: U(T) is created by enrichting T with // n(T)-layers. MacroMicroGridSpecifier& specifier, MsFEMTraits::LocalGridListType& subgrid_list, DiscreteFunctionType& coarse_scale_part, DiscreteFunctionType& fine_scale_part, DiscreteFunctionType& solution) const { DSC::Profiler::ScopedTiming st("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero"); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); DiscreteFunctionType coarse_msfem_solution("Coarse Part MsFEM Solution", coarse_space); coarse_msfem_solution.clear(); //! define the right hand side assembler tool // (for linear and non-linear elliptic and parabolic problems, for sources f and/or G ) typedef RightHandSideAssembler RhsAssembler; // Assemble and solve the local problems. Timing is done in assembleAndSolveAll-method MsFEMLocalProblemSolver localProblemSolver(specifier, subgrid_list, diffusion_op); localProblemSolver.assembleAndSolveAll(); //! define the discrete (elliptic) operator that describes our problem // discrete elliptic MsFEM operator (corresponds with MsFEM Matrix) // ( effect of the discretized differential operator on a certain discrete function ) const DiscreteEllipticMsFEMOperator elliptic_msfem_op(specifier, coarse_space, subgrid_list, diffusion_op); //! (stiffness) matrix MsLinearOperatorTypeType msfem_matrix("MsFEM stiffness matrix", coarse_space, coarse_space); //! right hand side vector // right hand side for the finite element method: DiscreteFunctionType msfem_rhs("MsFEM right hand side", coarse_space); msfem_rhs.clear(); // to assemble the computational time DSC_PROFILER.startTiming("msfem.assembleMatrix"); // assemble the MsFEM stiffness matrix elliptic_msfem_op.assemble_matrix(msfem_matrix); DSC_LOG_INFO << "Time to assemble MsFEM stiffness matrix: " << DSC_PROFILER.stopTiming("msfem.assembleMatrix") << "ms" << std::endl; // assemble right hand side DSC_PROFILER.startTiming("msfem.assembleRHS"); if (DSC_CONFIG_GET("msfem.petrov_galerkin", 1)) DSC_LOG_ERROR << "MsFEM does not work with Petrov-Galerkin at the moment!\n"; RhsAssembler::assemble_for_MsFEM_symmetric(f, specifier, subgrid_list, msfem_rhs); msfem_rhs.communicate(); DSC_LOG_INFO << "Time to assemble and communicate MsFEM rhs: " << DSC_PROFILER.stopTiming("msfem.assembleRHS") << "ms" << std::endl; BOOST_ASSERT_MSG(msfem_rhs.dofsValid(), "Coarse scale RHS DOFs need to be valid!"); DSC_PROFILER.startTiming("msfem.solveCoarse"); const InverseOperatorType msfem_biCGStab(msfem_matrix, 1e-8, 1e-8, DSC_CONFIG_GET("msfem.solver.iterations", msfem_rhs.size()), DSC_CONFIG_GET("msfem.solver.verbose", false), "bcgs", DSC_CONFIG_GET("msfem.solver.preconditioner_type", std::string("sor"))); msfem_biCGStab(msfem_rhs, coarse_msfem_solution); DSC_LOG_INFO << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.stopTiming("msfem.solveCoarse") << "ms." << std::endl; if (!coarse_msfem_solution.dofsValid()) DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!"); // get the dirichlet values solution.clear(); Dune::Multiscale::copyDirichletValues(coarse_space, solution); //! identify fine scale part of MsFEM solution (including the projection!) identify_fine_scale_part(specifier, subgrid_list, coarse_msfem_solution, fine_scale_part); { DSC::Profiler::ScopedTiming commFSTimer("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero.comm_fine_scale_part"); fine_scale_part.communicate(); } BOOST_ASSERT_MSG(coarse_scale_part.dofsValid(), "Coarse scale part DOFs need to be valid!"); BOOST_ASSERT_MSG(fine_scale_part.dofsValid(), "Fine scale part DOFs need to be valid!"); DS::HeterogenousProjection<>::project(coarse_msfem_solution, coarse_scale_part); // add coarse and fine scale part to solution solution += coarse_scale_part; solution += fine_scale_part; // seperate the msfem output from other output std::cout << std::endl << std::endl; } // solve_dirichlet_zero } // namespace MsFEM { } // namespace Multiscale { } // namespace Dune { <commit_msg>3x speedup for Elliptic_MsFEM_Solver::identify_fine_scale_part<commit_after>#include <config.h> #include <assert.h> #include <boost/assert.hpp> #include <dune/common/exceptions.hh> #include <dune/common/timer.hh> #include <dune/multiscale/common/righthandside_assembler.hh> #include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh> #include <dune/multiscale/msfem/msfem_grid_specifier.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/parameter/configcontainer.hh> #include <dune/stuff/common/profiler.hh> #include <dune/stuff/discretefunction/projection/heterogenous.hh> #include <sstream> #include "dune/multiscale/common/dirichletconstraints.hh" #include "dune/multiscale/common/traits.hh" #include "dune/multiscale/msfem/msfem_traits.hh" #include "msfem_solver.hh" namespace Dune { namespace Multiscale { namespace MsFEM { Elliptic_MsFEM_Solver::Elliptic_MsFEM_Solver(const DiscreteFunctionSpace& discreteFunctionSpace) : discreteFunctionSpace_(discreteFunctionSpace) {} void Elliptic_MsFEM_Solver::subgrid_to_hostrid_projection(const SubgridDiscreteFunctionType& sub_func, DiscreteFunctionType& host_func) const { host_func.clear(); Stuff::HeterogenousProjection<>::project(sub_func, host_func); } // subgrid_to_hostrid_projection void Elliptic_MsFEM_Solver::identify_fine_scale_part(MacroMicroGridSpecifier& specifier, MsFEMTraits::LocalGridListType& subgrid_list, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& fine_scale_part) const { fine_scale_part.clear(); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); DSC_LOG_INFO << "Indentifying fine scale part of the MsFEM solution... "; DiscreteFunctionType fine_correction("Boundary Corrector", discreteFunctionSpace_); // traverse coarse space for (auto& coarseCell : coarse_space) { LocalSolutionManager localSolManager(coarseCell, subgrid_list, specifier); localSolManager.loadLocalSolutions(); auto& localSolutions = localSolManager.getLocalSolutions(); auto coarseSolutionLF = coarse_msfem_solution.localFunction(coarseCell); DMM::MsFEMTraits::LocalGridDiscreteFunctionType local_correction("", localSolManager.space()); local_correction.clear(); if ((DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 3) || specifier.simplexCoarseGrid()) { BOOST_ASSERT_MSG(localSolutions.size() == Dune::GridSelector::dimgrid, "We should have dim local solutions per coarse element on triangular meshes!"); JacobianRangeType grad_coarse_msfem_on_entity; // We only need the gradient of the coarse scale part on the element, which is a constant. coarseSolutionLF.jacobian(coarseCell.geometry().center(), grad_coarse_msfem_on_entity); // get the coarse gradient on T, multiply it with the local correctors and sum it up. for (int spaceDimension = 0; spaceDimension < Dune::GridSelector::dimgrid; ++spaceDimension) { *localSolutions[spaceDimension] *= grad_coarse_msfem_on_entity[0][spaceDimension]; if (spaceDimension > 0) *localSolutions[0] += *localSolutions[spaceDimension]; } } else { //! @warning At this point, we assume to have the same types of elements in the coarse and fine grid! BOOST_ASSERT_MSG( static_cast<long long>(localSolutions.size() - localSolManager.numBoundaryCorrectors()) == static_cast<long long>(coarseSolutionLF.numDofs()), "The current implementation relies on having thesame types of elements on coarse and fine level!"); for (int dof = 0; dof < coarseSolutionLF.numDofs(); ++dof) { *localSolutions[dof] *= coarseSolutionLF[dof]; if (dof > 0) *localSolutions[0] += *localSolutions[dof]; } // add dirichlet corrector local_correction += *localSolutions[coarseSolutionLF.numDofs() + 1]; // substract neumann corrector local_correction -= *localSolutions[coarseSolutionLF.numDofs() + 1]; } // oversampling strategy 3: just sum up the local correctors: if ((DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 3)) { local_correction += *localSolutions[0]; } // oversampling strategy 1 or 2: restrict the local correctors to the element T, sum them up and apply a conforming // projection: if ((DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 1) || (DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 2)) { // DUNE_THROW(NotImplemented, "pretty sure this is bs. there's no sum of local correctors. restriction also no longer works"); // for (auto& local_entity : localSolManager.space()) { // if (subgrid_list.covers(coarseCell, local_entity)) { // const auto sub_loc_value = localSolutions[0]->localFunction(local_entity); // assert(localSolutions.size() == coarseSolutionLF.numDofs() + localSolManager.numBoundaryCorrectors()); // auto host_loc_value = fine_scale_part.localFunction(local_entity); // const auto number_of_nodes_entity = local_entity.count<LocalGrid::dimension>(); // for (auto i : DSC::valueRange(number_of_nodes_entity)) { // const auto node = local_entity.subEntity<LocalGrid::dimension>(i); // const auto global_index_node = gridPart.indexSet().index(*node); // // devide the value by the number of fine elements sharing the node (will be // // added numEntitiesSharingNode times) // const auto numEntitiesSharingNode = nodeToEntityMap[global_index_node].size(); // host_loc_value[i] += (sub_loc_value[i] / numEntitiesSharingNode); // } // } // } } Stuff::HeterogenousProjection<>::project(local_correction, fine_correction); fine_scale_part += fine_correction; } DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::solve_dirichlet_zero( const CommonTraits::DiffusionType& diffusion_op, const CommonTraits::FirstSourceType& f, // number of layers per coarse grid entity T: U(T) is created by enrichting T with // n(T)-layers. MacroMicroGridSpecifier& specifier, MsFEMTraits::LocalGridListType& subgrid_list, DiscreteFunctionType& coarse_scale_part, DiscreteFunctionType& fine_scale_part, DiscreteFunctionType& solution) const { DSC::Profiler::ScopedTiming st("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero"); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); DiscreteFunctionType coarse_msfem_solution("Coarse Part MsFEM Solution", coarse_space); coarse_msfem_solution.clear(); //! define the right hand side assembler tool // (for linear and non-linear elliptic and parabolic problems, for sources f and/or G ) typedef RightHandSideAssembler RhsAssembler; // Assemble and solve the local problems. Timing is done in assembleAndSolveAll-method MsFEMLocalProblemSolver localProblemSolver(specifier, subgrid_list, diffusion_op); localProblemSolver.assembleAndSolveAll(); //! define the discrete (elliptic) operator that describes our problem // discrete elliptic MsFEM operator (corresponds with MsFEM Matrix) // ( effect of the discretized differential operator on a certain discrete function ) const DiscreteEllipticMsFEMOperator elliptic_msfem_op(specifier, coarse_space, subgrid_list, diffusion_op); //! (stiffness) matrix MsLinearOperatorTypeType msfem_matrix("MsFEM stiffness matrix", coarse_space, coarse_space); //! right hand side vector // right hand side for the finite element method: DiscreteFunctionType msfem_rhs("MsFEM right hand side", coarse_space); msfem_rhs.clear(); // to assemble the computational time DSC_PROFILER.startTiming("msfem.assembleMatrix"); // assemble the MsFEM stiffness matrix elliptic_msfem_op.assemble_matrix(msfem_matrix); DSC_LOG_INFO << "Time to assemble MsFEM stiffness matrix: " << DSC_PROFILER.stopTiming("msfem.assembleMatrix") << "ms" << std::endl; // assemble right hand side DSC_PROFILER.startTiming("msfem.assembleRHS"); if (DSC_CONFIG_GET("msfem.petrov_galerkin", 1)) DSC_LOG_ERROR << "MsFEM does not work with Petrov-Galerkin at the moment!\n"; RhsAssembler::assemble_for_MsFEM_symmetric(f, specifier, subgrid_list, msfem_rhs); msfem_rhs.communicate(); DSC_LOG_INFO << "Time to assemble and communicate MsFEM rhs: " << DSC_PROFILER.stopTiming("msfem.assembleRHS") << "ms" << std::endl; BOOST_ASSERT_MSG(msfem_rhs.dofsValid(), "Coarse scale RHS DOFs need to be valid!"); DSC_PROFILER.startTiming("msfem.solveCoarse"); const InverseOperatorType msfem_biCGStab(msfem_matrix, 1e-8, 1e-8, DSC_CONFIG_GET("msfem.solver.iterations", msfem_rhs.size()), DSC_CONFIG_GET("msfem.solver.verbose", false), "bcgs", DSC_CONFIG_GET("msfem.solver.preconditioner_type", std::string("sor"))); msfem_biCGStab(msfem_rhs, coarse_msfem_solution); DSC_LOG_INFO << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.stopTiming("msfem.solveCoarse") << "ms." << std::endl; if (!coarse_msfem_solution.dofsValid()) DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!"); // get the dirichlet values solution.clear(); Dune::Multiscale::copyDirichletValues(coarse_space, solution); //! identify fine scale part of MsFEM solution (including the projection!) identify_fine_scale_part(specifier, subgrid_list, coarse_msfem_solution, fine_scale_part); { DSC::Profiler::ScopedTiming commFSTimer("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero.comm_fine_scale_part"); fine_scale_part.communicate(); } BOOST_ASSERT_MSG(coarse_scale_part.dofsValid(), "Coarse scale part DOFs need to be valid!"); BOOST_ASSERT_MSG(fine_scale_part.dofsValid(), "Fine scale part DOFs need to be valid!"); DS::HeterogenousProjection<>::project(coarse_msfem_solution, coarse_scale_part); // add coarse and fine scale part to solution solution += coarse_scale_part; solution += fine_scale_part; // seperate the msfem output from other output std::cout << std::endl << std::endl; } // solve_dirichlet_zero } // namespace MsFEM { } // namespace Multiscale { } // namespace Dune { <|endoftext|>
<commit_before>#include <config.h> #include <dune/common/exceptions.hh> #include <dune/stuff/common/validation.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/common/configuration.hh> #include <math.h> #include <sstream> #include "dune/multiscale/problems/base.hh" #include "synthetic.hh" namespace Dune { namespace Multiscale { namespace Problem { namespace Synthetic { static constexpr double epsilon = 0.05; ModelProblemData::ModelProblemData() : IModelProblemData() , boundaryInfo_(DSG::BoundaryInfos::NormalBased<typename View::Intersection>::create(boundary_settings())) , subBoundaryInfo_() {} std::string ModelProblemData::getMacroGridFile() const { return ("../dune/multiscale/grids/macro_grids/elliptic/msfem_cube_three.dgf"); } std::pair<CommonTraits::DomainType, CommonTraits::DomainType> ModelProblemData::gridCorners() const { CommonTraits::DomainType lowerLeft(0.0); CommonTraits::DomainType upperRight(1.0); return {lowerLeft, upperRight}; } const ModelProblemData::BoundaryInfoType& ModelProblemData::boundaryInfo() const { return *boundaryInfo_; } const ModelProblemData::SubBoundaryInfoType& ModelProblemData::subBoundaryInfo() const { return subBoundaryInfo_; } ParameterTree ModelProblemData::boundary_settings() const { Dune::ParameterTree boundarySettings; if (DSC_CONFIG.has_sub("problem.boundaryInfo")) { boundarySettings = DSC_CONFIG.sub("problem.boundaryInfo"); } else { boundarySettings["default"] = "dirichlet"; boundarySettings["compare_tolerance"] = "1e-10"; switch (CommonTraits::world_dim) { case 1: break; case 2: break; case 3: boundarySettings["neumann.0"] = "[0.0 0.0 1.0]"; boundarySettings["neumann.1"] = "[0.0 0.0 -1.0]"; } } return boundarySettings; } Source::Source() {} Diffusion::Diffusion() {} ExactSolution::ExactSolution() {} PURE HOT void Source::evaluate(const DomainType& x, RangeType& y) const { constexpr double pi_square = M_PI * M_PI; const double x0_eps = (x[0] / epsilon); const double cos_2_pi_x0_eps = cos(2.0 * M_PI * x0_eps); const double sin_2_pi_x0_eps = sin(2.0 * M_PI * x0_eps); const double coefficient_0 = 2.0 * (1.0 / (8.0 * M_PI * M_PI)) * (1.0 / (2.0 + cos_2_pi_x0_eps)); const double coefficient_1 = (1.0 / (8.0 * M_PI * M_PI)) * (1.0 + (0.5 * cos_2_pi_x0_eps)); const double sin_2_pi_x0 = sin(2.0 * M_PI * x[0]); const double cos_2_pi_x0 = cos(2.0 * M_PI * x[0]); const double sin_2_pi_x1 = sin(2.0 * M_PI * x[1]); const double d_x0_coefficient_0 = pow(2.0 + cos_2_pi_x0_eps, -2.0) * (1.0 / (2.0 * M_PI)) * (1.0 / epsilon) * sin_2_pi_x0_eps; const auto grad_u = (2.0 * M_PI * cos_2_pi_x0 * sin_2_pi_x1) + ((-1.0) * epsilon * M_PI * (sin_2_pi_x0 * sin_2_pi_x1 * sin_2_pi_x0_eps)) + (M_PI * (cos_2_pi_x0 * sin_2_pi_x1 * cos_2_pi_x0_eps)); const auto d_x0_x0_u = -(4.0 * pi_square * sin_2_pi_x0 * sin_2_pi_x1) - (2.0 * pi_square * (epsilon + (1.0 / epsilon)) * cos_2_pi_x0 * sin_2_pi_x1 * sin_2_pi_x0_eps) - (4.0 * pi_square * sin_2_pi_x0 * sin_2_pi_x1 * cos_2_pi_x0_eps); const auto d_x1_x1_u = -(4.0 * pi_square * sin_2_pi_x0 * sin_2_pi_x1) - (2.0 * pi_square * epsilon * cos_2_pi_x0 * sin_2_pi_x1 * sin_2_pi_x0_eps); y = -(d_x0_coefficient_0 * grad_u) - (coefficient_0 * d_x0_x0_u) - (coefficient_1 * d_x1_x1_u); } void Diffusion::evaluate(const DomainType& x, Diffusion::RangeType& ret) const { const double x0_eps = (x[0] / epsilon); constexpr double inv_pi8pi = 1. / (8.0 * M_PI * M_PI); const double cos_eval = cos(2.0 * M_PI * x0_eps); ret[0][0] = 2.0 * inv_pi8pi * (1.0 / (2.0 + cos_eval)); ret[1][1] = inv_pi8pi * (1.0 + (0.5 * cos_eval)); } PURE HOT void Diffusion::diffusiveFlux(const DomainType& x, const Problem::JacobianRangeType& direction, Problem::JacobianRangeType& flux) const { Diffusion::RangeType eval; evaluate(x, eval); flux[0][0] = eval[0][0] * direction[0][0]; flux[0][1] = eval[1][1] * direction[0][1]; } // diffusiveFlux size_t Diffusion::order() const { return 2; } size_t Source::order() const { return 1; } // evaluate size_t ExactSolution::order() const { return 1; } std::string ExactSolution::name() const { return "synthetic.exact"; } PURE HOT void ExactSolution::evaluate(const DomainType& x, RangeType& y) const { // approximation obtained by homogenized solution + first corrector constexpr double M_TWOPI = M_PI * 2.0; const double x0_eps = (x[0] / epsilon); const double sin_2_pi_x0_eps = sin(M_TWOPI * x0_eps); const double x0_2_pi = M_TWOPI * x[0]; const double x1_2_pi = M_TWOPI * x[1]; const double sin_2_pi_x0 = sin(x0_2_pi); const double cos_2_pi_x0 = cos(x0_2_pi); const double sin_2_pi_x1 = sin(x1_2_pi); y = sin_2_pi_x0 * sin_2_pi_x1 + (0.5 * epsilon * cos_2_pi_x0 * sin_2_pi_x1 * sin_2_pi_x0_eps); } // evaluate PURE HOT void ExactSolution::jacobian(const DomainType& x, JacobianRangeType& grad_u) const { constexpr double M_TWOPI = M_PI * 2.0; const double x0_eps = (x[0] / epsilon); const double cos_2_pi_x0_eps = cos(M_TWOPI * x0_eps); const double sin_2_pi_x0_eps = sin(M_TWOPI * x0_eps); const double x0_2_pi = M_TWOPI * x[0]; const double x1_2_pi = M_TWOPI * x[1]; const double sin_2_pi_x0 = sin(x0_2_pi); const double cos_2_pi_x0 = cos(x0_2_pi); const double sin_2_pi_x1 = sin(x1_2_pi); const double cos_2_pi_x1 = cos(x1_2_pi); const double eps_pi_sin_2_pi_x0_eps = epsilon * M_PI * sin_2_pi_x0_eps; grad_u[0][1] = (M_TWOPI * sin_2_pi_x0 * cos_2_pi_x1) + (eps_pi_sin_2_pi_x0_eps * cos_2_pi_x0 * cos_2_pi_x1); grad_u[0][0] = (M_TWOPI * cos_2_pi_x0 * sin_2_pi_x1) - (eps_pi_sin_2_pi_x0_eps * sin_2_pi_x0 * sin_2_pi_x1) + (M_PI * cos_2_pi_x0 * sin_2_pi_x1 * cos_2_pi_x0_eps); } PURE void DirichletData::evaluate(const DomainType& x, RangeType& y) const { solution_.evaluate(x, y); } // evaluate PURE void DirichletData::jacobian(const DomainType& x, JacobianRangeType& y) const { solution_.jacobian(x, y); } // jacobian PURE void NeumannData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.0; } // evaluate } // namespace Nine } // namespace Problem } // namespace Multiscale { } // namespace Dune { <commit_msg>optimize synthetic problem eval<commit_after>#include <config.h> #include <dune/common/exceptions.hh> #include <dune/stuff/common/validation.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/common/configuration.hh> #include <math.h> #include <sstream> #include "dune/multiscale/problems/base.hh" #include "synthetic.hh" namespace Dune { namespace Multiscale { namespace Problem { namespace Synthetic { static constexpr double epsilon = 0.05; static constexpr double M_TWOPI = M_PI * 2.0; ModelProblemData::ModelProblemData() : IModelProblemData() , boundaryInfo_(DSG::BoundaryInfos::NormalBased<typename View::Intersection>::create(boundary_settings())) , subBoundaryInfo_() {} std::string ModelProblemData::getMacroGridFile() const { return ("../dune/multiscale/grids/macro_grids/elliptic/msfem_cube_three.dgf"); } std::pair<CommonTraits::DomainType, CommonTraits::DomainType> ModelProblemData::gridCorners() const { CommonTraits::DomainType lowerLeft(0.0); CommonTraits::DomainType upperRight(1.0); return {lowerLeft, upperRight}; } const ModelProblemData::BoundaryInfoType& ModelProblemData::boundaryInfo() const { return *boundaryInfo_; } const ModelProblemData::SubBoundaryInfoType& ModelProblemData::subBoundaryInfo() const { return subBoundaryInfo_; } ParameterTree ModelProblemData::boundary_settings() const { Dune::ParameterTree boundarySettings; if (DSC_CONFIG.has_sub("problem.boundaryInfo")) { boundarySettings = DSC_CONFIG.sub("problem.boundaryInfo"); } else { boundarySettings["default"] = "dirichlet"; boundarySettings["compare_tolerance"] = "1e-10"; switch (CommonTraits::world_dim) { case 1: break; case 2: break; case 3: boundarySettings["neumann.0"] = "[0.0 0.0 1.0]"; boundarySettings["neumann.1"] = "[0.0 0.0 -1.0]"; } } return boundarySettings; } Source::Source() {} Diffusion::Diffusion() {} ExactSolution::ExactSolution() {} PURE HOT void Source::evaluate(const DomainType& x, RangeType& y) const { constexpr double pi_square = M_PI * M_PI; const double x0_eps = (x[0] / epsilon); const double cos_2_pi_x0_eps = cos(M_TWOPI * x0_eps); const double sin_2_pi_x0_eps = sin(M_TWOPI * x0_eps); const double coefficient_0 = 2.0 * (1.0 / (8.0 * M_PI * M_PI)) * (1.0 / (2.0 + cos_2_pi_x0_eps)); const double coefficient_1 = (1.0 / (8.0 * M_PI * M_PI)) * (1.0 + (0.5 * cos_2_pi_x0_eps)); const double sin_2_pi_x0 = sin(M_TWOPI * x[0]); const double cos_2_pi_x0 = cos(M_TWOPI * x[0]); const double sin_2_pi_x1 = sin(M_TWOPI * x[1]); const double d_x0_coefficient_0 = pow(2.0 + cos_2_pi_x0_eps, -2.0) * (1.0 / (M_TWOPI)) * (1.0 / epsilon) * sin_2_pi_x0_eps; const auto grad_u = (M_TWOPI * cos_2_pi_x0 * sin_2_pi_x1) + ((-1.0) * epsilon * M_PI * (sin_2_pi_x0 * sin_2_pi_x1 * sin_2_pi_x0_eps)) + (M_PI * (cos_2_pi_x0 * sin_2_pi_x1 * cos_2_pi_x0_eps)); const auto d_x0_x0_u = -(4.0 * pi_square * sin_2_pi_x0 * sin_2_pi_x1) - (2.0 * pi_square * (epsilon + (1.0 / epsilon)) * cos_2_pi_x0 * sin_2_pi_x1 * sin_2_pi_x0_eps) - (4.0 * pi_square * sin_2_pi_x0 * sin_2_pi_x1 * cos_2_pi_x0_eps); const auto d_x1_x1_u = -(4.0 * pi_square * sin_2_pi_x0 * sin_2_pi_x1) - (2.0 * pi_square * epsilon * cos_2_pi_x0 * sin_2_pi_x1 * sin_2_pi_x0_eps); y = -(d_x0_coefficient_0 * grad_u) - (coefficient_0 * d_x0_x0_u) - (coefficient_1 * d_x1_x1_u); } void Diffusion::evaluate(const DomainType& x, Diffusion::RangeType& ret) const { const double x0_eps = (x[0] / epsilon); constexpr double inv_pi8pi = 1. / (8.0 * M_PI * M_PI); const double cos_eval = cos(M_TWOPI * x0_eps); ret[0][0] = 2.0 * inv_pi8pi * (1.0 / (2.0 + cos_eval)); ret[1][1] = inv_pi8pi * (1.0 + (0.5 * cos_eval)); } PURE HOT void Diffusion::diffusiveFlux(const DomainType& x, const Problem::JacobianRangeType& direction, Problem::JacobianRangeType& flux) const { Diffusion::RangeType eval; evaluate(x, eval); flux[0][0] = eval[0][0] * direction[0][0]; flux[0][1] = eval[1][1] * direction[0][1]; } // diffusiveFlux size_t Diffusion::order() const { return 2; } size_t Source::order() const { return 1; } // evaluate size_t ExactSolution::order() const { return 1; } std::string ExactSolution::name() const { return "synthetic.exact"; } PURE HOT void ExactSolution::evaluate(const DomainType& x, RangeType& y) const { // approximation obtained by homogenized solution + first corrector const double x0_eps = (x[0] / epsilon); const double sin_2_pi_x0_eps = sin(M_TWOPI * x0_eps); const double x0_2_pi = M_TWOPI * x[0]; const double x1_2_pi = M_TWOPI * x[1]; const double sin_2_pi_x0 = sin(x0_2_pi); const double cos_2_pi_x0 = cos(x0_2_pi); const double sin_2_pi_x1 = sin(x1_2_pi); y = sin_2_pi_x0 * sin_2_pi_x1 + (0.5 * epsilon * cos_2_pi_x0 * sin_2_pi_x1 * sin_2_pi_x0_eps); } // evaluate PURE HOT void ExactSolution::jacobian(const DomainType& x, JacobianRangeType& grad_u) const { const double x0_eps = (x[0] / epsilon); const double cos_2_pi_x0_eps = cos(M_TWOPI * x0_eps); const double sin_2_pi_x0_eps = sin(M_TWOPI * x0_eps); const double x0_2_pi = M_TWOPI * x[0]; const double x1_2_pi = M_TWOPI * x[1]; const double sin_2_pi_x0 = sin(x0_2_pi); const double cos_2_pi_x0 = cos(x0_2_pi); const double sin_2_pi_x1 = sin(x1_2_pi); const double cos_2_pi_x1 = cos(x1_2_pi); const double eps_pi_sin_2_pi_x0_eps = epsilon * M_PI * sin_2_pi_x0_eps; grad_u[0][1] = (M_TWOPI * sin_2_pi_x0 * cos_2_pi_x1) + (eps_pi_sin_2_pi_x0_eps * cos_2_pi_x0 * cos_2_pi_x1); grad_u[0][0] = (M_TWOPI * cos_2_pi_x0 * sin_2_pi_x1) - (eps_pi_sin_2_pi_x0_eps * sin_2_pi_x0 * sin_2_pi_x1) + (M_PI * cos_2_pi_x0 * sin_2_pi_x1 * cos_2_pi_x0_eps); } PURE void DirichletData::evaluate(const DomainType& x, RangeType& y) const { solution_.evaluate(x, y); } // evaluate PURE void DirichletData::jacobian(const DomainType& x, JacobianRangeType& y) const { solution_.jacobian(x, y); } // jacobian PURE void NeumannData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.0; } // evaluate } // namespace Nine } // namespace Problem } // namespace Multiscale { } // namespace Dune { <|endoftext|>
<commit_before>// Copyright 2012-2013 Samplecount S.L. // // 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 METHCLA_AUDIO_SYNTHDEF_HPP_INCLUDED #define METHCLA_AUDIO_SYNTHDEF_HPP_INCLUDED #include <methcla/engine.h> #include <methcla/plugin.h> #include "Methcla/Plugin/Loader.hpp" #include "Methcla/Utility/Hash.hpp" #include <boost/utility.hpp> #include <cstring> #include <list> #include <memory> #include <oscpp/server.hpp> #include <string> #include <unordered_map> #include <vector> namespace Methcla { namespace Audio { // class Port // { // public: // Port(Methcla_PortDescriptor port, uint32_t index, const char* symbol="") // : m_port(port) // , m_index(index) // , m_symbol(symbol) // { } // // Methcla_PortType type() const { return m_port.type; } // Methcla_PortDirection direction() const { return m_port.direction; } // uint32_t index() const { return m_index; } // const char* symbol() const { return m_symbol.c_str(); } // // private: // Methcla_PortDescriptor m_port; // uint32_t m_index; // std::string m_symbol; // }; class Synth; class SynthDef : boost::noncopyable { public: SynthDef(const Methcla_SynthDef* def); ~SynthDef(); inline const char* uri() const { return m_descriptor->uri; } inline size_t instanceSize () const { return m_descriptor->instance_size; } // inline size_t numPorts() const { return m_ports.size(); } // inline const Port& port(size_t i) const { return m_ports.at(i); } // // inline size_t numAudioInputs () const { return m_numAudioInputs; } // inline size_t numAudioOutputs () const { return m_numAudioOutputs; } // inline size_t numControlInputs () const { return m_numControlInputs; } // inline size_t numControlOutputs () const { return m_numControlOutputs; } // NOTE: Uses static data and should only be called from a single thread (normally the audio thread) at a time. const Methcla_SynthOptions* configure(OSCPP::Server::ArgStream options) const; //* Return port descriptor at index. bool portDescriptor(const Methcla_SynthOptions* options, size_t index, Methcla_PortDescriptor* port) const; void construct(const Methcla_World* world, const Methcla_SynthOptions* options, Synth* owner, Methcla_Synth* synth) const; void destroy(const Methcla_World* world, Methcla_Synth* synth) const; inline void connect(Methcla_Synth* synth, Methcla_PortCount port, void* data) const { m_descriptor->connect(synth, port, data); } inline void activate(const Methcla_World* world, Methcla_Synth* synth) const { if (m_descriptor->activate) m_descriptor->activate(world, synth); } inline void process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames) const { m_descriptor->process(world, synth, numFrames); } private: const Methcla_SynthDef* m_descriptor; Methcla_SynthOptions* m_options; // Only access from one thread // std::vector<Port> m_ports; // size_t m_numAudioInputs; // size_t m_numAudioOutputs; // size_t m_numControlInputs; // size_t m_numControlOutputs; }; typedef std::unordered_map<const char*, std::shared_ptr<SynthDef>, Utility::Hash::cstr_hash, Utility::Hash::cstr_equal> SynthDefMap; //* Plugin library. class PluginLibrary : boost::noncopyable { public: PluginLibrary(const Methcla_Library* lib, std::shared_ptr<Methcla::Plugin::Library> plugin=nullptr); ~PluginLibrary(); private: const Methcla_Library* m_lib; std::shared_ptr<Methcla::Plugin::Library> m_plugin; }; class PluginManager : boost::noncopyable { public: //* Load plugins from static functions. void loadPlugins(const Methcla_Host* host, const std::list<Methcla_LibraryFunction>& funcs); //* Load plugins from directory. void loadPlugins(const Methcla_Host* host, const std::string& directory); private: typedef std::list<std::shared_ptr<PluginLibrary>> Libraries; Libraries m_libs; }; } } #endif // METHCLA_AUDIO_SYNTHDEF_HPP_INCLUDED <commit_msg>Remove stale code<commit_after>// Copyright 2012-2013 Samplecount S.L. // // 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 METHCLA_AUDIO_SYNTHDEF_HPP_INCLUDED #define METHCLA_AUDIO_SYNTHDEF_HPP_INCLUDED #include <methcla/engine.h> #include <methcla/plugin.h> #include "Methcla/Plugin/Loader.hpp" #include "Methcla/Utility/Hash.hpp" #include <boost/utility.hpp> #include <cstring> #include <list> #include <memory> #include <oscpp/server.hpp> #include <string> #include <unordered_map> namespace Methcla { namespace Audio { class Synth; class SynthDef : boost::noncopyable { public: SynthDef(const Methcla_SynthDef* def); ~SynthDef(); inline const char* uri() const { return m_descriptor->uri; } inline size_t instanceSize () const { return m_descriptor->instance_size; } // NOTE: Uses static data and should only be called from a single thread (normally the audio thread) at a time. const Methcla_SynthOptions* configure(OSCPP::Server::ArgStream options) const; //* Return port descriptor at index. bool portDescriptor(const Methcla_SynthOptions* options, size_t index, Methcla_PortDescriptor* port) const; void construct(const Methcla_World* world, const Methcla_SynthOptions* options, Synth* owner, Methcla_Synth* synth) const; void destroy(const Methcla_World* world, Methcla_Synth* synth) const; inline void connect(Methcla_Synth* synth, Methcla_PortCount port, void* data) const { m_descriptor->connect(synth, port, data); } inline void activate(const Methcla_World* world, Methcla_Synth* synth) const { if (m_descriptor->activate) m_descriptor->activate(world, synth); } inline void process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames) const { m_descriptor->process(world, synth, numFrames); } private: const Methcla_SynthDef* m_descriptor; Methcla_SynthOptions* m_options; // Only access from one thread }; typedef std::unordered_map<const char*, std::shared_ptr<SynthDef>, Utility::Hash::cstr_hash, Utility::Hash::cstr_equal> SynthDefMap; //* Plugin library. class PluginLibrary : boost::noncopyable { public: PluginLibrary(const Methcla_Library* lib, std::shared_ptr<Methcla::Plugin::Library> plugin=nullptr); ~PluginLibrary(); private: const Methcla_Library* m_lib; std::shared_ptr<Methcla::Plugin::Library> m_plugin; }; class PluginManager : boost::noncopyable { public: //* Load plugins from static functions. void loadPlugins(const Methcla_Host* host, const std::list<Methcla_LibraryFunction>& funcs); //* Load plugins from directory. void loadPlugins(const Methcla_Host* host, const std::string& directory); private: typedef std::list<std::shared_ptr<PluginLibrary>> Libraries; Libraries m_libs; }; } } #endif // METHCLA_AUDIO_SYNTHDEF_HPP_INCLUDED <|endoftext|>
<commit_before>// Copyright (c) 2020 The Orbit 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 <absl/flags/flag.h> #include <absl/flags/parse.h> #include <absl/flags/usage.h> #include <QApplication> #include <QDir> #include <QFontDatabase> #include <QMessageBox> #include <QProcessEnvironment> #include <QProgressDialog> #include <QStyleFactory> #include "App.h" #include "ApplicationOptions.h" #include "CrashHandler.h" #include "CrashOptions.h" #include "Error.h" #include "GlutContext.h" #include "OrbitBase/Logging.h" #include "OrbitGgp/Error.h" #include "OrbitSsh/Context.h" #include "OrbitSsh/Credentials.h" #include "OrbitSshQt/Session.h" #include "OrbitStartupWindow.h" #include "Path.h" #include "deploymentconfigurations.h" #include "opengldetect.h" #include "orbitmainwindow.h" #include "servicedeploymanager.h" #include "version.h" ABSL_FLAG(bool, enable_stale_features, false, "Enable obsolete features that are not working or are not " "implemented in the client's UI"); ABSL_FLAG(bool, devmode, false, "Enable developer mode in the client's UI"); ABSL_FLAG(uint16_t, asio_port, 44766, "The service's Asio tcp_server port (use default value if unsure)"); ABSL_FLAG(uint16_t, grpc_port, 44765, "The service's GRPC server port (use default value if unsure)"); ABSL_FLAG(bool, local, false, "Connects to local instance of OrbitService"); // TODO: remove this once we deprecated legacy parameters static void ParseLegacyCommandLine(int argc, char* argv[], ApplicationOptions* options) { for (size_t i = 0; i < static_cast<size_t>(argc); ++i) { const char* arg = argv[i]; if (absl::StartsWith(arg, "gamelet:")) { ERROR( "the 'gamelet:<host>:<port>' option is deprecated and will be " "removed soon, please use -remote <host> instead."); options->asio_server_address = arg + std::strlen("gamelet:"); } } } using ServiceDeployManager = OrbitQt::ServiceDeployManager; using DeploymentConfiguration = OrbitQt::DeploymentConfiguration; using OrbitStartupWindow = OrbitQt::OrbitStartupWindow; using Error = OrbitQt::Error; using ScopedConnection = OrbitSshQt::ScopedConnection; using Ports = ServiceDeployManager::Ports; using SshCredentials = OrbitSsh::Credentials; using Context = OrbitSsh::Context; static outcome::result<Ports> DeployOrbitService( std::optional<ServiceDeployManager>& service_deploy_manager, const DeploymentConfiguration& deployment_configuration, Context* context, const SshCredentials& ssh_credentials, const Ports& remote_ports) { QProgressDialog progress_dialog{}; service_deploy_manager.emplace(deployment_configuration, context, ssh_credentials, remote_ports); QObject::connect(&progress_dialog, &QProgressDialog::canceled, &service_deploy_manager.value(), &ServiceDeployManager::Cancel); QObject::connect(&service_deploy_manager.value(), &ServiceDeployManager::statusMessage, &progress_dialog, &QProgressDialog::setLabelText); QObject::connect( &service_deploy_manager.value(), &ServiceDeployManager::statusMessage, [](const QString& msg) { LOG("Status message: %s", msg.toStdString()); }); return service_deploy_manager->Exec(); } static outcome::result<void> RunUiInstance( QApplication* app, std::optional<DeploymentConfiguration> deployment_configuration, Context* context, ApplicationOptions options) { std::optional<OrbitQt::ServiceDeployManager> service_deploy_manager; OUTCOME_TRY(result, [&]() -> outcome::result<std::tuple<Ports, QString>> { const Ports remote_ports{/*.asio_port =*/absl::GetFlag(FLAGS_asio_port), /*.grpc_port =*/absl::GetFlag(FLAGS_grpc_port)}; if (deployment_configuration) { OrbitStartupWindow sw{}; OUTCOME_TRY(result, sw.Run<OrbitSsh::Credentials>()); if (std::holds_alternative<OrbitSsh::Credentials>(result)) { // The user chose a remote profiling target. OUTCOME_TRY( tunnel_ports, DeployOrbitService(service_deploy_manager, deployment_configuration.value(), context, std::get<SshCredentials>(result), remote_ports)); return std::make_tuple(tunnel_ports, QString{}); } else { // The user chose to open a capture. return std::make_tuple(remote_ports, std::get<QString>(result)); } } else { // When the local flag is present return std::make_tuple(remote_ports, QString{}); } }()); const auto& [ports, capture_path] = result; options.asio_server_address = absl::StrFormat("127.0.0.1:%d", ports.asio_port); options.grpc_server_address = absl::StrFormat("127.0.0.1:%d", ports.grpc_port); OrbitMainWindow w(app, std::move(options)); w.showMaximized(); w.PostInit(); std::optional<std::error_code> error; auto error_handler = [&]() -> ScopedConnection { if (service_deploy_manager) { return OrbitSshQt::ScopedConnection{QObject::connect( &service_deploy_manager.value(), &ServiceDeployManager::socketErrorOccurred, &service_deploy_manager.value(), [&](std::error_code e) { error = e; w.close(); app->quit(); })}; } else { return ScopedConnection(); } }(); if (!capture_path.isEmpty()) { OUTCOME_TRY(w.OpenCapture(capture_path.toStdString())); } app->exec(); GOrbitApp->OnExit(); if (error) { return outcome::failure(error.value()); } else { return outcome::success(); } } static void StyleOrbit(QApplication& app) { QApplication::setStyle(QStyleFactory::create("Fusion")); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53, 53, 53)); darkPalette.setColor(QPalette::WindowText, Qt::white); darkPalette.setColor(QPalette::Base, QColor(25, 25, 25)); darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ToolTipBase, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ButtonText, Qt::white); darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218)); darkPalette.setColor(QPalette::HighlightedText, Qt::black); QColor light_gray{160, 160, 160}; QColor dark_gray{90, 90, 90}; QColor darker_gray{80, 80, 80}; darkPalette.setColor(QPalette::Disabled, QPalette::Window, dark_gray); darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Base, darker_gray); darkPalette.setColor(QPalette::Disabled, QPalette::AlternateBase, dark_gray); darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipBase, dark_gray); darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipText, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Text, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Button, darker_gray); darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::BrightText, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Link, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, dark_gray); QApplication::setPalette(darkPalette); app.setStyleSheet( "QToolTip { color: #ffffff; background-color: #2a82da; border: 1px " "solid white; }"); } static std::optional<OrbitQt::DeploymentConfiguration> FigureOutDeploymentConfiguration() { if (absl::GetFlag(FLAGS_local)) { return std::nullopt; } auto env = QProcessEnvironment::systemEnvironment(); const char* const kEnvExecutablePath = "ORBIT_COLLECTOR_EXECUTABLE_PATH"; const char* const kEnvRootPassword = "ORBIT_COLLECTOR_ROOT_PASSWORD"; const char* const kEnvPackagePath = "ORBIT_COLLECTOR_PACKAGE_PATH"; const char* const kEnvSignaturePath = "ORBIT_COLLECTOR_SIGNATURE_PATH"; const char* const kEnvNoDeployment = "ORBIT_COLLECTOR_NO_DEPLOYMENT"; if (env.contains(kEnvExecutablePath) && env.contains(kEnvRootPassword)) { return OrbitQt::BareExecutableAndRootPasswordDeployment{ env.value(kEnvExecutablePath).toStdString(), env.value(kEnvRootPassword).toStdString()}; } else if (env.contains(kEnvPackagePath) && env.contains(kEnvSignaturePath)) { return OrbitQt::SignedDebianPackageDeployment{ env.value(kEnvPackagePath).toStdString(), env.value(kEnvSignaturePath).toStdString()}; } else if (env.contains(kEnvNoDeployment)) { return OrbitQt::NoDeployment{}; } else { return OrbitQt::SignedDebianPackageDeployment{}; } } static void DisplayErrorToUser(const QString& message) { QMessageBox::critical(nullptr, QApplication::applicationName(), message); } int main(int argc, char* argv[]) { const std::string log_file_path = Path::GetLogFilePath(); InitLogFile(log_file_path); absl::SetProgramUsageMessage("CPU Profiler"); absl::ParseCommandLine(argc, argv); #if __linux__ QCoreApplication::setAttribute(Qt::AA_DontUseNativeDialogs); #endif OrbitGl::GlutContext glut_context{&argc, argv}; QApplication app(argc, argv); QCoreApplication::setApplicationName("Orbit Profiler [BETA]"); QCoreApplication::setApplicationVersion(OrbitQt::kVersionString); const std::string dump_path = Path::GetDumpPath(); #ifdef _WIN32 const char* handler_name = "crashpad_handler.exe"; #else const char* handler_name = "crashpad_handler"; #endif const std::string handler_path = QDir(QCoreApplication::applicationDirPath()) .absoluteFilePath(handler_name) .toStdString(); const std::string crash_server_url = CrashServerOptions::GetUrl(); const std::vector<std::string> attachments = {Path::GetLogFilePath()}; CrashHandler crash_handler(dump_path, handler_path, crash_server_url, attachments); ApplicationOptions options; ParseLegacyCommandLine(argc, argv, &options); StyleOrbit(app); const auto deployment_configuration = FigureOutDeploymentConfiguration(); const auto open_gl_version = OrbitQt::DetectOpenGlVersion(); if (!open_gl_version) { DisplayErrorToUser( "OpenGL support was not found. Please make sure you're not trying to " "start Orbit in a remote session and make sure you have a recent " "graphics driver installed. Then try again!"); return -1; } LOG("Detected OpenGL version: %i.%i", open_gl_version->major, open_gl_version->minor); if (open_gl_version->major < 2) { DisplayErrorToUser( QString( "The minimum required version of OpenGL is 2.0. But this machine " "only supports up to version %1.%2. Please make sure you're not " "trying to start Orbit in a remote session and make sure you have " "a recent graphics driver installed. Then try again!") .arg(open_gl_version->major) .arg(open_gl_version->minor)); return -1; } auto context = Context::Create(); if (!context) { DisplayErrorToUser( QString("An error occurred while initializing ssh: %1") .arg(QString::fromStdString(context.error().message()))); return -1; } while (true) { const auto result = RunUiInstance(&app, deployment_configuration, &(context.value()), options); if (result || result.error() == make_error_code(Error::kUserClosedStartUpWindow) || !deployment_configuration) { // It was either a clean shutdown or the deliberately closed the // dialog, or we started with the --local flag. return 0; } else if (result.error() == make_error_code(OrbitGgp::Error::kCouldNotUseGgpCli)) { DisplayErrorToUser(QString::fromStdString(result.error().message())); return 1; } else if (result.error() != make_error_code(Error::kUserCanceledServiceDeployment)) { DisplayErrorToUser( QString("An error occurred: %1") .arg(QString::fromStdString(result.error().message()))); } } } <commit_msg>Restart Orbit on error<commit_after>// Copyright (c) 2020 The Orbit 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 <absl/flags/flag.h> #include <absl/flags/parse.h> #include <absl/flags/usage.h> #include <QApplication> #include <QDir> #include <QFontDatabase> #include <QMessageBox> #include <QProcessEnvironment> #include <QProgressDialog> #include <QStyleFactory> #ifdef _WIN32 #include <process.h> #else #include <unistd.h> #endif #include "App.h" #include "ApplicationOptions.h" #include "CrashHandler.h" #include "CrashOptions.h" #include "Error.h" #include "GlutContext.h" #include "OrbitBase/Logging.h" #include "OrbitGgp/Error.h" #include "OrbitSsh/Context.h" #include "OrbitSsh/Credentials.h" #include "OrbitSshQt/Session.h" #include "OrbitStartupWindow.h" #include "Path.h" #include "deploymentconfigurations.h" #include "opengldetect.h" #include "orbitmainwindow.h" #include "servicedeploymanager.h" #include "version.h" ABSL_FLAG(bool, enable_stale_features, false, "Enable obsolete features that are not working or are not " "implemented in the client's UI"); ABSL_FLAG(bool, devmode, false, "Enable developer mode in the client's UI"); ABSL_FLAG(uint16_t, asio_port, 44766, "The service's Asio tcp_server port (use default value if unsure)"); ABSL_FLAG(uint16_t, grpc_port, 44765, "The service's GRPC server port (use default value if unsure)"); ABSL_FLAG(bool, local, false, "Connects to local instance of OrbitService"); // TODO: remove this once we deprecated legacy parameters static void ParseLegacyCommandLine(int argc, char* argv[], ApplicationOptions* options) { for (size_t i = 0; i < static_cast<size_t>(argc); ++i) { const char* arg = argv[i]; if (absl::StartsWith(arg, "gamelet:")) { ERROR( "the 'gamelet:<host>:<port>' option is deprecated and will be " "removed soon, please use -remote <host> instead."); options->asio_server_address = arg + std::strlen("gamelet:"); } } } using ServiceDeployManager = OrbitQt::ServiceDeployManager; using DeploymentConfiguration = OrbitQt::DeploymentConfiguration; using OrbitStartupWindow = OrbitQt::OrbitStartupWindow; using Error = OrbitQt::Error; using ScopedConnection = OrbitSshQt::ScopedConnection; using Ports = ServiceDeployManager::Ports; using SshCredentials = OrbitSsh::Credentials; using Context = OrbitSsh::Context; static outcome::result<Ports> DeployOrbitService( std::optional<ServiceDeployManager>& service_deploy_manager, const DeploymentConfiguration& deployment_configuration, Context* context, const SshCredentials& ssh_credentials, const Ports& remote_ports) { QProgressDialog progress_dialog{}; service_deploy_manager.emplace(deployment_configuration, context, ssh_credentials, remote_ports); QObject::connect(&progress_dialog, &QProgressDialog::canceled, &service_deploy_manager.value(), &ServiceDeployManager::Cancel); QObject::connect(&service_deploy_manager.value(), &ServiceDeployManager::statusMessage, &progress_dialog, &QProgressDialog::setLabelText); QObject::connect( &service_deploy_manager.value(), &ServiceDeployManager::statusMessage, [](const QString& msg) { LOG("Status message: %s", msg.toStdString()); }); return service_deploy_manager->Exec(); } static outcome::result<void> RunUiInstance( QApplication* app, std::optional<DeploymentConfiguration> deployment_configuration, Context* context, ApplicationOptions options) { std::optional<OrbitQt::ServiceDeployManager> service_deploy_manager; OUTCOME_TRY(result, [&]() -> outcome::result<std::tuple<Ports, QString>> { const Ports remote_ports{/*.asio_port =*/absl::GetFlag(FLAGS_asio_port), /*.grpc_port =*/absl::GetFlag(FLAGS_grpc_port)}; if (deployment_configuration) { OrbitStartupWindow sw{}; OUTCOME_TRY(result, sw.Run<OrbitSsh::Credentials>()); if (std::holds_alternative<OrbitSsh::Credentials>(result)) { // The user chose a remote profiling target. OUTCOME_TRY( tunnel_ports, DeployOrbitService(service_deploy_manager, deployment_configuration.value(), context, std::get<SshCredentials>(result), remote_ports)); return std::make_tuple(tunnel_ports, QString{}); } else { // The user chose to open a capture. return std::make_tuple(remote_ports, std::get<QString>(result)); } } else { // When the local flag is present return std::make_tuple(remote_ports, QString{}); } }()); const auto& [ports, capture_path] = result; options.asio_server_address = absl::StrFormat("127.0.0.1:%d", ports.asio_port); options.grpc_server_address = absl::StrFormat("127.0.0.1:%d", ports.grpc_port); OrbitMainWindow w(app, std::move(options)); w.showMaximized(); w.PostInit(); std::optional<std::error_code> error; auto error_handler = [&]() -> ScopedConnection { if (service_deploy_manager) { return OrbitSshQt::ScopedConnection{QObject::connect( &service_deploy_manager.value(), &ServiceDeployManager::socketErrorOccurred, &service_deploy_manager.value(), [&](std::error_code e) { error = e; w.close(); app->quit(); })}; } else { return ScopedConnection(); } }(); if (!capture_path.isEmpty()) { OUTCOME_TRY(w.OpenCapture(capture_path.toStdString())); } app->exec(); GOrbitApp->OnExit(); if (error) { return outcome::failure(error.value()); } else { return outcome::success(); } } static void StyleOrbit(QApplication& app) { QApplication::setStyle(QStyleFactory::create("Fusion")); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53, 53, 53)); darkPalette.setColor(QPalette::WindowText, Qt::white); darkPalette.setColor(QPalette::Base, QColor(25, 25, 25)); darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ToolTipBase, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ButtonText, Qt::white); darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218)); darkPalette.setColor(QPalette::HighlightedText, Qt::black); QColor light_gray{160, 160, 160}; QColor dark_gray{90, 90, 90}; QColor darker_gray{80, 80, 80}; darkPalette.setColor(QPalette::Disabled, QPalette::Window, dark_gray); darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Base, darker_gray); darkPalette.setColor(QPalette::Disabled, QPalette::AlternateBase, dark_gray); darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipBase, dark_gray); darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipText, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Text, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Button, darker_gray); darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::BrightText, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Link, light_gray); darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, dark_gray); QApplication::setPalette(darkPalette); app.setStyleSheet( "QToolTip { color: #ffffff; background-color: #2a82da; border: 1px " "solid white; }"); } static std::optional<OrbitQt::DeploymentConfiguration> FigureOutDeploymentConfiguration() { if (absl::GetFlag(FLAGS_local)) { return std::nullopt; } auto env = QProcessEnvironment::systemEnvironment(); const char* const kEnvExecutablePath = "ORBIT_COLLECTOR_EXECUTABLE_PATH"; const char* const kEnvRootPassword = "ORBIT_COLLECTOR_ROOT_PASSWORD"; const char* const kEnvPackagePath = "ORBIT_COLLECTOR_PACKAGE_PATH"; const char* const kEnvSignaturePath = "ORBIT_COLLECTOR_SIGNATURE_PATH"; const char* const kEnvNoDeployment = "ORBIT_COLLECTOR_NO_DEPLOYMENT"; if (env.contains(kEnvExecutablePath) && env.contains(kEnvRootPassword)) { return OrbitQt::BareExecutableAndRootPasswordDeployment{ env.value(kEnvExecutablePath).toStdString(), env.value(kEnvRootPassword).toStdString()}; } else if (env.contains(kEnvPackagePath) && env.contains(kEnvSignaturePath)) { return OrbitQt::SignedDebianPackageDeployment{ env.value(kEnvPackagePath).toStdString(), env.value(kEnvSignaturePath).toStdString()}; } else if (env.contains(kEnvNoDeployment)) { return OrbitQt::NoDeployment{}; } else { return OrbitQt::SignedDebianPackageDeployment{}; } } static void DisplayErrorToUser(const QString& message) { QMessageBox::critical(nullptr, QApplication::applicationName(), message); } int main(int argc, char* argv[]) { { const std::string log_file_path = Path::GetLogFilePath(); InitLogFile(log_file_path); absl::SetProgramUsageMessage("CPU Profiler"); absl::ParseCommandLine(argc, argv); #if __linux__ QCoreApplication::setAttribute(Qt::AA_DontUseNativeDialogs); #endif OrbitGl::GlutContext glut_context{&argc, argv}; QApplication app(argc, argv); QCoreApplication::setApplicationName("Orbit Profiler [BETA]"); QCoreApplication::setApplicationVersion(OrbitQt::kVersionString); const std::string dump_path = Path::GetDumpPath(); #ifdef _WIN32 const char* handler_name = "crashpad_handler.exe"; #else const char* handler_name = "crashpad_handler"; #endif const std::string handler_path = QDir(QCoreApplication::applicationDirPath()) .absoluteFilePath(handler_name) .toStdString(); const std::string crash_server_url = CrashServerOptions::GetUrl(); const std::vector<std::string> attachments = {Path::GetLogFilePath()}; CrashHandler crash_handler(dump_path, handler_path, crash_server_url, attachments); ApplicationOptions options; ParseLegacyCommandLine(argc, argv, &options); StyleOrbit(app); const auto deployment_configuration = FigureOutDeploymentConfiguration(); const auto open_gl_version = OrbitQt::DetectOpenGlVersion(); if (!open_gl_version) { DisplayErrorToUser( "OpenGL support was not found. Please make sure you're not trying to " "start Orbit in a remote session and make sure you have a recent " "graphics driver installed. Then try again!"); return -1; } LOG("Detected OpenGL version: %i.%i", open_gl_version->major, open_gl_version->minor); if (open_gl_version->major < 2) { DisplayErrorToUser( QString( "The minimum required version of OpenGL is 2.0. But this machine " "only supports up to version %1.%2. Please make sure you're not " "trying to start Orbit in a remote session and make sure you " "have a recent graphics driver installed. Then try again!") .arg(open_gl_version->major) .arg(open_gl_version->minor)); return -1; } auto context = Context::Create(); if (!context) { DisplayErrorToUser( QString("An error occurred while initializing ssh: %1") .arg(QString::fromStdString(context.error().message()))); return -1; } while (true) { const auto result = RunUiInstance(&app, deployment_configuration, &(context.value()), options); if (result || result.error() == make_error_code(Error::kUserClosedStartUpWindow) || !deployment_configuration) { // It was either a clean shutdown or the deliberately closed the // dialog, or we started with the --local flag. return 0; } else if (result.error() == make_error_code(OrbitGgp::Error::kCouldNotUseGgpCli)) { DisplayErrorToUser(QString::fromStdString(result.error().message())); return 1; } else if (result.error() != make_error_code(Error::kUserCanceledServiceDeployment)) { DisplayErrorToUser( QString("An error occurred: %1") .arg(QString::fromStdString(result.error().message()))); break; } } } execv(QCoreApplication::applicationFilePath().toUtf8().data(), argv); UNREACHABLE(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: Triangle.cc Language: C++ Date: $Date$ Version: $Revision$ Description: --------------------------------------------------------------------------- This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Triangle.hh" #include "Polygon.hh" #include "Plane.hh" #include "vlMath.hh" #include "CellArr.hh" #include "Line.hh" int vlTriangle::EvaluatePosition(float x[3], float closestPoint[3], int& subId, float pcoords[3], float& dist2, float weights[MAX_CELL_SIZE]) { int i, j; vlPolygon poly; float *pt1, *pt2, *pt3, n[3], xProj[3]; float rhs[2], c1[2], c2[2]; float closestPoint[3], det; vlPlane plane; vlMath math; float maxComponent; int idx, indices[2]; subId = 0; pcoords[0] = pcoords[1] = pcoords[2] = 0.0; // // Get normal for triangle // pt1 = this->Points.GetPoint(1); pt2 = this->Points.GetPoint(2); pt3 = this->Points.GetPoint(0); poly.ComputeNormal (pt1, pt2, pt3, n); // // Project point to plane // plane.ProjectPoint(x,pt1,n,xProj); // // Construct matrices. Since we have over determined system, need to find // which 2 out of 3 equations to use to develop equations. (Any 2 should // work since we've projected point to plane.) // for (maxComponent=0.0, i=0; i<3; i++) { if (n[i] > maxComponent) { maxComponent = n[i]; idx = i; } } for (j=0, i=0; i<3; i++) { if ( i != idx ) indices[j++] = i; } for (i=0; i<2; i++) { rhs[i] = xProj[indices[i]] - pt3[indices[i]]; c1[i] = pt1[indices[i]] - pt3[indices[i]]; c2[i] = pt2[indices[i]] - pt3[indices[i]]; } if ( (det = math.Determinate2x2(c1,c2)) == 0.0 ) return 0; pcoords[0] = math.Determinate2x2 (rhs,c2) / det; pcoords[1] = math.Determinate2x2 (c1,rhs) / det; pcoords[2] = 1.0 - pcoords[0] - pcoords[1]; // // Okay, now find closest point to element // if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 && pcoords[1] >= 0.0 && pcoords[1] <= 1.0 && pcoords[2] >= 0.0 && pcoords[2] <= 1.0 ) { dist2 = math.Distance2BetweenPoints(xProj,x); //projection distance weights[0] = pcoords[2]; weights[1] = pcoords[0]; weights[2] = pcoords[1]; return 1; } else { for (i=0; i<2; i++) { if (pcoords[i] < 0.0) pcoords[i] = 0.0; if (pcoords[i] > 1.0) pcoords[i] = 1.0; } if ( (1.0 - pcoords[0] - pcoords[1]) < 0.0 ) { float ratio = pcoords[0]/pcoords[1]; pcoords[1] = 1.0 / (1.0 + ratio); pcoords[0] = ratio * pcoords[1]; } this->EvaluateLocation(subId, pcoords, closestPoint, weights); dist2 = math.Distance2BetweenPoints(closestPoint,x); return 0; } } void vlTriangle::EvaluateLocation(int& subId, float pcoords[3], float x[3], float weights[MAX_CELL_SIZE]) { float u3; float *pt1, *pt2, *pt3; int i; pt1 = this->Points.GetPoint(1); pt2 = this->Points.GetPoint(2); pt3 = this->Points.GetPoint(0); u3 = 1.0 - pcoords[0] - pcoords[1]; for (i=0; i<3; i++) { x[i] = pt1[i]*pcoords[0] + pt2[i]*pcoords[1] + pt3[i]*u3; } weights[0] = u3; weights[1] = pcoords[0]; weights[2] = pcoords[1]; } // // Marching triangles // typedef int EDGE_LIST; typedef struct { EDGE_LIST edges[3]; } LINE_CASES; static LINE_CASES lineCases[] = { {-1, -1, -1}, {0, 2, -1}, {1, 0, -1}, {1, 2, -1}, {2, 1, -1}, {0, 1, -1}, {2, 0, -1}, {-1, -1, -1} }; void vlTriangle::Contour(float value, vlFloatScalars *cellScalars, vlFloatPoints *points, vlCellArray *verts, vlCellArray *lines, vlCellArray *polys, vlFloatScalars *scalars) { static int CASE_MASK[3] = {1,2,4}; LINE_CASES *lineCase; EDGE_LIST *edge; int i, j, index, *vert; static int edges[3][2] = { {0,1}, {1,2}, {2,0} }; int pts[2]; float t, *x1, *x2, x[3]; // Build the case table for ( i=0, index = 0; i < 3; i++) if (cellScalars->GetScalar(i) >= value) index |= CASE_MASK[i]; lineCase = lineCases + index; edge = lineCase->edges; for ( ; edge[0] > -1; edge += 2 ) { for (i=0; i<2; i++) // insert line { vert = edges[edge[i]]; t = (value - cellScalars->GetScalar(vert[0])) / (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0])); x1 = this->Points.GetPoint(vert[0]); x2 = this->Points.GetPoint(vert[1]); for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]); pts[i] = points->InsertNextPoint(x); scalars->InsertNextScalar(value); } lines->InsertNextCell(2,pts); } } vlCell *vlTriangle::GetEdge(int edgeId) { static vlLine line; // load point id's line.PointIds.SetId(0,this->PointIds.GetId(edgeId)); line.PointIds.SetId(1,this->PointIds.GetId((edgeId+1) % 3)); // load coordinates line.Points.SetPoint(0,this->Points.GetPoint(edgeId)); line.Points.SetPoint(1,this->Points.GetPoint((edgeId+1) % 3)); return &line; } <commit_msg>*** empty log message ***<commit_after>/*========================================================================= Program: Visualization Library Module: Triangle.cc Language: C++ Date: $Date$ Version: $Revision$ Description: --------------------------------------------------------------------------- This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Triangle.hh" #include "Polygon.hh" #include "Plane.hh" #include "vlMath.hh" #include "CellArr.hh" #include "Line.hh" int vlTriangle::EvaluatePosition(float x[3], float closestPoint[3], int& subId, float pcoords[3], float& dist2, float weights[MAX_CELL_SIZE]) { int i, j; vlPolygon poly; float *pt1, *pt2, *pt3, n[3]; float rhs[2], c1[2], c2[2]; float det; vlPlane plane; vlMath math; float maxComponent; int idx, indices[2]; subId = 0; pcoords[0] = pcoords[1] = pcoords[2] = 0.0; // // Get normal for triangle // pt1 = this->Points.GetPoint(1); pt2 = this->Points.GetPoint(2); pt3 = this->Points.GetPoint(0); poly.ComputeNormal (pt1, pt2, pt3, n); // // Project point to plane // plane.ProjectPoint(x,pt1,n,closestPoint); // // Construct matrices. Since we have over determined system, need to find // which 2 out of 3 equations to use to develop equations. (Any 2 should // work since we've projected point to plane.) // for (maxComponent=0.0, i=0; i<3; i++) { if (n[i] > maxComponent) { maxComponent = n[i]; idx = i; } } for (j=0, i=0; i<3; i++) { if ( i != idx ) indices[j++] = i; } for (i=0; i<2; i++) { rhs[i] = closestPoint[indices[i]] - pt3[indices[i]]; c1[i] = pt1[indices[i]] - pt3[indices[i]]; c2[i] = pt2[indices[i]] - pt3[indices[i]]; } if ( (det = math.Determinate2x2(c1,c2)) == 0.0 ) return 0; pcoords[0] = math.Determinate2x2 (rhs,c2) / det; pcoords[1] = math.Determinate2x2 (c1,rhs) / det; pcoords[2] = 1.0 - pcoords[0] - pcoords[1]; // // Okay, now find closest point to element // if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 && pcoords[1] >= 0.0 && pcoords[1] <= 1.0 && pcoords[2] >= 0.0 && pcoords[2] <= 1.0 ) { dist2 = math.Distance2BetweenPoints(closestPoint,x); //projection distance weights[0] = pcoords[2]; weights[1] = pcoords[0]; weights[2] = pcoords[1]; return 1; } else { for (i=0; i<2; i++) { if (pcoords[i] < 0.0) pcoords[i] = 0.0; if (pcoords[i] > 1.0) pcoords[i] = 1.0; } if ( (1.0 - pcoords[0] - pcoords[1]) < 0.0 ) { float ratio = pcoords[0]/pcoords[1]; pcoords[1] = 1.0 / (1.0 + ratio); pcoords[0] = ratio * pcoords[1]; } this->EvaluateLocation(subId, pcoords, closestPoint, weights); dist2 = math.Distance2BetweenPoints(closestPoint,x); return 0; } } void vlTriangle::EvaluateLocation(int& subId, float pcoords[3], float x[3], float weights[MAX_CELL_SIZE]) { float u3; float *pt1, *pt2, *pt3; int i; pt1 = this->Points.GetPoint(1); pt2 = this->Points.GetPoint(2); pt3 = this->Points.GetPoint(0); u3 = 1.0 - pcoords[0] - pcoords[1]; for (i=0; i<3; i++) { x[i] = pt1[i]*pcoords[0] + pt2[i]*pcoords[1] + pt3[i]*u3; } weights[0] = u3; weights[1] = pcoords[0]; weights[2] = pcoords[1]; } // // Marching triangles // typedef int EDGE_LIST; typedef struct { EDGE_LIST edges[3]; } LINE_CASES; static LINE_CASES lineCases[] = { {-1, -1, -1}, {0, 2, -1}, {1, 0, -1}, {1, 2, -1}, {2, 1, -1}, {0, 1, -1}, {2, 0, -1}, {-1, -1, -1} }; void vlTriangle::Contour(float value, vlFloatScalars *cellScalars, vlFloatPoints *points, vlCellArray *verts, vlCellArray *lines, vlCellArray *polys, vlFloatScalars *scalars) { static int CASE_MASK[3] = {1,2,4}; LINE_CASES *lineCase; EDGE_LIST *edge; int i, j, index, *vert; static int edges[3][2] = { {0,1}, {1,2}, {2,0} }; int pts[2]; float t, *x1, *x2, x[3]; // Build the case table for ( i=0, index = 0; i < 3; i++) if (cellScalars->GetScalar(i) >= value) index |= CASE_MASK[i]; lineCase = lineCases + index; edge = lineCase->edges; for ( ; edge[0] > -1; edge += 2 ) { for (i=0; i<2; i++) // insert line { vert = edges[edge[i]]; t = (value - cellScalars->GetScalar(vert[0])) / (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0])); x1 = this->Points.GetPoint(vert[0]); x2 = this->Points.GetPoint(vert[1]); for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]); pts[i] = points->InsertNextPoint(x); scalars->InsertNextScalar(value); } lines->InsertNextCell(2,pts); } } vlCell *vlTriangle::GetEdge(int edgeId) { static vlLine line; // load point id's line.PointIds.SetId(0,this->PointIds.GetId(edgeId)); line.PointIds.SetId(1,this->PointIds.GetId((edgeId+1) % 3)); // load coordinates line.Points.SetPoint(0,this->Points.GetPoint(edgeId)); line.Points.SetPoint(1,this->Points.GetPoint((edgeId+1) % 3)); return &line; } <|endoftext|>
<commit_before>/* * Copyright 2011-2017 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include "common.h" #include "bgfx_utils.h" #include "imgui/imgui.h" namespace { struct PosColorVertex { float m_x; float m_y; float m_z; uint32_t m_abgr; static void init() { ms_decl .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true) .end(); }; static bgfx::VertexDecl ms_decl; }; bgfx::VertexDecl PosColorVertex::ms_decl; static PosColorVertex s_cubeVertices[8] = { {-1.0f, 1.0f, 1.0f, 0xff000000 }, { 1.0f, 1.0f, 1.0f, 0xff0000ff }, {-1.0f, -1.0f, 1.0f, 0xff00ff00 }, { 1.0f, -1.0f, 1.0f, 0xff00ffff }, {-1.0f, 1.0f, -1.0f, 0xffff0000 }, { 1.0f, 1.0f, -1.0f, 0xffff00ff }, {-1.0f, -1.0f, -1.0f, 0xffffff00 }, { 1.0f, -1.0f, -1.0f, 0xffffffff }, }; static const uint16_t s_cubeIndices[36] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 0, 2, 4, // 4 4, 2, 6, 1, 5, 3, // 6 5, 7, 3, 0, 4, 1, // 8 4, 5, 1, 2, 3, 6, // 10 6, 3, 7, }; class ExampleInstancing : public entry::AppI { public: ExampleInstancing(const char* _name, const char* _description) : entry::AppI(_name, _description) { } void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override { Args args(_argc, _argv); m_width = _width; m_height = _height; m_debug = BGFX_DEBUG_NONE; m_reset = BGFX_RESET_VSYNC; bgfx::init(args.m_type, args.m_pciId); bgfx::reset(m_width, m_height, m_reset); // Enable debug text. bgfx::setDebug(m_debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); // Create vertex stream declaration. PosColorVertex::init(); // Create static vertex buffer. m_vbh = bgfx::createVertexBuffer( bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ) , PosColorVertex::ms_decl ); // Create static index buffer. m_ibh = bgfx::createIndexBuffer( bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) ); // Create program from shaders. m_program = loadProgram("vs_instancing", "fs_instancing"); m_timeOffset = bx::getHPCounter(); imguiCreate(); } int shutdown() override { imguiDestroy(); // Cleanup. bgfx::destroy(m_ibh); bgfx::destroy(m_vbh); bgfx::destroy(m_program); // Shutdown bgfx. bgfx::shutdown(); return 0; } bool update() override { if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) ) { imguiBeginFrame(m_mouseState.m_mx , m_mouseState.m_my , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , m_mouseState.m_mz , uint16_t(m_width) , uint16_t(m_height) ); showExampleDialog(this); imguiEndFrame(); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) ); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::touch(0); float time = (float)( (bx::getHPCounter() - m_timeOffset)/double(bx::getHPFrequency() ) ); // Get renderer capabilities info. const bgfx::Caps* caps = bgfx::getCaps(); // Check if instancing is supported. if (0 == (BGFX_CAPS_INSTANCING & caps->supported) ) { // When instancing is not supported by GPU, implement alternative // code path that doesn't use instancing. bool blink = uint32_t(time*3.0f)&1; bgfx::dbgTextPrintf(0, 0, blink ? 0x1f : 0x01, " Instancing is not supported by GPU. "); } else { float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -35.0f }; // Set view and projection matrix for view 0. const bgfx::HMD* hmd = bgfx::getHMD(); if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) ) { float view[16]; bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye); bgfx::setViewTransform(0, view, hmd->eye[0].projection, BGFX_VIEW_STEREO, hmd->eye[1].projection); // Set view 0 default viewport. // // Use HMD's width/height since HMD's internal frame buffer size // might be much larger than window size. bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height); } else { float view[16]; bx::mtxLookAt(view, eye, at); float proj[16]; bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth); bgfx::setViewTransform(0, view, proj); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) ); } const uint16_t instanceStride = 80; const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(121, instanceStride); if (NULL != idb) { uint8_t* data = idb->data; // Write instance data for 11x11 cubes. for (uint32_t yy = 0, numInstances = 0; yy < 11 && numInstances < idb->num; ++yy) { for (uint32_t xx = 0; xx < 11 && numInstances < idb->num; ++xx, ++numInstances) { float* mtx = (float*)data; bx::mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f); mtx[12] = -15.0f + float(xx)*3.0f; mtx[13] = -15.0f + float(yy)*3.0f; mtx[14] = 0.0f; float* color = (float*)&data[64]; color[0] = bx::fsin(time+float(xx)/11.0f)*0.5f+0.5f; color[1] = bx::fcos(time+float(yy)/11.0f)*0.5f+0.5f; color[2] = bx::fsin(time*3.0f)*0.5f+0.5f; color[3] = 1.0f; data += instanceStride; } } // Set vertex and index buffer. bgfx::setVertexBuffer(0, m_vbh); bgfx::setIndexBuffer(m_ibh); // Set instance data buffer. bgfx::setInstanceDataBuffer(idb); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0, m_program); } } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); return true; } return false; } entry::MouseState m_mouseState; uint32_t m_width; uint32_t m_height; uint32_t m_debug; uint32_t m_reset; bgfx::VertexBufferHandle m_vbh; bgfx::IndexBufferHandle m_ibh; bgfx::ProgramHandle m_program; int64_t m_timeOffset; }; } // namespace ENTRY_IMPLEMENT_MAIN(ExampleInstancing, "05-instancing", "Geometry instancing."); <commit_msg>Cleanup.<commit_after>/* * Copyright 2011-2017 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include "common.h" #include "bgfx_utils.h" #include "imgui/imgui.h" namespace { struct PosColorVertex { float m_x; float m_y; float m_z; uint32_t m_abgr; static void init() { ms_decl .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true) .end(); }; static bgfx::VertexDecl ms_decl; }; bgfx::VertexDecl PosColorVertex::ms_decl; static PosColorVertex s_cubeVertices[8] = { {-1.0f, 1.0f, 1.0f, 0xff000000 }, { 1.0f, 1.0f, 1.0f, 0xff0000ff }, {-1.0f, -1.0f, 1.0f, 0xff00ff00 }, { 1.0f, -1.0f, 1.0f, 0xff00ffff }, {-1.0f, 1.0f, -1.0f, 0xffff0000 }, { 1.0f, 1.0f, -1.0f, 0xffff00ff }, {-1.0f, -1.0f, -1.0f, 0xffffff00 }, { 1.0f, -1.0f, -1.0f, 0xffffffff }, }; static const uint16_t s_cubeIndices[36] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 0, 2, 4, // 4 4, 2, 6, 1, 5, 3, // 6 5, 7, 3, 0, 4, 1, // 8 4, 5, 1, 2, 3, 6, // 10 6, 3, 7, }; class ExampleInstancing : public entry::AppI { public: ExampleInstancing(const char* _name, const char* _description) : entry::AppI(_name, _description) { } void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override { Args args(_argc, _argv); m_width = _width; m_height = _height; m_debug = BGFX_DEBUG_NONE; m_reset = BGFX_RESET_VSYNC; bgfx::init(args.m_type, args.m_pciId); bgfx::reset(m_width, m_height, m_reset); // Enable debug text. bgfx::setDebug(m_debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); // Create vertex stream declaration. PosColorVertex::init(); // Create static vertex buffer. m_vbh = bgfx::createVertexBuffer( bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ) , PosColorVertex::ms_decl ); // Create static index buffer. m_ibh = bgfx::createIndexBuffer( bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) ); // Create program from shaders. m_program = loadProgram("vs_instancing", "fs_instancing"); m_timeOffset = bx::getHPCounter(); imguiCreate(); } int shutdown() override { imguiDestroy(); // Cleanup. bgfx::destroy(m_ibh); bgfx::destroy(m_vbh); bgfx::destroy(m_program); // Shutdown bgfx. bgfx::shutdown(); return 0; } bool update() override { if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) ) { imguiBeginFrame(m_mouseState.m_mx , m_mouseState.m_my , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , m_mouseState.m_mz , uint16_t(m_width) , uint16_t(m_height) ); showExampleDialog(this); imguiEndFrame(); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) ); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::touch(0); float time = (float)( (bx::getHPCounter() - m_timeOffset)/double(bx::getHPFrequency() ) ); // Get renderer capabilities info. const bgfx::Caps* caps = bgfx::getCaps(); // Check if instancing is supported. if (0 == (BGFX_CAPS_INSTANCING & caps->supported) ) { // When instancing is not supported by GPU, implement alternative // code path that doesn't use instancing. bool blink = uint32_t(time*3.0f)&1; bgfx::dbgTextPrintf(0, 0, blink ? 0x1f : 0x01, " Instancing is not supported by GPU. "); } else { float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -35.0f }; // Set view and projection matrix for view 0. const bgfx::HMD* hmd = bgfx::getHMD(); if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) ) { float view[16]; bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye); bgfx::setViewTransform(0, view, hmd->eye[0].projection, BGFX_VIEW_STEREO, hmd->eye[1].projection); // Set view 0 default viewport. // // Use HMD's width/height since HMD's internal frame buffer size // might be much larger than window size. bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height); } else { float view[16]; bx::mtxLookAt(view, eye, at); float proj[16]; bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth); bgfx::setViewTransform(0, view, proj); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) ); } // 80 bytes stride = 64 bytes for 4x4 matrix + 16 bytes for RGBA color. const uint16_t instanceStride = 80; const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(121, instanceStride); if (NULL != idb) { uint8_t* data = idb->data; // Write instance data for 11x11 cubes. for (uint32_t yy = 0, numInstances = 0; yy < 11 && numInstances < idb->num; ++yy) { for (uint32_t xx = 0; xx < 11 && numInstances < idb->num; ++xx, ++numInstances) { float* mtx = (float*)data; bx::mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f); mtx[12] = -15.0f + float(xx)*3.0f; mtx[13] = -15.0f + float(yy)*3.0f; mtx[14] = 0.0f; float* color = (float*)&data[64]; color[0] = bx::fsin(time+float(xx)/11.0f)*0.5f+0.5f; color[1] = bx::fcos(time+float(yy)/11.0f)*0.5f+0.5f; color[2] = bx::fsin(time*3.0f)*0.5f+0.5f; color[3] = 1.0f; data += instanceStride; } } // Set vertex and index buffer. bgfx::setVertexBuffer(0, m_vbh); bgfx::setIndexBuffer(m_ibh); // Set instance data buffer. bgfx::setInstanceDataBuffer(idb); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0, m_program); } } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); return true; } return false; } entry::MouseState m_mouseState; uint32_t m_width; uint32_t m_height; uint32_t m_debug; uint32_t m_reset; bgfx::VertexBufferHandle m_vbh; bgfx::IndexBufferHandle m_ibh; bgfx::ProgramHandle m_program; int64_t m_timeOffset; }; } // namespace ENTRY_IMPLEMENT_MAIN(ExampleInstancing, "05-instancing", "Geometry instancing."); <|endoftext|>
<commit_before>/* ** Copyright 2011-2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <exception> #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/notification/node_cache.hh" using namespace com::centreon::broker::notification; node_cache::node_cache() {} node_cache::node_cache(node_cache const& obj) { node_cache::operator=(obj); } node_cache& node_cache::operator=(node_cache const& obj) { if (this != &obj) { _service_statuses = obj._service_statuses; _host_statuses = obj._host_statuses; } return (*this); } bool node_cache::load(std::string const& cache_file) { logging::debug(logging::low) << "Notification: loading the node cache " << cache_file <<"."; // Create the streams. misc::shared_ptr<file::stream> file(new file::stream(cache_file)); misc::shared_ptr<compression::stream> compression(new compression::stream(9)); misc::shared_ptr<bbdo::stream> bbdo(new bbdo::stream(true, false)); // Connect the streams. file->process(true, false); compression->process(true, false); compression->read_from(file); bbdo->read_from(compression); misc::shared_ptr<io::data> data; try { while (true) { bbdo->read(data); write(data); } } catch (io::exceptions::shutdown) { // Normal termination of the stream (ie nothing to read anymore) logging::debug(logging::low) << "Notification: finished loading the node cache " << cache_file << " succesfully."; } catch (std::exception e) { // Abnormal termination of the stream. logging::error(logging::high) << "Notification: could not load the node cache " << cache_file << ": " << e.what(); return (false); } return (true); } bool node_cache::unload(std::string const& cache_file) { // Create the streams. misc::shared_ptr<file::stream> file(new file::stream(cache_file)); misc::shared_ptr<compression::stream> compression(new compression::stream(9)); misc::shared_ptr<bbdo::stream> bbdo(new bbdo::stream(false, true)); // Connect the streams. file->process(false, true); compression->process(false, true); compression->write_to(file); bbdo->write_to(compression); misc::shared_ptr<io::data> data; try { while (true) { bbdo->read(data); write(data); } } catch (io::exceptions::shutdown) { // Normal termination of the stream (ie nothing to write anymore) logging::debug(logging::low) << "Notification: finished writing the node cache " << cache_file << " succesfully."; } catch (std::exception e) { // Abnormal termination of the stream. logging::error(logging::high) << "Notification: could not write the node cache " << cache_file << ": " << e.what(); return (false); } return (true); } void node_cache::process(bool in, bool out) { (void)in; (void)out; } void node_cache::read(misc::shared_ptr<io::data> &d) { //if (!_process_out) throw (io::exceptions::shutdown(true, true) << "Node cache is empty"); } unsigned int node_cache::write(const misc::shared_ptr<io::data> &d) { // Check that data exists. unsigned int retval(1); if (data.isNull()) return 1; unsigned int type(data->type()); unsigned short cat(io::events::category_of_type(type)); unsigned short elem(io::events::element_of_type(type)); } <commit_msg>Notification: Fix compilation.<commit_after>/* ** Copyright 2011-2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <exception> #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/notification/node_cache.hh" using namespace com::centreon::broker::notification; node_cache::node_cache() {} node_cache::node_cache(node_cache const& obj) { node_cache::operator=(obj); } node_cache& node_cache::operator=(node_cache const& obj) { if (this != &obj) { _service_statuses = obj._service_statuses; _host_statuses = obj._host_statuses; } return (*this); } bool node_cache::load(std::string const& cache_file) { logging::debug(logging::low) << "Notification: loading the node cache " << cache_file <<"."; // Create the streams. misc::shared_ptr<file::stream> file(new file::stream(cache_file)); misc::shared_ptr<compression::stream> compression(new compression::stream(9)); misc::shared_ptr<bbdo::stream> bbdo(new bbdo::stream(true, false)); // Connect the streams. file->process(true, false); compression->process(true, false); compression->read_from(file); bbdo->read_from(compression); misc::shared_ptr<io::data> data; try { while (true) { bbdo->read(data); write(data); } } catch (io::exceptions::shutdown) { // Normal termination of the stream (ie nothing to read anymore) logging::debug(logging::low) << "Notification: finished loading the node cache " << cache_file << " succesfully."; } catch (std::exception e) { // Abnormal termination of the stream. logging::error(logging::high) << "Notification: could not load the node cache " << cache_file << ": " << e.what(); return (false); } return (true); } bool node_cache::unload(std::string const& cache_file) { // Create the streams. misc::shared_ptr<file::stream> file(new file::stream(cache_file)); misc::shared_ptr<compression::stream> compression(new compression::stream(9)); misc::shared_ptr<bbdo::stream> bbdo(new bbdo::stream(false, true)); // Connect the streams. file->process(false, true); compression->process(false, true); compression->write_to(file); bbdo->write_to(compression); misc::shared_ptr<io::data> data; try { while (true) { bbdo->read(data); write(data); } } catch (io::exceptions::shutdown) { // Normal termination of the stream (ie nothing to write anymore) logging::debug(logging::low) << "Notification: finished writing the node cache " << cache_file << " succesfully."; } catch (std::exception e) { // Abnormal termination of the stream. logging::error(logging::high) << "Notification: could not write the node cache " << cache_file << ": " << e.what(); return (false); } return (true); } void node_cache::process(bool in, bool out) { (void)in; (void)out; } void node_cache::read(misc::shared_ptr<io::data> &d) { //if (!_process_out) throw (io::exceptions::shutdown(true, true) << "Node cache is empty"); } unsigned int node_cache::write(const misc::shared_ptr<io::data> &data) { // Check that data exists. unsigned int retval(1); if (data.isNull()) return 1; unsigned int type(data->type()); unsigned short cat(io::events::category_of_type(type)); unsigned short elem(io::events::element_of_type(type)); } <|endoftext|>
<commit_before>/* ** See Copyright Notice in LICENSE. **/ #include "luno.hxx" #include <cppuhelper/typeprovider.hxx> #include <com/sun/star/beans/MethodConcept.hpp> #include <com/sun/star/reflection/ParamMode.hpp> using com::sun::star::beans::UnknownPropertyException; using com::sun::star::beans::XIntrospectionAccess; using namespace com::sun::star::lang; using namespace com::sun::star::reflection; using namespace com::sun::star::script; using namespace com::sun::star::uno; using namespace rtl; #define OUSTRTOASCII(s) OUStringToOString(s, RTL_TEXTENCODING_ASCII_US).getStr() #define LUNO_ADAPTER_PUSH_WRAPPED(ref) \ LUNO_PUSH_REG_WRAPPED(); \ lua_rawgeti(L, -1, ref); \ lua_replace(L, -2) #define LUNO_ADAPTER_PUSH_ADAPTERS(ref) \ LUNO_PUSH_REG_ADAPTERS(); \ lua_rawgeti(L, -1, ref); \ lua_replace(L, -2) namespace luno { /** Wraps table at index. */ LunoAdapter::LunoAdapter(lua_State *L_, const int index, const Any &aTypes, const Any &aImpleId) : L(L_), m_WrappedRef(0), m_AdapterRef(0), m_Types(aTypes), m_ImpleId(aImpleId) { const int top = lua_gettop(L); // push wrapped value to wrapped LUNO_PUSH_REG_WRAPPED(); lua_pushvalue(L, index); m_WrappedRef = luaL_ref(L, -2); LUNO_PUSH_REG_ADAPTERS(); lua_pushlightuserdata(L, this); m_AdapterRef = luaL_ref(L, -2); lua_settop(L, top); } LunoAdapter::~LunoAdapter() { const int top = lua_gettop(L); if (m_WrappedRef) { LUNO_PUSH_REG_WRAPPED(); luaL_unref(L, -1, m_WrappedRef); m_WrappedRef = 0; } if (m_AdapterRef) { LUNO_PUSH_REG_ADAPTERS(); luaL_unref(L, -1, m_AdapterRef); m_AdapterRef = 0; } lua_settop(L, top); } LunoAdapter *LunoAdapter::create(lua_State *L_, const int index, const Sequence< Type > &aTypes, const Sequence< sal_Int8 > &aImpleId) { // ToDo get types and id at first request Any aTypes_; Any aImpleId_; aTypes_ <<= aTypes; aImpleId_ <<= aImpleId; return new LunoAdapter(L_, index, aTypes_, aImpleId_); } Sequence< sal_Int16 > LunoAdapter::getOutParamIndexes(const OUString &aName) throw (RuntimeException) { Sequence< sal_Int16 > ret; Runtime runtime; Reference< XInterface > rAdapter( runtime.getImple()->xAdapterFactory->createAdapter(this, getWrappedTypes())); Reference< XIntrospectionAccess > xIntrospectionAcc( runtime.getImple()->xIntrospection->inspect(makeAny(rAdapter))); if (!xIntrospectionAcc.is()) throw RuntimeException( OUSTRCONST("Failed to create adapter."), Reference< XInterface >()); Reference< XIdlMethod > xIdlMethod( xIntrospectionAcc->getMethod(aName, com::sun::star::beans::MethodConcept::ALL)); if (!xIdlMethod.is()) throw RuntimeException( OUSTRCONST("Failed to get reflection for ") + aName, Reference< XInterface >()); const Sequence< ParamInfo > aInfos(xIdlMethod->getParameterInfos()); const ParamInfo *pInfos = aInfos.getConstArray(); const int length = aInfos.getLength(); int out = 0; int i = 0; for (i = 0; i < length; ++i) { if (pInfos[i].aMode != ParamMode_IN) ++out; } if (out) { sal_Int16 j = 0; ret.realloc(out); sal_Int16 *pOutIndexes = ret.getArray(); for (i = 0; i < length; ++i) { if (pInfos[i].aMode != ParamMode_IN) { pOutIndexes[j] = i; ++j; } } } return ret; } Reference< XIntrospectionAccess > LunoAdapter::getIntrospection() throw (RuntimeException) { return Reference< XIntrospectionAccess >(); } Sequence< Type > LunoAdapter::getWrappedTypes() const { Sequence< Type > aTypes; m_Types >>= aTypes; return aTypes; } // Call lua_gettable in safe mode static int luno_gettable(lua_State *L) { // 1: table, 2: key lua_pushvalue(L, 2); // key lua_gettable(L, 1); return 1; } #define THROW_ON_ERROR(error) \ if (error) \ { \ size_t length; \ const char *message = lua_tolstring(L, -1, &length); \ const OUString aMessage(message, length, RTL_TEXTENCODING_UTF8); \ lua_pop(L, 1); \ throw RuntimeException(aMessage, Reference< XInterface >()); \ } #define CHECK_WRAPPED(ref) \ if (!ref) \ throw RuntimeException(OUSTRCONST("Nothing wrapped"), Reference< XInterface >()) Any LunoAdapter::invoke(const OUString &aName, const Sequence< Any > &aParams, Sequence< sal_Int16 > &aOutParamIndex, Sequence< Any > &aOutParam) throw (IllegalArgumentException, CannotConvertException, InvocationTargetException, RuntimeException) { static const OUString aNameGetSomething(RTL_CONSTASCII_USTRINGPARAM("getSomething")); static const OUString aNameGetTypes(RTL_CONSTASCII_USTRINGPARAM("getTypes")); static const OUString aNameGetImplementationId(RTL_CONSTASCII_USTRINGPARAM("getImplementationId")); const int nParams = (int)aParams.getLength(); if (!nParams) { // return cached value if (aName.equals(aNameGetTypes)) return m_Types; else if (aName.equals(aNameGetImplementationId)) return m_ImpleId; } else if (nParams == 1 && aName.equals(aNameGetSomething)) { Sequence< sal_Int8 > id; if (aParams[0] >>= id) return makeAny(getSomething(id)); } Any retAny; const int top = lua_gettop(L); try { CHECK_WRAPPED(m_WrappedRef); Runtime runtime; LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); // reuse // find function to call with error checking lua_pushcfunction(L, luno_gettable); lua_pushvalue(L, -2); // wrapped lua_pushstring(L, OUSTRTOASCII(aName)); const int e = lua_pcall(L, 2, 1, 0); THROW_ON_ERROR(e); if (!lua_isfunction(L, -1)) { // ToDo check is callable? lua_settop(L, top); throw RuntimeException( OUSTRCONST("Method not found: ") + aName, Reference< XInterface >()); } lua_insert(L, top + 1); // wrapped - func -> func - wrapped // push arguments const Any *pParams = aParams.getConstArray(); for (int i = 0; i < nParams; ++i) runtime.anyToLua(L, pParams[i]); // call, obj + params, var args const int error = lua_pcall(L, nParams + 1, LUA_MULTRET, 0); if (error) { // ToDo test throw exception from Lua if (error == LUA_ERRRUN) { if (lua_isuserdata(L, -1)) { LunoAdapted *p = luno_proxy_getudata(L, -1, LUNO_META_STRUCT); if (p != NULL && p->Wrapped.getValueTypeClass() == TypeClass_EXCEPTION) { lua_settop(L, top); throw InvocationTargetException(OUString(), Reference< XInterface >(), p->Wrapped); } } size_t length; const char *message = lua_tolstring(L, -1, &length); throw RuntimeException(OUString(message, length, RTL_TEXTENCODING_UTF8), Reference< XInterface >()); } else { // ToDo LUA_ERRGCMM size_t length; const char *s = lua_tolstring(L, -1, &length); throw RuntimeException( OUString(s, length, RTL_TEXTENCODING_UTF8), Reference< XInterface >()); } } // ignore normal return value and wrapped obj const int nOut = lua_gettop(L) - top - 1; if (lua_gettop(L) - top > 0) retAny = runtime.luaToAny(L, top + 1); if (nOut > 1) { aOutParamIndex = getOutParamIndexes(aName); const int nOutParams = (int)aOutParamIndex.getLength(); if (nOut != nOutParams) throw RuntimeException( OUSTRCONST("luno: illegal number of out values for method: ") + aName, Reference< XInterface >()); aOutParam.realloc(nOutParams); for (int i = 0; i < nOutParams; ++i) aOutParam[i] = runtime.luaToAny(L, top + 1 + i); } lua_settop(L, top); } catch (RuntimeException &e) { lua_settop(L, top); throw; } return retAny; } // Call lua_settable in safe mode static int luno_settable(lua_State *L) { // i: table, 2: key, 3: value lua_pushvalue(L, 2); // key lua_pushvalue(L, 3); // value lua_settable(L, 1); return 0; } void LunoAdapter::setValue(const OUString &aName, const Any &aValue) throw (UnknownPropertyException, CannotConvertException, InvocationTargetException, RuntimeException) { CHECK_WRAPPED(m_WrappedRef); lua_pushcfunction(L, luno_settable); LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); lua_pushstring(L, OUSTRTOASCII(aName)); try { Runtime runtime; runtime.anyToLua(L, aValue); } catch (RuntimeException &e) { lua_pop(L, 3); throw; } const int e = lua_pcall(L, 3, 1, 0); THROW_ON_ERROR(e); } Any LunoAdapter::getValue(const OUString &aName) throw (UnknownPropertyException, RuntimeException) { CHECK_WRAPPED(m_WrappedRef); const int top = lua_gettop(L); Any a; lua_pushcfunction(L, luno_gettable); LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); lua_pushstring(L, OUSTRTOASCII(aName)); const int e = lua_pcall(L, 2, 1, 0); THROW_ON_ERROR(e); Runtime runtime; try { a = runtime.luaToAny(L, -1); } catch (RuntimeException &e) { lua_settop(L, top); throw; } lua_pop(L, 1); // result return a; } sal_Bool LunoAdapter::hasMethod(const OUString &aName) throw (RuntimeException) { sal_Bool b = sal_False; CHECK_WRAPPED(m_WrappedRef); lua_pushcfunction(L, luno_gettable); LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); lua_pushstring(L, OUSTRTOASCII(aName)); const int e = lua_pcall(L, 2, 1, 0); THROW_ON_ERROR(e); if (!lua_isfunction(L, -1)) b = sal_True; lua_pop(L, 1); // value return b; } sal_Bool LunoAdapter::hasProperty(const OUString &aName) throw (RuntimeException) { CHECK_WRAPPED(m_WrappedRef); sal_Bool b = sal_False; lua_pushcfunction(L, luno_gettable); LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); lua_pushstring(L, OUSTRTOASCII(aName)); const int e = lua_pcall(L, 2, 1, 0); THROW_ON_ERROR(e); if (!lua_isnil(L, -1)) b = sal_True; lua_pop(L, 1); // value return b; } static cppu::OImplementationId g_Id(sal_False); Sequence< sal_Int8 > LunoAdapter::getUnoTunnelImplementationId() { return g_Id.getImplementationId(); } sal_Int64 LunoAdapter::getSomething(const Sequence< sal_Int8 > &aIdentifier) throw (RuntimeException) { if (aIdentifier == g_Id.getImplementationId()) return reinterpret_cast< sal_Int64 >(this); return 0; } } // luno <commit_msg>Fix extract exception from material holder<commit_after>/* ** See Copyright Notice in LICENSE. **/ #include "luno.hxx" #include <cppuhelper/typeprovider.hxx> #include <com/sun/star/beans/MethodConcept.hpp> #include <com/sun/star/reflection/ParamMode.hpp> using com::sun::star::beans::UnknownPropertyException; using com::sun::star::beans::XIntrospectionAccess; using namespace com::sun::star::lang; using namespace com::sun::star::reflection; using namespace com::sun::star::script; using namespace com::sun::star::uno; using namespace rtl; #define OUSTRTOASCII(s) OUStringToOString(s, RTL_TEXTENCODING_ASCII_US).getStr() #define LUNO_ADAPTER_PUSH_WRAPPED(ref) \ LUNO_PUSH_REG_WRAPPED(); \ lua_rawgeti(L, -1, ref); \ lua_replace(L, -2) #define LUNO_ADAPTER_PUSH_ADAPTERS(ref) \ LUNO_PUSH_REG_ADAPTERS(); \ lua_rawgeti(L, -1, ref); \ lua_replace(L, -2) namespace luno { /** Wraps table at index. */ LunoAdapter::LunoAdapter(lua_State *L_, const int index, const Any &aTypes, const Any &aImpleId) : L(L_), m_WrappedRef(0), m_AdapterRef(0), m_Types(aTypes), m_ImpleId(aImpleId) { const int top = lua_gettop(L); // push wrapped value to wrapped LUNO_PUSH_REG_WRAPPED(); lua_pushvalue(L, index); m_WrappedRef = luaL_ref(L, -2); LUNO_PUSH_REG_ADAPTERS(); lua_pushlightuserdata(L, this); m_AdapterRef = luaL_ref(L, -2); lua_settop(L, top); } LunoAdapter::~LunoAdapter() { const int top = lua_gettop(L); if (m_WrappedRef) { LUNO_PUSH_REG_WRAPPED(); luaL_unref(L, -1, m_WrappedRef); m_WrappedRef = 0; } if (m_AdapterRef) { LUNO_PUSH_REG_ADAPTERS(); luaL_unref(L, -1, m_AdapterRef); m_AdapterRef = 0; } lua_settop(L, top); } LunoAdapter *LunoAdapter::create(lua_State *L_, const int index, const Sequence< Type > &aTypes, const Sequence< sal_Int8 > &aImpleId) { // ToDo get types and id at first request Any aTypes_; Any aImpleId_; aTypes_ <<= aTypes; aImpleId_ <<= aImpleId; return new LunoAdapter(L_, index, aTypes_, aImpleId_); } Sequence< sal_Int16 > LunoAdapter::getOutParamIndexes(const OUString &aName) throw (RuntimeException) { Sequence< sal_Int16 > ret; Runtime runtime; Reference< XInterface > rAdapter( runtime.getImple()->xAdapterFactory->createAdapter(this, getWrappedTypes())); Reference< XIntrospectionAccess > xIntrospectionAcc( runtime.getImple()->xIntrospection->inspect(makeAny(rAdapter))); if (!xIntrospectionAcc.is()) throw RuntimeException( OUSTRCONST("Failed to create adapter."), Reference< XInterface >()); Reference< XIdlMethod > xIdlMethod( xIntrospectionAcc->getMethod(aName, com::sun::star::beans::MethodConcept::ALL)); if (!xIdlMethod.is()) throw RuntimeException( OUSTRCONST("Failed to get reflection for ") + aName, Reference< XInterface >()); const Sequence< ParamInfo > aInfos(xIdlMethod->getParameterInfos()); const ParamInfo *pInfos = aInfos.getConstArray(); const int length = aInfos.getLength(); int out = 0; int i = 0; for (i = 0; i < length; ++i) { if (pInfos[i].aMode != ParamMode_IN) ++out; } if (out) { sal_Int16 j = 0; ret.realloc(out); sal_Int16 *pOutIndexes = ret.getArray(); for (i = 0; i < length; ++i) { if (pInfos[i].aMode != ParamMode_IN) { pOutIndexes[j] = i; ++j; } } } return ret; } Reference< XIntrospectionAccess > LunoAdapter::getIntrospection() throw (RuntimeException) { return Reference< XIntrospectionAccess >(); } Sequence< Type > LunoAdapter::getWrappedTypes() const { Sequence< Type > aTypes; m_Types >>= aTypes; return aTypes; } // Call lua_gettable in safe mode static int luno_gettable(lua_State *L) { // 1: table, 2: key lua_pushvalue(L, 2); // key lua_gettable(L, 1); return 1; } #define THROW_ON_ERROR(error) \ if (error) \ { \ size_t length; \ const char *message = lua_tolstring(L, -1, &length); \ const OUString aMessage(message, length, RTL_TEXTENCODING_UTF8); \ lua_pop(L, 1); \ throw RuntimeException(aMessage, Reference< XInterface >()); \ } #define CHECK_WRAPPED(ref) \ if (!ref) \ throw RuntimeException(OUSTRCONST("Nothing wrapped"), Reference< XInterface >()) Any LunoAdapter::invoke(const OUString &aName, const Sequence< Any > &aParams, Sequence< sal_Int16 > &aOutParamIndex, Sequence< Any > &aOutParam) throw (IllegalArgumentException, CannotConvertException, InvocationTargetException, RuntimeException) { static const OUString aNameGetSomething(RTL_CONSTASCII_USTRINGPARAM("getSomething")); static const OUString aNameGetTypes(RTL_CONSTASCII_USTRINGPARAM("getTypes")); static const OUString aNameGetImplementationId(RTL_CONSTASCII_USTRINGPARAM("getImplementationId")); const int nParams = (int)aParams.getLength(); if (!nParams) { // return cached value if (aName.equals(aNameGetTypes)) return m_Types; else if (aName.equals(aNameGetImplementationId)) return m_ImpleId; } else if (nParams == 1 && aName.equals(aNameGetSomething)) { Sequence< sal_Int8 > id; if (aParams[0] >>= id) return makeAny(getSomething(id)); } Any retAny; const int top = lua_gettop(L); try { CHECK_WRAPPED(m_WrappedRef); Runtime runtime; LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); // reuse // find function to call with error checking lua_pushcfunction(L, luno_gettable); lua_pushvalue(L, -2); // wrapped lua_pushstring(L, OUSTRTOASCII(aName)); const int e = lua_pcall(L, 2, 1, 0); THROW_ON_ERROR(e); if (!lua_isfunction(L, -1)) { // ToDo check is callable? lua_settop(L, top); throw RuntimeException( OUSTRCONST("Method not found: ") + aName, Reference< XInterface >()); } lua_insert(L, top + 1); // wrapped - func -> func - wrapped // push arguments const Any *pParams = aParams.getConstArray(); for (int i = 0; i < nParams; ++i) runtime.anyToLua(L, pParams[i]); // call, obj + params, var args const int error = lua_pcall(L, nParams + 1, LUA_MULTRET, 0); if (error) { // ToDo test throw exception from Lua if (error == LUA_ERRRUN) { if (lua_isuserdata(L, -1)) { LunoAdapted *p = luno_proxy_getudata(L, -1, LUNO_META_STRUCT); if (p != NULL && p->Wrapped.getValueTypeClass() == TypeClass_EXCEPTION) { lua_settop(L, top); Exception e; p->Wrapped >>= e; throw InvocationTargetException(e.Message, Reference< XInterface >(), p->Wrapped); } } size_t length; const char *message = lua_tolstring(L, -1, &length); throw RuntimeException(OUString(message, length, RTL_TEXTENCODING_UTF8), Reference< XInterface >()); } else { // ToDo LUA_ERRGCMM size_t length; const char *s = lua_tolstring(L, -1, &length); throw RuntimeException( OUString(s, length, RTL_TEXTENCODING_UTF8), Reference< XInterface >()); } } // ignore normal return value and wrapped obj const int nOut = lua_gettop(L) - top - 1; if (lua_gettop(L) - top > 0) retAny = runtime.luaToAny(L, top + 1); if (nOut > 1) { aOutParamIndex = getOutParamIndexes(aName); const int nOutParams = (int)aOutParamIndex.getLength(); if (nOut != nOutParams) throw RuntimeException( OUSTRCONST("luno: illegal number of out values for method: ") + aName, Reference< XInterface >()); aOutParam.realloc(nOutParams); for (int i = 0; i < nOutParams; ++i) aOutParam[i] = runtime.luaToAny(L, top + 1 + i); } lua_settop(L, top); } catch (RuntimeException &e) { lua_settop(L, top); throw; } return retAny; } // Call lua_settable in safe mode static int luno_settable(lua_State *L) { // i: table, 2: key, 3: value lua_pushvalue(L, 2); // key lua_pushvalue(L, 3); // value lua_settable(L, 1); return 0; } void LunoAdapter::setValue(const OUString &aName, const Any &aValue) throw (UnknownPropertyException, CannotConvertException, InvocationTargetException, RuntimeException) { CHECK_WRAPPED(m_WrappedRef); lua_pushcfunction(L, luno_settable); LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); lua_pushstring(L, OUSTRTOASCII(aName)); try { Runtime runtime; runtime.anyToLua(L, aValue); } catch (RuntimeException &e) { lua_pop(L, 3); throw; } const int e = lua_pcall(L, 3, 1, 0); THROW_ON_ERROR(e); } Any LunoAdapter::getValue(const OUString &aName) throw (UnknownPropertyException, RuntimeException) { CHECK_WRAPPED(m_WrappedRef); const int top = lua_gettop(L); Any a; lua_pushcfunction(L, luno_gettable); LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); lua_pushstring(L, OUSTRTOASCII(aName)); const int e = lua_pcall(L, 2, 1, 0); THROW_ON_ERROR(e); Runtime runtime; try { a = runtime.luaToAny(L, -1); } catch (RuntimeException &e) { lua_settop(L, top); throw; } lua_pop(L, 1); // result return a; } sal_Bool LunoAdapter::hasMethod(const OUString &aName) throw (RuntimeException) { sal_Bool b = sal_False; CHECK_WRAPPED(m_WrappedRef); lua_pushcfunction(L, luno_gettable); LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); lua_pushstring(L, OUSTRTOASCII(aName)); const int e = lua_pcall(L, 2, 1, 0); THROW_ON_ERROR(e); if (!lua_isfunction(L, -1)) b = sal_True; lua_pop(L, 1); // value return b; } sal_Bool LunoAdapter::hasProperty(const OUString &aName) throw (RuntimeException) { CHECK_WRAPPED(m_WrappedRef); sal_Bool b = sal_False; lua_pushcfunction(L, luno_gettable); LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef); lua_pushstring(L, OUSTRTOASCII(aName)); const int e = lua_pcall(L, 2, 1, 0); THROW_ON_ERROR(e); if (!lua_isnil(L, -1)) b = sal_True; lua_pop(L, 1); // value return b; } static cppu::OImplementationId g_Id(sal_False); Sequence< sal_Int8 > LunoAdapter::getUnoTunnelImplementationId() { return g_Id.getImplementationId(); } sal_Int64 LunoAdapter::getSomething(const Sequence< sal_Int8 > &aIdentifier) throw (RuntimeException) { if (aIdentifier == g_Id.getImplementationId()) return reinterpret_cast< sal_Int64 >(this); return 0; } } // luno <|endoftext|>
<commit_before>/** * @author pinkasfeld joseph * Copyright (c) Aldebaran Robotics 2010, 2011 All Rights Reserved. */ #include "allaser.h" #include <iostream> #include <alcommon/alproxy.h> #include <alproxies/almemoryproxy.h> #include <boost/shared_ptr.hpp> #include <alcommon/albroker.h> #include <alcommon/almodule.h> #include <sstream> #include <pthread.h> #include <signal.h> #include <cmath> #include <qi/log.hpp> #if defined (__linux__) #include <sys/prctl.h> #endif extern "C" { # include "urg_ctrl.h" # include "scip_handler.h" } #define MODE_ON 0 #define MODE_OFF 1 #define SEND_MODE_ON 2 #define SEND_MODE_OFF 3 #define MIDDLE_ANGLE 384 #define DEFAULT_MIN_ANGLE 43 #define DEFAULT_MAX_ANGLE 725 #define MIN_ANGLE_LASER 43 #define MAX_ANGLE_LASER 725 #define RESOLUTION_LASER 1024 #define MIN_LENGTH_LASER 20 #define MAX_LENGTH_LASER 5600 #include <sys/time.h> using namespace AL; using namespace std; pthread_t urgThreadId; boost::shared_ptr<ALMemoryProxy> gSTM; static int mode = MODE_ON; static urg_t urg; static int angle_min = DEFAULT_MIN_ANGLE; static int angle_max = DEFAULT_MAX_ANGLE; static int length_min = MIN_LENGTH_LASER; static int length_max = MAX_LENGTH_LASER; static void urg_exit(urg_t *urg, const char *message) { qiLogInfo("hardware.allaser", "%s: %s\n", message, urg_error(urg)); urg_disconnect(urg); qiLogInfo("hardware.allaser", "urg_exit\n"); pthread_exit((void *)NULL); } #define URG_DEFAULT_SPEED (19200) #define URG_FAST_SPEED (500000) void * urgThread(void * arg) { #if defined (__linux__) // thread name prctl(PR_SET_NAME, "ALLaser::urgThread", 0, 0, 0); #endif ALValue urgdata; long *data = NULL; int data_max; int ret; int n; int i,imemory,refTime,end,sampleTime, beginThread; std::string valueName="Device/Laser/Value"; /* Connection */ connectToLaser(); /* Reserve the Receive data buffer */ data_max = urg_dataMax(&urg); data = (long*)malloc(sizeof(long) * data_max); if (data == NULL) { perror("data buffer"); pthread_exit((void *)NULL); } /* prepare ALValue for ALMemory*/ urgdata.arraySetSize(data_max); for (i=0; i< data_max;i++) { urgdata[i].arraySetSize(4); urgdata[i][0]= (int)0; urgdata[i][1]= (double)0.0; urgdata[i][2]= (int)0; urgdata[i][3]= (int)0; } /* insert ALvalue in ALMemory*/ gSTM->insertData(valueName,urgdata); gSTM->insertData("Device/Laser/LaserEnable",(bool)1); gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI)*(DEFAULT_MIN_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER)); gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI)*(DEFAULT_MAX_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER)); gSTM->insertData("Device/Laser/MinLength",(float)(length_min)); gSTM->insertData("Device/Laser/MaxLength",(float)(length_max)); printf("ALLASER Running\n"); while(1) { if(mode==SEND_MODE_ON){ ret = urg_laserOn(&urg); if (ret < 0) { urg_exit(&urg, "urg_requestData()"); } mode=MODE_ON; /* Connection */ connectToLaser(); } if(mode==SEND_MODE_OFF){ scip_qt(&urg.serial_, NULL, ScipNoWaitReply); mode=MODE_OFF; } if(mode==MODE_ON){ /* Request Data using GD-Command */ ret = urg_requestData(&urg, URG_GD, angle_min, angle_max); if (ret < 0) { urg_exit(&urg, "urg_requestData()"); } refTime = getLocalTime(); /* Obtain Data */ n = urg_receiveData(&urg, data, data_max); if (n < 0) { urg_exit(&urg, "urg_receiveData()"); } end= getLocalTime(); sampleTime=end-refTime; imemory=0; for (i = 0; i < n; ++i) { int x, y; double angle=index2rad(i); int length = data[i]; if((length>=length_min)&&(length<=length_max)){ x = (int)((double)length * cos(angle)); y = (int)((double)length * sin(angle)); urgdata[imemory][0]= length; urgdata[imemory][1]= angle; urgdata[imemory][2]= x; urgdata[imemory][3]= y; imemory++; } } for(;imemory<data_max;imemory++){ urgdata[imemory][0]= 0; urgdata[imemory][1]= 0; urgdata[imemory][2]= 0; urgdata[imemory][3]= 0; } gSTM->insertData(valueName,urgdata); usleep(1000); }else{ usleep(10000); } } urg_disconnect(&urg); free(data); } //______________________________________________ // constructor //______________________________________________ ALLaser::ALLaser(boost::shared_ptr<ALBroker> pBroker, const std::string& pName ): ALModule(pBroker, pName ) { setModuleDescription( "Allow control over Hokuyo laser when available on Nao's head." ); functionName("laserOFF", "ALLaser", "Disable laser light"); BIND_METHOD( ALLaser::laserOFF ); functionName("laserON", "ALLaser", "Enable laser light and sampling"); BIND_METHOD( ALLaser::laserON ); functionName("setOpeningAngle", "ALLaser", "Set openning angle of the laser"); addParam("angle_min_f", "float containing the min value in rad, this value must be upper than -2.35619449 "); addParam("angle_max_f", "float containing the max value in rad, this value must be lower than 2.092349795 "); addMethodExample( "python", "# Set the opening angle at -90/90 degres\n" "laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n" "laser.setOpeningAngle(-1.570796327,1.570796327)\n" ); BIND_METHOD( ALLaser::setOpeningAngle ); functionName("setDetectingLength", "ALLaser", "Set detection threshold of the laser"); addParam("length_min_l", "int containing the min length that the laser will detect(mm), this value must be upper than 20 mm"); addParam("length_max_l", "int containing the max length that the laser will detect(mm), this value must be lower than 5600 mm"); addMethodExample( "python", "# Set detection threshold at 500/3000 mm\n" "laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n" "laser.setDetectingLength(500,3000)\n" ); BIND_METHOD( ALLaser::setDetectingLength ); // get broker on DCM and ALMemory try { gSTM = getParentBroker()->getMemoryProxy(); } catch(ALError& e) { qiLogError("hardware.allaser") << "Could not connect to Memory. Error: " << e.what() << std::endl; } pthread_create(&urgThreadId, NULL, urgThread, NULL); } //______________________________________________ // destructor //______________________________________________ ALLaser::~ALLaser() { pthread_cancel(urgThreadId); } void ALLaser::laserOFF(void){ mode = SEND_MODE_OFF; gSTM->insertData("Device/Laser/LaserEnable",(bool)0); } void ALLaser::laserON(void){ mode = SEND_MODE_ON; gSTM->insertData("Device/Laser/LaserEnable",(bool)1); } void ALLaser::setOpeningAngle(const AL::ALValue& angle_min_f, const AL::ALValue& angle_max_f){ angle_min = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_min_f / (2.0 * M_PI)); angle_max = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_max_f / (2.0 * M_PI)); if(angle_min<MIN_ANGLE_LASER) angle_min = MIN_ANGLE_LASER; if(angle_max>MAX_ANGLE_LASER) angle_max = MAX_ANGLE_LASER; if(angle_min>=angle_max){ angle_min = MIN_ANGLE_LASER; angle_max = MAX_ANGLE_LASER; } gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI) *(angle_min - MIDDLE_ANGLE) / RESOLUTION_LASER)); gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI) *(angle_max - MIDDLE_ANGLE) / RESOLUTION_LASER)); } void ALLaser::setDetectingLength(const AL::ALValue& length_min_l,const AL::ALValue& length_max_l){ length_min=(int)length_min_l; length_max=(int)length_max_l; if(length_min<MIN_LENGTH_LASER) length_min = MIN_LENGTH_LASER; if(length_max>MAX_LENGTH_LASER) length_min = MAX_LENGTH_LASER; if(length_min>=length_max){ length_min = MIN_LENGTH_LASER; length_max = MAX_LENGTH_LASER; } gSTM->insertData("Device/Laser/MinLength",(int)length_min); gSTM->insertData("Device/Laser/MaxLength",(int)length_max); } //_________________________________________________ // Service functions //_________________________________________________ void connectToLaser(void){ //const char device[] = "COM3"; /* Example when using Windows */ const char deviceACM[] = "/dev/ttyACM0"; /* Example when using Linux */ const char deviceUSB[] = "/dev/ttyUSB0"; /* Example when using Linux */ int ret; ret = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED); if (ret < 0) { std::stringstream ss; ss << "Connection failure to " << deviceUSB << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; ret = urg_connect(&urg, deviceUSB, URG_FAST_SPEED); if (ret < 0) { std::stringstream ss; ss << "Connection failure to " << deviceUSB << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; ret = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED); if (ret < 0) { std::stringstream ss; ss << "Connection failure to " << deviceACM << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; ret = urg_connect(&urg, deviceACM, URG_FAST_SPEED); if (ret < 0) { std::stringstream ss; ss << "Connection failure to " << deviceACM << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; //rtprintf("ALLaser : Fail connecting to %s at %d: %s\n",deviceACM,URG_FAST_SPEED, urg_error(&urg)); pthread_exit((void *)NULL); } } else { scip_ss(&urg.serial_, URG_FAST_SPEED); urg_disconnect(&urg); ret = urg_connect(&urg, deviceACM, URG_FAST_SPEED); if (ret < 0) { std::stringstream ss; ss << "Disconnect failure from " << deviceACM << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; pthread_exit((void *)NULL); } } } } else { /*switch to full speed*/ scip_ss(&urg.serial_, URG_FAST_SPEED); urg_disconnect(&urg); ret = urg_connect(&urg, deviceUSB, URG_FAST_SPEED); if (ret < 0) { std::stringstream ss; ss << "Disconnect failure from " << deviceUSB << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; pthread_exit((void *)NULL); } } } unsigned int getLocalTime(void){ struct timeval tv; unsigned int val; gettimeofday(&tv, NULL); val = (unsigned int)((unsigned int)(tv.tv_usec/1000) + (unsigned int)(tv.tv_sec*1000)); // Time in ms return val; } double index2rad(int index){ double radian = (2.0 * M_PI) * (index - MIDDLE_ANGLE + angle_min) / RESOLUTION_LASER; return radian; } <commit_msg>ALLASER: added separate functions to connect to laser via USB and ACM<commit_after>/** * @author pinkasfeld joseph * Copyright (c) Aldebaran Robotics 2010, 2011 All Rights Reserved. */ #include "allaser.h" #include <iostream> #include <alcommon/alproxy.h> #include <alproxies/almemoryproxy.h> #include <boost/shared_ptr.hpp> #include <alcommon/albroker.h> #include <alcommon/almodule.h> #include <sstream> #include <pthread.h> #include <signal.h> #include <cmath> #include <qi/log.hpp> #if defined (__linux__) #include <sys/prctl.h> #endif extern "C" { # include "urg_ctrl.h" # include "scip_handler.h" } #define MODE_ON 0 #define MODE_OFF 1 #define SEND_MODE_ON 2 #define SEND_MODE_OFF 3 #define MIDDLE_ANGLE 384 #define DEFAULT_MIN_ANGLE 43 #define DEFAULT_MAX_ANGLE 725 #define MIN_ANGLE_LASER 43 #define MAX_ANGLE_LASER 725 #define RESOLUTION_LASER 1024 #define MIN_LENGTH_LASER 20 #define MAX_LENGTH_LASER 5600 #include <sys/time.h> using namespace AL; using namespace std; pthread_t urgThreadId; boost::shared_ptr<ALMemoryProxy> gSTM; static int mode = MODE_ON; static urg_t urg; static int angle_min = DEFAULT_MIN_ANGLE; static int angle_max = DEFAULT_MAX_ANGLE; static int length_min = MIN_LENGTH_LASER; static int length_max = MAX_LENGTH_LASER; static void urg_exit(urg_t *urg, const char *message) { qiLogInfo("hardware.allaser", "%s: %s\n", message, urg_error(urg)); urg_disconnect(urg); qiLogInfo("hardware.allaser", "urg_exit\n"); pthread_exit((void *)NULL); } #define URG_DEFAULT_SPEED (19200) #define URG_FAST_SPEED (500000) void * urgThread(void * arg) { #if defined (__linux__) // thread name prctl(PR_SET_NAME, "ALLaser::urgThread", 0, 0, 0); #endif ALValue urgdata; long *data = NULL; int data_max; int ret; int n; int i,imemory,refTime,end,sampleTime, beginThread; std::string valueName="Device/Laser/Value"; /* Connection */ connectToLaser(); /* Reserve the Receive data buffer */ data_max = urg_dataMax(&urg); data = (long*)malloc(sizeof(long) * data_max); if (data == NULL) { perror("data buffer"); pthread_exit((void *)NULL); } /* prepare ALValue for ALMemory*/ urgdata.arraySetSize(data_max); for (i=0; i< data_max;i++) { urgdata[i].arraySetSize(4); urgdata[i][0]= (int)0; urgdata[i][1]= (double)0.0; urgdata[i][2]= (int)0; urgdata[i][3]= (int)0; } /* insert ALvalue in ALMemory*/ gSTM->insertData(valueName,urgdata); gSTM->insertData("Device/Laser/LaserEnable",(bool)1); gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI)*(DEFAULT_MIN_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER)); gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI)*(DEFAULT_MAX_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER)); gSTM->insertData("Device/Laser/MinLength",(float)(length_min)); gSTM->insertData("Device/Laser/MaxLength",(float)(length_max)); printf("ALLASER Running\n"); while(1) { if(mode==SEND_MODE_ON){ ret = urg_laserOn(&urg); if (ret < 0) { urg_exit(&urg, "urg_requestData()"); } mode=MODE_ON; /* Connection */ connectToLaser(); } if(mode==SEND_MODE_OFF){ scip_qt(&urg.serial_, NULL, ScipNoWaitReply); mode=MODE_OFF; } if(mode==MODE_ON){ /* Request Data using GD-Command */ ret = urg_requestData(&urg, URG_GD, angle_min, angle_max); if (ret < 0) { urg_exit(&urg, "urg_requestData()"); } refTime = getLocalTime(); /* Obtain Data */ n = urg_receiveData(&urg, data, data_max); if (n < 0) { urg_exit(&urg, "urg_receiveData()"); } end= getLocalTime(); sampleTime=end-refTime; imemory=0; for (i = 0; i < n; ++i) { int x, y; double angle=index2rad(i); int length = data[i]; if((length>=length_min)&&(length<=length_max)){ x = (int)((double)length * cos(angle)); y = (int)((double)length * sin(angle)); urgdata[imemory][0]= length; urgdata[imemory][1]= angle; urgdata[imemory][2]= x; urgdata[imemory][3]= y; imemory++; } } for(;imemory<data_max;imemory++){ urgdata[imemory][0]= 0; urgdata[imemory][1]= 0; urgdata[imemory][2]= 0; urgdata[imemory][3]= 0; } gSTM->insertData(valueName,urgdata); usleep(1000); }else{ usleep(10000); } } urg_disconnect(&urg); free(data); } //______________________________________________ // constructor //______________________________________________ ALLaser::ALLaser(boost::shared_ptr<ALBroker> pBroker, const std::string& pName ): ALModule(pBroker, pName ) { setModuleDescription( "Allow control over Hokuyo laser when available on Nao's head." ); functionName("laserOFF", "ALLaser", "Disable laser light"); BIND_METHOD( ALLaser::laserOFF ); functionName("laserON", "ALLaser", "Enable laser light and sampling"); BIND_METHOD( ALLaser::laserON ); functionName("setOpeningAngle", "ALLaser", "Set openning angle of the laser"); addParam("angle_min_f", "float containing the min value in rad, this value must be upper than -2.35619449 "); addParam("angle_max_f", "float containing the max value in rad, this value must be lower than 2.092349795 "); addMethodExample( "python", "# Set the opening angle at -90/90 degres\n" "laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n" "laser.setOpeningAngle(-1.570796327,1.570796327)\n" ); BIND_METHOD( ALLaser::setOpeningAngle ); functionName("setDetectingLength", "ALLaser", "Set detection threshold of the laser"); addParam("length_min_l", "int containing the min length that the laser will detect(mm), this value must be upper than 20 mm"); addParam("length_max_l", "int containing the max length that the laser will detect(mm), this value must be lower than 5600 mm"); addMethodExample( "python", "# Set detection threshold at 500/3000 mm\n" "laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n" "laser.setDetectingLength(500,3000)\n" ); BIND_METHOD( ALLaser::setDetectingLength ); // get broker on DCM and ALMemory try { gSTM = getParentBroker()->getMemoryProxy(); } catch(ALError& e) { qiLogError("hardware.allaser") << "Could not connect to Memory. Error: " << e.what() << std::endl; } pthread_create(&urgThreadId, NULL, urgThread, NULL); } //______________________________________________ // destructor //______________________________________________ ALLaser::~ALLaser() { pthread_cancel(urgThreadId); } void ALLaser::laserOFF(void){ mode = SEND_MODE_OFF; gSTM->insertData("Device/Laser/LaserEnable",(bool)0); } void ALLaser::laserON(void){ mode = SEND_MODE_ON; gSTM->insertData("Device/Laser/LaserEnable",(bool)1); } void ALLaser::setOpeningAngle(const AL::ALValue& angle_min_f, const AL::ALValue& angle_max_f){ angle_min = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_min_f / (2.0 * M_PI)); angle_max = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_max_f / (2.0 * M_PI)); if(angle_min<MIN_ANGLE_LASER) angle_min = MIN_ANGLE_LASER; if(angle_max>MAX_ANGLE_LASER) angle_max = MAX_ANGLE_LASER; if(angle_min>=angle_max){ angle_min = MIN_ANGLE_LASER; angle_max = MAX_ANGLE_LASER; } gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI) *(angle_min - MIDDLE_ANGLE) / RESOLUTION_LASER)); gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI) *(angle_max - MIDDLE_ANGLE) / RESOLUTION_LASER)); } void ALLaser::setDetectingLength(const AL::ALValue& length_min_l,const AL::ALValue& length_max_l){ length_min=(int)length_min_l; length_max=(int)length_max_l; if(length_min<MIN_LENGTH_LASER) length_min = MIN_LENGTH_LASER; if(length_max>MAX_LENGTH_LASER) length_min = MAX_LENGTH_LASER; if(length_min>=length_max){ length_min = MIN_LENGTH_LASER; length_max = MAX_LENGTH_LASER; } gSTM->insertData("Device/Laser/MinLength",(int)length_min); gSTM->insertData("Device/Laser/MaxLength",(int)length_max); } //_________________________________________________ // Service functions //_________________________________________________ int connectToLaserViaUSB(void) { int success = -1; const char deviceUSB[] = "/dev/ttyUSB0"; /* Example when using Linux */ // Try to connect at low speed. success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED); if (success < 0) { std::stringstream ss; ss << "Connection failure to " << deviceUSB << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; return success; } else { // Try to switch to full speed. scip_ss(&urg.serial_, URG_FAST_SPEED); urg_disconnect(&urg); success = urg_connect(&urg, deviceUSB, URG_FAST_SPEED); if (success < 0) { std::stringstream ss; ss << "Connection failure to " << deviceUSB << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; // Fall back to low speed. success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED); return success; } else { return success; } } } int connectToLaserViaACM(void) { int success = -1; const char deviceACM[] = "/dev/ttyACM0"; /* Example when using Linux */ success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED); if (success < 0) { std::stringstream ss; ss << "Connection failure to " << deviceACM << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; return success; } else { // Try to switch to full speed. scip_ss(&urg.serial_, URG_FAST_SPEED); urg_disconnect(&urg); success = urg_connect(&urg, deviceACM, URG_FAST_SPEED); if (success < 0) { std::stringstream ss; ss << "Connection failure from " << deviceACM << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; // Fall back to low speed. success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED); return success; } else { return success; } } } void connectToLaser(void){ //const char device[] = "COM3"; /* Example when using Windows */ const char deviceACM[] = "/dev/ttyACM0"; /* Example when using Linux */ const char deviceUSB[] = "/dev/ttyUSB0"; /* Example when using Linux */ int ret; ret = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED); if (ret < 0) { std::stringstream ss; ss << "Connection failure to " << deviceUSB << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; ret = urg_connect(&urg, deviceUSB, URG_FAST_SPEED); if (ret < 0) { std::stringstream ss; ss << "Connection failure to " << deviceUSB << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; ret = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED); if (ret < 0) { std::stringstream ss; ss << "Connection failure to " << deviceACM << " at " << URG_DEFAULT_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; ret = urg_connect(&urg, deviceACM, URG_FAST_SPEED); if (ret < 0) { std::stringstream ss; ss << "Connection failure to " << deviceACM << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; //rtprintf("ALLaser : Fail connecting to %s at %d: %s\n",deviceACM,URG_FAST_SPEED, urg_error(&urg)); pthread_exit((void *)NULL); } } else { scip_ss(&urg.serial_, URG_FAST_SPEED); urg_disconnect(&urg); ret = urg_connect(&urg, deviceACM, URG_FAST_SPEED); if (ret < 0) { std::stringstream ss; ss << "Disconnect failure from " << deviceACM << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; pthread_exit((void *)NULL); } } } } else { /*switch to full speed*/ scip_ss(&urg.serial_, URG_FAST_SPEED); urg_disconnect(&urg); ret = urg_connect(&urg, deviceUSB, URG_FAST_SPEED); if (ret < 0) { std::stringstream ss; ss << "Disconnect failure from " << deviceUSB << " at " << URG_FAST_SPEED << ". " << urg_error(&urg); qiLogDebug("hardware.allaser") << ss.str() << std::endl; pthread_exit((void *)NULL); } } } unsigned int getLocalTime(void){ struct timeval tv; unsigned int val; gettimeofday(&tv, NULL); val = (unsigned int)((unsigned int)(tv.tv_usec/1000) + (unsigned int)(tv.tv_sec*1000)); // Time in ms return val; } double index2rad(int index){ double radian = (2.0 * M_PI) * (index - MIDDLE_ANGLE + angle_min) / RESOLUTION_LASER; return radian; } <|endoftext|>
<commit_before>#include "internal.hpp" #include "clause.hpp" #include "iterator.hpp" #include "proof.hpp" #include "macros.hpp" #include "message.hpp" #include <algorithm> namespace CaDiCaL { /*------------------------------------------------------------------------*/ void Internal::learn_empty_clause () { assert (!unsat); LOG ("learned empty clause"); if (proof) proof->trace_empty_clause (); unsat = true; } void Internal::learn_unit_clause (int lit) { LOG ("learned unit clause %d", lit); if (proof) proof->trace_unit_clause (lit); iterating = true; stats.fixed++; } /*------------------------------------------------------------------------*/ // Important variables recently used in conflict analysis are 'bumped', // which means to move them to the front of the VMTF decision queue. The // 'bumped' time stamp is updated accordingly. It is used to determine // whether the 'queue.assigned' pointer has to be moved in 'unassign'. void Internal::bump_variable (Var * v) { if (!v->next) return; if (queue.assigned == v) queue.assigned = v->prev ? v->prev : v->next; queue.dequeue (v), queue.enqueue (v); v->bumped = ++stats.bumped; int idx = var2idx (v); if (!vals[idx]) queue.assigned = v; LOG ("VMTF bumped and moved to front %d", idx); } // Initially we proposed to bump the variable in the current 'bumped' stamp // order only. This maintains the current order between bumped variables. // On few benchmarks this however lead to a large number of propagations per // seconds, which can be reduced by an order of magnitude by focusing // somewhat on recently assigned variables more, particularly in this // situation. This can easily be achieved by using the sum of the 'bumped' // time stamp and trail height 'trail' for comparison. Note that 'bumped' // is always increasing and gets really large, while 'trail' can never be // larger than the number of variables, so there is likely a potential for // further optimization. struct bump_earlier { Internal * internal; bump_earlier (Internal * s) : internal (s) { } bool operator () (int a, int b) { Var & u = internal->var (a), & v = internal->var (b); return u.bumped + u.trail < v.bumped + v.trail; } }; void Internal::bump_variables () { START (bump); reverse (seen.begin (), seen.end ()); stable_sort (seen.begin (), seen.end (), bump_earlier (this)); for (const_int_iterator i = seen.begin (); i != seen.end (); i++) bump_variable (&var (*i)); STOP (bump); } /*------------------------------------------------------------------------*/ // Clause activity is replaced by a move to front scheme as well with // 'resolved' as time stamp. Only long and high glue clauses are stamped // since small or low glue clauses are kept anyhow (and do not actually have // a 'resolved' field). We keep the relative order of bumped clauses by // sorting them first. void Internal::bump_resolved_clauses () { START (bump); sort (resolved.begin (), resolved.end (), resolved_earlier ()); for (const_clause_iterator i = resolved.begin (); i != resolved.end (); i++) (*i)->resolved () = ++stats.resolved; STOP (bump); resolved.clear (); } void Internal::resolve_clause (Clause * c) { if (!c->redundant) return; if (c->size <= opts.keepsize) return; if (c->glue <= opts.keepglue) return; assert (c->extended); resolved.push_back (c); } /*------------------------------------------------------------------------*/ // During conflict analysis literals not seen yet either become part of the // first-uip clauses (if on lower decision level), are dropped (if fixed), // or are resolved away (if on the current decision level and different from // the first UIP). At the same time we update the number of seen literals on // a decision level and the smallest trail position of a seen literal for // each decision level. This both helps conflict clause minimization. The // number of seen levels is the glucose level (also called glue, or LBD). inline bool Internal::analyze_literal (int lit) { Var & v = var (lit); if (v.seen) return false; if (!v.level) return false; assert (val (lit) < 0); if (v.level < level) clause.push_back (lit); Level & l = control[v.level]; if (!l.seen++) { LOG ("found new level %d contributing to conflict", v.level); levels.push_back (v.level); } if (v.trail < l.trail) l.trail = v.trail; v.seen = true; seen.push_back (lit); LOG ("analyzed literal %d assigned at level %d", lit, v.level); return v.level == level; } /*------------------------------------------------------------------------*/ void Internal::clear_seen () { for (const_int_iterator i = seen.begin (); i != seen.end (); i++) var (*i).seen = false; seen.clear (); } void Internal::clear_levels () { for (const_int_iterator i = levels.begin (); i != levels.end (); i++) control[*i].reset (); levels.clear (); } /*------------------------------------------------------------------------*/ // By sorting the first UIP clause literals, we establish the invariant that // the two watched literals are on the largest decision highest level. struct trail_greater { Internal * internal; trail_greater (Internal * s) : internal (s) { } bool operator () (int a, int b) { return internal->var (a).trail > internal->var (b).trail; } }; void Internal::analyze () { assert (conflict); if (!level) { learn_empty_clause (); conflict = 0; return; } START (analyze); // First derive the first UIP clause. // Clause * reason = conflict; LOG (reason, "analyzing conflict"); resolve_clause (reason); int open = 0, uip = 0; const_int_iterator i = trail.end (); for (;;) { const const_literal_iterator end = reason->end (); const_literal_iterator j = reason->begin (); while (j != end) if (analyze_literal (*j++)) open++; while (!var (uip = *--i).seen) ; if (!--open) break; reason = var (uip).reason; LOG (reason, "analyzing %d reason", uip); } LOG ("first UIP %d", uip); clause.push_back (-uip); check_clause (); // Update glue statistics. // bump_resolved_clauses (); const int glue = (int) levels.size (); LOG ("1st UIP clause of size %d and glue %d", (int) clause.size (), glue); UPDATE_AVG (fast_glue_avg, glue); UPDATE_AVG (slow_glue_avg, glue); if (opts.minimize) minimize_clause (); // minimize clause stats.units += (clause.size () == 1); stats.binaries += (clause.size () == 2); bump_variables (); // Update decision heuristics. // Determine back jump level, backtrack and assign flipped literal. // Clause * driving_clause = 0; int jump = 0; if (clause.size () > 1) { sort (clause.begin (), clause.end (), trail_greater (this)); driving_clause = new_learned_clause (glue); jump = var (clause[1]).level; } UPDATE_AVG (jump_avg, jump); backtrack (jump); assign (-uip, driving_clause); // Clean up. // clear_seen (); clause.clear (); clear_levels (); conflict = 0; STOP (analyze); } // We wait reporting a learned unit until propagation of that unit is // completed. Otherwise the 'i' report line might prematurely give the // number of remaining variables. void Internal::iterate () { iterating = false; report ('i'); } }; <commit_msg>moved variable bumping thus same as 015<commit_after>#include "internal.hpp" #include "clause.hpp" #include "iterator.hpp" #include "proof.hpp" #include "macros.hpp" #include "message.hpp" #include <algorithm> namespace CaDiCaL { /*------------------------------------------------------------------------*/ void Internal::learn_empty_clause () { assert (!unsat); LOG ("learned empty clause"); if (proof) proof->trace_empty_clause (); unsat = true; } void Internal::learn_unit_clause (int lit) { LOG ("learned unit clause %d", lit); if (proof) proof->trace_unit_clause (lit); iterating = true; stats.fixed++; } /*------------------------------------------------------------------------*/ // Important variables recently used in conflict analysis are 'bumped', // which means to move them to the front of the VMTF decision queue. The // 'bumped' time stamp is updated accordingly. It is used to determine // whether the 'queue.assigned' pointer has to be moved in 'unassign'. void Internal::bump_variable (Var * v) { if (!v->next) return; if (queue.assigned == v) queue.assigned = v->prev ? v->prev : v->next; queue.dequeue (v), queue.enqueue (v); v->bumped = ++stats.bumped; int idx = var2idx (v); if (!vals[idx]) queue.assigned = v; LOG ("VMTF bumped and moved to front %d", idx); } // Initially we proposed to bump the variable in the current 'bumped' stamp // order only. This maintains the current order between bumped variables. // On few benchmarks this however lead to a large number of propagations per // seconds, which can be reduced by an order of magnitude by focusing // somewhat on recently assigned variables more, particularly in this // situation. This can easily be achieved by using the sum of the 'bumped' // time stamp and trail height 'trail' for comparison. Note that 'bumped' // is always increasing and gets really large, while 'trail' can never be // larger than the number of variables, so there is likely a potential for // further optimization. struct bump_earlier { Internal * internal; bump_earlier (Internal * s) : internal (s) { } bool operator () (int a, int b) { Var & u = internal->var (a), & v = internal->var (b); return u.bumped + u.trail < v.bumped + v.trail; } }; void Internal::bump_variables () { START (bump); sort (seen.begin (), seen.end (), bump_earlier (this)); for (const_int_iterator i = seen.begin (); i != seen.end (); i++) bump_variable (&var (*i)); STOP (bump); } /*------------------------------------------------------------------------*/ // Clause activity is replaced by a move to front scheme as well with // 'resolved' as time stamp. Only long and high glue clauses are stamped // since small or low glue clauses are kept anyhow (and do not actually have // a 'resolved' field). We keep the relative order of bumped clauses by // sorting them first. void Internal::bump_resolved_clauses () { START (bump); sort (resolved.begin (), resolved.end (), resolved_earlier ()); for (const_clause_iterator i = resolved.begin (); i != resolved.end (); i++) (*i)->resolved () = ++stats.resolved; STOP (bump); resolved.clear (); } void Internal::resolve_clause (Clause * c) { if (!c->redundant) return; if (c->size <= opts.keepsize) return; if (c->glue <= opts.keepglue) return; assert (c->extended); resolved.push_back (c); } /*------------------------------------------------------------------------*/ // During conflict analysis literals not seen yet either become part of the // first-uip clauses (if on lower decision level), are dropped (if fixed), // or are resolved away (if on the current decision level and different from // the first UIP). At the same time we update the number of seen literals on // a decision level and the smallest trail position of a seen literal for // each decision level. This both helps conflict clause minimization. The // number of seen levels is the glucose level (also called glue, or LBD). inline bool Internal::analyze_literal (int lit) { Var & v = var (lit); if (v.seen) return false; if (!v.level) return false; assert (val (lit) < 0); if (v.level < level) clause.push_back (lit); Level & l = control[v.level]; if (!l.seen++) { LOG ("found new level %d contributing to conflict", v.level); levels.push_back (v.level); } if (v.trail < l.trail) l.trail = v.trail; v.seen = true; seen.push_back (lit); LOG ("analyzed literal %d assigned at level %d", lit, v.level); return v.level == level; } /*------------------------------------------------------------------------*/ void Internal::clear_seen () { for (const_int_iterator i = seen.begin (); i != seen.end (); i++) var (*i).seen = false; seen.clear (); } void Internal::clear_levels () { for (const_int_iterator i = levels.begin (); i != levels.end (); i++) control[*i].reset (); levels.clear (); } /*------------------------------------------------------------------------*/ // By sorting the first UIP clause literals, we establish the invariant that // the two watched literals are on the largest decision highest level. struct trail_greater { Internal * internal; trail_greater (Internal * s) : internal (s) { } bool operator () (int a, int b) { return internal->var (a).trail > internal->var (b).trail; } }; void Internal::analyze () { assert (conflict); if (!level) { learn_empty_clause (); conflict = 0; return; } START (analyze); // First derive the first UIP clause. // Clause * reason = conflict; LOG (reason, "analyzing conflict"); resolve_clause (reason); int open = 0, uip = 0; const_int_iterator i = trail.end (); for (;;) { const const_literal_iterator end = reason->end (); const_literal_iterator j = reason->begin (); while (j != end) if (analyze_literal (*j++)) open++; while (!var (uip = *--i).seen) ; if (!--open) break; reason = var (uip).reason; LOG (reason, "analyzing %d reason", uip); } LOG ("first UIP %d", uip); clause.push_back (-uip); check_clause (); // Update glue statistics. // bump_resolved_clauses (); const int glue = (int) levels.size (); LOG ("1st UIP clause of size %d and glue %d", (int) clause.size (), glue); UPDATE_AVG (fast_glue_avg, glue); UPDATE_AVG (slow_glue_avg, glue); if (opts.minimize) minimize_clause (); // minimize clause stats.units += (clause.size () == 1); stats.binaries += (clause.size () == 2); // Determine back jump level, backtrack and assign flipped literal. // Clause * driving_clause = 0; int jump = 0; if (clause.size () > 1) { sort (clause.begin (), clause.end (), trail_greater (this)); driving_clause = new_learned_clause (glue); jump = var (clause[1]).level; } UPDATE_AVG (jump_avg, jump); backtrack (jump); assign (-uip, driving_clause); bump_variables (); // Update decision heuristics. // Clean up. // clear_seen (); clause.clear (); clear_levels (); conflict = 0; STOP (analyze); } // We wait reporting a learned unit until propagation of that unit is // completed. Otherwise the 'i' report line might prematurely give the // number of remaining variables. void Internal::iterate () { iterating = false; report ('i'); } }; <|endoftext|>
<commit_before>// Copyright 2020 Tangent Animation // // 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, // including without limitation, as related to merchantability and fitness // for a particular purpose. // // In no event shall any copyright holder be liable for any damages of any kind // arising from the use of this software, whether in contract, tort or otherwise. // See the License for the specific language governing permissions and // limitations under the License. #include "renderPass.h" #include "camera.h" #include "renderBuffer.h" #include "renderParam.h" #include "utils.h" #include <render/camera.h> #include <render/scene.h> #include <render/session.h> #include <util/util_types.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/imaging/hd/camera.h> #include <pxr/imaging/hd/renderPassState.h> PXR_NAMESPACE_OPEN_SCOPE // clang-format off #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #endif TF_DEFINE_PRIVATE_TOKENS(_tokens, (color) (depth) ); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // clang-format on HdCyclesRenderPass::HdCyclesRenderPass(HdCyclesRenderDelegate* delegate, HdRenderIndex* index, HdRprimCollection const& collection) : HdRenderPass(index, collection) , m_delegate(delegate) { } HdCyclesRenderPass::~HdCyclesRenderPass() {} void HdCyclesRenderPass::_Execute(HdRenderPassStateSharedPtr const& renderPassState, TfTokenVector const& renderTags) { auto* renderParam = reinterpret_cast<HdCyclesRenderParam*>( m_delegate->GetRenderParam()); HdRenderPassAovBindingVector aovBindings = renderPassState->GetAovBindings(); if (renderParam->GetAovBindings() != aovBindings) { renderParam->SetAovBindings(aovBindings); if(!aovBindings.empty()) { renderParam->SetDisplayAov(aovBindings[0]); } } const auto vp = renderPassState->GetViewport(); GfMatrix4d projMtx = renderPassState->GetProjectionMatrix(); GfMatrix4d viewMtx = renderPassState->GetWorldToViewMatrix(); m_isConverged = renderParam->IsConverged(); // XXX: Need to cast away constness to process updated camera params since // the Hydra camera doesn't update the Cycles camera directly. HdCyclesCamera* hdCam = const_cast<HdCyclesCamera*>( dynamic_cast<HdCyclesCamera const*>(renderPassState->GetCamera())); ccl::Camera* active_camera = renderParam->GetCyclesSession()->scene->camera; bool shouldUpdate = false; if (projMtx != m_projMtx || viewMtx != m_viewMtx) { m_projMtx = projMtx; m_viewMtx = viewMtx; const float fov_rad = atan(1.0f / m_projMtx[1][1]) * 2.0f; hdCam->SetFOV(fov_rad); shouldUpdate = true; } if(!shouldUpdate) shouldUpdate = hdCam->IsDirty(); if (shouldUpdate) { hdCam->ApplyCameraSettings(active_camera); // Needed for now, as houdini looks through a generated camera // and doesn't copy the projection type (as of 18.0.532) bool is_ortho = round(m_projMtx[3][3]) == 1.0; if (is_ortho) { active_camera->type = ccl::CameraType::CAMERA_ORTHOGRAPHIC; } else active_camera->type = ccl::CameraType::CAMERA_PERSPECTIVE; active_camera->tag_update(); // DirectReset here instead of Interrupt for faster IPR camera orbits renderParam->DirectReset(); } const auto width = static_cast<int>(vp[2]); const auto height = static_cast<int>(vp[3]); if (width != m_width || height != m_height) { m_width = width; m_height = height; // TODO: Due to the startup flow of Cycles, this gets called after a tiled render // has already started. Sometimes causing the original tiled render to complete // before actually rendering at the appropriate size. This seems to be a Cycles // issue, however the startup flow of HdCycles has LOTS of room for improvement... renderParam->SetViewport(m_width, m_height); // TODO: This is very hacky... But stops the tiled render double render issue... if (renderParam->IsTiledRender()) { renderParam->StartRender(); } renderParam->Interrupt(); } // Tiled renders early out because we do the blitting on render tile callback if (renderParam->IsTiledRender()) return; if (!renderParam->GetCyclesSession()) return; if (!renderParam->GetCyclesScene()) return; ccl::DisplayBuffer* display = renderParam->GetCyclesSession()->display; if (!display) return; renderParam->GetCyclesSession()->acquire_display(); HdFormat colorFormat = display->half_float ? HdFormatFloat16Vec4 : HdFormatUNorm8Vec4; unsigned char* hpixels = (display->half_float) ? (unsigned char*)display->rgba_half.host_pointer : (unsigned char*)display->rgba_byte.host_pointer; if (!hpixels) { renderParam->GetCyclesSession()->release_display(); return; } int w = display->draw_width; int h = display->draw_height; if (w == 0 || h == 0) { renderParam->GetCyclesSession()->release_display(); return; } // Blit if (!aovBindings.empty()) { // Blit from the framebuffer to currently selected aovs... for (auto& aov : aovBindings) { if (!TF_VERIFY(aov.renderBuffer != nullptr)) { continue; } auto* rb = static_cast<HdCyclesRenderBuffer*>(aov.renderBuffer); rb->SetConverged(m_isConverged); // Needed as a stopgap, because Houdini dellocates renderBuffers // when changing render settings. This causes the current blit to // fail (Probably can be fixed with proper render thread management) if (!rb->WasUpdated()) { if (aov.aovName == renderParam->GetDisplayAovToken()) { rb->Blit(colorFormat, w, h, 0, w, reinterpret_cast<uint8_t*>(hpixels)); } } else { rb->SetWasUpdated(false); } } } renderParam->GetCyclesSession()->release_display(); } PXR_NAMESPACE_CLOSE_SCOPE <commit_msg>Changed logic to use Cycles lock<commit_after>// Copyright 2020 Tangent Animation // // 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, // including without limitation, as related to merchantability and fitness // for a particular purpose. // // In no event shall any copyright holder be liable for any damages of any kind // arising from the use of this software, whether in contract, tort or otherwise. // See the License for the specific language governing permissions and // limitations under the License. #include "renderPass.h" #include "camera.h" #include "renderBuffer.h" #include "renderParam.h" #include "utils.h" #include <render/camera.h> #include <render/scene.h> #include <render/session.h> #include <util/util_types.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/imaging/hd/camera.h> #include <pxr/imaging/hd/renderPassState.h> PXR_NAMESPACE_OPEN_SCOPE // clang-format off #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #endif TF_DEFINE_PRIVATE_TOKENS(_tokens, (color) (depth) ); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // clang-format on HdCyclesRenderPass::HdCyclesRenderPass(HdCyclesRenderDelegate* delegate, HdRenderIndex* index, HdRprimCollection const& collection) : HdRenderPass(index, collection) , m_delegate(delegate) { } HdCyclesRenderPass::~HdCyclesRenderPass() {} void HdCyclesRenderPass::_Execute(HdRenderPassStateSharedPtr const& renderPassState, TfTokenVector const& renderTags) { auto* renderParam = reinterpret_cast<HdCyclesRenderParam*>( m_delegate->GetRenderParam()); HdRenderPassAovBindingVector aovBindings = renderPassState->GetAovBindings(); if (renderParam->GetAovBindings() != aovBindings) { renderParam->SetAovBindings(aovBindings); if(!aovBindings.empty()) { renderParam->SetDisplayAov(aovBindings[0]); } } const auto vp = renderPassState->GetViewport(); GfMatrix4d projMtx = renderPassState->GetProjectionMatrix(); GfMatrix4d viewMtx = renderPassState->GetWorldToViewMatrix(); m_isConverged = renderParam->IsConverged(); // XXX: Need to cast away constness to process updated camera params since // the Hydra camera doesn't update the Cycles camera directly. HdCyclesCamera* hdCam = const_cast<HdCyclesCamera*>( dynamic_cast<HdCyclesCamera const*>(renderPassState->GetCamera())); ccl::Camera* active_camera = renderParam->GetCyclesSession()->scene->camera; bool shouldUpdate = false; if (projMtx != m_projMtx || viewMtx != m_viewMtx) { m_projMtx = projMtx; m_viewMtx = viewMtx; const float fov_rad = atan(1.0f / m_projMtx[1][1]) * 2.0f; hdCam->SetFOV(fov_rad); shouldUpdate = true; } if(!shouldUpdate) shouldUpdate = hdCam->IsDirty(); if (shouldUpdate) { hdCam->ApplyCameraSettings(active_camera); // Needed for now, as houdini looks through a generated camera // and doesn't copy the projection type (as of 18.0.532) bool is_ortho = round(m_projMtx[3][3]) == 1.0; if (is_ortho) { active_camera->type = ccl::CameraType::CAMERA_ORTHOGRAPHIC; } else active_camera->type = ccl::CameraType::CAMERA_PERSPECTIVE; active_camera->tag_update(); // DirectReset here instead of Interrupt for faster IPR camera orbits renderParam->DirectReset(); } const auto width = static_cast<int>(vp[2]); const auto height = static_cast<int>(vp[3]); if (width != m_width || height != m_height) { m_width = width; m_height = height; // TODO: Due to the startup flow of Cycles, this gets called after a tiled render // has already started. Sometimes causing the original tiled render to complete // before actually rendering at the appropriate size. This seems to be a Cycles // issue, however the startup flow of HdCycles has LOTS of room for improvement... renderParam->SetViewport(m_width, m_height); // TODO: This is very hacky... But stops the tiled render double render issue... if (renderParam->IsTiledRender()) { renderParam->StartRender(); } renderParam->Interrupt(); } // Tiled renders early out because we do the blitting on render tile callback if (renderParam->IsTiledRender()) return; if (!renderParam->GetCyclesSession()) return; if (!renderParam->GetCyclesScene()) return; ccl::DisplayBuffer* display = renderParam->GetCyclesSession()->display; if (!display) return; ccl::thread_scoped_lock display_lock = renderParam->GetCyclesSession()->acquire_display_lock(); HdFormat colorFormat = display->half_float ? HdFormatFloat16Vec4 : HdFormatUNorm8Vec4; unsigned char* hpixels = (display->half_float) ? (unsigned char*)display->rgba_half.host_pointer : (unsigned char*)display->rgba_byte.host_pointer; if (!hpixels) return; int w = display->draw_width; int h = display->draw_height; if (w == 0 || h == 0) return; // Blit if (!aovBindings.empty()) { // Blit from the framebuffer to currently selected aovs... for (auto& aov : aovBindings) { if (!TF_VERIFY(aov.renderBuffer != nullptr)) { continue; } auto* rb = static_cast<HdCyclesRenderBuffer*>(aov.renderBuffer); rb->SetConverged(m_isConverged); // Needed as a stopgap, because Houdini dellocates renderBuffers // when changing render settings. This causes the current blit to // fail (Probably can be fixed with proper render thread management) if (!rb->WasUpdated()) { if (aov.aovName == renderParam->GetDisplayAovToken()) { rb->Blit(colorFormat, w, h, 0, w, reinterpret_cast<uint8_t*>(hpixels)); } } else { rb->SetWasUpdated(false); } } } } PXR_NAMESPACE_CLOSE_SCOPE <|endoftext|>
<commit_before>/*============================================================================= Copyright (C) 2021 yumetodo <yume-wikijp@live.jp> Distributed under the Boost Software License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef YUMETODO_INFERIOR_IOTA_VIEW_HPP_ #define YUMETODO_INFERIOR_IOTA_VIEW_HPP_ #include <cstddef> #include <iterator> namespace inferior { namespace ranges { namespace detail { template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, nullptr_t> = nullptr> class iota_view_iterator { private: T i; public: using iterator_category = std::random_access_iterator_tag; using iterator_concept = std::random_access_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T*; using reference = T; constexpr iota_view_iterator() : i() { } constexpr iota_view_iterator(T n) : i(n) { } constexpr iota_view_iterator& operator=(const iota_view_iterator& o) noexcept { i = o.i; return *this; } constexpr bool operator == (const iota_view_iterator& rhs) const noexcept { return i == rhs.i; } constexpr bool operator != (const iota_view_iterator& rhs) const noexcept { return i != rhs.i; } constexpr T operator * () const noexcept { return i; } constexpr T operator[](difference_type n) const noexcept { return static_cast<T>(i + n); } constexpr iota_view_iterator operator+(difference_type n) const noexcept { return{ static_cast<T>(i + n) }; } constexpr iota_view_iterator operator-(difference_type n) const noexcept { return{ static_cast<T>(i - n) }; } constexpr difference_type operator-(const iota_view_iterator& it) const noexcept { return static_cast<difference_type>(i - it.i); } constexpr bool operator<(const iota_view_iterator& n) const noexcept { return i < n.i; } constexpr bool operator<=(const iota_view_iterator& n) const noexcept { return i <= n.i; } constexpr bool operator>(const iota_view_iterator& n) const noexcept { return i > n.i; } constexpr bool operator>=(const iota_view_iterator& n) const noexcept { return i >= n.i; } constexpr iota_view_iterator& operator += (iota_view_iterator it) noexcept { i = static_cast<T>(i + it.i); return *this; } constexpr iota_view_iterator& operator -= (iota_view_iterator it) noexcept { i = static_cast<T>(i - it.i); return *this; } constexpr iota_view_iterator& operator ++ () noexcept { ++i; return *this; } constexpr iota_view_iterator operator ++ (int) noexcept { auto t = *this; ++i; return t; } constexpr iota_view_iterator& operator -- () noexcept { --i; return *this; } constexpr iota_view_iterator operator -- (int) noexcept { auto t = *this; --i; return t; } }; template<typename T> constexpr iota_view_iterator<T> operator+(typename iota_view_iterator<T>::difference_type n, const iota_view_iterator<T>& it) noexcept { return static_cast<T>(it + n); } } template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, nullptr_t> = nullptr> class iota_view { public: using value_type = std::remove_cv_t<T>; using iterator = detail::iota_view_iterator<value_type>; private: value_type begin_, end_; public: constexpr iota_view(T n) : begin_(0), end_(n) {} constexpr iota_view(T begin, T end) : begin_(begin), end_(end) {} constexpr iterator begin() const noexcept { return{ begin_ }; } constexpr iterator end() const noexcept { return{ end_ }; } }; namespace views { template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, nullptr_t> = nullptr> constexpr iota_view<T> iota(const T& begin, const T& end) noexcept { return{ begin, end }; } } } namespace views = ranges::views; } #endif //YUMETODO_INFERIOR_IOTA_VIEW_HPP_ <commit_msg>fix(iota_view): fix compile error in gcc<commit_after>/*============================================================================= Copyright (C) 2021 yumetodo <yume-wikijp@live.jp> Distributed under the Boost Software License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef YUMETODO_INFERIOR_IOTA_VIEW_HPP_ #define YUMETODO_INFERIOR_IOTA_VIEW_HPP_ #include <cstddef> #include <iterator> namespace inferior { namespace ranges { namespace detail { template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, std::nullptr_t> = nullptr> class iota_view_iterator { private: T i; public: using iterator_category = std::random_access_iterator_tag; using iterator_concept = std::random_access_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T*; using reference = T; iota_view_iterator() = default; constexpr iota_view_iterator(T n) noexcept : i(n) { } iota_view_iterator(const iota_view_iterator&) = default; iota_view_iterator(iota_view_iterator&&) = default; iota_view_iterator& operator=(const iota_view_iterator&) = default; iota_view_iterator& operator=(iota_view_iterator&&) = default; constexpr bool operator == (const iota_view_iterator& rhs) const noexcept { return i == rhs.i; } constexpr bool operator != (const iota_view_iterator& rhs) const noexcept { return i != rhs.i; } constexpr T operator * () const noexcept { return i; } constexpr T operator[](difference_type n) const noexcept { return static_cast<T>(i + n); } constexpr iota_view_iterator operator+(difference_type n) const noexcept { return{ static_cast<T>(i + n) }; } constexpr iota_view_iterator operator-(difference_type n) const noexcept { return{ static_cast<T>(i - n) }; } constexpr difference_type operator-(const iota_view_iterator& it) const noexcept { return static_cast<difference_type>(i - it.i); } constexpr bool operator<(const iota_view_iterator& n) const noexcept { return i < n.i; } constexpr bool operator<=(const iota_view_iterator& n) const noexcept { return i <= n.i; } constexpr bool operator>(const iota_view_iterator& n) const noexcept { return i > n.i; } constexpr bool operator>=(const iota_view_iterator& n) const noexcept { return i >= n.i; } constexpr iota_view_iterator& operator += (iota_view_iterator it) noexcept { i = static_cast<T>(i + it.i); return *this; } constexpr iota_view_iterator& operator -= (iota_view_iterator it) noexcept { i = static_cast<T>(i - it.i); return *this; } constexpr iota_view_iterator& operator ++ () noexcept { ++i; return *this; } constexpr iota_view_iterator operator ++ (int) noexcept { auto t = *this; ++i; return t; } constexpr iota_view_iterator& operator -- () noexcept { --i; return *this; } constexpr iota_view_iterator operator -- (int) noexcept { auto t = *this; --i; return t; } }; template<typename T> constexpr iota_view_iterator<T> operator+(typename iota_view_iterator<T>::difference_type n, const iota_view_iterator<T>& it) noexcept { return static_cast<T>(it + n); } } template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, std::nullptr_t> = nullptr> class iota_view { public: using value_type = std::remove_cv_t<T>; using iterator = detail::iota_view_iterator<value_type>; private: value_type begin_, end_; public: constexpr iota_view(T n) : begin_(0), end_(n) {} constexpr iota_view(T begin, T end) : begin_(begin), end_(end) {} constexpr iterator begin() const noexcept { return{ begin_ }; } constexpr iterator end() const noexcept { return{ end_ }; } }; namespace views { template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, std::nullptr_t> = nullptr> constexpr iota_view<T> iota(const T& begin, const T& end) noexcept { return{ begin, end }; } } } namespace views = ranges::views; } #endif //YUMETODO_INFERIOR_IOTA_VIEW_HPP_ <|endoftext|>
<commit_before>/** * \file TransverseMercator.hpp * * Copyright (c) Charles Karney (2008) <charles@karney.com> * and licensed under the LGPL. **********************************************************************/ #if !defined(TRANSVERSEMERCATOR_HPP) #define TRANSVERSEMERCATOR_HPP "$Id$" #include <cmath> namespace GeographicLib { class TransverseMercator { private: const double _a, _f, _k0, _e2, _e, _e2m, _e1, _n, _a1, _h1, _h2, _h3, _h4, _h1p, _h2p, _h3p, _h4p, _tol; const int _numit; #if defined(_MSC_VER) // These have poor relative accuracy near x = 0. However, for mapping // applications, we only need good absolute accuracy. // For small arguments we would write // // asinh(x) = asin(x) -x^3/3-5*x^7/56-63*x^11/1408-143*x^15/5120 ... // atanh(x) = atan(x) +2*x^3/3+2*x^7/7+2*x^11/11+2*x^15/15 // // The accuracy of asinh is also bad for large negative arguments. This is // easy to fix in the definition of asinh. Instead we call these functions // with positive arguments and enforce the correct parity separately. static inline double asinh(double x) { return log(x + sqrt(1 + x * x)); } static inline double atanh(double x) { return log((1 + x)/(1 - x))/2; } #endif double Convergence(double phi, double l) const; double Scale(double phi, double l) const; public: TransverseMercator(double a, double f, double k0); void Forward(double lon0, double lat, double lon, double& x, double& y, double& gamma, double& k) const; void Reverse(double lon0, double x, double y, double& lat, double& lon, double& gamma, double& k) const; // Specialization for WGS84 ellipsoid and UTM scale factor const static TransverseMercator UTM; }; } #endif <commit_msg>Add closing namespace comment<commit_after>/** * \file TransverseMercator.hpp * * Copyright (c) Charles Karney (2008) <charles@karney.com> * and licensed under the LGPL. **********************************************************************/ #if !defined(TRANSVERSEMERCATOR_HPP) #define TRANSVERSEMERCATOR_HPP "$Id$" #include <cmath> namespace GeographicLib { class TransverseMercator { private: const double _a, _f, _k0, _e2, _e, _e2m, _e1, _n, _a1, _h1, _h2, _h3, _h4, _h1p, _h2p, _h3p, _h4p, _tol; const int _numit; #if defined(_MSC_VER) // These have poor relative accuracy near x = 0. However, for mapping // applications, we only need good absolute accuracy. // For small arguments we would write // // asinh(x) = asin(x) -x^3/3-5*x^7/56-63*x^11/1408-143*x^15/5120 ... // atanh(x) = atan(x) +2*x^3/3+2*x^7/7+2*x^11/11+2*x^15/15 // // The accuracy of asinh is also bad for large negative arguments. This is // easy to fix in the definition of asinh. Instead we call these functions // with positive arguments and enforce the correct parity separately. static inline double asinh(double x) { return log(x + sqrt(1 + x * x)); } static inline double atanh(double x) { return log((1 + x)/(1 - x))/2; } #endif double Convergence(double phi, double l) const; double Scale(double phi, double l) const; public: TransverseMercator(double a, double f, double k0); void Forward(double lon0, double lat, double lon, double& x, double& y, double& gamma, double& k) const; void Reverse(double lon0, double x, double y, double& lat, double& lon, double& gamma, double& k) const; // Specialization for WGS84 ellipsoid and UTM scale factor const static TransverseMercator UTM; }; } // namespace GeographicLib #endif <|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. * ************************************************************************/ #ifndef OOX_VML_VMLDRAWING_HXX #define OOX_VML_VMLDRAWING_HXX #include <map> #include <memory> #include "oox/ole/oleobjecthelper.hxx" namespace com { namespace sun { namespace star { namespace awt { struct Rectangle; } namespace awt { class XControlModel; } namespace drawing { class XDrawPage; } namespace drawing { class XShape; } } } } namespace oox { namespace core { class XmlFilterBase; } } namespace oox { namespace ole { class EmbeddedForm; } } namespace oox { namespace vml { class ShapeBase; class ShapeContainer; struct ShapeClientData; // ============================================================================ /** Enumerates different types of VML drawings. */ enum DrawingType { VMLDRAWING_WORD, /// Word: One shape per drawing. VMLDRAWING_EXCEL, /// Excel: OLE objects are part of VML. VMLDRAWING_POWERPOINT /// PowerPoint: OLE objects are part of DrawingML. }; // ============================================================================ /** Contains information about an OLE object embedded in a draw page. */ struct OleObjectInfo : public ::oox::ole::OleObjectInfo { ::rtl::OUString maShapeId; /// Shape identifier for shape lookup. ::rtl::OUString maName; /// Programmatical name of the OLE object. bool mbAutoLoad; const bool mbDmlShape; /// True = DrawingML shape (PowerPoint), false = VML shape (Excel/Word). explicit OleObjectInfo( bool bDmlShape = false ); /** Sets the string representation of the passed numeric shape identifier. */ void setShapeId( sal_Int32 nShapeId ); }; // ============================================================================ /** Contains information about a form control embedded in a draw page. */ struct ControlInfo { ::rtl::OUString maShapeId; /// Shape identifier for shape lookup. ::rtl::OUString maFragmentPath; /// Path to the fragment describing the form control properties. ::rtl::OUString maName; /// Programmatical name of the form control. explicit ControlInfo(); /** Sets the string representation of the passed numeric shape identifier. */ void setShapeId( sal_Int32 nShapeId ); }; // ============================================================================ /** Represents the collection of VML shapes for a complete draw page. */ class Drawing { public: explicit Drawing( ::oox::core::XmlFilterBase& rFilter, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& rxDrawPage, DrawingType eType ); virtual ~Drawing(); /** Returns the filter object that imports/exports this VML drawing. */ inline ::oox::core::XmlFilterBase& getFilter() const { return mrFilter; } /** Returns the application type containing the drawing. */ inline DrawingType getType() const { return meType; } /** Returns read/write access to the container of shapes and templates. */ inline ShapeContainer& getShapes() { return *mxShapes; } /** Returns read access to the container of shapes and templates. */ inline const ShapeContainer& getShapes() const { return *mxShapes; } /** Returns the form object used to process ActiveX form controls. */ ::oox::ole::EmbeddedForm& getControlForm() const; /** Registers the passed embedded OLE object. The related shape will then load the OLE object data from the specified fragment. */ void registerOleObject( const OleObjectInfo& rOleObject ); /** Registers the passed embedded form control. The related shape will then load the control properties from the specified fragment. */ void registerControl( const ControlInfo& rControl ); /** Final processing after import of the fragment. */ void finalizeFragmentImport(); /** Creates and inserts all UNO shapes into the passed container. The virtual function notifyShapeInserted() will be called for each new shape. */ void convertAndInsert() const; /** Returns the registered info structure for an OLE object, if extant. */ const OleObjectInfo* getOleObjectInfo( const ::rtl::OUString& rShapeId ) const; /** Returns the registered info structure for a form control, if extant. */ const ControlInfo* getControlInfo( const ::rtl::OUString& rShapeId ) const; /** Derived classes may disable conversion of specific shapes. */ virtual bool isShapeSupported( const ShapeBase& rShape ) const; /** Derived classes may calculate the shape rectangle from a non-standard anchor information string. */ virtual bool convertShapeClientAnchor( ::com::sun::star::awt::Rectangle& orShapeRect, const ::rtl::OUString& rShapeAnchor ) const; /** Derived classes may convert additional form control properties from the passed VML shape client data. */ virtual void convertControlClientData( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& rxCtrlModel, const ShapeClientData& rClientData ) const; /** Derived classes may want to know that a shape has been inserted. Will be called from the convertAndInsert() implementation. */ virtual void notifyShapeInserted( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rxShape, const ::com::sun::star::awt::Rectangle& rShapeRect ); private: typedef ::std::auto_ptr< ::oox::ole::EmbeddedForm > EmbeddedFormPtr; typedef ::std::auto_ptr< ShapeContainer > ShapeContainerPtr; typedef ::std::map< ::rtl::OUString, OleObjectInfo > OleObjectInfoMap; typedef ::std::map< ::rtl::OUString, ControlInfo > ControlInfoMap; ::oox::core::XmlFilterBase& mrFilter; /// Filter object that imports/exports the VML drawing. ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > mxDrawPage; /// UNO draw page used to insert the shapes. mutable EmbeddedFormPtr mxCtrlForm; /// The control form used to process ActiveX controls. ShapeContainerPtr mxShapes; /// All shapes and shape templates. OleObjectInfoMap maOleObjects; /// Info about all embedded OLE objects, mapped by shape id. ControlInfoMap maControls; /// Info about all embedded form controls, mapped by control name. const DrawingType meType; /// Application type containing the drawing. }; // ============================================================================ } // namespace vml } // namespace oox #endif <commit_msg>dr78: typo in comment<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. * ************************************************************************/ #ifndef OOX_VML_VMLDRAWING_HXX #define OOX_VML_VMLDRAWING_HXX #include <map> #include <memory> #include "oox/ole/oleobjecthelper.hxx" namespace com { namespace sun { namespace star { namespace awt { struct Rectangle; } namespace awt { class XControlModel; } namespace drawing { class XDrawPage; } namespace drawing { class XShape; } } } } namespace oox { namespace core { class XmlFilterBase; } } namespace oox { namespace ole { class EmbeddedForm; } } namespace oox { namespace vml { class ShapeBase; class ShapeContainer; struct ShapeClientData; // ============================================================================ /** Enumerates different types of VML drawings. */ enum DrawingType { VMLDRAWING_WORD, /// Word: One shape per drawing. VMLDRAWING_EXCEL, /// Excel: OLE objects are part of VML. VMLDRAWING_POWERPOINT /// PowerPoint: OLE objects are part of DrawingML. }; // ============================================================================ /** Contains information about an OLE object embedded in a draw page. */ struct OleObjectInfo : public ::oox::ole::OleObjectInfo { ::rtl::OUString maShapeId; /// Shape identifier for shape lookup. ::rtl::OUString maName; /// Programmatical name of the OLE object. bool mbAutoLoad; const bool mbDmlShape; /// True = DrawingML shape (PowerPoint), false = VML shape (Excel/Word). explicit OleObjectInfo( bool bDmlShape = false ); /** Sets the string representation of the passed numeric shape identifier. */ void setShapeId( sal_Int32 nShapeId ); }; // ============================================================================ /** Contains information about a form control embedded in a draw page. */ struct ControlInfo { ::rtl::OUString maShapeId; /// Shape identifier for shape lookup. ::rtl::OUString maFragmentPath; /// Path to the fragment describing the form control properties. ::rtl::OUString maName; /// Programmatical name of the form control. explicit ControlInfo(); /** Sets the string representation of the passed numeric shape identifier. */ void setShapeId( sal_Int32 nShapeId ); }; // ============================================================================ /** Represents the collection of VML shapes for a complete draw page. */ class Drawing { public: explicit Drawing( ::oox::core::XmlFilterBase& rFilter, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& rxDrawPage, DrawingType eType ); virtual ~Drawing(); /** Returns the filter object that imports/exports this VML drawing. */ inline ::oox::core::XmlFilterBase& getFilter() const { return mrFilter; } /** Returns the application type containing the drawing. */ inline DrawingType getType() const { return meType; } /** Returns read/write access to the container of shapes and templates. */ inline ShapeContainer& getShapes() { return *mxShapes; } /** Returns read access to the container of shapes and templates. */ inline const ShapeContainer& getShapes() const { return *mxShapes; } /** Returns the form object used to process ActiveX form controls. */ ::oox::ole::EmbeddedForm& getControlForm() const; /** Registers the passed embedded OLE object. The related shape will then load the OLE object data from the specified fragment. */ void registerOleObject( const OleObjectInfo& rOleObject ); /** Registers the passed embedded form control. The related shape will then load the control properties from the specified fragment. */ void registerControl( const ControlInfo& rControl ); /** Final processing after import of the fragment. */ void finalizeFragmentImport(); /** Creates and inserts all UNO shapes into the draw page. The virtual function notifyShapeInserted() will be called for each new shape. */ void convertAndInsert() const; /** Returns the registered info structure for an OLE object, if extant. */ const OleObjectInfo* getOleObjectInfo( const ::rtl::OUString& rShapeId ) const; /** Returns the registered info structure for a form control, if extant. */ const ControlInfo* getControlInfo( const ::rtl::OUString& rShapeId ) const; /** Derived classes may disable conversion of specific shapes. */ virtual bool isShapeSupported( const ShapeBase& rShape ) const; /** Derived classes may calculate the shape rectangle from a non-standard anchor information string. */ virtual bool convertShapeClientAnchor( ::com::sun::star::awt::Rectangle& orShapeRect, const ::rtl::OUString& rShapeAnchor ) const; /** Derived classes may convert additional form control properties from the passed VML shape client data. */ virtual void convertControlClientData( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& rxCtrlModel, const ShapeClientData& rClientData ) const; /** Derived classes may want to know that a shape has been inserted. Will be called from the convertAndInsert() implementation. */ virtual void notifyShapeInserted( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rxShape, const ::com::sun::star::awt::Rectangle& rShapeRect ); private: typedef ::std::auto_ptr< ::oox::ole::EmbeddedForm > EmbeddedFormPtr; typedef ::std::auto_ptr< ShapeContainer > ShapeContainerPtr; typedef ::std::map< ::rtl::OUString, OleObjectInfo > OleObjectInfoMap; typedef ::std::map< ::rtl::OUString, ControlInfo > ControlInfoMap; ::oox::core::XmlFilterBase& mrFilter; /// Filter object that imports/exports the VML drawing. ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > mxDrawPage; /// UNO draw page used to insert the shapes. mutable EmbeddedFormPtr mxCtrlForm; /// The control form used to process ActiveX controls. ShapeContainerPtr mxShapes; /// All shapes and shape templates. OleObjectInfoMap maOleObjects; /// Info about all embedded OLE objects, mapped by shape id. ControlInfoMap maControls; /// Info about all embedded form controls, mapped by control name. const DrawingType meType; /// Application type containing the drawing. }; // ============================================================================ } // namespace vml } // namespace oox #endif <|endoftext|>
<commit_before>// Copyright (c) 2018-2019 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bls/bls.h> #include <hash.h> #include <random.h> #include <tinyformat.h> #ifndef BUILD_SYSCOIN_INTERNAL #include <support/allocators/mt_pooled_secure.h> #endif #include <assert.h> #include <string.h> void CBLSId::SetInt(int x) { impl.SetHex(strprintf("%x", x)); fValid = true; UpdateHash(); } void CBLSId::SetHash(const uint256& hash) { impl = hash; fValid = true; UpdateHash(); } CBLSId CBLSId::FromInt(int64_t i) { CBLSId id; id.SetInt(i); return id; } CBLSId CBLSId::FromHash(const uint256& hash) { CBLSId id; id.SetHash(hash); return id; } void CBLSSecretKey::AggregateInsecure(const CBLSSecretKey& o) { assert(IsValid() && o.IsValid()); impl = bls::PrivateKey::AggregateInsecure({impl, o.impl}); UpdateHash(); } CBLSSecretKey CBLSSecretKey::AggregateInsecure(const std::vector<CBLSSecretKey>& sks) { if (sks.empty()) { return CBLSSecretKey(); } std::vector<bls::PrivateKey> v; v.reserve(sks.size()); for (auto& sk : sks) { v.emplace_back(sk.impl); } auto agg = bls::PrivateKey::AggregateInsecure(v); CBLSSecretKey ret; ret.impl = agg; ret.fValid = true; ret.UpdateHash(); return ret; } #ifndef BUILD_SYSCOIN_INTERNAL void CBLSSecretKey::MakeNewKey() { unsigned char buf[32]; while (true) { GetStrongRandBytes(buf, sizeof(buf)); try { impl = bls::PrivateKey::FromBytes((const uint8_t*)buf); break; } catch (...) { } } fValid = true; UpdateHash(); } #endif bool CBLSSecretKey::SecretKeyShare(const std::vector<CBLSSecretKey>& msk, const CBLSId& _id) { fValid = false; UpdateHash(); if (!_id.IsValid()) { return false; } std::vector<bls::PrivateKey> mskVec; mskVec.reserve(msk.size()); for (const CBLSSecretKey& sk : msk) { if (!sk.IsValid()) { return false; } mskVec.emplace_back(sk.impl); } try { impl = bls::BLS::PrivateKeyShare(mskVec, (const uint8_t*)_id.impl.begin()); } catch (...) { return false; } fValid = true; UpdateHash(); return true; } CBLSPublicKey CBLSSecretKey::GetPublicKey() const { if (!IsValid()) { return CBLSPublicKey(); } CBLSPublicKey pubKey; pubKey.impl = impl.GetPublicKey(); pubKey.fValid = true; pubKey.UpdateHash(); return pubKey; } CBLSSignature CBLSSecretKey::Sign(const uint256& hash) const { if (!IsValid()) { return CBLSSignature(); } CBLSSignature sigRet; sigRet.impl = impl.SignInsecurePrehashed((const uint8_t*)hash.begin()); sigRet.fValid = true; sigRet.UpdateHash(); return sigRet; } void CBLSPublicKey::AggregateInsecure(const CBLSPublicKey& o) { assert(IsValid() && o.IsValid()); impl = bls::PublicKey::AggregateInsecure({impl, o.impl}); UpdateHash(); } CBLSPublicKey CBLSPublicKey::AggregateInsecure(const std::vector<CBLSPublicKey>& pks) { if (pks.empty()) { return CBLSPublicKey(); } std::vector<bls::PublicKey> v; v.reserve(pks.size()); for (auto& pk : pks) { v.emplace_back(pk.impl); } auto agg = bls::PublicKey::AggregateInsecure(v); CBLSPublicKey ret; ret.impl = agg; ret.fValid = true; ret.UpdateHash(); return ret; } bool CBLSPublicKey::PublicKeyShare(const std::vector<CBLSPublicKey>& mpk, const CBLSId& _id) { fValid = false; UpdateHash(); if (!_id.IsValid()) { return false; } std::vector<bls::PublicKey> mpkVec; mpkVec.reserve(mpk.size()); for (const CBLSPublicKey& pk : mpk) { if (!pk.IsValid()) { return false; } mpkVec.emplace_back(pk.impl); } try { impl = bls::BLS::PublicKeyShare(mpkVec, (const uint8_t*)_id.impl.begin()); } catch (...) { return false; } fValid = true; UpdateHash(); return true; } bool CBLSPublicKey::DHKeyExchange(const CBLSSecretKey& sk, const CBLSPublicKey& pk) { fValid = false; UpdateHash(); if (!sk.IsValid() || !pk.IsValid()) { return false; } impl = bls::BLS::DHKeyExchange(sk.impl, pk.impl); fValid = true; UpdateHash(); return true; } void CBLSSignature::AggregateInsecure(const CBLSSignature& o) { assert(IsValid() && o.IsValid()); impl = bls::InsecureSignature::Aggregate({impl, o.impl}); UpdateHash(); } CBLSSignature CBLSSignature::AggregateInsecure(const std::vector<CBLSSignature>& sigs) { if (sigs.empty()) { return CBLSSignature(); } std::vector<bls::InsecureSignature> v; v.reserve(sigs.size()); for (auto& pk : sigs) { v.emplace_back(pk.impl); } auto agg = bls::InsecureSignature::Aggregate(v); CBLSSignature ret; ret.impl = agg; ret.fValid = true; ret.UpdateHash(); return ret; } CBLSSignature CBLSSignature::AggregateSecure(const std::vector<CBLSSignature>& sigs, const std::vector<CBLSPublicKey>& pks, const uint256& hash) { if (sigs.size() != pks.size() || sigs.empty()) { return CBLSSignature(); } std::vector<bls::Signature> v; v.reserve(sigs.size()); for (size_t i = 0; i < sigs.size(); i++) { bls::AggregationInfo aggInfo = bls::AggregationInfo::FromMsgHash(pks[i].impl, hash.begin()); v.emplace_back(bls::Signature::FromInsecureSig(sigs[i].impl, aggInfo)); } auto aggSig = bls::Signature::AggregateSigs(v); CBLSSignature ret; ret.impl = aggSig.GetInsecureSig(); ret.fValid = true; ret.UpdateHash(); return ret; } void CBLSSignature::SubInsecure(const CBLSSignature& o) { assert(IsValid() && o.IsValid()); impl = impl.DivideBy({o.impl}); UpdateHash(); } bool CBLSSignature::VerifyInsecure(const CBLSPublicKey& pubKey, const uint256& hash) const { if (!IsValid() || !pubKey.IsValid()) { return false; } try { return impl.Verify({(const uint8_t*)hash.begin()}, {pubKey.impl}); } catch (...) { return false; } } bool CBLSSignature::VerifyInsecureAggregated(const std::vector<CBLSPublicKey>& pubKeys, const std::vector<uint256>& hashes) const { if (!IsValid()) { return false; } assert(!pubKeys.empty() && !hashes.empty() && pubKeys.size() == hashes.size()); std::vector<bls::PublicKey> pubKeyVec; std::vector<const uint8_t*> hashes2; hashes2.reserve(hashes.size()); pubKeyVec.reserve(pubKeys.size()); for (size_t i = 0; i < pubKeys.size(); i++) { auto& p = pubKeys[i]; if (!p.IsValid()) { return false; } pubKeyVec.push_back(p.impl); hashes2.push_back((uint8_t*)hashes[i].begin()); } try { return impl.Verify(hashes2, pubKeyVec); } catch (...) { return false; } } bool CBLSSignature::VerifySecureAggregated(const std::vector<CBLSPublicKey>& pks, const uint256& hash) const { if (pks.empty()) { return false; } std::vector<bls::AggregationInfo> v; v.reserve(pks.size()); for (auto& pk : pks) { auto aggInfo = bls::AggregationInfo::FromMsgHash(pk.impl, hash.begin()); v.emplace_back(aggInfo); } bls::AggregationInfo aggInfo = bls::AggregationInfo::MergeInfos(v); bls::Signature aggSig = bls::Signature::FromInsecureSig(impl, aggInfo); return aggSig.Verify(); } bool CBLSSignature::Recover(const std::vector<CBLSSignature>& sigs, const std::vector<CBLSId>& ids) { fValid = false; UpdateHash(); if (sigs.empty() || ids.empty() || sigs.size() != ids.size()) { return false; } std::vector<bls::InsecureSignature> sigsVec; std::vector<const uint8_t*> idsVec; sigsVec.reserve(sigs.size()); idsVec.reserve(sigs.size()); for (size_t i = 0; i < sigs.size(); i++) { if (!sigs[i].IsValid() || !ids[i].IsValid()) { return false; } sigsVec.emplace_back(sigs[i].impl); idsVec.emplace_back(ids[i].impl.begin()); } try { impl = bls::BLS::RecoverSig(sigsVec, idsVec); } catch (...) { return false; } fValid = true; UpdateHash(); return true; } #ifndef BUILD_SYSCOIN_INTERNAL static std::once_flag init_flag; static mt_pooled_secure_allocator<uint8_t>* secure_allocator_instance; static void create_secure_allocator() { // make sure LockedPoolManager is initialized first (ensures destruction order) LockedPoolManager::Instance(); // static variable in function scope ensures it's initialized when first accessed // and destroyed before LockedPoolManager static mt_pooled_secure_allocator<uint8_t> a(sizeof(bn_t) + sizeof(size_t)); secure_allocator_instance = &a; } static mt_pooled_secure_allocator<uint8_t>& get_secure_allocator() { std::call_once(init_flag, create_secure_allocator); return *secure_allocator_instance; } static void* secure_allocate(size_t n) { uint8_t* ptr = get_secure_allocator().allocate(n + sizeof(size_t)); *(size_t*)ptr = n; return ptr + sizeof(size_t); } static void secure_free(void* p) { if (!p) { return; } uint8_t* ptr = (uint8_t*)p - sizeof(size_t); size_t n = *(size_t*)ptr; return get_secure_allocator().deallocate(ptr, n); } #endif bool BLSInit() { #ifndef BUILD_SYSCOIN_INTERNAL bls::BLS::SetSecureAllocator(secure_allocate, secure_free); #endif return true; } <commit_msg>bls: Directly assign some aggregation results (#3899)<commit_after>// Copyright (c) 2018-2019 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bls/bls.h> #include <hash.h> #include <random.h> #include <tinyformat.h> #ifndef BUILD_SYSCOIN_INTERNAL #include <support/allocators/mt_pooled_secure.h> #endif #include <assert.h> #include <string.h> void CBLSId::SetInt(int x) { impl.SetHex(strprintf("%x", x)); fValid = true; UpdateHash(); } void CBLSId::SetHash(const uint256& hash) { impl = hash; fValid = true; UpdateHash(); } CBLSId CBLSId::FromInt(int64_t i) { CBLSId id; id.SetInt(i); return id; } CBLSId CBLSId::FromHash(const uint256& hash) { CBLSId id; id.SetHash(hash); return id; } void CBLSSecretKey::AggregateInsecure(const CBLSSecretKey& o) { assert(IsValid() && o.IsValid()); impl = bls::PrivateKey::AggregateInsecure({impl, o.impl}); UpdateHash(); } CBLSSecretKey CBLSSecretKey::AggregateInsecure(const std::vector<CBLSSecretKey>& sks) { if (sks.empty()) { return CBLSSecretKey(); } std::vector<bls::PrivateKey> v; v.reserve(sks.size()); for (auto& sk : sks) { v.emplace_back(sk.impl); } CBLSSecretKey ret; ret.impl = bls::PrivateKey::AggregateInsecure(v); ret.fValid = true; ret.UpdateHash(); return ret; } #ifndef BUILD_SYSCOIN_INTERNAL void CBLSSecretKey::MakeNewKey() { unsigned char buf[32]; while (true) { GetStrongRandBytes(buf, sizeof(buf)); try { impl = bls::PrivateKey::FromBytes((const uint8_t*)buf); break; } catch (...) { } } fValid = true; UpdateHash(); } #endif bool CBLSSecretKey::SecretKeyShare(const std::vector<CBLSSecretKey>& msk, const CBLSId& _id) { fValid = false; UpdateHash(); if (!_id.IsValid()) { return false; } std::vector<bls::PrivateKey> mskVec; mskVec.reserve(msk.size()); for (const CBLSSecretKey& sk : msk) { if (!sk.IsValid()) { return false; } mskVec.emplace_back(sk.impl); } try { impl = bls::BLS::PrivateKeyShare(mskVec, (const uint8_t*)_id.impl.begin()); } catch (...) { return false; } fValid = true; UpdateHash(); return true; } CBLSPublicKey CBLSSecretKey::GetPublicKey() const { if (!IsValid()) { return CBLSPublicKey(); } CBLSPublicKey pubKey; pubKey.impl = impl.GetPublicKey(); pubKey.fValid = true; pubKey.UpdateHash(); return pubKey; } CBLSSignature CBLSSecretKey::Sign(const uint256& hash) const { if (!IsValid()) { return CBLSSignature(); } CBLSSignature sigRet; sigRet.impl = impl.SignInsecurePrehashed((const uint8_t*)hash.begin()); sigRet.fValid = true; sigRet.UpdateHash(); return sigRet; } void CBLSPublicKey::AggregateInsecure(const CBLSPublicKey& o) { assert(IsValid() && o.IsValid()); impl = bls::PublicKey::AggregateInsecure({impl, o.impl}); UpdateHash(); } CBLSPublicKey CBLSPublicKey::AggregateInsecure(const std::vector<CBLSPublicKey>& pks) { if (pks.empty()) { return CBLSPublicKey(); } std::vector<bls::PublicKey> v; v.reserve(pks.size()); for (auto& pk : pks) { v.emplace_back(pk.impl); } CBLSPublicKey ret; ret.impl = bls::PublicKey::AggregateInsecure(v); ret.fValid = true; ret.UpdateHash(); return ret; } bool CBLSPublicKey::PublicKeyShare(const std::vector<CBLSPublicKey>& mpk, const CBLSId& _id) { fValid = false; UpdateHash(); if (!_id.IsValid()) { return false; } std::vector<bls::PublicKey> mpkVec; mpkVec.reserve(mpk.size()); for (const CBLSPublicKey& pk : mpk) { if (!pk.IsValid()) { return false; } mpkVec.emplace_back(pk.impl); } try { impl = bls::BLS::PublicKeyShare(mpkVec, (const uint8_t*)_id.impl.begin()); } catch (...) { return false; } fValid = true; UpdateHash(); return true; } bool CBLSPublicKey::DHKeyExchange(const CBLSSecretKey& sk, const CBLSPublicKey& pk) { fValid = false; UpdateHash(); if (!sk.IsValid() || !pk.IsValid()) { return false; } impl = bls::BLS::DHKeyExchange(sk.impl, pk.impl); fValid = true; UpdateHash(); return true; } void CBLSSignature::AggregateInsecure(const CBLSSignature& o) { assert(IsValid() && o.IsValid()); impl = bls::InsecureSignature::Aggregate({impl, o.impl}); UpdateHash(); } CBLSSignature CBLSSignature::AggregateInsecure(const std::vector<CBLSSignature>& sigs) { if (sigs.empty()) { return CBLSSignature(); } std::vector<bls::InsecureSignature> v; v.reserve(sigs.size()); for (auto& pk : sigs) { v.emplace_back(pk.impl); } CBLSSignature ret; ret.impl = bls::InsecureSignature::Aggregate(v); ret.fValid = true; ret.UpdateHash(); return ret; } CBLSSignature CBLSSignature::AggregateSecure(const std::vector<CBLSSignature>& sigs, const std::vector<CBLSPublicKey>& pks, const uint256& hash) { if (sigs.size() != pks.size() || sigs.empty()) { return CBLSSignature(); } std::vector<bls::Signature> v; v.reserve(sigs.size()); for (size_t i = 0; i < sigs.size(); i++) { bls::AggregationInfo aggInfo = bls::AggregationInfo::FromMsgHash(pks[i].impl, hash.begin()); v.emplace_back(bls::Signature::FromInsecureSig(sigs[i].impl, aggInfo)); } CBLSSignature ret; ret.impl = bls::Signature::AggregateSigs(v).GetInsecureSig(); ret.fValid = true; ret.UpdateHash(); return ret; } void CBLSSignature::SubInsecure(const CBLSSignature& o) { assert(IsValid() && o.IsValid()); impl = impl.DivideBy({o.impl}); UpdateHash(); } bool CBLSSignature::VerifyInsecure(const CBLSPublicKey& pubKey, const uint256& hash) const { if (!IsValid() || !pubKey.IsValid()) { return false; } try { return impl.Verify({(const uint8_t*)hash.begin()}, {pubKey.impl}); } catch (...) { return false; } } bool CBLSSignature::VerifyInsecureAggregated(const std::vector<CBLSPublicKey>& pubKeys, const std::vector<uint256>& hashes) const { if (!IsValid()) { return false; } assert(!pubKeys.empty() && !hashes.empty() && pubKeys.size() == hashes.size()); std::vector<bls::PublicKey> pubKeyVec; std::vector<const uint8_t*> hashes2; hashes2.reserve(hashes.size()); pubKeyVec.reserve(pubKeys.size()); for (size_t i = 0; i < pubKeys.size(); i++) { auto& p = pubKeys[i]; if (!p.IsValid()) { return false; } pubKeyVec.push_back(p.impl); hashes2.push_back((uint8_t*)hashes[i].begin()); } try { return impl.Verify(hashes2, pubKeyVec); } catch (...) { return false; } } bool CBLSSignature::VerifySecureAggregated(const std::vector<CBLSPublicKey>& pks, const uint256& hash) const { if (pks.empty()) { return false; } std::vector<bls::AggregationInfo> v; v.reserve(pks.size()); for (auto& pk : pks) { auto aggInfo = bls::AggregationInfo::FromMsgHash(pk.impl, hash.begin()); v.emplace_back(aggInfo); } bls::AggregationInfo aggInfo = bls::AggregationInfo::MergeInfos(v); bls::Signature aggSig = bls::Signature::FromInsecureSig(impl, aggInfo); return aggSig.Verify(); } bool CBLSSignature::Recover(const std::vector<CBLSSignature>& sigs, const std::vector<CBLSId>& ids) { fValid = false; UpdateHash(); if (sigs.empty() || ids.empty() || sigs.size() != ids.size()) { return false; } std::vector<bls::InsecureSignature> sigsVec; std::vector<const uint8_t*> idsVec; sigsVec.reserve(sigs.size()); idsVec.reserve(sigs.size()); for (size_t i = 0; i < sigs.size(); i++) { if (!sigs[i].IsValid() || !ids[i].IsValid()) { return false; } sigsVec.emplace_back(sigs[i].impl); idsVec.emplace_back(ids[i].impl.begin()); } try { impl = bls::BLS::RecoverSig(sigsVec, idsVec); } catch (...) { return false; } fValid = true; UpdateHash(); return true; } #ifndef BUILD_SYSCOIN_INTERNAL static std::once_flag init_flag; static mt_pooled_secure_allocator<uint8_t>* secure_allocator_instance; static void create_secure_allocator() { // make sure LockedPoolManager is initialized first (ensures destruction order) LockedPoolManager::Instance(); // static variable in function scope ensures it's initialized when first accessed // and destroyed before LockedPoolManager static mt_pooled_secure_allocator<uint8_t> a(sizeof(bn_t) + sizeof(size_t)); secure_allocator_instance = &a; } static mt_pooled_secure_allocator<uint8_t>& get_secure_allocator() { std::call_once(init_flag, create_secure_allocator); return *secure_allocator_instance; } static void* secure_allocate(size_t n) { uint8_t* ptr = get_secure_allocator().allocate(n + sizeof(size_t)); *(size_t*)ptr = n; return ptr + sizeof(size_t); } static void secure_free(void* p) { if (!p) { return; } uint8_t* ptr = (uint8_t*)p - sizeof(size_t); size_t n = *(size_t*)ptr; return get_secure_allocator().deallocate(ptr, n); } #endif bool BLSInit() { #ifndef BUILD_SYSCOIN_INTERNAL bls::BLS::SetSecureAllocator(secure_allocate, secure_free); #endif return true; } <|endoftext|>
<commit_before>#include "chainparamsbase.h" #include "callrpc.h" #include "util.h" #include "utilstrencodings.h" #include "rpc/protocol.h" #include "support/events.h" #include "rpc/client.h" #include <event2/buffer.h> #include <event2/keyvalq_struct.h> /** Reply structure for request_done to fill in */ struct HTTPReply { HTTPReply(): status(0), error(-1) {} int status; int error; std::string body; }; const char *http_errorstring(int code) { switch(code) { #if LIBEVENT_VERSION_NUMBER >= 0x02010300 case EVREQ_HTTP_TIMEOUT: return "timeout reached"; case EVREQ_HTTP_EOF: return "EOF reached"; case EVREQ_HTTP_INVALID_HEADER: return "error while reading header, or invalid header"; case EVREQ_HTTP_BUFFER_ERROR: return "error encountered while reading or writing"; case EVREQ_HTTP_REQUEST_CANCEL: return "request was canceled"; case EVREQ_HTTP_DATA_TOO_LONG: return "response body is larger than allowed"; #endif default: return "unknown"; } } static void http_request_done(struct evhttp_request *req, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); if (req == NULL) { /* If req is NULL, it means an error occurred while connecting: the * error code will have been passed to http_error_cb. */ reply->status = 0; return; } reply->status = evhttp_request_get_response_code(req); struct evbuffer *buf = evhttp_request_get_input_buffer(req); if (buf) { size_t size = evbuffer_get_length(buf); const char *data = (const char*)evbuffer_pullup(buf, size); if (data) reply->body = std::string(data, size); evbuffer_drain(buf, size); } } #if LIBEVENT_VERSION_NUMBER >= 0x02010300 static void http_error_cb(enum evhttp_request_error err, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); reply->error = err; } #endif UniValue CallRPC(const std::string& strMethod, const UniValue& params, bool connectToMainchain) { std::string strhost = "-rpcconnect"; std::string strport = "-rpcport"; std::string struser = "-rpcuser"; std::string strpassword = "-rpcpassword"; int port = GetArg(strport, BaseParams().RPCPort()); if (connectToMainchain) { strhost = "-mainchainhost"; strport = "-mainchainrpcport"; strpassword = "-mainchainrpcpassword"; struser = "-mainchainrpcuser"; port = GetArg(strport, BaseParams().MainchainRPCPort()); } std::string host = GetArg(strhost, DEFAULT_RPCCONNECT); // Obtain event base raii_event_base base = obtain_event_base(); // Synchronously look up hostname raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port); evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT)); HTTPReply response; raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response); if (req == NULL) throw std::runtime_error("create http request failed"); #if LIBEVENT_VERSION_NUMBER >= 0x02010300 evhttp_request_set_error_cb(req.get(), http_error_cb); #endif // Get credentials std::string strRPCUserColonPass; if (GetArg("-rpcpassword", "") == "") { // Try fall back to cookie-based authentication if no password is provided if (!connectToMainchain && !GetAuthCookie(&strRPCUserColonPass)) { throw std::runtime_error(strprintf( _("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"), GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str())); } // Try fall back to cookie-based authentication if no password is provided if (connectToMainchain && !GetMainchainAuthCookie(&strRPCUserColonPass)) { throw std::runtime_error(strprintf( _("Could not locate mainchain RPC credentials. No authentication cookie could be found, and no mainchainrpcpassword is set in the configuration file (%s)"), GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str())); } } else { if (struser == "") throw std::runtime_error( _("Could not locate mainchain RPC credentials. No authentication cookie could be found, and no mainchainrpcuser is set in the configuration file")); else strRPCUserColonPass = GetArg(struser, "") + ":" + GetArg(strpassword, ""); } struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get()); assert(output_headers); evhttp_add_header(output_headers, "Host", host.c_str()); evhttp_add_header(output_headers, "Connection", "close"); evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str()); // Attach request data std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n"; struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get()); assert(output_buffer); evbuffer_add(output_buffer, strRequest.data(), strRequest.size()); int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/"); req.release(); // ownership moved to evcon in above call if (r != 0) { throw CConnectionFailed("send http request failed"); } event_base_dispatch(base.get()); if (response.status == 0) throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error)); else if (response.status == HTTP_UNAUTHORIZED) if (connectToMainchain) throw std::runtime_error("incorrect mainchainrpcuser or mainchainrpcpassword (authorization failed)"); else throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) throw std::runtime_error(strprintf("server returned HTTP error %d", response.status)); else if (response.body.empty()) throw std::runtime_error("no response from server"); // Parse reply UniValue valReply(UniValue::VSTR); if (!valReply.read(response.body)) throw std::runtime_error("couldn't parse reply from server"); const UniValue& reply = valReply.get_obj(); if (reply.empty()) throw std::runtime_error("expected reply to have result, error and id properties"); return reply; } bool IsConfirmedBitcoinBlock(const uint256& genesishash, const uint256& hash, int nMinConfirmationDepth) { try { UniValue params(UniValue::VARR); params.push_back(UniValue(0)); UniValue reply = CallRPC("getblockhash", params, true); if (!find_value(reply, "error").isNull()) return false; UniValue result = find_value(reply, "result"); if (!result.isStr()) return false; if (result.get_str() != genesishash.GetHex()) return false; params = UniValue(UniValue::VARR); params.push_back(hash.GetHex()); reply = CallRPC("getblock", params, true); if (!find_value(reply, "error").isNull()) return false; result = find_value(reply, "result"); if (!result.isObject()) return false; result = find_value(result.get_obj(), "confirmations"); return result.isNum() && result.get_int64() >= nMinConfirmationDepth; } catch (CConnectionFailed& e) { LogPrintf("ERROR: Lost connection to bitcoind RPC, you will want to restart after fixing this!\n"); return false; } catch (...) { LogPrintf("ERROR: Failure connecting to bitcoind RPC, you will want to restart after fixing this!\n"); return false; } return true; } <commit_msg>Use getblockheader instead of getblock when checking if block is in the main chain<commit_after>#include "chainparamsbase.h" #include "callrpc.h" #include "util.h" #include "utilstrencodings.h" #include "rpc/protocol.h" #include "support/events.h" #include "rpc/client.h" #include <event2/buffer.h> #include <event2/keyvalq_struct.h> /** Reply structure for request_done to fill in */ struct HTTPReply { HTTPReply(): status(0), error(-1) {} int status; int error; std::string body; }; const char *http_errorstring(int code) { switch(code) { #if LIBEVENT_VERSION_NUMBER >= 0x02010300 case EVREQ_HTTP_TIMEOUT: return "timeout reached"; case EVREQ_HTTP_EOF: return "EOF reached"; case EVREQ_HTTP_INVALID_HEADER: return "error while reading header, or invalid header"; case EVREQ_HTTP_BUFFER_ERROR: return "error encountered while reading or writing"; case EVREQ_HTTP_REQUEST_CANCEL: return "request was canceled"; case EVREQ_HTTP_DATA_TOO_LONG: return "response body is larger than allowed"; #endif default: return "unknown"; } } static void http_request_done(struct evhttp_request *req, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); if (req == NULL) { /* If req is NULL, it means an error occurred while connecting: the * error code will have been passed to http_error_cb. */ reply->status = 0; return; } reply->status = evhttp_request_get_response_code(req); struct evbuffer *buf = evhttp_request_get_input_buffer(req); if (buf) { size_t size = evbuffer_get_length(buf); const char *data = (const char*)evbuffer_pullup(buf, size); if (data) reply->body = std::string(data, size); evbuffer_drain(buf, size); } } #if LIBEVENT_VERSION_NUMBER >= 0x02010300 static void http_error_cb(enum evhttp_request_error err, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); reply->error = err; } #endif UniValue CallRPC(const std::string& strMethod, const UniValue& params, bool connectToMainchain) { std::string strhost = "-rpcconnect"; std::string strport = "-rpcport"; std::string struser = "-rpcuser"; std::string strpassword = "-rpcpassword"; int port = GetArg(strport, BaseParams().RPCPort()); if (connectToMainchain) { strhost = "-mainchainhost"; strport = "-mainchainrpcport"; strpassword = "-mainchainrpcpassword"; struser = "-mainchainrpcuser"; port = GetArg(strport, BaseParams().MainchainRPCPort()); } std::string host = GetArg(strhost, DEFAULT_RPCCONNECT); // Obtain event base raii_event_base base = obtain_event_base(); // Synchronously look up hostname raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port); evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT)); HTTPReply response; raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response); if (req == NULL) throw std::runtime_error("create http request failed"); #if LIBEVENT_VERSION_NUMBER >= 0x02010300 evhttp_request_set_error_cb(req.get(), http_error_cb); #endif // Get credentials std::string strRPCUserColonPass; if (GetArg("-rpcpassword", "") == "") { // Try fall back to cookie-based authentication if no password is provided if (!connectToMainchain && !GetAuthCookie(&strRPCUserColonPass)) { throw std::runtime_error(strprintf( _("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"), GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str())); } // Try fall back to cookie-based authentication if no password is provided if (connectToMainchain && !GetMainchainAuthCookie(&strRPCUserColonPass)) { throw std::runtime_error(strprintf( _("Could not locate mainchain RPC credentials. No authentication cookie could be found, and no mainchainrpcpassword is set in the configuration file (%s)"), GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str())); } } else { if (struser == "") throw std::runtime_error( _("Could not locate mainchain RPC credentials. No authentication cookie could be found, and no mainchainrpcuser is set in the configuration file")); else strRPCUserColonPass = GetArg(struser, "") + ":" + GetArg(strpassword, ""); } struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get()); assert(output_headers); evhttp_add_header(output_headers, "Host", host.c_str()); evhttp_add_header(output_headers, "Connection", "close"); evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str()); // Attach request data std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n"; struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get()); assert(output_buffer); evbuffer_add(output_buffer, strRequest.data(), strRequest.size()); int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/"); req.release(); // ownership moved to evcon in above call if (r != 0) { throw CConnectionFailed("send http request failed"); } event_base_dispatch(base.get()); if (response.status == 0) throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error)); else if (response.status == HTTP_UNAUTHORIZED) if (connectToMainchain) throw std::runtime_error("incorrect mainchainrpcuser or mainchainrpcpassword (authorization failed)"); else throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) throw std::runtime_error(strprintf("server returned HTTP error %d", response.status)); else if (response.body.empty()) throw std::runtime_error("no response from server"); // Parse reply UniValue valReply(UniValue::VSTR); if (!valReply.read(response.body)) throw std::runtime_error("couldn't parse reply from server"); const UniValue& reply = valReply.get_obj(); if (reply.empty()) throw std::runtime_error("expected reply to have result, error and id properties"); return reply; } bool IsConfirmedBitcoinBlock(const uint256& genesishash, const uint256& hash, int nMinConfirmationDepth) { try { UniValue params(UniValue::VARR); params.push_back(UniValue(0)); UniValue reply = CallRPC("getblockhash", params, true); if (!find_value(reply, "error").isNull()) return false; UniValue result = find_value(reply, "result"); if (!result.isStr()) return false; if (result.get_str() != genesishash.GetHex()) return false; params = UniValue(UniValue::VARR); params.push_back(hash.GetHex()); reply = CallRPC("getblockheader", params, true); if (!find_value(reply, "error").isNull()) return false; result = find_value(reply, "result"); if (!result.isObject()) return false; result = find_value(result.get_obj(), "confirmations"); return result.isNum() && result.get_int64() >= nMinConfirmationDepth; } catch (CConnectionFailed& e) { LogPrintf("ERROR: Lost connection to bitcoind RPC, you will want to restart after fixing this!\n"); return false; } catch (...) { LogPrintf("ERROR: Failure connecting to bitcoind RPC, you will want to restart after fixing this!\n"); return false; } return true; } <|endoftext|>
<commit_before><commit_msg>Add menu shortcuts on linux instead of & everywhere.<commit_after><|endoftext|>
<commit_before><commit_msg>win_safe_util: fix uninitialized variable<commit_after><|endoftext|>
<commit_before><commit_msg>render view: Clear the text selection cache when we get an empty selection.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); #if defined(OS_WIN) std::wstring pepper_plugin = plugin_lib.value(); #else std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value()); #endif pepper_plugin.append(L";application/x-ppapi-tests"); launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { const wchar_t kDocRoot[] = L"third_party/ppapi/tests"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateForkingServer(kDocRoot); ASSERT_TRUE(server); RunTestURL(server->TestServerPage("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_DeviceContext2D) { #else TEST_F(PPAPITest, DeviceContext2D) { #endif RunTest("DeviceContext2D"); } #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_ImageData) { #else TEST_F(PPAPITest, ImageData) { #endif RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } // http://crbug.com/48734 TEST_F(PPAPITest, FAILS_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest, PaintAgggregator) { RunTestViaHTTP("PaintAggregator"); } // http://crbug.com/48544 #if defined(OS_LINUX) // TODO(jabdelmalek) this fails on Linux for unknown reasons. TEST_F(PPAPITest, FAILS_Scrollbar) { #else TEST_F(PPAPITest, Scrollbar) { #endif RunTest("Scrollbar"); } <commit_msg>Enable URLLoader test on Windows and Linux.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); #if defined(OS_WIN) std::wstring pepper_plugin = plugin_lib.value(); #else std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value()); #endif pepper_plugin.append(L";application/x-ppapi-tests"); launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { const wchar_t kDocRoot[] = L"third_party/ppapi/tests"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateForkingServer(kDocRoot); ASSERT_TRUE(server); RunTestURL(server->TestServerPage("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_DeviceContext2D) { #else TEST_F(PPAPITest, DeviceContext2D) { #endif RunTest("DeviceContext2D"); } #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_ImageData) { #else TEST_F(PPAPITest, ImageData) { #endif RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } #if defined(OS_MACOSX) // http://crbug.com/48734 TEST_F(PPAPITest, FAILS_URLLoader) { #else TEST_F(PPAPITest, URLLoader) { #endif RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest, PaintAgggregator) { RunTestViaHTTP("PaintAggregator"); } // http://crbug.com/48544 #if defined(OS_LINUX) // TODO(jabdelmalek) this fails on Linux for unknown reasons. TEST_F(PPAPITest, FAILS_Scrollbar) { #else TEST_F(PPAPITest, Scrollbar) { #endif RunTest("Scrollbar"); } <|endoftext|>
<commit_before><commit_msg>Mark WorkerTest.WorkerMapGc as flaky<commit_after><|endoftext|>
<commit_before>/* * Copyright 2013 Jeremie Roy. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include <wchar.h> // wcslen #include "text_metrics.h" #include "utf8.h" TextMetrics::TextMetrics(FontManager* _fontManager) : m_fontManager(_fontManager) { clearText(); } void TextMetrics::clearText() { m_width = m_height = m_x = m_lineHeight = m_lineGap = 0; } void TextMetrics::appendText(FontHandle _fontHandle, const char* _string) { const FontInfo& font = m_fontManager->getFontInfo(_fontHandle); if (font.lineGap > m_lineGap) { m_lineGap = font.lineGap; } if ( (font.ascender - font.descender) > m_lineHeight) { m_height -= m_lineHeight; m_lineHeight = font.ascender - font.descender; m_height += m_lineHeight; } CodePoint codepoint = 0; uint32_t state = 0; for (; *_string; ++_string) { if (!utf8_decode(&state, (uint32_t*)&codepoint, *_string) ) { const GlyphInfo* glyph = m_fontManager->getGlyphInfo(_fontHandle, codepoint); if (NULL != glyph) { if (codepoint == L'\n') { m_height += m_lineGap + font.ascender - font.descender; m_lineGap = font.lineGap; m_lineHeight = font.ascender - font.descender; m_x = 0; break; } m_x += glyph->advance_x; if(m_x > m_width) { m_width = m_x; } } else { BX_CHECK(false, "Glyph not found"); } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); } void TextMetrics::appendText(FontHandle _fontHandle, const wchar_t* _string) { const FontInfo& font = m_fontManager->getFontInfo(_fontHandle); if (font.lineGap > m_lineGap) { m_lineGap = font.lineGap; } if ( (font.ascender - font.descender) > m_lineHeight) { m_height -= m_lineHeight; m_lineHeight = font.ascender - font.descender; m_height += m_lineHeight; } for (uint32_t ii = 0, end = (uint32_t)wcslen(_string); ii < end; ++ii) { uint32_t codepoint = _string[ii]; const GlyphInfo* glyph = m_fontManager->getGlyphInfo(_fontHandle, codepoint); if (NULL != glyph) { if (codepoint == L'\n') { m_height += m_lineGap + font.ascender - font.descender; m_lineGap = font.lineGap; m_lineHeight = font.ascender - font.descender; m_x = 0; break; } m_x += glyph->advance_x; if(m_x > m_width) { m_width = m_x; } } else { BX_CHECK(false, "Glyph not found"); } } } TextLineMetrics::TextLineMetrics(const FontInfo& _fontInfo) { m_lineHeight = _fontInfo.ascender - _fontInfo.descender + _fontInfo.lineGap; } uint32_t TextLineMetrics::getLineCount(const char* _string) const { CodePoint codepoint = 0; uint32_t state = 0; uint32_t lineCount = 1; for (; *_string; ++_string) { if (utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if(codepoint == L'\n') { ++lineCount; } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); return lineCount; } uint32_t TextLineMetrics::getLineCount(const wchar_t* _string) const { uint32_t lineCount = 1; for ( ;*_string != L'\0'; ++_string) { if(*_string == L'\n') { ++lineCount; } } return lineCount; } void TextLineMetrics::getSubText(const char* _string, uint32_t _firstLine, uint32_t _lastLine, const char*& _begin, const char*& _end) { CodePoint codepoint = 0; uint32_t state = 0; // y is bottom of a text line uint32_t currentLine = 0; while(*_string && (currentLine < _firstLine) ) { for (; *_string; ++_string) { if (utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if (codepoint == L'\n') { ++currentLine; ++_string; break; } } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); _begin = _string; while ( (*_string) && (currentLine < _lastLine) ) { for (; *_string; ++_string) { if(utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if(codepoint == L'\n') { ++currentLine; ++_string; break; } } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); _end = _string; } void TextLineMetrics::getSubText(const wchar_t* _string, uint32_t _firstLine, uint32_t _lastLine, const wchar_t*& _begin, const wchar_t*& _end) { uint32_t currentLine = 0; while ( (*_string != L'\0') && (currentLine < _firstLine) ) { for ( ;*_string != L'\0'; ++_string) { if(*_string == L'\n') { ++currentLine; ++_string; break; } } } _begin = _string; while ( (*_string != L'\0') && (currentLine < _lastLine) ) { for ( ;*_string != L'\0'; ++_string) { if(*_string == L'\n') { ++currentLine; ++_string; break; } } } _end = _string; } void TextLineMetrics::getVisibleText(const char* _string, float _top, float _bottom, const char*& _begin, const char*& _end) { CodePoint codepoint = 0; uint32_t state = 0; // y is bottom of a text line float y = m_lineHeight; while (*_string && (y < _top) ) { for (; *_string; ++_string) { if(utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if(codepoint == L'\n') { y += m_lineHeight; ++_string; break; } } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); _begin = _string; // y is now top of a text line y -= m_lineHeight; while ( (*_string) && (y < _bottom) ) { for (; *_string; ++_string) { if(utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if(codepoint == L'\n') { y += m_lineHeight; ++_string; break; } } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); _end = _string; } void TextLineMetrics::getVisibleText(const wchar_t* _string, float _top, float _bottom, const wchar_t*& _begin, const wchar_t*& _end) { // y is bottom of a text line float y = m_lineHeight; const wchar_t* _textEnd = _string + wcslen(_string); while (y < _top) { for (const wchar_t* _current = _string; _current < _textEnd; ++_current) { if(*_current == L'\n') { y += m_lineHeight; ++_string; break; } } } _begin = _string; // y is now top of a text line y -= m_lineHeight; while (y < _bottom ) { for (const wchar_t* _current = _string; _current < _textEnd; ++_current) { if(*_current == L'\n') { y += m_lineHeight; ++_string; break; } } } _end = _string; } <commit_msg>TextMetrics includes \n (#1063)<commit_after>/* * Copyright 2013 Jeremie Roy. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include <wchar.h> // wcslen #include "text_metrics.h" #include "utf8.h" TextMetrics::TextMetrics(FontManager* _fontManager) : m_fontManager(_fontManager) { clearText(); } void TextMetrics::clearText() { m_width = m_height = m_x = m_lineHeight = m_lineGap = 0; } void TextMetrics::appendText(FontHandle _fontHandle, const char* _string) { const FontInfo& font = m_fontManager->getFontInfo(_fontHandle); if (font.lineGap > m_lineGap) { m_lineGap = font.lineGap; } if ( (font.ascender - font.descender) > m_lineHeight) { m_height -= m_lineHeight; m_lineHeight = font.ascender - font.descender; m_height += m_lineHeight; } CodePoint codepoint = 0; uint32_t state = 0; for (; *_string; ++_string) { if (!utf8_decode(&state, (uint32_t*)&codepoint, *_string) ) { const GlyphInfo* glyph = m_fontManager->getGlyphInfo(_fontHandle, codepoint); if (NULL != glyph) { if (codepoint == L'\n') { m_height += m_lineGap + font.ascender - font.descender; m_lineGap = font.lineGap; m_lineHeight = font.ascender - font.descender; m_x = 0; } m_x += glyph->advance_x; if(m_x > m_width) { m_width = m_x; } } else { BX_CHECK(false, "Glyph not found"); } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); } void TextMetrics::appendText(FontHandle _fontHandle, const wchar_t* _string) { const FontInfo& font = m_fontManager->getFontInfo(_fontHandle); if (font.lineGap > m_lineGap) { m_lineGap = font.lineGap; } if ( (font.ascender - font.descender) > m_lineHeight) { m_height -= m_lineHeight; m_lineHeight = font.ascender - font.descender; m_height += m_lineHeight; } for (uint32_t ii = 0, end = (uint32_t)wcslen(_string); ii < end; ++ii) { uint32_t codepoint = _string[ii]; const GlyphInfo* glyph = m_fontManager->getGlyphInfo(_fontHandle, codepoint); if (NULL != glyph) { if (codepoint == L'\n') { m_height += m_lineGap + font.ascender - font.descender; m_lineGap = font.lineGap; m_lineHeight = font.ascender - font.descender; m_x = 0; } m_x += glyph->advance_x; if(m_x > m_width) { m_width = m_x; } } else { BX_CHECK(false, "Glyph not found"); } } } TextLineMetrics::TextLineMetrics(const FontInfo& _fontInfo) { m_lineHeight = _fontInfo.ascender - _fontInfo.descender + _fontInfo.lineGap; } uint32_t TextLineMetrics::getLineCount(const char* _string) const { CodePoint codepoint = 0; uint32_t state = 0; uint32_t lineCount = 1; for (; *_string; ++_string) { if (utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if(codepoint == L'\n') { ++lineCount; } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); return lineCount; } uint32_t TextLineMetrics::getLineCount(const wchar_t* _string) const { uint32_t lineCount = 1; for ( ;*_string != L'\0'; ++_string) { if(*_string == L'\n') { ++lineCount; } } return lineCount; } void TextLineMetrics::getSubText(const char* _string, uint32_t _firstLine, uint32_t _lastLine, const char*& _begin, const char*& _end) { CodePoint codepoint = 0; uint32_t state = 0; // y is bottom of a text line uint32_t currentLine = 0; while(*_string && (currentLine < _firstLine) ) { for (; *_string; ++_string) { if (utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if (codepoint == L'\n') { ++currentLine; ++_string; break; } } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); _begin = _string; while ( (*_string) && (currentLine < _lastLine) ) { for (; *_string; ++_string) { if(utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if(codepoint == L'\n') { ++currentLine; ++_string; break; } } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); _end = _string; } void TextLineMetrics::getSubText(const wchar_t* _string, uint32_t _firstLine, uint32_t _lastLine, const wchar_t*& _begin, const wchar_t*& _end) { uint32_t currentLine = 0; while ( (*_string != L'\0') && (currentLine < _firstLine) ) { for ( ;*_string != L'\0'; ++_string) { if(*_string == L'\n') { ++currentLine; ++_string; break; } } } _begin = _string; while ( (*_string != L'\0') && (currentLine < _lastLine) ) { for ( ;*_string != L'\0'; ++_string) { if(*_string == L'\n') { ++currentLine; ++_string; break; } } } _end = _string; } void TextLineMetrics::getVisibleText(const char* _string, float _top, float _bottom, const char*& _begin, const char*& _end) { CodePoint codepoint = 0; uint32_t state = 0; // y is bottom of a text line float y = m_lineHeight; while (*_string && (y < _top) ) { for (; *_string; ++_string) { if(utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if(codepoint == L'\n') { y += m_lineHeight; ++_string; break; } } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); _begin = _string; // y is now top of a text line y -= m_lineHeight; while ( (*_string) && (y < _bottom) ) { for (; *_string; ++_string) { if(utf8_decode(&state, (uint32_t*)&codepoint, *_string) == UTF8_ACCEPT) { if(codepoint == L'\n') { y += m_lineHeight; ++_string; break; } } } } BX_CHECK(state == UTF8_ACCEPT, "The string is not well-formed"); _end = _string; } void TextLineMetrics::getVisibleText(const wchar_t* _string, float _top, float _bottom, const wchar_t*& _begin, const wchar_t*& _end) { // y is bottom of a text line float y = m_lineHeight; const wchar_t* _textEnd = _string + wcslen(_string); while (y < _top) { for (const wchar_t* _current = _string; _current < _textEnd; ++_current) { if(*_current == L'\n') { y += m_lineHeight; ++_string; break; } } } _begin = _string; // y is now top of a text line y -= m_lineHeight; while (y < _bottom ) { for (const wchar_t* _current = _string; _current < _textEnd; ++_current) { if(*_current == L'\n') { y += m_lineHeight; ++_string; break; } } } _end = _string; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkIOUtil.h" #include "mitkPyramidImageRegistrationMethod.h" #include <itkTransformFileWriter.h> int mitkPyramidImageRegistrationMethodTest( int argc, char* argv[] ) { if( argc < 4 ) { MITK_ERROR << "Not enough input \n Usage: <TEST_NAME> fixed moving type [output_image [output_transform]]" << "\n \t fixed : the path to the fixed image \n" << " \t moving : path to the image to be registered" << " \t type : Affine or Rigid defining the type of the transformation" << " \t output_image : output file optional, (full) path, and optionally output_transform : also (full)path to file"; return EXIT_FAILURE; } MITK_TEST_BEGIN("PyramidImageRegistrationMethodTest"); mitk::Image::Pointer fixedImage = mitk::IOUtil::LoadImage( argv[1] ); mitk::Image::Pointer movingImage = mitk::IOUtil::LoadImage( argv[2] ); std::string type_flag( argv[3] ); mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetFixedImage( fixedImage ); registrationMethod->SetMovingImage( movingImage ); if( type_flag == "Rigid" ) { registrationMethod->SetTransformToRigid(); } else if( type_flag == "Affine" ) { registrationMethod->SetTransformToAffine(); } else { MITK_WARN << " No type specified, using 'Affine' ."; } registrationMethod->Update(); bool imageOutput = false; bool transformOutput = false; std::string image_out_filename, transform_out_filename; std::string first_output( argv[4] ); // check for txt, otherwise suppose it is an image if( first_output.find(".tfm") != std::string::npos ) { transformOutput = true; transform_out_filename = first_output; } else { imageOutput = true; image_out_filename = first_output; } if( argc > 4 ) { std::string second_output( argv[5] ); if( second_output.find(".tfm") != std::string::npos ) { transformOutput = true; transform_out_filename = second_output; } } MITK_INFO << " Selected output: " << transform_out_filename << " " << image_out_filename; try{ unsigned int paramCount = registrationMethod->GetNumberOfParameters(); double* params = new double[ paramCount ]; registrationMethod->GetParameters( &params[0] ); std::cout << "Parameters: "; for( unsigned int i=0; i< paramCount; i++) { std::cout << params[ i ] << " "; } std::cout << std::endl; if( imageOutput ) { mitk::IOUtil::SaveImage( registrationMethod->GetResampledMovingImage(), image_out_filename.c_str() ); } if( transformOutput ) { itk::TransformFileWriter::Pointer writer = itk::TransformFileWriter::New(); // Get transform parameter for resampling / saving // Affine if( paramCount == 12 ) { typedef itk::AffineTransform< double > TransformType; TransformType::Pointer transform = TransformType::New(); TransformType::ParametersType affine_params( paramCount ); registrationMethod->GetParameters( &affine_params[0] ); transform->SetParameters( affine_params ); writer->SetInput( transform ); } // Rigid else { typedef itk::Euler3DTransform< double > RigidTransformType; RigidTransformType::Pointer rtransform = RigidTransformType::New(); RigidTransformType::ParametersType rigid_params( paramCount ); registrationMethod->GetParameters( &rigid_params[0] ); rtransform->SetParameters( rigid_params ); writer->SetInput( rtransform ); } writer->SetFileName( transform_out_filename ); writer->Update(); } } catch( const std::exception &e) { MITK_ERROR << "Caught exception: " << e.what(); } MITK_TEST_END(); } <commit_msg>Switched expected ending for transform files to txt<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkIOUtil.h" #include "mitkPyramidImageRegistrationMethod.h" #include <itkTransformFileWriter.h> int mitkPyramidImageRegistrationMethodTest( int argc, char* argv[] ) { if( argc < 4 ) { MITK_ERROR << "Not enough input \n Usage: <TEST_NAME> fixed moving type [output_image [output_transform]]" << "\n \t fixed : the path to the fixed image \n" << " \t moving : path to the image to be registered" << " \t type : Affine or Rigid defining the type of the transformation" << " \t output_image : output file optional, (full) path, and optionally output_transform : also (full)path to file"; return EXIT_FAILURE; } MITK_TEST_BEGIN("PyramidImageRegistrationMethodTest"); mitk::Image::Pointer fixedImage = mitk::IOUtil::LoadImage( argv[1] ); mitk::Image::Pointer movingImage = mitk::IOUtil::LoadImage( argv[2] ); std::string type_flag( argv[3] ); mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetFixedImage( fixedImage ); registrationMethod->SetMovingImage( movingImage ); if( type_flag == "Rigid" ) { registrationMethod->SetTransformToRigid(); } else if( type_flag == "Affine" ) { registrationMethod->SetTransformToAffine(); } else { MITK_WARN << " No type specified, using 'Affine' ."; } registrationMethod->Update(); bool imageOutput = false; bool transformOutput = false; std::string image_out_filename, transform_out_filename; std::string first_output( argv[4] ); // check for txt, otherwise suppose it is an image if( first_output.find(".txt") != std::string::npos ) { transformOutput = true; transform_out_filename = first_output; } else { imageOutput = true; image_out_filename = first_output; } if( argc > 4 ) { std::string second_output( argv[5] ); if( second_output.find(".txt") != std::string::npos ) { transformOutput = true; transform_out_filename = second_output; } } MITK_INFO << " Selected output: " << transform_out_filename << " " << image_out_filename; try{ unsigned int paramCount = registrationMethod->GetNumberOfParameters(); double* params = new double[ paramCount ]; registrationMethod->GetParameters( &params[0] ); std::cout << "Parameters: "; for( unsigned int i=0; i< paramCount; i++) { std::cout << params[ i ] << " "; } std::cout << std::endl; if( imageOutput ) { mitk::IOUtil::SaveImage( registrationMethod->GetResampledMovingImage(), image_out_filename.c_str() ); } if( transformOutput ) { itk::TransformFileWriter::Pointer writer = itk::TransformFileWriter::New(); // Get transform parameter for resampling / saving // Affine if( paramCount == 12 ) { typedef itk::AffineTransform< double > TransformType; TransformType::Pointer transform = TransformType::New(); TransformType::ParametersType affine_params( paramCount ); registrationMethod->GetParameters( &affine_params[0] ); transform->SetParameters( affine_params ); writer->SetInput( transform ); } // Rigid else { typedef itk::Euler3DTransform< double > RigidTransformType; RigidTransformType::Pointer rtransform = RigidTransformType::New(); RigidTransformType::ParametersType rigid_params( paramCount ); registrationMethod->GetParameters( &rigid_params[0] ); rtransform->SetParameters( rigid_params ); writer->SetInput( rtransform ); } writer->SetFileName( transform_out_filename ); writer->Update(); } } catch( const std::exception &e) { MITK_ERROR << "Caught exception: " << e.what(); } MITK_TEST_END(); } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System */ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include "cvmfs_config.h" #include "uri_map.h" #include <cassert> #include <cinttypes> using namespace std; // NOLINT WebRequest::WebRequest(const struct mg_request_info *req) { string method = req->request_method; if (method == "GET") verb_ = WebRequest::kGet; else if (method == "PUT") verb_ = WebRequest::kPut; else if (method == "POST") verb_ = WebRequest::kPost; else if (method == "DELETE") verb_ = WebRequest::kDelete; else verb_ = WebRequest::kUnknown; uri_ = req->uri; } //------------------------------------------------------------------------------ void WebReply::Send(Code code, const string &msg, struct mg_connection *conn) { string header; switch (code) { case k200: header = "HTTP/1.1 200 OK\r\n"; break; case k400: header = "HTTP/1.1 400 Bad Request\r\n"; break; case k404: header = "HTTP/1.1 404 Not Found\r\n"; break; case k405: header = "HTTP/1.1 405 Method Not Allowed\r\n"; break; case k500: header = "HTTP/1.1 500 Internal Server Error\r\n"; break; default: assert(false); } mg_printf(conn, "%s" "Content-Type: text/plain\r\n" "Content-Length: %" PRIuPTR "\r\n" "\r\n" "%s", header.c_str(), msg.length(), msg.c_str()); } //------------------------------------------------------------------------------ void UriMap::Clear() { rules_.clear(); } void UriMap::Register(const WebRequest &request, UriHandler *handler) { Pathspec path_spec(request.uri()); assert(path_spec.IsValid() && path_spec.IsAbsolute()); rules_.push_back(Match(path_spec, request.verb(), handler)); } UriHandler *UriMap::Route(const WebRequest &request) { for (unsigned i = 0; i < rules_.size(); ++i) { if ( (rules_[i].uri_spec.IsPrefixMatching(request.uri())) && (rules_[i].verb == request.verb()) ) { return rules_[i].handler; } } return NULL; } bool UriMap::IsKnownUri(const std::string &uri) { for (unsigned i = 0; i < rules_.size(); ++i) { if (rules_[i].uri_spec.IsPrefixMatching(uri)) return true; } return false; } <commit_msg>fix c++11 style include<commit_after>/** * This file is part of the CernVM File System */ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include "cvmfs_config.h" #include "uri_map.h" #include <inttypes.h> #include <cassert> using namespace std; // NOLINT WebRequest::WebRequest(const struct mg_request_info *req) { string method = req->request_method; if (method == "GET") verb_ = WebRequest::kGet; else if (method == "PUT") verb_ = WebRequest::kPut; else if (method == "POST") verb_ = WebRequest::kPost; else if (method == "DELETE") verb_ = WebRequest::kDelete; else verb_ = WebRequest::kUnknown; uri_ = req->uri; } //------------------------------------------------------------------------------ void WebReply::Send(Code code, const string &msg, struct mg_connection *conn) { string header; switch (code) { case k200: header = "HTTP/1.1 200 OK\r\n"; break; case k400: header = "HTTP/1.1 400 Bad Request\r\n"; break; case k404: header = "HTTP/1.1 404 Not Found\r\n"; break; case k405: header = "HTTP/1.1 405 Method Not Allowed\r\n"; break; case k500: header = "HTTP/1.1 500 Internal Server Error\r\n"; break; default: assert(false); } mg_printf(conn, "%s" "Content-Type: text/plain\r\n" "Content-Length: %" PRIuPTR "\r\n" "\r\n" "%s", header.c_str(), msg.length(), msg.c_str()); } //------------------------------------------------------------------------------ void UriMap::Clear() { rules_.clear(); } void UriMap::Register(const WebRequest &request, UriHandler *handler) { Pathspec path_spec(request.uri()); assert(path_spec.IsValid() && path_spec.IsAbsolute()); rules_.push_back(Match(path_spec, request.verb(), handler)); } UriHandler *UriMap::Route(const WebRequest &request) { for (unsigned i = 0; i < rules_.size(); ++i) { if ( (rules_[i].uri_spec.IsPrefixMatching(request.uri())) && (rules_[i].verb == request.verb()) ) { return rules_[i].handler; } } return NULL; } bool UriMap::IsKnownUri(const std::string &uri) { for (unsigned i = 0; i < rules_.size(); ++i) { if (rules_[i].uri_spec.IsPrefixMatching(uri)) return true; } return false; } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ryan Luna, Ioan Sucan */ #include "console_bridge/console.h" #include <boost/thread/mutex.hpp> #include <iostream> #include <cstdio> #include <cstdarg> /// @cond IGNORE struct DefaultOutputHandler { DefaultOutputHandler(void) { output_handler_ = static_cast<console_bridge::OutputHandler*>(&std_output_handler_); previous_output_handler_ = output_handler_; logLevel_ = console_bridge::LOG_DEBUG; } console_bridge::OutputHandlerSTD std_output_handler_; console_bridge::OutputHandler *output_handler_; console_bridge::OutputHandler *previous_output_handler_; console_bridge::LogLevel logLevel_; boost::mutex lock_; // it is likely the outputhandler does some I/O, so we serialize it }; // we use this function because we want to handle static initialization correctly // however, the first run of this function is not thread safe, due to the use of a static // variable inside the function. For this reason, we ensure the first call happens during // static initialization using a proxy class static DefaultOutputHandler* getDOH(void) { static DefaultOutputHandler DOH; return &DOH; } #define USE_DOH \ DefaultOutputHandler *doh = getDOH(); \ boost::mutex::scoped_lock slock(doh->lock_) #define MAX_BUFFER_SIZE 1024 /// @endcond void console_bridge::noOutputHandler(void) { USE_DOH; doh->previous_output_handler_ = doh->output_handler_; doh->output_handler_ = NULL; } void console_bridge::restorePreviousOutputHandler(void) { USE_DOH; std::swap(doh->previous_output_handler_, doh->output_handler_); } void console_bridge::useOutputHandler(OutputHandler *oh) { USE_DOH; doh->previous_output_handler_ = doh->output_handler_; doh->output_handler_ = oh; } console_bridge::OutputHandler* console_bridge::getOutputHandler(void) { return getDOH()->output_handler_; } void console_bridge::log(const char *file, int line, LogLevel level, const char* m, ...) { USE_DOH; if (doh->output_handler_ && level >= doh->logLevel_) { va_list __ap; va_start(__ap, m); char buf[MAX_BUFFER_SIZE]; vsnprintf(buf, sizeof(buf), m, __ap); va_end(__ap); buf[MAX_BUFFER_SIZE - 1] = '\0'; doh->output_handler_->log(buf, level, file, line); } } void console_bridge::setLogLevel(LogLevel level) { USE_DOH; doh->logLevel_ = level; } console_bridge::LogLevel console_bridge::getLogLevel(void) { USE_DOH; return doh->logLevel_; } static const char* LogLevelString[4] = {"Debug: ", "Info: ", "Warning: ", "Error: "}; void console_bridge::OutputHandlerSTD::log(const std::string &text, LogLevel level, const char *filename, int line) { if (level >= LOG_WARN) { std::cerr << LogLevelString[level] << text << std::endl; std::cerr << " at line " << line << " in " << filename << std::endl; std::cerr.flush(); } else { std::cout << LogLevelString[level] << text << std::endl; std::cout.flush(); } } console_bridge::OutputHandlerFile::OutputHandlerFile(const char *filename) : OutputHandler() { file_ = fopen(filename, "a"); if (!file_) std::cerr << "Unable to open log file: '" << filename << "'" << std::endl; } console_bridge::OutputHandlerFile::~OutputHandlerFile(void) { if (file_) if (fclose(file_) != 0) std::cerr << "Error closing logfile" << std::endl; } void console_bridge::OutputHandlerFile::log(const std::string &text, LogLevel level, const char *filename, int line) { if (file_) { fprintf(file_, "%s%s\n", LogLevelString[level], text.c_str()); if(level >= LOG_WARN) fprintf(file_, " at line %d in %s\n", line, filename); fflush(file_); } } <commit_msg>Increased default warning level to WARN from DEBUG<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ryan Luna, Ioan Sucan */ #include "console_bridge/console.h" #include <boost/thread/mutex.hpp> #include <iostream> #include <cstdio> #include <cstdarg> /// @cond IGNORE struct DefaultOutputHandler { DefaultOutputHandler(void) { output_handler_ = static_cast<console_bridge::OutputHandler*>(&std_output_handler_); previous_output_handler_ = output_handler_; logLevel_ = console_bridge::LOG_WARN; } console_bridge::OutputHandlerSTD std_output_handler_; console_bridge::OutputHandler *output_handler_; console_bridge::OutputHandler *previous_output_handler_; console_bridge::LogLevel logLevel_; boost::mutex lock_; // it is likely the outputhandler does some I/O, so we serialize it }; // we use this function because we want to handle static initialization correctly // however, the first run of this function is not thread safe, due to the use of a static // variable inside the function. For this reason, we ensure the first call happens during // static initialization using a proxy class static DefaultOutputHandler* getDOH(void) { static DefaultOutputHandler DOH; return &DOH; } #define USE_DOH \ DefaultOutputHandler *doh = getDOH(); \ boost::mutex::scoped_lock slock(doh->lock_) #define MAX_BUFFER_SIZE 1024 /// @endcond void console_bridge::noOutputHandler(void) { USE_DOH; doh->previous_output_handler_ = doh->output_handler_; doh->output_handler_ = NULL; } void console_bridge::restorePreviousOutputHandler(void) { USE_DOH; std::swap(doh->previous_output_handler_, doh->output_handler_); } void console_bridge::useOutputHandler(OutputHandler *oh) { USE_DOH; doh->previous_output_handler_ = doh->output_handler_; doh->output_handler_ = oh; } console_bridge::OutputHandler* console_bridge::getOutputHandler(void) { return getDOH()->output_handler_; } void console_bridge::log(const char *file, int line, LogLevel level, const char* m, ...) { USE_DOH; if (doh->output_handler_ && level >= doh->logLevel_) { va_list __ap; va_start(__ap, m); char buf[MAX_BUFFER_SIZE]; vsnprintf(buf, sizeof(buf), m, __ap); va_end(__ap); buf[MAX_BUFFER_SIZE - 1] = '\0'; doh->output_handler_->log(buf, level, file, line); } } void console_bridge::setLogLevel(LogLevel level) { USE_DOH; doh->logLevel_ = level; } console_bridge::LogLevel console_bridge::getLogLevel(void) { USE_DOH; return doh->logLevel_; } static const char* LogLevelString[4] = {"Debug: ", "Info: ", "Warning: ", "Error: "}; void console_bridge::OutputHandlerSTD::log(const std::string &text, LogLevel level, const char *filename, int line) { if (level >= LOG_WARN) { std::cerr << LogLevelString[level] << text << std::endl; std::cerr << " at line " << line << " in " << filename << std::endl; std::cerr.flush(); } else { std::cout << LogLevelString[level] << text << std::endl; std::cout.flush(); } } console_bridge::OutputHandlerFile::OutputHandlerFile(const char *filename) : OutputHandler() { file_ = fopen(filename, "a"); if (!file_) std::cerr << "Unable to open log file: '" << filename << "'" << std::endl; } console_bridge::OutputHandlerFile::~OutputHandlerFile(void) { if (file_) if (fclose(file_) != 0) std::cerr << "Error closing logfile" << std::endl; } void console_bridge::OutputHandlerFile::log(const std::string &text, LogLevel level, const char *filename, int line) { if (file_) { fprintf(file_, "%s%s\n", LogLevelString[level], text.c_str()); if(level >= LOG_WARN) fprintf(file_, " at line %d in %s\n", line, filename); fflush(file_); } } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "consumer.hh" #include "globals.hh" using namespace boost::filesystem; using namespace std; #include <fstream> Consumer::Consumer(string throwaway) : _playlist_file_(std::move(throwaway)) , _write_to_file_(true) { std::ifstream file(_playlist_file_); if (file) { string temp; while (getline(file, temp)) { _playlist_lines_.insert(temp); } } } void Consumer::_sorted_insert_song_(const std::string& str) { bool inserted = _playlist_lines_.insert(str).second; if (NONO && inserted) { printf("Insert `%s` into playlist `%s`.\n", str.c_str(), _playlist_file_.c_str()); } } Consumer::~Consumer() { if (_write_to_file_) { if (!NONO) { std::ofstream file(_playlist_file_); for (const auto& s : _playlist_lines_) { file << s << '\n'; } if (USE_MPC && system("mpc -q") == 0) { system("mpc -q clear"); system("mpc -q update"); string pl = "mpc -q load " + path(_playlist_file_).filename().replace_extension().string(); system(pl.c_str()); } } else if (USE_MPC) { printf("$ mpc clear\n"); string pl = path(_playlist_file_).filename().replace_extension().string(); printf("$ mpc load %s\n", pl.c_str()); } } } #include <taglib/fileref.h> void Consumer::_apply_tags_(const path& path, const string& artist, const string& title) { using namespace TagLib; FileRef file(path.c_str()); Tag* tags = file.tag(); if (!tags) { fprintf(stderr, "Music file `%s` has no tags!\n", path.c_str()); return; } if (tags->artist() != artist) { if (NONO) { printf(" Artist: `%s` -> `%s`\n", tags->artist().toCString(), artist.c_str()); } else { tags->setArtist(artist); } } if (tags->title() != title) { if (NONO) { printf(" Title: `%s` -> `%s`\n", tags->title().toCString(), title.c_str()); } else { tags->setTitle(title); } } if (!NONO) { file.save(); } } <commit_msg>Echo `$ mpc update` in NONO mode<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "consumer.hh" #include "globals.hh" using namespace boost::filesystem; using namespace std; #include <fstream> Consumer::Consumer(string throwaway) : _playlist_file_(std::move(throwaway)) , _write_to_file_(true) { std::ifstream file(_playlist_file_); if (file) { string temp; while (getline(file, temp)) { _playlist_lines_.insert(temp); } } } void Consumer::_sorted_insert_song_(const std::string& str) { bool inserted = _playlist_lines_.insert(str).second; if (NONO && inserted) { printf("Insert `%s` into playlist `%s`.\n", str.c_str(), _playlist_file_.c_str()); } } Consumer::~Consumer() { if (_write_to_file_) { if (!NONO) { std::ofstream file(_playlist_file_); for (const auto& s : _playlist_lines_) { file << s << '\n'; } if (USE_MPC && system("mpc -q") == 0) { system("mpc -q clear"); system("mpc -q update"); string pl = "mpc -q load " + path(_playlist_file_).filename().replace_extension().string(); system(pl.c_str()); } } else if (USE_MPC) { printf("$ mpc clear\n"); printf("$ mpc update\n"); string pl = path(_playlist_file_).filename().replace_extension().string(); printf("$ mpc load %s\n", pl.c_str()); } } } #include <taglib/fileref.h> void Consumer::_apply_tags_(const path& path, const string& artist, const string& title) { using namespace TagLib; FileRef file(path.c_str()); Tag* tags = file.tag(); if (!tags) { fprintf(stderr, "Music file `%s` has no tags!\n", path.c_str()); return; } if (tags->artist() != artist) { if (NONO) { printf(" Artist: `%s` -> `%s`\n", tags->artist().toCString(), artist.c_str()); } else { tags->setArtist(artist); } } if (tags->title() != title) { if (NONO) { printf(" Title: `%s` -> `%s`\n", tags->title().toCString(), title.c_str()); } else { tags->setTitle(title); } } if (!NONO) { file.save(); } } <|endoftext|>
<commit_before>#include "CpuID.hpp" namespace cos { CpuID::Vendor CpuID::getVendor() { if(vendor == Vendor::NotSet) findVendor(); return vendor; } const char* CpuID::getVendorString() { if(vendor == Vendor::NotSet) findVendor(); return VENDOR_STRINGS[static_cast<uint8>(vendor)]; } const char* CpuID::getModelString() { if(modelString[0] == 0) calcBrandString(); return modelString; } uint8 CpuID::getStepID() { if(displayStepID == 0) getVersion(); return displayStepID; } uint8 CpuID::getModelID() { if(displayModelID == 0) getVersion(); return displayModelID; } uint8 CpuID::getFamilyID() { if(displayFamilyID == 0) getVersion(); return displayFamilyID; } uint8 CpuID::getTypeID() { if(displayTypeID == 0) getVersion(); return displayTypeID; } uint16 CpuID::getClflushLineSize() { if(clflushLineSize == 0) getVersion(); return clflushLineSize; } uint8 CpuID::getNumLogicalProcessors() { if(numLogicalProcessors == 0) getVersion(); return numLogicalProcessors; } uint8 CpuID::getInitialAPICID() { if(initialAPICID == 0) getVersion(); return initialAPICID; } bool CpuID::hasFeature(FeatureECX f) { if(featuresECX == 0) getVersion(); return featuresECX & static_cast<uint32>(f); } bool CpuID::hasFeature(FeatureEDX f) { if(featuresEDX == 0) getVersion(); return featuresEDX & static_cast<uint32>(f); } bool CpuID::cpuid(uint32 in, uint32 out[4]) { if(in > maxValueEAX && (in < 0x80000000 || in > maxExtValueEAX)) // invalid value for eax { return false; } asm volatile("cpuid": "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3]) : "a"(in)); return true; } void CpuID::findVendor() { uint32 registers[4] = {0, 0, 0, 0}; cpuid(0x0, registers); // update maxValue for eax maxValueEAX = registers[0]; // Intel check if( registers[1] == VENDOR_CODES[0][0] && registers[2] == VENDOR_CODES[0][1] && registers[3] == VENDOR_CODES[0][2]) { vendor = Vendor::Intel; } // AMD check else if(registers[1] == VENDOR_CODES[1][0] && registers[2] == VENDOR_CODES[1][1] && registers[3] == VENDOR_CODES[1][2]) { vendor = Vendor::AMD; } else { vendor = Vendor::Unknown; } getMaxExtValueEax(); } void CpuID::getVersion() { if(vendor == Vendor::NotSet) findVendor(); uint32 registers[4] = {0, 0, 0, 0}; cpuid(0x1, registers); // parse eax displayStepID = registers[0] & 0xf; // bits 0-3 uint8 modelID = registers[0] >> 4 & 0xf; // bits 4-7 uint8 familyID = registers[0] >> 8 & 0xf; // bits 8-11 displayTypeID = registers[0] >> 12 & 0x3; // bits 12-13 uint8 extModelID = registers[0] >> 16 & 0xf; // bits 16-19 *only needed when familyID is 0x6 or 0xf uint8 extFamilyID = registers[0] >> 20 & 0xff; // bits 20-27 *only needed when familyID is 0xf // handle final familyID if(familyID == 0xf) displayFamilyID = familyID + extFamilyID; else displayFamilyID = familyID; // handle final modelID if(familyID == 0x6 || familyID == 0xf) displayModelID = extModelID << 4 | modelID; else displayModelID = modelID; // parse ebx //uint8 brandIdx = registers[1] & 0xff; // brand string index is no longer used clflushLineSize = (registers[1] >> 8 & 0xff) * 8; numLogicalProcessors = registers[1] >> 16 & 0xff; initialAPICID = registers[1] >> 24 & 0xff; // parse ecx featuresECX = registers[2]; // parse edx featuresEDX = registers[3]; } void CpuID::getMaxExtValueEax() { uint32 registers[4] = {0, 0, 0, 0}; cpuid(0x80000000, registers); maxExtValueEAX = registers[0]; } // assuming brand string is supported void CpuID::calcBrandString() { if(maxExtValueEAX == 0) getMaxExtValueEax(); uint32 registers[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint32* registersSet0 = &registers[0]; // bytes 0 - 15 uint32* registersSet1 = &registers[4]; // bytes 16 - 31 uint32* registersSet2 = &registers[8]; // bytes 32 - 47 cpuid(0x80000002, registersSet0); cpuid(0x80000003, registersSet1); cpuid(0x80000004, registersSet2); for(int i = 0; i < 48; i += 4) { for(int j = 0; j < 4; j++) { modelString[i + j] = registers[i / 4] >> 8 * j & 0xff; } } modelString[46] = 'H'; } const char* CpuID::VENDOR_STRINGS[3] = { "GenuineIntel", "AuthenticAMD", "Unknown", }; const uint32 CpuID::VENDOR_CODES[3][3] = { // Intel {0x756e6547, 0x6c65746e, 0x49656e69}, // "uneG", "letn", "Ieni" // AMD {0x68747541, 0x444d4163, 0x69746e65}, // "htuA", "DMAc", "itne" // Unknown {0x0, 0x0, 0x0}, }; CpuID::Vendor CpuID::vendor = CpuID::Vendor::NotSet; uint8 CpuID::displayStepID = 0; uint8 CpuID::displayModelID = 0; uint8 CpuID::displayFamilyID = 0; uint8 CpuID::displayTypeID = 0; char CpuID::modelString[48] = {0}; uint16 CpuID::clflushLineSize = 0; uint8 CpuID::numLogicalProcessors = 0; uint8 CpuID::initialAPICID = 0; uint32 CpuID::featuresECX = 0; uint32 CpuID::featuresEDX = 0; uint16 CpuID::maxValueEAX = 0; uint32 CpuID::maxExtValueEAX = 0x80000000; uint32 CpuID::maxValueECX = 0; } <commit_msg>Spacing fix.<commit_after>#include "CpuID.hpp" namespace cos { CpuID::Vendor CpuID::getVendor() { if(vendor == Vendor::NotSet) findVendor(); return vendor; } const char* CpuID::getVendorString() { if(vendor == Vendor::NotSet) findVendor(); return VENDOR_STRINGS[static_cast<uint8>(vendor)]; } const char* CpuID::getModelString() { if(modelString[0] == 0) calcBrandString(); return modelString; } uint8 CpuID::getStepID() { if(displayStepID == 0) getVersion(); return displayStepID; } uint8 CpuID::getModelID() { if(displayModelID == 0) getVersion(); return displayModelID; } uint8 CpuID::getFamilyID() { if(displayFamilyID == 0) getVersion(); return displayFamilyID; } uint8 CpuID::getTypeID() { if(displayTypeID == 0) getVersion(); return displayTypeID; } uint16 CpuID::getClflushLineSize() { if(clflushLineSize == 0) getVersion(); return clflushLineSize; } uint8 CpuID::getNumLogicalProcessors() { if(numLogicalProcessors == 0) getVersion(); return numLogicalProcessors; } uint8 CpuID::getInitialAPICID() { if(initialAPICID == 0) getVersion(); return initialAPICID; } bool CpuID::hasFeature(FeatureECX f) { if(featuresECX == 0) getVersion(); return featuresECX & static_cast<uint32>(f); } bool CpuID::hasFeature(FeatureEDX f) { if(featuresEDX == 0) getVersion(); return featuresEDX & static_cast<uint32>(f); } bool CpuID::cpuid(uint32 in, uint32 out[4]) { if(in > maxValueEAX && (in < 0x80000000 || in > maxExtValueEAX)) // invalid value for eax { return false; } asm volatile("cpuid" : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3]) : "a"(in)); return true; } void CpuID::findVendor() { uint32 registers[4] = {0, 0, 0, 0}; cpuid(0x0, registers); // update maxValue for eax maxValueEAX = registers[0]; // Intel check if( registers[1] == VENDOR_CODES[0][0] && registers[2] == VENDOR_CODES[0][1] && registers[3] == VENDOR_CODES[0][2]) { vendor = Vendor::Intel; } // AMD check else if(registers[1] == VENDOR_CODES[1][0] && registers[2] == VENDOR_CODES[1][1] && registers[3] == VENDOR_CODES[1][2]) { vendor = Vendor::AMD; } else { vendor = Vendor::Unknown; } getMaxExtValueEax(); } void CpuID::getVersion() { if(vendor == Vendor::NotSet) findVendor(); uint32 registers[4] = {0, 0, 0, 0}; cpuid(0x1, registers); // parse eax displayStepID = registers[0] & 0xf; // bits 0-3 uint8 modelID = registers[0] >> 4 & 0xf; // bits 4-7 uint8 familyID = registers[0] >> 8 & 0xf; // bits 8-11 displayTypeID = registers[0] >> 12 & 0x3; // bits 12-13 uint8 extModelID = registers[0] >> 16 & 0xf; // bits 16-19 *only needed when familyID is 0x6 or 0xf uint8 extFamilyID = registers[0] >> 20 & 0xff; // bits 20-27 *only needed when familyID is 0xf // handle final familyID if(familyID == 0xf) displayFamilyID = familyID + extFamilyID; else displayFamilyID = familyID; // handle final modelID if(familyID == 0x6 || familyID == 0xf) displayModelID = extModelID << 4 | modelID; else displayModelID = modelID; // parse ebx //uint8 brandIdx = registers[1] & 0xff; // brand string index is no longer used clflushLineSize = (registers[1] >> 8 & 0xff) * 8; numLogicalProcessors = registers[1] >> 16 & 0xff; initialAPICID = registers[1] >> 24 & 0xff; // parse ecx featuresECX = registers[2]; // parse edx featuresEDX = registers[3]; } void CpuID::getMaxExtValueEax() { uint32 registers[4] = {0, 0, 0, 0}; cpuid(0x80000000, registers); maxExtValueEAX = registers[0]; } // assuming brand string is supported void CpuID::calcBrandString() { if(maxExtValueEAX == 0) getMaxExtValueEax(); uint32 registers[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint32* registersSet0 = &registers[0]; // bytes 0 - 15 uint32* registersSet1 = &registers[4]; // bytes 16 - 31 uint32* registersSet2 = &registers[8]; // bytes 32 - 47 cpuid(0x80000002, registersSet0); cpuid(0x80000003, registersSet1); cpuid(0x80000004, registersSet2); for(int i = 0; i < 48; i += 4) { for(int j = 0; j < 4; j++) { modelString[i + j] = registers[i / 4] >> 8 * j & 0xff; } } modelString[46] = 'H'; } const char* CpuID::VENDOR_STRINGS[3] = { "GenuineIntel", "AuthenticAMD", "Unknown", }; const uint32 CpuID::VENDOR_CODES[3][3] = { // Intel {0x756e6547, 0x6c65746e, 0x49656e69}, // "uneG", "letn", "Ieni" // AMD {0x68747541, 0x444d4163, 0x69746e65}, // "htuA", "DMAc", "itne" // Unknown {0x0, 0x0, 0x0}, }; CpuID::Vendor CpuID::vendor = CpuID::Vendor::NotSet; uint8 CpuID::displayStepID = 0; uint8 CpuID::displayModelID = 0; uint8 CpuID::displayFamilyID = 0; uint8 CpuID::displayTypeID = 0; char CpuID::modelString[48] = {0}; uint16 CpuID::clflushLineSize = 0; uint8 CpuID::numLogicalProcessors = 0; uint8 CpuID::initialAPICID = 0; uint32 CpuID::featuresECX = 0; uint32 CpuID::featuresEDX = 0; uint16 CpuID::maxValueEAX = 0; uint32 CpuID::maxExtValueEAX = 0x80000000; uint32 CpuID::maxValueECX = 0; } <|endoftext|>
<commit_before>#include <mart-common/MartTime.h> #include <mart-common/algorithm.h> #include <mart-netlib/udp.hpp> #include <atomic> #include <fstream> #include <iostream> #include <optional> #include <string_view> #include <vector> #include <im_str/im_str.hpp> namespace udp = mart::nw::ip::udp; using namespace std::chrono_literals; std::vector<std::string_view> make_arglist( int argc, char** argv ) { std::vector<std::string_view> ret; for( int i = 0; i < argc; ++i ) { ret.emplace_back( argv[i] ); } return ret; } std::optional<udp::endpoint> get_local_address( const std::vector<std::string_view>& args ) { return udp::try_parse_v4_endpoint( "127.0.0.1:3435" ); } std::optional<std::string> get_filename( const std::vector<std::string_view>& args ) { return std::string{"Testfile"}; } std::string_view to_stringview( mart::ConstMemoryView data ) { return std::string_view{data.asConstCharPtr(), data.size()}; } int main( int argc, char** argv ) { const auto arglist = make_arglist( argc, argv ); const udp::endpoint local_ep = get_local_address( arglist ).value(); const auto file_name = get_filename( arglist ).value(); udp::Socket sock; sock.set_rx_timeout( 1000ms ); sock.bind( local_ep ); std::cout << "Listening on " << local_ep.toStringEx() << " and writing to" << file_name << std::endl; std::string buffer( 1000, '\0' ); while( true ) { auto res = sock.try_recv( mart::view_elements_mutable( buffer ).asBytes() ); if( res.isValid() ) { auto msg = to_stringview( res ); if( msg == "EXIT" ) { return 0; } std::ofstream file( file_name, std::ios_base::out | std::ios_base::trunc ); file.seekp( 0 ); file << msg << "\n"; std::cout << "\"" << msg << "\"" << std::endl; } } std::cout << "Server shutting down\n" << std::flush; }<commit_msg>[examples] fix warnings about unused parameters<commit_after>#include <mart-common/MartTime.h> #include <mart-common/algorithm.h> #include <mart-netlib/udp.hpp> #include <atomic> #include <fstream> #include <iostream> #include <optional> #include <string_view> #include <vector> #include <im_str/im_str.hpp> namespace udp = mart::nw::ip::udp; using namespace std::chrono_literals; std::vector<std::string_view> make_arglist( int argc, char** argv ) { std::vector<std::string_view> ret; for( int i = 0; i < argc; ++i ) { ret.emplace_back( argv[i] ); } return ret; } std::optional<udp::endpoint> get_local_address( const std::vector<std::string_view>& ) { return udp::try_parse_v4_endpoint( "127.0.0.1:3435" ); } std::optional<std::string> get_filename( const std::vector<std::string_view>& ) { return std::string{"Testfile"}; } std::string_view to_stringview( mart::ConstMemoryView data ) { return std::string_view{data.asConstCharPtr(), data.size()}; } int main( int argc, char** argv ) { const auto arglist = make_arglist( argc, argv ); const udp::endpoint local_ep = get_local_address( arglist ).value(); const auto file_name = get_filename( arglist ).value(); udp::Socket sock; sock.set_rx_timeout( 1000ms ); sock.bind( local_ep ); std::cout << "Listening on " << local_ep.toStringEx() << " and writing to" << file_name << std::endl; std::string buffer( 1000, '\0' ); while( true ) { auto res = sock.try_recv( mart::view_elements_mutable( buffer ).asBytes() ); if( res.isValid() ) { auto msg = to_stringview( res ); if( msg == "EXIT" ) { return 0; } std::ofstream file( file_name, std::ios_base::out | std::ios_base::trunc ); file.seekp( 0 ); file << msg << "\n"; std::cout << "\"" << msg << "\"" << std::endl; } } std::cout << "Server shutting down\n" << std::flush; }<|endoftext|>
<commit_before>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "Matrix.h" #include "Vector.h" #include "Dictionary.h" #include "Model.h" #include "Utils.h" #include "Real.h" #include "Args.h" #include <iostream> #include <iomanip> #include <thread> #include <time.h> #include <string> #include <math.h> #include <vector> #include <atomic> #include <fenv.h> Args args; namespace info { clock_t start; std::atomic<int64_t> allWords(0); std::atomic<int64_t> allN(0); double allLoss(0.0); } void saveVectors(Dictionary& dict, Matrix& input, Matrix& output) { int32_t N = dict.getNumWords(); std::wofstream ofs(args.output + ".vec"); if (ofs.is_open()) { ofs << N << ' ' << args.dim << std::endl; for (int32_t i = 0; i < N; i++) { ofs << dict.getWord(i) << ' '; Vector embedding(args.dim); embedding.zero(); const std::vector<int32_t>& ngrams = dict.getNgrams(i); for (auto it = ngrams.begin(); it != ngrams.end(); ++it) { embedding.addRow(input, *it); } embedding.mul(1.0 / ngrams.size()); embedding.writeToStream(ofs); ofs << std::endl; } ofs.close(); } else { std::wcout << "Error opening file for writing" << std::endl; } } void saveModel(Dictionary& dict, Matrix& input, Matrix& output) { std::ofstream ofs(args.output + ".bin"); args.save(ofs); dict.save(ofs); input.save(ofs); output.save(ofs); ofs.close(); } void loadModel(Dictionary& dict, Matrix& input, Matrix& output) { std::ifstream ifs(args.output + ".bin"); args.load(ifs); dict.load(ifs); input.load(ifs); output.load(ifs); ifs.close(); } void printInfo(Model& model, long long numTokens) { real progress = real(info::allWords) / (args.epoch * numTokens); real avLoss = info::allLoss / info::allN; float time = float(clock() - info::start) / CLOCKS_PER_SEC; float wst = float(info::allWords) / time; int eta = int(time / progress * (1 - progress) / args.thread); int etah = eta / 3600; int etam = (eta - etah * 3600) / 60; std::wcout << std::fixed; std::wcout << "\rProgress: " << std::setprecision(1) << 100 * progress << "%"; std::wcout << " words/sec/thread: " << std::setprecision(0) << wst; std::wcout << " lr: " << std::setprecision(6) << model.getLearningRate(); std::wcout << " loss: " << std::setprecision(6) << avLoss; std::wcout << " eta: " << etah << "h" << etam << "m "; std::wcout << std::flush; } void supervised(Model& model, const std::vector<int32_t>& line, const std::vector<int32_t>& labels, double& loss, int32_t& N) { if (labels.size() == 0 || line.size() == 0) return; std::uniform_int_distribution<> uniform(0, labels.size() - 1); int32_t i = uniform(model.rng); model.update(line, labels[i], loss, N); } void cbow(Dictionary& dict, Model& model, const std::vector<int32_t>& line, double& loss, int32_t& N) { int32_t n = line.size(); std::vector<int32_t> bow; std::uniform_int_distribution<> uniform(1, args.ws); for (int32_t w = 0; w < n; w++) { int32_t wb = uniform(model.rng); bow.clear(); for (int32_t c = -wb; c <= wb; c++) { if (c != 0 && w + c >= 0 && w + c < n) { const std::vector<int32_t>& ngrams = dict.getNgrams(line[w + c]); for (auto it = ngrams.cbegin(); it != ngrams.cend(); ++it) { bow.push_back(*it); } } } model.update(bow, line[w], loss, N); } } void skipGram(Dictionary& dict, Model& model, const std::vector<int32_t>& line, double& loss, int32_t& N) { int32_t n = line.size(); std::uniform_int_distribution<> uniform(1, args.ws); for (int32_t w = 0; w < n; w++) { int32_t wb = uniform(model.rng); const std::vector<int32_t>& ngrams = dict.getNgrams(line[w]); for (int32_t c = -wb; c <= wb; c++) { if (c != 0 && w + c >= 0 && w + c < n) { int32_t target = line[w + c]; model.update(ngrams, target, loss, N); } } } } void test(Dictionary& dict, Model& model) { int32_t N = 0; double precision = 0.0; std::vector<int32_t> line, labels; std::wifstream ifs(args.test); while (!ifs.eof()) { dict.getLine(ifs, line, labels, model.rng); dict.addNgrams(line, args.wordNgrams); if (labels.size() > 0 && line.size() > 0) { int32_t i = model.predict(line); for (auto& t : labels) { if (i == t) { precision += 1.0; break; } } N++; } } ifs.close(); std::wcout << std::setprecision(3) << "P@1: " << precision / N << std::endl; std::wcout << std::setprecision(3) << "Sentences: " << N << std::endl; } void thread_function(Dictionary& dict, Matrix& input, Matrix& output, int32_t threadId) { std::wifstream ifs(args.input); utils::seek(ifs, threadId * utils::size(ifs) / args.thread); Model model(input, output, args.dim, args.lr, threadId); if (args.model == model_name::sup) { model.setLabelFreq(dict.getLabelFreq()); } else { model.setLabelFreq(dict.getWordFreq()); } const int64_t ntokens = dict.getNumTokens(); int64_t tokenCount = 0; int64_t prevTokenCount = 0; double loss = 0.0; int32_t N = 0; std::vector<int32_t> line, labels; while (info::allWords < args.epoch * ntokens) { tokenCount += dict.getLine(ifs, line, labels, model.rng); if (args.model == model_name::sup) { dict.addNgrams(line, args.wordNgrams); supervised(model, line, labels, loss, N); } else if (args.model == model_name::cbow) { cbow(dict, model, line, loss, N); } else if (args.model == model_name::sg) { skipGram(dict, model, line, loss, N); } if (tokenCount - prevTokenCount > 10000) { info::allWords += tokenCount - prevTokenCount; prevTokenCount = tokenCount; info::allLoss += loss; info::allN += N; loss = 0.0; N = 0; real progress = real(info::allWords) / (args.epoch * ntokens); model.setLearningRate(args.lr * (1.0 - progress)); if (threadId == 0) printInfo(model, ntokens); } } if (threadId == 0) { printInfo(model, ntokens); std::wcout << std::endl; } if (args.model == model_name::sup && threadId == 0) { test(dict, model); } ifs.close(); } int main(int argc, char** argv) { std::locale::global(std::locale("")); args.parseArgs(argc, argv); utils::initTables(); Dictionary dict; dict.readFromFile(args.input); Matrix input(dict.getNumWords() + args.bucket, args.dim); Matrix output; if (args.model == model_name::sup) { output = Matrix(dict.getNumLabels(), args.dim); } else { output = Matrix(dict.getNumWords(), args.dim); } input.uniform(1.0 / args.dim); output.zero(); info::start = clock(); std::vector<std::thread> threads; for (int32_t i = 0; i < args.thread; i++) { threads.push_back(std::thread(&thread_function, std::ref(dict), std::ref(input), std::ref(output), i)); } for (auto it = threads.begin(); it != threads.end(); ++it) { it->join(); } std::wcout << "training took: " << float(clock() - info::start) / CLOCKS_PER_SEC / args.thread << " s" << std::endl; if (args.output.size() != 0) { saveModel(dict, input, output); saveVectors(dict, input, output); } utils::freeTables(); return 0; } <commit_msg>Remove unused variable & change long long to int64_t<commit_after>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "Matrix.h" #include "Vector.h" #include "Dictionary.h" #include "Model.h" #include "Utils.h" #include "Real.h" #include "Args.h" #include <iostream> #include <iomanip> #include <thread> #include <time.h> #include <string> #include <math.h> #include <vector> #include <atomic> #include <fenv.h> Args args; namespace info { clock_t start; std::atomic<int64_t> allWords(0); std::atomic<int64_t> allN(0); double allLoss(0.0); } void saveVectors(Dictionary& dict, Matrix& input, Matrix& output) { int32_t N = dict.getNumWords(); std::wofstream ofs(args.output + ".vec"); if (ofs.is_open()) { ofs << N << ' ' << args.dim << std::endl; for (int32_t i = 0; i < N; i++) { ofs << dict.getWord(i) << ' '; Vector embedding(args.dim); embedding.zero(); const std::vector<int32_t>& ngrams = dict.getNgrams(i); for (auto it = ngrams.begin(); it != ngrams.end(); ++it) { embedding.addRow(input, *it); } embedding.mul(1.0 / ngrams.size()); embedding.writeToStream(ofs); ofs << std::endl; } ofs.close(); } else { std::wcout << "Error opening file for writing" << std::endl; } } void saveModel(Dictionary& dict, Matrix& input, Matrix& output) { std::ofstream ofs(args.output + ".bin"); args.save(ofs); dict.save(ofs); input.save(ofs); output.save(ofs); ofs.close(); } void loadModel(Dictionary& dict, Matrix& input, Matrix& output) { std::ifstream ifs(args.output + ".bin"); args.load(ifs); dict.load(ifs); input.load(ifs); output.load(ifs); ifs.close(); } void printInfo(Model& model, int64_t numTokens) { real progress = real(info::allWords) / (args.epoch * numTokens); real avLoss = info::allLoss / info::allN; float time = float(clock() - info::start) / CLOCKS_PER_SEC; float wst = float(info::allWords) / time; int eta = int(time / progress * (1 - progress) / args.thread); int etah = eta / 3600; int etam = (eta - etah * 3600) / 60; std::wcout << std::fixed; std::wcout << "\rProgress: " << std::setprecision(1) << 100 * progress << "%"; std::wcout << " words/sec/thread: " << std::setprecision(0) << wst; std::wcout << " lr: " << std::setprecision(6) << model.getLearningRate(); std::wcout << " loss: " << std::setprecision(6) << avLoss; std::wcout << " eta: " << etah << "h" << etam << "m "; std::wcout << std::flush; } void supervised(Model& model, const std::vector<int32_t>& line, const std::vector<int32_t>& labels, double& loss, int32_t& N) { if (labels.size() == 0 || line.size() == 0) return; std::uniform_int_distribution<> uniform(0, labels.size() - 1); int32_t i = uniform(model.rng); model.update(line, labels[i], loss, N); } void cbow(Dictionary& dict, Model& model, const std::vector<int32_t>& line, double& loss, int32_t& N) { int32_t n = line.size(); std::vector<int32_t> bow; std::uniform_int_distribution<> uniform(1, args.ws); for (int32_t w = 0; w < n; w++) { int32_t wb = uniform(model.rng); bow.clear(); for (int32_t c = -wb; c <= wb; c++) { if (c != 0 && w + c >= 0 && w + c < n) { const std::vector<int32_t>& ngrams = dict.getNgrams(line[w + c]); for (auto it = ngrams.cbegin(); it != ngrams.cend(); ++it) { bow.push_back(*it); } } } model.update(bow, line[w], loss, N); } } void skipGram(Dictionary& dict, Model& model, const std::vector<int32_t>& line, double& loss, int32_t& N) { int32_t n = line.size(); std::uniform_int_distribution<> uniform(1, args.ws); for (int32_t w = 0; w < n; w++) { int32_t wb = uniform(model.rng); const std::vector<int32_t>& ngrams = dict.getNgrams(line[w]); for (int32_t c = -wb; c <= wb; c++) { if (c != 0 && w + c >= 0 && w + c < n) { int32_t target = line[w + c]; model.update(ngrams, target, loss, N); } } } } void test(Dictionary& dict, Model& model) { int32_t N = 0; double precision = 0.0; std::vector<int32_t> line, labels; std::wifstream ifs(args.test); while (!ifs.eof()) { dict.getLine(ifs, line, labels, model.rng); dict.addNgrams(line, args.wordNgrams); if (labels.size() > 0 && line.size() > 0) { int32_t i = model.predict(line); for (auto& t : labels) { if (i == t) { precision += 1.0; break; } } N++; } } ifs.close(); std::wcout << std::setprecision(3) << "P@1: " << precision / N << std::endl; std::wcout << std::setprecision(3) << "Sentences: " << N << std::endl; } void thread_function(Dictionary& dict, Matrix& input, Matrix& output, int32_t threadId) { std::wifstream ifs(args.input); utils::seek(ifs, threadId * utils::size(ifs) / args.thread); Model model(input, output, args.dim, args.lr, threadId); if (args.model == model_name::sup) { model.setLabelFreq(dict.getLabelFreq()); } else { model.setLabelFreq(dict.getWordFreq()); } const int64_t ntokens = dict.getNumTokens(); int64_t tokenCount = 0; double loss = 0.0; int32_t N = 0; std::vector<int32_t> line, labels; while (info::allWords < args.epoch * ntokens) { tokenCount += dict.getLine(ifs, line, labels, model.rng); if (args.model == model_name::sup) { dict.addNgrams(line, args.wordNgrams); supervised(model, line, labels, loss, N); } else if (args.model == model_name::cbow) { cbow(dict, model, line, loss, N); } else if (args.model == model_name::sg) { skipGram(dict, model, line, loss, N); } if (tokenCount > 10000) { info::allWords += tokenCount; info::allLoss += loss; info::allN += N; tokenCount = 0; loss = 0.0; N = 0; real progress = real(info::allWords) / (args.epoch * ntokens); model.setLearningRate(args.lr * (1.0 - progress)); if (threadId == 0) printInfo(model, ntokens); } } if (threadId == 0) { printInfo(model, ntokens); std::wcout << std::endl; } if (args.model == model_name::sup && threadId == 0) { test(dict, model); } ifs.close(); } int main(int argc, char** argv) { std::locale::global(std::locale("")); args.parseArgs(argc, argv); utils::initTables(); Dictionary dict; dict.readFromFile(args.input); Matrix input(dict.getNumWords() + args.bucket, args.dim); Matrix output; if (args.model == model_name::sup) { output = Matrix(dict.getNumLabels(), args.dim); } else { output = Matrix(dict.getNumWords(), args.dim); } input.uniform(1.0 / args.dim); output.zero(); info::start = clock(); std::vector<std::thread> threads; for (int32_t i = 0; i < args.thread; i++) { threads.push_back(std::thread(&thread_function, std::ref(dict), std::ref(input), std::ref(output), i)); } for (auto it = threads.begin(); it != threads.end(); ++it) { it->join(); } float trainTime = float(clock() - info::start) / CLOCKS_PER_SEC / args.thread; std::wcout << "training took: " << trainTime << " sec" << std::endl; if (args.output.size() != 0) { saveModel(dict, input, output); saveVectors(dict, input, output); } utils::freeTables(); return 0; } <|endoftext|>
<commit_before>#include "ScrollingMsg.hpp" #include "utilities.hpp" #include <iostream> using std::cout; using std::endl; ScrollingMsg::ScrollingMsg() :m_current_w(0) ,m_current_h(0) ,m_friendly_name("None") ,m_loops(0) ,m_current_loop(0) ,m_scroll_time(12.0f) ,m_text() { }; ScrollingMsg::ScrollingMsg( const int width, const int height, const std::string& font, const std::string& friendly_name, const int& loop, const std::string& msg, const double& scroll_time, const int& y_pos, const bool dropshadow, const bool underlay) :m_current_w(width) ,m_current_h(height) ,m_friendly_name(friendly_name) ,m_loops(loop) ,m_current_loop(0) ,m_scroll_time(scroll_time) ,m_text(msg, width, y_pos, font, dropshadow, underlay) { }; ScrollingMsg::~ScrollingMsg() { } void ScrollingMsg::Resize(const int width, const int height) { m_current_w = width; m_current_h = height; }; bool ScrollingMsg::Update(const float dt) { //d_pos = d/t * dt int xpos = m_text.X(); xpos -= ((m_current_w + m_text.width())/m_scroll_time)*dt; if(xpos<(-1.0f*m_text.width())) {//wraparound xpos = m_current_w; m_current_loop += 1; } m_text.X(xpos); return (m_loops > 0 && m_current_loop >= m_loops); }; void ScrollingMsg::Draw(cairo_t* context, const float dt) { m_text.Draw(context, dt); } ScrollingMsgController::ScrollingMsgController() { } void ScrollingMsgController::AddMsg(const int width, const int height, const std::string& font, const std::string& friendly_name, const int& loop, const std::string& msg, const double& scroll_time, const int& y_pos, const bool dropshadow, const bool underlay) { m_msgs[friendly_name]=ScrollingMsg(width, height, font, friendly_name, loop, msg, scroll_time, y_pos, dropshadow, underlay); } void ScrollingMsgController::RemoveMsg(const std::string& friendly_name) { std::map< std::string, ScrollingMsg >::iterator msg = m_msgs.find(friendly_name); if(msg!=m_msgs.end()) { m_msgs.erase(msg); } }; void ScrollingMsgController::Update(float dt) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end();) { if(imsg->second.Update(dt)) { imsg = m_msgs.erase(imsg); }else{ ++imsg; } } }; void ScrollingMsgController::Draw(cairo_t* context, const float dt) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end(); ++imsg) { imsg->second.Draw(context, dt); } } void ScrollingMsgController::Resize(const int width, const int height) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end(); ++imsg) { imsg->second.Resize(width, height); } } <commit_msg>fixes #15<commit_after>#include "ScrollingMsg.hpp" #include "utilities.hpp" #include <iostream> using std::cout; using std::endl; ScrollingMsg::ScrollingMsg() :m_current_w(0) ,m_current_h(0) ,m_friendly_name("None") ,m_loops(0) ,m_current_loop(0) ,m_scroll_time(12.0f) ,m_text() { }; ScrollingMsg::ScrollingMsg( const int width, const int height, const std::string& font, const std::string& friendly_name, const int& loop, const std::string& msg, const double& scroll_time, const int& y_pos, const bool dropshadow, const bool underlay) :m_current_w(width) ,m_current_h(height) ,m_friendly_name(friendly_name) ,m_loops(loop) ,m_current_loop(0) ,m_scroll_time(scroll_time) ,m_text(msg, width, y_pos, font, dropshadow, underlay) { }; ScrollingMsg::~ScrollingMsg() { } void ScrollingMsg::Resize(const int width, const int height) { m_current_w = width; m_current_h = height; }; bool ScrollingMsg::Update(const float dt) { //d_pos = d/t * dt int xpos = m_text.X(); xpos -= ((m_current_w + m_text.width())/m_scroll_time)*dt; if(xpos<(-1.0f*m_text.width())) {//wraparound xpos = m_current_w; m_current_loop += 1; } m_text.X(xpos); return (m_loops > 0 && m_current_loop > m_loops); }; void ScrollingMsg::Draw(cairo_t* context, const float dt) { m_text.Draw(context, dt); } ScrollingMsgController::ScrollingMsgController() { } void ScrollingMsgController::AddMsg(const int width, const int height, const std::string& font, const std::string& friendly_name, const int& loop, const std::string& msg, const double& scroll_time, const int& y_pos, const bool dropshadow, const bool underlay) { m_msgs[friendly_name]=ScrollingMsg(width, height, font, friendly_name, loop, msg, scroll_time, y_pos, dropshadow, underlay); } void ScrollingMsgController::RemoveMsg(const std::string& friendly_name) { std::map< std::string, ScrollingMsg >::iterator msg = m_msgs.find(friendly_name); if(msg!=m_msgs.end()) { m_msgs.erase(msg); } }; void ScrollingMsgController::Update(float dt) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end();) { if(imsg->second.Update(dt)) { imsg = m_msgs.erase(imsg); }else{ ++imsg; } } }; void ScrollingMsgController::Draw(cairo_t* context, const float dt) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end(); ++imsg) { imsg->second.Draw(context, dt); } } void ScrollingMsgController::Resize(const int width, const int height) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end(); ++imsg) { imsg->second.Resize(width, height); } } <|endoftext|>
<commit_before>#include "MemCheck.h" #include "POGLRenderContext.h" #include "POGLRenderState.h" #include "POGLDevice.h" #include "POGLEnum.h" #include "POGLVertexBuffer.h" #include "POGLIndexBuffer.h" #include "POGLTexture2D.h" #include "POGLShader.h" #include "POGLProgramData.h" #include "POGLFactory.h" #include "POGLFramebuffer.h" #include "POGLProgram.h" #include <algorithm> POGLRenderContext::POGLRenderContext(IPOGLDevice* device) : mRenderState(nullptr), mDevice(device) { } POGLRenderContext::~POGLRenderContext() { } void POGLRenderContext::Destroy() { POGL_SAFE_RELEASE(mRenderState); } IPOGLDevice* POGLRenderContext::GetDevice() { mDevice->AddRef(); return mDevice; } IPOGLShader* POGLRenderContext::CreateShaderFromFile(const POGL_CHAR* path, POGLShaderType::Enum type) { POGL_ISTREAM stream(path); if (!stream.is_open()) THROW_EXCEPTION(POGLResourceException, "Shader at path: '%s' could not be found", path); // Read the entire file into memory POGL_STRING str((std::istreambuf_iterator<POGL_CHAR>(stream)), std::istreambuf_iterator<POGL_CHAR>()); return CreateShaderFromMemory(str.c_str(), str.length(), type); } IPOGLShader* POGLRenderContext::CreateShaderFromMemory(const POGL_CHAR* memory, POGL_UINT32 size, POGLShaderType::Enum type) { // Generate a shader ID based on the supplied memory, size and type const GLuint shaderID = POGLFactory::CreateShader(memory, size, type); POGLShader* shader = new POGLShader(type); shader->PostConstruct(shaderID); return shader; } IPOGLProgram* POGLRenderContext::CreateProgramFromShaders(IPOGLShader** shaders) { if (shaders == nullptr) THROW_EXCEPTION(POGLResourceException, "You must supply at least one shader to be able to create a program"); // Attach all the shaders to the program const GLuint programID = POGLFactory::CreateProgram(shaders); POGLProgram* program = new POGLProgram(); program->PostConstruct(programID, GetRenderState()); return program; } IPOGLTexture1D* POGLRenderContext::CreateTexture1D() { return nullptr; } IPOGLTexture2D* POGLRenderContext::CreateTexture2D(const POGL_SIZE& size, POGLTextureFormat::Enum format, const void* bytes) { if (size.width <= 0) THROW_EXCEPTION(POGLResourceException, "You cannot create a texture with width: %d", size.width); if (size.height <= 0) THROW_EXCEPTION(POGLResourceException, "You cannot create a texture with height: %d", size.height); const GLenum _format = POGLEnum::ConvertToTextureFormatEnum(format); const GLenum _internalFormat = POGLEnum::ConvertToInternalTextureFormatEnum(format); const GLenum minFilter = POGLEnum::Convert(POGLMinFilter::DEFAULT); const GLenum magFilter = POGLEnum::Convert(POGLMagFilter::DEFAULT); const GLenum textureWrap = POGLEnum::Convert(POGLTextureWrap::DEFAULT); const GLuint textureID = POGLFactory::GenTextureID(); glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, _internalFormat, size.width, size.height, 0, _format, GL_UNSIGNED_BYTE, bytes); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, textureWrap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, textureWrap); const GLenum status = glGetError(); if (status != GL_NO_ERROR) { THROW_EXCEPTION(POGLResourceException, "Could not create 2D texture. Reason: 0x%x", status); } POGLTexture2D* texture = new POGLTexture2D(size, format); texture->PostConstruct(textureID); mRenderState->ForceSetTextureResource((POGLTextureResource*)texture->GetResourcePtr()); return texture; } IPOGLTexture3D* POGLRenderContext::CreateTexture3D() { return nullptr; } void POGLRenderContext::ResizeTexture2D(IPOGLTexture2D* texture, const POGL_SIZE& size) { if (texture == nullptr) THROW_EXCEPTION(POGLStateException, "You cannot resize a non-existing texture"); if (size.width <= 0) THROW_EXCEPTION(POGLStateException, "You cannot resize a texture to 0 width"); if (size.height <= 0) THROW_EXCEPTION(POGLStateException, "You cannot resize a texture to 0 height"); POGLTexture2D* impl = static_cast<POGLTexture2D*>(texture); POGLTextureResource* resource = impl->GetResourcePtr(); mRenderState->BindTextureResource(resource, 0); const POGLTextureFormat::Enum format = resource->GetTextureFormat(); const GLenum _format = POGLEnum::ConvertToTextureFormatEnum(format); const GLenum _internalFormat = POGLEnum::ConvertToInternalTextureFormatEnum(format); glTexImage2D(GL_TEXTURE_2D, 0, _internalFormat, size.width, size.height, 0, _format, GL_UNSIGNED_BYTE, NULL); impl->SetSize(size); CHECK_GL("Could not set new texture size"); } IPOGLFramebuffer* POGLRenderContext::CreateFramebuffer(IPOGLTexture** textures) { return CreateFramebuffer(textures, nullptr); } IPOGLFramebuffer* POGLRenderContext::CreateFramebuffer(IPOGLTexture** textures, IPOGLTexture* depthStencilTexture) { // // Generate a framebuffer ID // const GLuint framebufferID = POGLFactory::GenFramebufferObjectID(textures, depthStencilTexture); // // Convert the textures array into a std::vector // std::vector<IPOGLTexture*> texturesVector; if (textures != nullptr) { for (IPOGLTexture** ptr = textures; *ptr != nullptr; ++ptr) { IPOGLTexture* texture = *ptr; texturesVector.push_back(texture); } } // // Create the actual object // POGLFramebuffer* framebuffer = new POGLFramebuffer(texturesVector, depthStencilTexture); framebuffer->PostConstruct(framebufferID); mRenderState->SetFramebuffer(framebuffer); return framebuffer; } IPOGLVertexBuffer* POGLRenderContext::CreateVertexBuffer(const void* memory, POGL_UINT32 memorySize, const POGL_VERTEX_LAYOUT* layout, POGLPrimitiveType::Enum primitiveType, POGLBufferUsage::Enum bufferUsage) { if (memorySize == 0) THROW_EXCEPTION(POGLStateException, "You cannot create a non-existing vertex buffer"); if (layout == nullptr) THROW_EXCEPTION(POGLStateException, "You cannot create a vertex buffer without a layout"); const POGL_UINT32 numVertices = memorySize / layout->vertexSize; const GLenum usage = POGLEnum::Convert(bufferUsage); const GLenum type = POGLEnum::Convert(primitiveType); const GLuint bufferID = POGLFactory::GenBufferID(); const GLuint vaoID = POGLFactory::GenVertexArrayObjectID(bufferID, layout); // // Create the object // POGLVertexBuffer* vb = new POGLVertexBuffer(numVertices, layout, type, usage); vb->PostConstruct(bufferID, vaoID); // // Fill the buffer with data // glBufferData(GL_ARRAY_BUFFER, memorySize, memory, usage); // // Make sure to mark this buffer as the current vertex buffer // mRenderState->ForceSetVertexBuffer(vb); const GLenum error = glGetError(); if (error != GL_NO_ERROR) THROW_EXCEPTION(POGLResourceException, "Failed to create a vertex buffer. Reason: 0x%x", error); // Finished return vb; } IPOGLVertexBuffer* POGLRenderContext::CreateVertexBuffer(const POGL_POSITION_VERTEX* memory, POGL_UINT32 memorySize, POGLPrimitiveType::Enum primitiveType, POGLBufferUsage::Enum bufferUsage) { return CreateVertexBuffer(memory, memorySize, &POGL_POSITION_VERTEX_LAYOUT, primitiveType, bufferUsage); } IPOGLVertexBuffer* POGLRenderContext::CreateVertexBuffer(const POGL_POSITION_COLOR_VERTEX* memory, POGL_UINT32 memorySize, POGLPrimitiveType::Enum primitiveType, POGLBufferUsage::Enum bufferUsage) { return CreateVertexBuffer(memory, memorySize, &POGL_POSITION_COLOR_VERTEX_LAYOUT, primitiveType, bufferUsage); } IPOGLVertexBuffer* POGLRenderContext::CreateVertexBuffer(const POGL_POSITION_TEXCOORD_VERTEX* memory, POGL_UINT32 memorySize, POGLPrimitiveType::Enum primitiveType, POGLBufferUsage::Enum bufferUsage) { return CreateVertexBuffer(memory, memorySize, &POGL_POSITION_TEXCOORD_VERTEX_LAYOUT, primitiveType, bufferUsage); } IPOGLIndexBuffer* POGLRenderContext::CreateIndexBuffer(const void* memory, POGL_UINT32 memorySize, POGLVertexType::Enum type, POGLBufferUsage::Enum bufferUsage) { if (memorySize == 0) THROW_EXCEPTION(POGLStateException, "You cannot create a non-existing index buffer"); if (type == POGLVertexType::FLOAT || type == POGLVertexType::DOUBLE) THROW_EXCEPTION(POGLStateException, "You are not allowed to create an index buffer of a decimal type"); const POGL_UINT32 typeSize = POGLEnum::VertexTypeSize(type); const POGL_UINT32 numIndices = memorySize / typeSize; const GLuint bufferID = POGLFactory::GenBufferID(); const GLenum usage = POGLEnum::Convert(bufferUsage); const GLenum indiceType = POGLEnum::Convert(type); // // Fill the buffer with data // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferID); if (memory != nullptr) glBufferData(GL_ELEMENT_ARRAY_BUFFER, memorySize, memory, usage); POGLIndexBuffer* ib = new POGLIndexBuffer(typeSize, numIndices, indiceType, usage); ib->PostConstruct(bufferID); // // Make sure to mark this buffer as the current index buffer // mRenderState->ForceSetIndexBuffer(ib); const GLenum error = glGetError(); if (error != GL_NO_ERROR) THROW_EXCEPTION(POGLResourceException, "Failed to create a index buffer. Reason: 0x%x", error); // Finished return ib; } IPOGLResource* POGLRenderContext::CloneResource(IPOGLResource* resource) { THROW_NOT_IMPLEMENTED_EXCEPTION(); } void POGLRenderContext::CopyResource(IPOGLResource* source, IPOGLResource* destination) { THROW_NOT_IMPLEMENTED_EXCEPTION(); } void POGLRenderContext::CopyResource(IPOGLResource* source, IPOGLResource* destination, POGL_UINT32 sourceOffset, POGL_UINT32 destinationOffset, POGL_UINT32 size) { THROW_NOT_IMPLEMENTED_EXCEPTION(); } IPOGLRenderState* POGLRenderContext::Apply(IPOGLProgram* program) { if (program == nullptr) THROW_EXCEPTION(POGLResourceException, "You are not allowed to apply a non-existing program"); mRenderState->Apply(static_cast<POGLProgram*>(program)); mRenderState->AddRef(); return mRenderState; } void* POGLRenderContext::Map(IPOGLResource* resource, POGLResourceMapType::Enum e) { auto type = resource->GetType(); if (type == POGLResourceType::VERTEXBUFFER) { POGLVertexBuffer* vb = static_cast<POGLVertexBuffer*>(resource); mRenderState->BindVertexBuffer(vb); return glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); } THROW_NOT_IMPLEMENTED_EXCEPTION(); } void* POGLRenderContext::Map(IPOGLResource* resource, POGL_UINT32 offset, POGL_UINT32 length, POGLResourceMapType::Enum e) { auto type = resource->GetType(); if (type == POGLResourceType::VERTEXBUFFER) { POGLVertexBuffer* vb = static_cast<POGLVertexBuffer*>(resource); const POGL_UINT32 memorySize = vb->GetCount() * vb->GetLayout()->vertexSize; if (offset + length > memorySize) THROW_EXCEPTION(POGLStateException, "You cannot map with offset: %d and length: %d when the vertex buffer size is: %d", offset, length, memorySize); mRenderState->BindVertexBuffer(vb); return glMapBufferRange(GL_ARRAY_BUFFER, offset, length, GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT); } THROW_NOT_IMPLEMENTED_EXCEPTION(); } void POGLRenderContext::Unmap(IPOGLResource* resource) { auto type = resource->GetType(); if (type == POGLResourceType::VERTEXBUFFER) { glUnmapBuffer(GL_ARRAY_BUFFER); return; } THROW_NOT_IMPLEMENTED_EXCEPTION(); } void POGLRenderContext::SetViewport(const POGL_RECT& viewport) { mRenderState->SetViewport(viewport); } void POGLRenderContext::InitializeRenderState() { if (mRenderState == nullptr) { mRenderState = new POGLRenderState(this); } } <commit_msg>No need to bind the index buffer unless we want to save data to it<commit_after>#include "MemCheck.h" #include "POGLRenderContext.h" #include "POGLRenderState.h" #include "POGLDevice.h" #include "POGLEnum.h" #include "POGLVertexBuffer.h" #include "POGLIndexBuffer.h" #include "POGLTexture2D.h" #include "POGLShader.h" #include "POGLProgramData.h" #include "POGLFactory.h" #include "POGLFramebuffer.h" #include "POGLProgram.h" #include <algorithm> POGLRenderContext::POGLRenderContext(IPOGLDevice* device) : mRenderState(nullptr), mDevice(device) { } POGLRenderContext::~POGLRenderContext() { } void POGLRenderContext::Destroy() { POGL_SAFE_RELEASE(mRenderState); } IPOGLDevice* POGLRenderContext::GetDevice() { mDevice->AddRef(); return mDevice; } IPOGLShader* POGLRenderContext::CreateShaderFromFile(const POGL_CHAR* path, POGLShaderType::Enum type) { POGL_ISTREAM stream(path); if (!stream.is_open()) THROW_EXCEPTION(POGLResourceException, "Shader at path: '%s' could not be found", path); // Read the entire file into memory POGL_STRING str((std::istreambuf_iterator<POGL_CHAR>(stream)), std::istreambuf_iterator<POGL_CHAR>()); return CreateShaderFromMemory(str.c_str(), str.length(), type); } IPOGLShader* POGLRenderContext::CreateShaderFromMemory(const POGL_CHAR* memory, POGL_UINT32 size, POGLShaderType::Enum type) { // Generate a shader ID based on the supplied memory, size and type const GLuint shaderID = POGLFactory::CreateShader(memory, size, type); POGLShader* shader = new POGLShader(type); shader->PostConstruct(shaderID); return shader; } IPOGLProgram* POGLRenderContext::CreateProgramFromShaders(IPOGLShader** shaders) { if (shaders == nullptr) THROW_EXCEPTION(POGLResourceException, "You must supply at least one shader to be able to create a program"); // Attach all the shaders to the program const GLuint programID = POGLFactory::CreateProgram(shaders); POGLProgram* program = new POGLProgram(); program->PostConstruct(programID, GetRenderState()); return program; } IPOGLTexture1D* POGLRenderContext::CreateTexture1D() { return nullptr; } IPOGLTexture2D* POGLRenderContext::CreateTexture2D(const POGL_SIZE& size, POGLTextureFormat::Enum format, const void* bytes) { if (size.width <= 0) THROW_EXCEPTION(POGLResourceException, "You cannot create a texture with width: %d", size.width); if (size.height <= 0) THROW_EXCEPTION(POGLResourceException, "You cannot create a texture with height: %d", size.height); const GLenum _format = POGLEnum::ConvertToTextureFormatEnum(format); const GLenum _internalFormat = POGLEnum::ConvertToInternalTextureFormatEnum(format); const GLenum minFilter = POGLEnum::Convert(POGLMinFilter::DEFAULT); const GLenum magFilter = POGLEnum::Convert(POGLMagFilter::DEFAULT); const GLenum textureWrap = POGLEnum::Convert(POGLTextureWrap::DEFAULT); const GLuint textureID = POGLFactory::GenTextureID(); glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, _internalFormat, size.width, size.height, 0, _format, GL_UNSIGNED_BYTE, bytes); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, textureWrap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, textureWrap); const GLenum status = glGetError(); if (status != GL_NO_ERROR) { THROW_EXCEPTION(POGLResourceException, "Could not create 2D texture. Reason: 0x%x", status); } POGLTexture2D* texture = new POGLTexture2D(size, format); texture->PostConstruct(textureID); mRenderState->ForceSetTextureResource((POGLTextureResource*)texture->GetResourcePtr()); return texture; } IPOGLTexture3D* POGLRenderContext::CreateTexture3D() { return nullptr; } void POGLRenderContext::ResizeTexture2D(IPOGLTexture2D* texture, const POGL_SIZE& size) { if (texture == nullptr) THROW_EXCEPTION(POGLStateException, "You cannot resize a non-existing texture"); if (size.width <= 0) THROW_EXCEPTION(POGLStateException, "You cannot resize a texture to 0 width"); if (size.height <= 0) THROW_EXCEPTION(POGLStateException, "You cannot resize a texture to 0 height"); POGLTexture2D* impl = static_cast<POGLTexture2D*>(texture); POGLTextureResource* resource = impl->GetResourcePtr(); mRenderState->BindTextureResource(resource, 0); const POGLTextureFormat::Enum format = resource->GetTextureFormat(); const GLenum _format = POGLEnum::ConvertToTextureFormatEnum(format); const GLenum _internalFormat = POGLEnum::ConvertToInternalTextureFormatEnum(format); glTexImage2D(GL_TEXTURE_2D, 0, _internalFormat, size.width, size.height, 0, _format, GL_UNSIGNED_BYTE, NULL); impl->SetSize(size); CHECK_GL("Could not set new texture size"); } IPOGLFramebuffer* POGLRenderContext::CreateFramebuffer(IPOGLTexture** textures) { return CreateFramebuffer(textures, nullptr); } IPOGLFramebuffer* POGLRenderContext::CreateFramebuffer(IPOGLTexture** textures, IPOGLTexture* depthStencilTexture) { // // Generate a framebuffer ID // const GLuint framebufferID = POGLFactory::GenFramebufferObjectID(textures, depthStencilTexture); // // Convert the textures array into a std::vector // std::vector<IPOGLTexture*> texturesVector; if (textures != nullptr) { for (IPOGLTexture** ptr = textures; *ptr != nullptr; ++ptr) { IPOGLTexture* texture = *ptr; texturesVector.push_back(texture); } } // // Create the actual object // POGLFramebuffer* framebuffer = new POGLFramebuffer(texturesVector, depthStencilTexture); framebuffer->PostConstruct(framebufferID); mRenderState->SetFramebuffer(framebuffer); return framebuffer; } IPOGLVertexBuffer* POGLRenderContext::CreateVertexBuffer(const void* memory, POGL_UINT32 memorySize, const POGL_VERTEX_LAYOUT* layout, POGLPrimitiveType::Enum primitiveType, POGLBufferUsage::Enum bufferUsage) { if (memorySize == 0) THROW_EXCEPTION(POGLStateException, "You cannot create a non-existing vertex buffer"); if (layout == nullptr) THROW_EXCEPTION(POGLStateException, "You cannot create a vertex buffer without a layout"); const POGL_UINT32 numVertices = memorySize / layout->vertexSize; const GLenum usage = POGLEnum::Convert(bufferUsage); const GLenum type = POGLEnum::Convert(primitiveType); const GLuint bufferID = POGLFactory::GenBufferID(); const GLuint vaoID = POGLFactory::GenVertexArrayObjectID(bufferID, layout); // // Create the object // POGLVertexBuffer* vb = new POGLVertexBuffer(numVertices, layout, type, usage); vb->PostConstruct(bufferID, vaoID); // // Fill the buffer with data // glBufferData(GL_ARRAY_BUFFER, memorySize, memory, usage); // // Make sure to mark this buffer as the current vertex buffer // mRenderState->ForceSetVertexBuffer(vb); const GLenum error = glGetError(); if (error != GL_NO_ERROR) THROW_EXCEPTION(POGLResourceException, "Failed to create a vertex buffer. Reason: 0x%x", error); // Finished return vb; } IPOGLVertexBuffer* POGLRenderContext::CreateVertexBuffer(const POGL_POSITION_VERTEX* memory, POGL_UINT32 memorySize, POGLPrimitiveType::Enum primitiveType, POGLBufferUsage::Enum bufferUsage) { return CreateVertexBuffer(memory, memorySize, &POGL_POSITION_VERTEX_LAYOUT, primitiveType, bufferUsage); } IPOGLVertexBuffer* POGLRenderContext::CreateVertexBuffer(const POGL_POSITION_COLOR_VERTEX* memory, POGL_UINT32 memorySize, POGLPrimitiveType::Enum primitiveType, POGLBufferUsage::Enum bufferUsage) { return CreateVertexBuffer(memory, memorySize, &POGL_POSITION_COLOR_VERTEX_LAYOUT, primitiveType, bufferUsage); } IPOGLVertexBuffer* POGLRenderContext::CreateVertexBuffer(const POGL_POSITION_TEXCOORD_VERTEX* memory, POGL_UINT32 memorySize, POGLPrimitiveType::Enum primitiveType, POGLBufferUsage::Enum bufferUsage) { return CreateVertexBuffer(memory, memorySize, &POGL_POSITION_TEXCOORD_VERTEX_LAYOUT, primitiveType, bufferUsage); } IPOGLIndexBuffer* POGLRenderContext::CreateIndexBuffer(const void* memory, POGL_UINT32 memorySize, POGLVertexType::Enum type, POGLBufferUsage::Enum bufferUsage) { if (memorySize == 0) THROW_EXCEPTION(POGLStateException, "You cannot create a non-existing index buffer"); if (type == POGLVertexType::FLOAT || type == POGLVertexType::DOUBLE) THROW_EXCEPTION(POGLStateException, "You are not allowed to create an index buffer of a decimal type"); const POGL_UINT32 typeSize = POGLEnum::VertexTypeSize(type); const POGL_UINT32 numIndices = memorySize / typeSize; const GLuint bufferID = POGLFactory::GenBufferID(); const GLenum usage = POGLEnum::Convert(bufferUsage); const GLenum indiceType = POGLEnum::Convert(type); POGLIndexBuffer* ib = new POGLIndexBuffer(typeSize, numIndices, indiceType, usage); ib->PostConstruct(bufferID); // // Fill the buffer with data // if (memory != nullptr) { glBufferData(GL_ELEMENT_ARRAY_BUFFER, memorySize, memory, usage); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferID); // // Make sure to mark this buffer as the current index buffer // mRenderState->ForceSetIndexBuffer(ib); } const GLenum error = glGetError(); if (error != GL_NO_ERROR) THROW_EXCEPTION(POGLResourceException, "Failed to create a index buffer. Reason: 0x%x", error); // Finished return ib; } IPOGLResource* POGLRenderContext::CloneResource(IPOGLResource* resource) { THROW_NOT_IMPLEMENTED_EXCEPTION(); } void POGLRenderContext::CopyResource(IPOGLResource* source, IPOGLResource* destination) { THROW_NOT_IMPLEMENTED_EXCEPTION(); } void POGLRenderContext::CopyResource(IPOGLResource* source, IPOGLResource* destination, POGL_UINT32 sourceOffset, POGL_UINT32 destinationOffset, POGL_UINT32 size) { THROW_NOT_IMPLEMENTED_EXCEPTION(); } IPOGLRenderState* POGLRenderContext::Apply(IPOGLProgram* program) { if (program == nullptr) THROW_EXCEPTION(POGLResourceException, "You are not allowed to apply a non-existing program"); mRenderState->Apply(static_cast<POGLProgram*>(program)); mRenderState->AddRef(); return mRenderState; } void* POGLRenderContext::Map(IPOGLResource* resource, POGLResourceMapType::Enum e) { auto type = resource->GetType(); if (type == POGLResourceType::VERTEXBUFFER) { POGLVertexBuffer* vb = static_cast<POGLVertexBuffer*>(resource); mRenderState->BindVertexBuffer(vb); return glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); } THROW_NOT_IMPLEMENTED_EXCEPTION(); } void* POGLRenderContext::Map(IPOGLResource* resource, POGL_UINT32 offset, POGL_UINT32 length, POGLResourceMapType::Enum e) { auto type = resource->GetType(); if (type == POGLResourceType::VERTEXBUFFER) { POGLVertexBuffer* vb = static_cast<POGLVertexBuffer*>(resource); const POGL_UINT32 memorySize = vb->GetCount() * vb->GetLayout()->vertexSize; if (offset + length > memorySize) THROW_EXCEPTION(POGLStateException, "You cannot map with offset: %d and length: %d when the vertex buffer size is: %d", offset, length, memorySize); mRenderState->BindVertexBuffer(vb); return glMapBufferRange(GL_ARRAY_BUFFER, offset, length, GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT); } THROW_NOT_IMPLEMENTED_EXCEPTION(); } void POGLRenderContext::Unmap(IPOGLResource* resource) { auto type = resource->GetType(); if (type == POGLResourceType::VERTEXBUFFER) { glUnmapBuffer(GL_ARRAY_BUFFER); return; } THROW_NOT_IMPLEMENTED_EXCEPTION(); } void POGLRenderContext::SetViewport(const POGL_RECT& viewport) { mRenderState->SetViewport(viewport); } void POGLRenderContext::InitializeRenderState() { if (mRenderState == nullptr) { mRenderState = new POGLRenderState(this); } } <|endoftext|>
<commit_before><commit_msg>Basic student file for homeworks. <commit_after><|endoftext|>
<commit_before>/*********************************************** * Author: Jun Jiang - jiangjun4@sina.com * Create: 2017-08-19 18:50 * Last modified : 2017-08-19 18:50 * Filename : DNN.cpp * Description : **********************************************/ #include "dnn/DNN.h" #include "dnn/Layer.h" #include "utils/Log.h" #include "utils/Shuffler.h" #include <vector> namespace abcdl{ namespace dnn{ void DNN::train(const abcdl::algebra::Mat& train_data, const abcdl::algebra::Mat& train_label, const abcdl::algebra::Mat& test_data, const abcdl::algebra::Mat& test_label){ LOG(INFO) << "dnn start training..."; size_t layer_size = _layers.size(); size_t num_train_data = train_data.rows(); CHECK(num_train_data == train_label.rows()); CHECK(train_data.cols() == _layers[0]->get_input_dim()); CHECK(train_label.cols() == _layers[_layers.size() -1]->get_output_dim()); abcdl::utils::Shuffler shuffler(num_train_data); abcdl::algebra::Mat data; abcdl::algebra::Mat label; for(size_t i = 0; i != _epoch; i++){ shuffler.shuffle(); for(size_t j = 0; j != num_train_data; j++){ train_data.get_row(&data, shuffler.get_row(j)); train_label.get_row(&label, shuffler.get_row(j)); for(size_t k = 0; k != layer_size; k++){ if(k == 0){ ((InputLayer*)_layers[k])->set_x(data); } _layers[k]->forward(_layers[k-1]); } //printf("[%ld][%ld]\n", j, num_train_data); for(size_t k = layer_size - 1; k > 0; k--){ if(k == layer_size - 1){ ((OutputLayer*)_layers[k])->set_y(label); _layers[k]->backward(_layers[k-1], nullptr); }else{ _layers[k]->backward(_layers[k-1], _layers[k+1]); } //mini_batch_update if(j % _batch_size == _batch_size - 1 || j == num_train_data - 1){ _layers[k]->update_gradient(j % _batch_size + 1, _alpha, _lamda); } } if(j % 100 == 0){ printf("Epoch[%ld/%ld] Train[%ld/%ld]\r", i + 1, _epoch, j, num_train_data); } } if(test_data.rows() > 0){ size_t num = evaluate(test_data, test_label); printf("Epoch[%ld][%ld/%ld] rate[%f]\n", i + 1, num, test_data.rows(), num/(real)test_data.rows()); } } } size_t DNN::evaluate(const abcdl::algebra::Mat& test_data, const abcdl::algebra::Mat& test_label){ CHECK(test_data.cols() == _layers[0]->get_input_dim()); CHECK(test_data.rows() == test_label.rows()); CHECK(test_label.cols() == _layers[_layers.size() - 1]->get_output_dim()); size_t rows = test_data.rows(); size_t predict_num = 0; abcdl::algebra::Mat mat; for(size_t i = 0; i != rows; i++){ predict(mat, test_data.get_row(i)); size_t p_label = mat.argmax(); size_t t_label = test_label.get_row(i).argmax(); if(p_label == t_label){ ++predict_num; }else{ printf("[%ld][%f][%ld]\n", p_label, mat.max(), t_label); } } return predict_num; } void DNN::predict(abcdl::algebra::Mat& result, const abcdl::algebra::Mat& predict_data){ CHECK(predict_data.cols() == _layers[0]->get_input_dim()); size_t layer_size = _layers.size(); for(size_t k = 0; k != layer_size; k++){ if(k == 0){ ((InputLayer*)_layers[k])->set_x(predict_data); } _layers[k]->forward(_layers[k-1]); } result = _layers[layer_size - 1]->get_activate_data(); } bool DNN::load_model(const std::string& path){ std::vector<abcdl::algebra::Mat*> models; if(!model_loader.read<real>(path, &models, "DNNMODEL") || models.size() % 2 != 0){ for(auto& model : models){ delete model; } models.clear(); return false; } for(auto& layer : _layers){ delete layer; } _layers.clear(); for(size_t i = 0; i != models.size() / 2; i++){ if(i == 0){ _layers.push_back(new InputLayer(models[0]->rows())); } if(i == models.size() / 2 - 1){ _layers.push_back(new OutputLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), new CrossEntropyCost(), *models[i * 2], *models[i * 2 + 1])); }else{ _layers.push_back(new FullConnLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), *models[i * 2], *models[i * 2 + 1])); } } for(auto& model : models){ delete model; } models.clear(); return true; } bool DNN::write_model(const std::string& path){ std::vector<abcdl::algebra::Mat*> models; for(size_t i = 1; i != _layers.size(); i++){ models.push_back(&_layers[i]->get_weight()); models.push_back(&_layers[i]->get_bias()); } return model_loader.write<real>(models, path, "DNNMODEL", false); } }//namespace dnn }//namespace abcdl <commit_msg>initialized<commit_after>/*********************************************** * Author: Jun Jiang - jiangjun4@sina.com * Create: 2017-08-19 18:50 * Last modified : 2017-08-19 18:50 * Filename : DNN.cpp * Description : **********************************************/ #include "dnn/DNN.h" #include "dnn/Layer.h" #include "utils/Log.h" #include "utils/Shuffler.h" #include <vector> namespace abcdl{ namespace dnn{ void DNN::train(const abcdl::algebra::Mat& train_data, const abcdl::algebra::Mat& train_label, const abcdl::algebra::Mat& test_data, const abcdl::algebra::Mat& test_label){ LOG(INFO) << "dnn start training..."; size_t layer_size = _layers.size(); size_t num_train_data = train_data.rows(); CHECK(num_train_data == train_label.rows()); CHECK(train_data.cols() == _layers[0]->get_input_dim()); CHECK(train_label.cols() == _layers[_layers.size() -1]->get_output_dim()); abcdl::utils::Shuffler shuffler(num_train_data); abcdl::algebra::Mat data; abcdl::algebra::Mat label; for(size_t i = 0; i != _epoch; i++){ shuffler.shuffle(); for(size_t j = 0; j != num_train_data; j++){ train_data.get_row(&data, shuffler.get_row(j)); train_label.get_row(&label, shuffler.get_row(j)); for(size_t k = 0; k != layer_size; k++){ if(k == 0){ ((InputLayer*)_layers[k])->set_x(data); } _layers[k]->forward(_layers[k-1]); } for(size_t k = layer_size - 1; k > 0; k--){ if(k == layer_size - 1){ ((OutputLayer*)_layers[k])->set_y(label); _layers[k]->backward(_layers[k-1], nullptr); }else{ _layers[k]->backward(_layers[k-1], _layers[k+1]); } //mini_batch_update if(j % _batch_size == _batch_size - 1 || j == num_train_data - 1){ _layers[k]->update_gradient(j % _batch_size + 1, _alpha, _lamda); } } if(j % 100 == 0){ printf("Epoch[%ld/%ld] Train[%ld/%ld]\r", i + 1, _epoch, j, num_train_data); } } if(test_data.rows() > 0){ size_t num = evaluate(test_data, test_label); printf("Epoch[%ld][%ld/%ld] rate[%f]\n", i + 1, num, test_data.rows(), num/(real)test_data.rows()); } } } size_t DNN::evaluate(const abcdl::algebra::Mat& test_data, const abcdl::algebra::Mat& test_label){ CHECK(test_data.cols() == _layers[0]->get_input_dim()); CHECK(test_data.rows() == test_label.rows()); CHECK(test_label.cols() == _layers[_layers.size() - 1]->get_output_dim()); size_t rows = test_data.rows(); size_t predict_num = 0; abcdl::algebra::Mat mat; for(size_t i = 0; i != rows; i++){ predict(mat, test_data.get_row(i)); if(mat.argmax() == test_label.get_row(i).argmax()){ ++predict_num; } } return predict_num; } void DNN::predict(abcdl::algebra::Mat& result, const abcdl::algebra::Mat& predict_data){ CHECK(predict_data.cols() == _layers[0]->get_input_dim()); size_t layer_size = _layers.size(); for(size_t k = 0; k != layer_size; k++){ if(k == 0){ ((InputLayer*)_layers[k])->set_x(predict_data); } _layers[k]->forward(_layers[k-1]); } result = _layers[layer_size - 1]->get_activate_data(); } bool DNN::load_model(const std::string& path){ std::vector<abcdl::algebra::Mat*> models; if(!model_loader.read<real>(path, &models, "DNNMODEL") || models.size() % 2 != 0){ for(auto& model : models){ delete model; } models.clear(); return false; } for(auto& layer : _layers){ delete layer; } _layers.clear(); for(size_t i = 0; i != models.size() / 2; i++){ if(i == 0){ _layers.push_back(new InputLayer(models[0]->rows())); } if(i == models.size() / 2 - 1){ _layers.push_back(new OutputLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), new CrossEntropyCost(), *models[i * 2], *models[i * 2 + 1])); }else{ _layers.push_back(new FullConnLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), *models[i * 2], *models[i * 2 + 1])); } } for(auto& model : models){ delete model; } models.clear(); return true; } bool DNN::write_model(const std::string& path){ std::vector<abcdl::algebra::Mat*> models; for(size_t i = 1; i != _layers.size(); i++){ models.push_back(&_layers[i]->get_weight()); models.push_back(&_layers[i]->get_bias()); } return model_loader.write<real>(models, path, "DNNMODEL", false); } }//namespace dnn }//namespace abcdl <|endoftext|>
<commit_before>#include <iostream> #include "macho/MachoBinary.h" #include "macho/FatBinary.h" #include "AbstractBinary.h" #include "macho/MachoBinaryVisitor.h" using namespace std; // Que quiero hacer? // Principalmente quiero que la libreria sea flexible para que pueda ser utilizada para varias cosas. // En particular, para hacer una tool de inspeccion de mach-o y tambien como un parser de mach-o para // el disassembler. Los dos escenarios son propicios para implementar algo tipo observer, donde cada // load command tiene su handler. El problema llega cuando queremos informacion de las sections. Que // es lo que hacemos? Las sections estan dentro de un segment o segment_64. Para llamar a los handlers // de las sections deberiamos tener una forma de inspeccionar los segment's. class MachoBinaryPrinterVisitor: public MachoBinaryVisitor { public: virtual ~MachoBinaryPrinterVisitor() = default; virtual bool handle_mach_header(const struct mach_header &header) override { LOG_DEBUG("CACA -> %s", __PRETTY_FUNCTION__); return true; } virtual bool handle_mach_header(const struct mach_header_64 &header) override { LOG_DEBUG("CACA -> %s", __PRETTY_FUNCTION__); return true; } }; int main(int argc, char **argv) { MachoBinary binary { new MachoBinaryPrinterVisitor() }; if (!binary.load(argv[1])) { cerr << "Could not open mach-o binary" << endl; return -1; } if (!binary.init()) { cerr << "Could not initialize mach-o binary" << endl; binary.unload(); return -1; } cout << "Welcome to reTools!" << endl; return 0; if (argc < 2) { cerr << "I need a binary to analyze" << endl; return -1; } FatBinary fat_binary { }; if (!fat_binary.load(argv[1])) { cerr << "Could not open mach-o binary" << endl; return -1; } if (!fat_binary.init()) { cerr << "Could not initialize mach-o binary" << endl; fat_binary.unload(); return -1; } // For each of the underlying binaries. for (AbstractBinary *sub_binary : fat_binary.binaries()) { } return 0; } <commit_msg>Not needed anymore.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <fstream> #include "init.h" // for pwalletMain #include "rpcserver.h" #include "rpcprotocol.h" #include "ui_interface.h" #include "base58.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> using namespace std; void EnsureWalletIsUnlocked(); namespace bt = boost::posix_time; // Extended DecodeDumpTime implementation, see this page for details: // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; const size_t formats_n = sizeof(formats)/sizeof(formats[0]); std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); bt::time_duration diff = pt - timet_start; return diff.ticks()/bt::time_duration::rep_type::ticks_per_second; } int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; for(size_t i=0; i<formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if(pt != bt::ptime()) break; } return pt_to_time_t(pt); } std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned char c : str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } class CTxDump { public: CBlockIndex *pindex; int64_t nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; UniValue importprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <gridcoinprivkey> [label] [bool:rescan]\n" "\n" "[label] -------> Optional; Label for imported address\n" "[bool:rescan] -> Optional; Default true\n" "WARNING: if true rescan of blockchain will occur. This could take up to 20 minutes.\n" "\n" "Adds a private key (as returned by dumpprivkey) to your wallet\n"); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; CKey key; bool fGood = vchSecret.SetString(strSecret); // If CBitcoinSecret key decode failed, try to decode the key as hex if(!fGood) { auto vecsecret = ParseHex(strSecret); if(!key.SetPrivKey(CPrivKey(vecsecret.begin(),vecsecret.end()))) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); } else { bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); } if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKeyID vchAddress = key.GetPubKey().GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return NullUniValue; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKey(key)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->SetAddressBookName(vchAddress, strLabel); if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return NullUniValue; } UniValue importwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet <filename>\n" "\n" "<filename> -> filename of the wallet to import\n" "\n" "Imports keys from a wallet dump file (see dumpwallet)\n"); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; bool fCompressed; CKey key; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID keyid = key.GetPubKey().GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKey(key)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks", pindexBest->nHeight - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->ReacceptWalletTransactions(); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return NullUniValue; } UniValue dumpprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <gridcoinaddress>\n" "<gridcoinaddress> -> Address of requested key\n" "\n" "Reveals the private key corresponding to <gridcoinaddress>\n"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Gridcoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); LOCK2(cs_main, pwalletMain->cs_wallet); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CSecret vchSecret; bool fCompressed; if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret, fCompressed).ToString(); } UniValue dumpwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet <filename>\n" "\n" "<filename> -> filename to dump wallet to\n" "\n" "Dumps all wallet keys in a human-readable format into the specified file.\n" "If a path is not specified in the filename, the data directory is used."); EnsureWalletIsUnlocked(); boost::filesystem::path PathForDump = boost::filesystem::path(params[0].get_str()); boost::filesystem::path DefaultPathDataDir = GetDataDir(); // If provided filename does not have a path, then append parent path, otherwise leave alone. if (PathForDump.parent_path().empty()) PathForDump = DefaultPathDataDir / PathForDump; ofstream file; file.open(PathForDump.string().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Gridcoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); bool IsCompressed; CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid]), strAddr); } else if (setKeyPool.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString(), strTime, strAddr); } else { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return NullUniValue; } <commit_msg>Have importwallet file path default to datadir<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <fstream> #include "init.h" // for pwalletMain #include "rpcserver.h" #include "rpcprotocol.h" #include "ui_interface.h" #include "base58.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> using namespace std; void EnsureWalletIsUnlocked(); namespace bt = boost::posix_time; // Extended DecodeDumpTime implementation, see this page for details: // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; const size_t formats_n = sizeof(formats)/sizeof(formats[0]); std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); bt::time_duration diff = pt - timet_start; return diff.ticks()/bt::time_duration::rep_type::ticks_per_second; } int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; for(size_t i=0; i<formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if(pt != bt::ptime()) break; } return pt_to_time_t(pt); } std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned char c : str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } class CTxDump { public: CBlockIndex *pindex; int64_t nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; UniValue importprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <gridcoinprivkey> [label] [bool:rescan]\n" "\n" "[label] -------> Optional; Label for imported address\n" "[bool:rescan] -> Optional; Default true\n" "WARNING: if true rescan of blockchain will occur. This could take up to 20 minutes.\n" "\n" "Adds a private key (as returned by dumpprivkey) to your wallet\n"); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; CKey key; bool fGood = vchSecret.SetString(strSecret); // If CBitcoinSecret key decode failed, try to decode the key as hex if(!fGood) { auto vecsecret = ParseHex(strSecret); if(!key.SetPrivKey(CPrivKey(vecsecret.begin(),vecsecret.end()))) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); } else { bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); } if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKeyID vchAddress = key.GetPubKey().GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return NullUniValue; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKey(key)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->SetAddressBookName(vchAddress, strLabel); if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return NullUniValue; } UniValue importwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet <filename>\n" "\n" "<filename> -> filename of the wallet to import\n" "\n" "Imports keys from a wallet dump file (see dumpwallet)\n" "If a path is not specified in the filename, the data directory is used."); boost::filesystem::path PathForImport = boost::filesystem::path(params[0].get_str()); boost::filesystem::path DefaultPathDataDir = GetDataDir(); // If provided filename does not have a path, then append parent path, otherwise leave alone. if (PathForImport.parent_path().empty()) PathForImport = DefaultPathDataDir / PathForImport; ifstream file; file.open(PathForImport.string().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; bool fCompressed; CKey key; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID keyid = key.GetPubKey().GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKey(key)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks", pindexBest->nHeight - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->ReacceptWalletTransactions(); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return NullUniValue; } UniValue dumpprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <gridcoinaddress>\n" "<gridcoinaddress> -> Address of requested key\n" "\n" "Reveals the private key corresponding to <gridcoinaddress>\n"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Gridcoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); LOCK2(cs_main, pwalletMain->cs_wallet); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CSecret vchSecret; bool fCompressed; if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret, fCompressed).ToString(); } UniValue dumpwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet <filename>\n" "\n" "<filename> -> filename to dump wallet to\n" "\n" "Dumps all wallet keys in a human-readable format into the specified file.\n" "If a path is not specified in the filename, the data directory is used."); EnsureWalletIsUnlocked(); boost::filesystem::path PathForDump = boost::filesystem::path(params[0].get_str()); boost::filesystem::path DefaultPathDataDir = GetDataDir(); // If provided filename does not have a path, then append parent path, otherwise leave alone. if (PathForDump.parent_path().empty()) PathForDump = DefaultPathDataDir / PathForDump; ofstream file; file.open(PathForDump.string().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Gridcoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); bool IsCompressed; CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid]), strAddr); } else if (setKeyPool.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString(), strTime, strAddr); } else { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return NullUniValue; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <fstream> #include "init.h" // for pwalletMain #include "rpcserver.h" #include "ui_interface.h" #include "base58.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); namespace bt = boost::posix_time; // Extended DecodeDumpTime implementation, see this page for details: // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; const size_t formats_n = sizeof(formats)/sizeof(formats[0]); std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); bt::time_duration diff = pt - timet_start; return diff.ticks()/bt::time_duration::rep_type::ticks_per_second; } int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; for(size_t i=0; i<formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if(pt != bt::ptime()) break; } return pt_to_time_t(pt); } std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } class CTxDump { public: CBlockIndex *pindex; int64_t nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <iadixcoinprivkey> [label] [rescan=true]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet <filename>\n" "Imports keys from a wallet dump file (see dumpwallet)."); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKey(key)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->ReacceptWalletTransactions(); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value exportwallet(const Array& params, bool fHelp) { CKey newKey; CKeyID keyID; CKey vchSecret; Value ret; string strAddress; CBitcoinAddress address; CWalletDB *cdb; CWallet *pwalletNew; DBErrors nLoadWalletRet; if (fHelp || params.size() != 3) throw runtime_error( "exportwallet <address> <filename> <secret>\n" "Export a wallet keys in a wallet file."); EnsureWalletIsUnlocked(); strAddress = params[0].get_str(); if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid IadixCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); newKey = CBitcoinSecret(vchSecret).GetKey(); pwalletNew = new CWallet (params[1].get_str()); cdb = new CWalletDB (params[1].get_str(), "cr+"); nLoadWalletRet = cdb->LoadWallet (pwalletNew); if (nLoadWalletRet != DB_LOAD_OK) { throw JSONRPCError(RPC_WALLET_ERROR, "Error creating new wallet"); return Value::null; } pwalletNew->AddKey (newKey); pwalletNew->ScanForWalletTransactions (pindexGenesisBlock, true); bitdb.dbenv.dbrename (NULL, params[1].get_str().c_str(), NULL, "wallet.dat", DB_AUTO_COMMIT); cdb->Close (); //pwalletNew->SetDefaultKey (newKey.GetPubKey()); pwalletNew->EncryptWallet (params[2].get_str().c_str()); bitdb.CloseDb (params[1].get_str()); delete cdb; delete pwalletNew; ret = (GetDataDir() / params[1].get_str()).string(); boost::filesystem::permissions(ret.get_str(), boost::filesystem::add_perms | boost::filesystem::others_read | boost::filesystem::others_write | boost::filesystem::group_read | boost::filesystem::group_write); return ret; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <iadixcoinaddress>\n" "Reveals the private key corresponding to <iadixcoinaddress>."); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid IadixCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet <filename>\n" "Dumps all wallet keys in a human-readable format."); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by IadixCoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid]), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <commit_msg>fix export<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <fstream> #include "init.h" // for pwalletMain #include "rpcserver.h" #include "ui_interface.h" #include "base58.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); namespace bt = boost::posix_time; // Extended DecodeDumpTime implementation, see this page for details: // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; const size_t formats_n = sizeof(formats)/sizeof(formats[0]); std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); bt::time_duration diff = pt - timet_start; return diff.ticks()/bt::time_duration::rep_type::ticks_per_second; } int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; for(size_t i=0; i<formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if(pt != bt::ptime()) break; } return pt_to_time_t(pt); } std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } class CTxDump { public: CBlockIndex *pindex; int64_t nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <iadixcoinprivkey> [label] [rescan=true]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet <filename>\n" "Imports keys from a wallet dump file (see dumpwallet)."); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKey(key)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->ReacceptWalletTransactions(); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value exportwallet(const Array& params, bool fHelp) { CKey newKey; CKeyID keyID; CKey vchSecret; Value ret; string strAddress; CBitcoinAddress address; CWalletDB *cdb; CWallet *pwalletNew; DBErrors nLoadWalletRet; if (fHelp || params.size() != 3) throw runtime_error( "exportwallet <address> <filename> <secret>\n" "Export a wallet keys in a wallet file."); EnsureWalletIsUnlocked(); strAddress = params[0].get_str(); if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid IadixCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); newKey = CBitcoinSecret(vchSecret).GetKey(); pwalletNew = new CWallet (params[1].get_str()); cdb = new CWalletDB (params[1].get_str(), "cr+"); nLoadWalletRet = cdb->LoadWallet (pwalletNew); if (nLoadWalletRet != DB_LOAD_OK) { throw JSONRPCError(RPC_WALLET_ERROR, "Error creating new wallet"); return Value::null; } pwalletNew->AddKey (newKey); pwalletNew->ScanForWalletTransactions (pindexGenesisBlock, true); //bitdb.dbenv.dbrename (NULL, params[1].get_str().c_str(), NULL, "wallet.dat", DB_AUTO_COMMIT); cdb->Close (); //pwalletNew->SetDefaultKey (newKey.GetPubKey()); pwalletNew->EncryptWallet (params[2].get_str().c_str()); //bitdb.CloseDb (params[1].get_str()); delete cdb; delete pwalletNew; ret = (GetDataDir() / params[1].get_str()).string(); boost::filesystem::permissions(ret.get_str(), boost::filesystem::add_perms | boost::filesystem::others_read | boost::filesystem::others_write | boost::filesystem::group_read | boost::filesystem::group_write); return ret; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <iadixcoinaddress>\n" "Reveals the private key corresponding to <iadixcoinaddress>."); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid IadixCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet <filename>\n" "Dumps all wallet keys in a human-readable format."); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by IadixCoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid]), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <|endoftext|>
<commit_before>/* Copyright © 2012, 2015 Vinícius dos Santos Oliveira This file is part of BlowThemAll. BlowThemAll is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "priv/rpcnode.h" #include <QtCore/QJsonDocument> #include <QtCore/QJsonObject> #include <QtCore/QJsonArray> using namespace Tufao; RpcNode::RpcNode(QObject *parent) : QObject(parent), priv(new Priv) {} RpcNode::RpcNode(AbstractMessageSocket *socket, QObject *parent) : QObject(parent), priv(new Priv(socket)) { if (priv->socket) { connect(priv->socket, &AbstractMessageSocket::newMessage, this, &RpcNode::handleMessage); } } RpcNode::~RpcNode() { delete priv; } QObject *RpcNode::methods() { return priv->methods; } void RpcNode::setMethods(QObject *object) { priv->methods = object; } AbstractMessageSocket *RpcNode::messageSocket() { return priv->socket; } void RpcNode::setMessageSocket(AbstractMessageSocket *socket) { if (priv->socket) { disconnect(priv->socket, &AbstractMessageSocket::newMessage, this, &RpcNode::handleMessage); } priv->socket = socket; if (priv->socket) { connect(priv->socket, &AbstractMessageSocket::newMessage, this, &RpcNode::handleMessage); } } QJsonValue RpcNode::callWith(const QString &remoteMethod, const QJsonArray &args, std::function<void(QJsonValue)> handler) { return priv->callWith(remoteMethod, args, handler); } QJsonValue RpcNode::callWith(const QString &remoteMethod, const QJsonObject &args, std::function<void(QJsonValue)> handler) { return priv->callWith(remoteMethod, args, handler); } void RpcNode::call(const QString &remoteMethod, const QJsonArray &args) { priv->call(remoteMethod, args); } void RpcNode::call(const QString &remoteMethod, const QJsonObject &args) { priv->call(remoteMethod, args); } void RpcNode::handleMessage(const QByteArray &msg) { QJsonParseError err; auto object = QJsonDocument::fromJson(msg, &err); if (err.error != QJsonParseError::NoError) { static const char data[] = "{\"jsonrpc\": \"2.0\", \"error\": " "{\"code\": -32700," " \"message\": \"Parse error\"}, " "\"id\": null}"; auto invalidJson = QByteArray::fromRawData(data, sizeof(data) - 1); priv->socket->sendMessage(invalidJson); return; } if (isRequestMessage(object)) { handleRequest(object); } else if (isResponseMessage(object)) { handleResponse(object.object()); } else { static QByteArray invalidJsonRpc = "{\"jsonrpc\": \"2.0\", \"error\": " "{\"code\": -32600, \"message\": \"Invalid JSON-RPC.\"}, " "\"id\": null}"; priv->socket->sendMessage(invalidJsonRpc); } } inline void RpcNode::handleRequest(const QJsonDocument &object) { if (object.isObject()) { QJsonObject response = processRequest(object.object()); if (!response.isEmpty()) { priv->socket->sendMessage(QJsonDocument{response} .toJson(QJsonDocument::Compact)); } } else if (object.isArray()) { QJsonArray batch = object.array(); if (batch.isEmpty()) { priv->socket->sendMessage("{\"jsonrpc\": \"2.0\", \"error\": " "{\"code\": -32600, " "\"message\": \"Invalid JSON-RPC.\"}, " "\"id\": null}"); return; } QJsonArray response; for (const QJsonValue &i: batch) { QJsonObject singleResponse = processRequest(i.toObject()); if (!singleResponse.isEmpty()) response.push_back(singleResponse); } priv->socket->sendMessage(QJsonDocument{response} .toJson(QJsonDocument::Compact)); } else { priv->socket->sendMessage("{\"jsonrpc\": \"2.0\", \"error\": " "{\"code\": -32600, " "\"message\": \"Invalid JSON-RPC.\"}, " "\"id\": null}"); } } inline void RpcNode::handleResponse(const QJsonObject &object) { if (!object.contains("id")) return; if (object.contains("error")) { QJsonValue error = object["error"]; if (!error.isObject()) return; emit this->error(object["id"], QJsonDocument{error.toObject()} .toJson(QJsonDocument::Compact)); return; } QJsonValue key = object["id"]; if (!object.contains("result") || !priv->calls.contains(key)) return; priv->calls[key](object["result"]); priv->calls.remove(key); } QJsonObject RpcNode::processRequest(const QJsonObject &request) { QJsonObject reply({{QString("jsonrpc"), QJsonValue("2.0")}}); if (!request.contains("method")) { reply["error"] = QJsonObject{{{"code", -32600}, {"message", "Invalid Request."}}}; reply["id"] = QJsonValue{}; return reply; } QJsonValue method = request["method"]; if (!method.isString()) { reply["error"] = QJsonObject{{{"code", -32600}, {"message", "Invalid Request."}}}; reply["id"] = QJsonValue{}; return reply; } if (request.contains("params")) { QJsonValue params = request["params"]; if (!params.isArray() && !params.isObject() && !params.isNull()) { reply["error"] = QJsonObject{{ {"code", -32600}, {"message", "Invalid Request."} }}; reply["id"] = QJsonValue{}; return reply; } } if (request.contains("id")) { QJsonValue id = request["id"]; if (!id.isString() && !id.isDouble() && !id.isNull()) { reply["error"] = QJsonObject{{{"code", -32600}, {"message", "Invalid Request."}}}; reply["id"] = QJsonValue{}; return reply; } reply["id"] = id; } QPair<QJsonValue, QJsonObject> result = processReply(method.toString(), request.value("params")); if (!reply.contains("id")) return {}; if (!result.second.isEmpty()) { reply["error"] = result.second; return reply; } reply["result"] = result.first; return reply; } inline QPair<QJsonValue, QJsonObject> RpcNode::processReply(const QString &method, const QJsonValue &args) { if (!priv->methods || (!args.isArray() && !args.isUndefined())) { return qMakePair(QJsonValue{}, QJsonObject{{{"code", METHOD_NOT_FOUND}, {"message", "Method not found"}}}); } QJsonArray params = args.toArray(); // 10 is the max number of args supported by moc/qobject/... if (params.size() > 10) { return qMakePair(QJsonValue{}, QJsonObject{{{"code", METHOD_NOT_FOUND}, {"message", "Method not found"}}}); } const QMetaObject *metaObject = priv->methods->metaObject(); int i = indexOfMethod(metaObject, method, params); if (i == -1) { return qMakePair(QJsonValue{}, QJsonObject{{{"code", METHOD_NOT_FOUND}, {"message", "Method not found"}}}); } QMetaMethod metaMethod = metaObject->method(i); { int size = params.size(); QVector<ArgumentHandler> argsHandler; QVector<QGenericArgument> args; argsHandler.resize(size); args.reserve(size); for (int i = 0;i != size;++i) args.push_back(argsHandler[i].convert(params[i])); ReturnHandler retHandler; QGenericReturnArgument ret = retHandler.convert(metaMethod.typeName()); metaMethod.invoke(priv->methods, Qt::DirectConnection, ret, (0 < size) ? args[0] : QGenericArgument(), (1 < size) ? args[1] : QGenericArgument(), (2 < size) ? args[2] : QGenericArgument(), (3 < size) ? args[3] : QGenericArgument(), (4 < size) ? args[4] : QGenericArgument(), (5 < size) ? args[5] : QGenericArgument(), (6 < size) ? args[6] : QGenericArgument(), (7 < size) ? args[7] : QGenericArgument(), (8 < size) ? args[8] : QGenericArgument(), (9 < size) ? args[9] : QGenericArgument()); return qMakePair(QJsonValue{retHandler}, QJsonObject{}); } } <commit_msg>fix: build issue with clang<commit_after>/* Copyright © 2012, 2015 Vinícius dos Santos Oliveira This file is part of BlowThemAll. BlowThemAll is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "priv/rpcnode.h" #include <QtCore/QJsonDocument> #include <QtCore/QJsonObject> #include <QtCore/QJsonArray> using namespace Tufao; RpcNode::RpcNode(QObject *parent) : QObject(parent), priv(new Priv) {} RpcNode::RpcNode(AbstractMessageSocket *socket, QObject *parent) : QObject(parent), priv(new Priv(socket)) { if (priv->socket) { connect(priv->socket, &AbstractMessageSocket::newMessage, this, &RpcNode::handleMessage); } } RpcNode::~RpcNode() { delete priv; } QObject *RpcNode::methods() { return priv->methods; } void RpcNode::setMethods(QObject *object) { priv->methods = object; } AbstractMessageSocket *RpcNode::messageSocket() { return priv->socket; } void RpcNode::setMessageSocket(AbstractMessageSocket *socket) { if (priv->socket) { disconnect(priv->socket, &AbstractMessageSocket::newMessage, this, &RpcNode::handleMessage); } priv->socket = socket; if (priv->socket) { connect(priv->socket, &AbstractMessageSocket::newMessage, this, &RpcNode::handleMessage); } } QJsonValue RpcNode::callWith(const QString &remoteMethod, const QJsonArray &args, std::function<void(QJsonValue)> handler) { return priv->callWith(remoteMethod, args, handler); } QJsonValue RpcNode::callWith(const QString &remoteMethod, const QJsonObject &args, std::function<void(QJsonValue)> handler) { return priv->callWith(remoteMethod, args, handler); } void RpcNode::call(const QString &remoteMethod, const QJsonArray &args) { priv->call(remoteMethod, args); } void RpcNode::call(const QString &remoteMethod, const QJsonObject &args) { priv->call(remoteMethod, args); } void RpcNode::handleMessage(const QByteArray &msg) { QJsonParseError err; auto object = QJsonDocument::fromJson(msg, &err); if (err.error != QJsonParseError::NoError) { static const char data[] = "{\"jsonrpc\": \"2.0\", \"error\": " "{\"code\": -32700," " \"message\": \"Parse error\"}, " "\"id\": null}"; auto invalidJson = QByteArray::fromRawData(data, sizeof(data) - 1); priv->socket->sendMessage(invalidJson); return; } if (isRequestMessage(object)) { handleRequest(object); } else if (isResponseMessage(object)) { handleResponse(object.object()); } else { static QByteArray invalidJsonRpc = "{\"jsonrpc\": \"2.0\", \"error\": " "{\"code\": -32600, \"message\": \"Invalid JSON-RPC.\"}, " "\"id\": null}"; priv->socket->sendMessage(invalidJsonRpc); } } inline void RpcNode::handleRequest(const QJsonDocument &object) { if (object.isObject()) { QJsonObject response = processRequest(object.object()); if (!response.isEmpty()) { priv->socket->sendMessage(QJsonDocument{response} .toJson(QJsonDocument::Compact)); } } else if (object.isArray()) { QJsonArray batch = object.array(); if (batch.isEmpty()) { priv->socket->sendMessage("{\"jsonrpc\": \"2.0\", \"error\": " "{\"code\": -32600, " "\"message\": \"Invalid JSON-RPC.\"}, " "\"id\": null}"); return; } QJsonArray response; for (const QJsonValue &i: batch) { QJsonObject singleResponse = processRequest(i.toObject()); if (!singleResponse.isEmpty()) response.push_back(singleResponse); } priv->socket->sendMessage(QJsonDocument{response} .toJson(QJsonDocument::Compact)); } else { priv->socket->sendMessage("{\"jsonrpc\": \"2.0\", \"error\": " "{\"code\": -32600, " "\"message\": \"Invalid JSON-RPC.\"}, " "\"id\": null}"); } } inline void RpcNode::handleResponse(const QJsonObject &object) { if (!object.contains("id")) return; if (object.contains("error")) { QJsonValue error = object["error"]; if (!error.isObject()) return; emit this->error(object["id"], QJsonDocument{error.toObject()} .toJson(QJsonDocument::Compact)); return; } QJsonValue key = object["id"]; if (!object.contains("result") || !priv->calls.contains(key)) return; priv->calls[key](object["result"]); priv->calls.remove(key); } QJsonObject RpcNode::processRequest(const QJsonObject &request) { QJsonObject reply({{QString("jsonrpc"), QJsonValue("2.0")}}); if (!request.contains("method")) { reply["error"] = QJsonObject{{{"code", -32600}, {"message", "Invalid Request."}}}; reply["id"] = QJsonValue{}; return reply; } QJsonValue method = request["method"]; if (!method.isString()) { reply["error"] = QJsonObject{{{"code", -32600}, {"message", "Invalid Request."}}}; reply["id"] = QJsonValue{}; return reply; } if (request.contains("params")) { QJsonValue params = request["params"]; if (!params.isArray() && !params.isObject() && !params.isNull()) { reply["error"] = QJsonObject{{ {"code", -32600}, {"message", "Invalid Request."} }}; reply["id"] = QJsonValue{}; return reply; } } if (request.contains("id")) { QJsonValue id = request["id"]; if (!id.isString() && !id.isDouble() && !id.isNull()) { reply["error"] = QJsonObject{{{"code", -32600}, {"message", "Invalid Request."}}}; reply["id"] = QJsonValue{}; return reply; } reply["id"] = id; } QPair<QJsonValue, QJsonObject> result = processReply(method.toString(), request.value("params")); if (!reply.contains("id")) return {}; if (!result.second.isEmpty()) { reply["error"] = result.second; return reply; } reply["result"] = result.first; return reply; } inline QPair<QJsonValue, QJsonObject> RpcNode::processReply(const QString &method, const QJsonValue &args) { if (!priv->methods || (!args.isArray() && !args.isUndefined())) { return qMakePair(QJsonValue{}, QJsonObject{{{"code", METHOD_NOT_FOUND}, {"message", "Method not found"}}}); } QJsonArray params = args.toArray(); // 10 is the max number of args supported by moc/qobject/... if (params.size() > 10) { return qMakePair(QJsonValue{}, QJsonObject{{{"code", METHOD_NOT_FOUND}, {"message", "Method not found"}}}); } const QMetaObject *metaObject = priv->methods->metaObject(); int i = indexOfMethod(metaObject, method, params); if (i == -1) { return qMakePair(QJsonValue{}, QJsonObject{{{"code", METHOD_NOT_FOUND}, {"message", "Method not found"}}}); } QMetaMethod metaMethod = metaObject->method(i); { int size = params.size(); QVector<ArgumentHandler> argsHandler; QVector<QGenericArgument> args; argsHandler.resize(size); args.reserve(size); for (int i = 0;i != size;++i) args.push_back(argsHandler[i].convert(params[i])); ReturnHandler retHandler; QGenericReturnArgument ret = retHandler.convert(metaMethod.typeName()); metaMethod.invoke(priv->methods, Qt::DirectConnection, ret, (0 < size) ? args[0] : QGenericArgument(), (1 < size) ? args[1] : QGenericArgument(), (2 < size) ? args[2] : QGenericArgument(), (3 < size) ? args[3] : QGenericArgument(), (4 < size) ? args[4] : QGenericArgument(), (5 < size) ? args[5] : QGenericArgument(), (6 < size) ? args[6] : QGenericArgument(), (7 < size) ? args[7] : QGenericArgument(), (8 < size) ? args[8] : QGenericArgument(), (9 < size) ? args[9] : QGenericArgument()); return qMakePair(static_cast<QJsonValue>(retHandler), QJsonObject{}); } } <|endoftext|>
<commit_before>/* Copyright 1989, 1990, 1995 by Abacus Research and * Development, Inc. All rights reserved. */ /* Forward declarations in SegmentLdr.h (DO NOT DELETE THIS LINE) */ #include <base/common.h> #include <FileMgr.h> #include <SegmentLdr.h> #include <MemoryMgr.h> #include <ResourceMgr.h> #include <StdFilePkg.h> #include <SysErr.h> #include <FontMgr.h> #include <OSEvent.h> #include <WindowMgr.h> #include <hfs/hfs.h> #include <base/cpu.h> #include <wind/wind.h> #include <rsys/segment.h> #include <vdriver/vdriver.h> #include <rsys/executor.h> #include <commandline/flags.h> #include <prefs/prefs.h> #include <osevent/osevent.h> #include <quickdraw/cquick.h> #include <rsys/desk.h> #include <hfs/dcache.h> #include <rsys/launch.h> #include <rsys/paths.h> #include <ctype.h> #include <algorithm> #if defined(CYGWIN32) #include "winfs.h" /* * NOTE: I've looked at MINGW32 0.1.3 and the io.h #defines * X_OK, which we use below. I think Sam uses 0.1.3, even though * ARDI is currently at 0.1.2. */ #if !defined(OLD_MINGWIN32) #include <io.h> /* needed for X_OK */ #else #define X_OK 4 /* this is really just to get segment.c to compile */ #endif #endif namespace Executor { char *ROMlib_errorstring; bool ROMlib_exit = false; typedef finderinfo *finderinfoptr; typedef GUEST<finderinfoptr> *finderinfohand; } using namespace Executor; static BOOLEAN argv_to_appfile(const char *uname, AppFile *ap) { auto spec = cmdlinePathToFSSpec(uname); if(!spec) return false; CInfoPBRec cinfo; cinfo.hFileInfo.ioVRefNum = spec->vRefNum; cinfo.hFileInfo.ioDirID = spec->parID; cinfo.hFileInfo.ioFDirIndex = 0; cinfo.hFileInfo.ioNamePtr = spec->name; if(PBGetCatInfo(&cinfo, false) != noErr) { warning_unexpected("%s: unable to get info on `%s'\n", ROMlib_appname.c_str(), uname); return false; } ap->fType = cinfo.hFileInfo.ioFlFndrInfo.fdType; ap->versNum = 0; str255assign(ap->fName, spec->name); WDPBRec wpb; wpb.ioNamePtr = spec->name; wpb.ioVRefNum = spec->vRefNum; wpb.ioWDProcID = TICK("unix"); wpb.ioWDDirID = spec->parID; if(PBOpenWD(&wpb, false) == noErr) ap->vRefNum = wpb.ioVRefNum; else ap->vRefNum = spec->vRefNum; return true; } void Executor::InitAppFiles(int argc, char **argv) { LM(CurApRefNum) = -1; assignPString(LM(CurApName), toMacRomanFilename(ROMlib_appname), sizeof(LM(CurApName)) - 1); GUEST<THz> saveZone = LM(TheZone); LM(TheZone) = LM(SysZone); finderinfohand fh = (finderinfohand) NewHandle((Size)sizeof(finderinfo) - sizeof(AppFile)); LM(TheZone) = saveZone; LM(AppParmHandle) = (Handle)fh; (*fh)->count = 0; (*fh)->message = ROMlib_print ? appPrint : appOpen; for(int i = 1; i < argc; i++) { AppFile appFile; if(argv_to_appfile(argv[i], &appFile)) { ROMlib_exit = true; INTEGER newcount = (*fh)->count + 1; (*fh)->count = newcount; SetHandleSize((Handle)fh, (char *)&(*fh)->files[newcount] - (char *)*fh); (*fh)->files[(*fh)->count - 1] = appFile; } } } void Executor::CountAppFiles(GUEST<INTEGER> *messagep, GUEST<INTEGER> *countp) /* IMII-57 */ { if(LM(AppParmHandle)) { if(messagep) *messagep = (*(finderinfohand)LM(AppParmHandle))->message; if(countp) *countp = (*(finderinfohand)LM(AppParmHandle))->count; } else *countp = 0; } void Executor::GetAppFiles(INTEGER index, AppFile *filep) /* IMII-58 */ { *filep = (*(finderinfohand)LM(AppParmHandle))->files[index - 1]; } void Executor::ClrAppFiles(INTEGER index) /* IMII-58 */ { if((*(finderinfohand)LM(AppParmHandle))->files[index - 1].fType) { (*(finderinfohand)LM(AppParmHandle))->files[index - 1].fType = 0; (*(finderinfohand)LM(AppParmHandle))->count = (*(finderinfohand)LM(AppParmHandle))->count - 1; } } void Executor::C_GetAppParms(StringPtr namep, GUEST<INTEGER> *rnp, GUEST<Handle> *aphandp) /* IMII-58 */ { str255assign(namep, LM(CurApName)); *rnp = LM(CurApRefNum); *aphandp = LM(AppParmHandle); } static BOOLEAN valid_browser(void) { OSErr err; FInfo finfo; err = GetFInfo(LM(FinderName), LM(BootDrive), &finfo); return !ROMlib_nobrowser && err == noErr && finfo.fdType == TICK("APPL"); } static void launch_browser(void) { /* Set the depth to what was specified on the command line; * if nothing was specified there, set the depth to the maximum * supported bits per pixel. */ SetDepth(LM(MainDevice), (flag_bpp ? std::min(flag_bpp, vdriver->maxBpp()) : vdriver->maxBpp()), 0, 0); Launch(LM(FinderName), LM(BootDrive)); } void Executor::C_ExitToShell() { static char beenhere = false; ALLOCABEGIN #if 1 Point pt; static GUEST<SFTypeList> applonly = { FOURCC('A', 'P', 'P', 'L') }; SFReply reply; struct { char quickbytes[grafSize]; GUEST<GrafPtr> qdthePort; GUEST<LONGINT> tmpA5; } a5space; WindowPeek t_w; int i; if(ROMlib_mods & optionKey) ROMlib_exit = true; /* NOTE: closing drivers is a bad thing in the long run, but for now we're doing it. We actually do it here *and* in reinitialize_things(). We have to do it here since we want the window taken out of the windowlist properly, before we hack it out ourself, but we have to do it in reinitializethings because launch calls that, but doesn't call exittoshell */ for(i = DESK_ACC_MIN; i <= DESK_ACC_MAX; ++i) CloseDriver(-i - 1); empty_timer_queues(); if(LM(WWExist) == EXIST_YES) { /* remove global datastructures associated with each window remaining in the application's window list */ for(t_w = LM(WindowList); t_w; t_w = WINDOW_NEXT_WINDOW(t_w)) pm_window_closed((WindowPtr)t_w); } LM(WindowList) = 0; if(!ROMlib_exit && (!beenhere || strncmp((char *)LM(CurApName) + 1, BROWSER_NAME, LM(CurApName)[0]) != 0)) { beenhere = true; /* if we call `InitWindows ()', we don't want it shouting about 32bit uncleanliness, &c */ size_info.application_p = false; if(LM(QDExist) == EXIST_NO) { EM_A5 = US_TO_SYN68K(&a5space.tmpA5); LM(CurrentA5) = guest_cast<Ptr>(EM_A5); InitGraf((Ptr)&a5space.qdthePort); } InitFonts(); FlushEvents(everyEvent, 0); if(LM(WWExist) == EXIST_NO) InitWindows(); if(LM(TEScrpHandle) == guest_cast<Handle>(-1) || LM(TEScrpHandle) == nullptr) TEInit(); if(LM(DlgFont) == 0 || LM(DlgFont) == -1) InitDialogs((ProcPtr)0); InitCursor(); if(valid_browser()) { /* NOTE: much of the initialization done above isn't really needed here, but I'd prefer to have the same environment when we auto-launch browser as when we choose an app using stdfile */ launch_browser(); } else { pt.h = 100; pt.v = 100; SFGetFile(pt, (StringPtr) "", nullptr, 1, applonly, nullptr, &reply); if(!reply.good) ROMlib_exit = true; else { LM(CurApName)[0] = std::min<uint8_t>(reply.fName[0], 31); BlockMoveData((Ptr)reply.fName + 1, (Ptr)LM(CurApName) + 1, (Size)LM(CurApName)[0]); Launch(LM(CurApName), reply.vRefNum); } } } #endif CloseResFile(0); ROMlib_OurClose(); dcache_invalidate_all(true); if(ROMlib_errorstring) { write(2, ROMlib_errorstring, strlen(ROMlib_errorstring)); gui_abort(); } exit(0); ALLOCAEND /* yeah, right, if exit fails... */ } #define JMPLINSTR 0x4EF9 #define MOVESPINSTR 0x3F3C #define LOADSEGTRAP 0xA9F0 void Executor::C_LoadSeg(INTEGER segno) { Handle newcode; unsigned short offbytes; INTEGER taboff, nentries, savenentries; GUEST<int16_t> *ptr, *saveptr; LM(ResLoad) = -1; /* CricketDraw III's behaviour suggested this */ newcode = GetResource(TICK("CODE"), segno); HLock(newcode); taboff = ((GUEST<INTEGER> *)*newcode)[0]; if((uint16_t)taboff == 0xA89F) /* magic compressed resource signature */ { /* We are totally dead here. We almost certainly can't use * `system_error' to inform the user because the window * manager probably is not yet running. */ ROMlib_launch_failure = (system_version >= 0x700 ? launch_compressed_ge7 : launch_compressed_lt7); C_ExitToShell(); } savenentries = nentries = ((GUEST<INTEGER> *)*newcode)[1]; saveptr = ptr = (GUEST<int16_t> *)((char *)SYN68K_TO_US(EM_A5) + taboff + LM(CurJTOffset)); while(--nentries >= 0) { if(ptr[1] != JMPLINSTR) { offbytes = *ptr; *ptr++ = segno; *ptr++ = JMPLINSTR; *(GUEST<LONGINT> *)ptr = US_TO_SYN68K(*newcode) + offbytes + 4; ptr += 2; } else ptr += 4; } ROMlib_destroy_blocks(US_TO_SYN68K(saveptr), 8L * savenentries, true); } #define SEGNOOFP(p) (((GUEST<INTEGER> *)p)[-1]) static void unpatch(Ptr segstart, Ptr p) { GUEST<INTEGER> *ip; Ptr firstpc; ip = (GUEST<INTEGER> *)p; firstpc = *(GUEST<Ptr> *)(p + 2); ip[1] = ip[-1]; /* the segment number */ ip[-1] = firstpc - segstart - 4; ip[0] = MOVESPINSTR; ip[2] = LOADSEGTRAP; } void Executor::C_UnloadSeg(Ptr addr) { Ptr p, segstart; char *top, *bottom; Handle h; INTEGER segno; if(*(GUEST<INTEGER> *)addr == JMPLINSTR) { segno = SEGNOOFP(addr); h = GetResource(TICK("CODE"), segno); if(!*h) LoadResource(h); segstart = *h; for(p = addr; SEGNOOFP(p) == segno; p += 8) unpatch(segstart, p); bottom = (char *)p; for(p = addr - 8; SEGNOOFP(p) == segno; p -= 8) unpatch(segstart, p); top = (char *)p + 6; /* +8 that we didn't zap, -2 that we went overboard on unpatch (see above) */ ROMlib_destroy_blocks(US_TO_SYN68K(top), bottom - top, false); HUnlock(h); HPurge(h); } } <commit_msg>add missing #include<commit_after>/* Copyright 1989, 1990, 1995 by Abacus Research and * Development, Inc. All rights reserved. */ /* Forward declarations in SegmentLdr.h (DO NOT DELETE THIS LINE) */ #include <base/common.h> #include <FileMgr.h> #include <SegmentLdr.h> #include <MemoryMgr.h> #include <ResourceMgr.h> #include <StdFilePkg.h> #include <SysErr.h> #include <FontMgr.h> #include <OSEvent.h> #include <WindowMgr.h> #include <hfs/hfs.h> #include <base/cpu.h> #include <wind/wind.h> #include <rsys/segment.h> #include <vdriver/vdriver.h> #include <rsys/executor.h> #include <commandline/flags.h> #include <prefs/prefs.h> #include <osevent/osevent.h> #include <quickdraw/cquick.h> #include <rsys/desk.h> #include <hfs/dcache.h> #include <rsys/launch.h> #include <rsys/paths.h> #include <rsys/macstrings.h> #include <ctype.h> #include <algorithm> #if defined(CYGWIN32) #include "winfs.h" /* * NOTE: I've looked at MINGW32 0.1.3 and the io.h #defines * X_OK, which we use below. I think Sam uses 0.1.3, even though * ARDI is currently at 0.1.2. */ #if !defined(OLD_MINGWIN32) #include <io.h> /* needed for X_OK */ #else #define X_OK 4 /* this is really just to get segment.c to compile */ #endif #endif namespace Executor { char *ROMlib_errorstring; bool ROMlib_exit = false; typedef finderinfo *finderinfoptr; typedef GUEST<finderinfoptr> *finderinfohand; } using namespace Executor; static BOOLEAN argv_to_appfile(const char *uname, AppFile *ap) { auto spec = cmdlinePathToFSSpec(uname); if(!spec) return false; CInfoPBRec cinfo; cinfo.hFileInfo.ioVRefNum = spec->vRefNum; cinfo.hFileInfo.ioDirID = spec->parID; cinfo.hFileInfo.ioFDirIndex = 0; cinfo.hFileInfo.ioNamePtr = spec->name; if(PBGetCatInfo(&cinfo, false) != noErr) { warning_unexpected("%s: unable to get info on `%s'\n", ROMlib_appname.c_str(), uname); return false; } ap->fType = cinfo.hFileInfo.ioFlFndrInfo.fdType; ap->versNum = 0; str255assign(ap->fName, spec->name); WDPBRec wpb; wpb.ioNamePtr = spec->name; wpb.ioVRefNum = spec->vRefNum; wpb.ioWDProcID = TICK("unix"); wpb.ioWDDirID = spec->parID; if(PBOpenWD(&wpb, false) == noErr) ap->vRefNum = wpb.ioVRefNum; else ap->vRefNum = spec->vRefNum; return true; } void Executor::InitAppFiles(int argc, char **argv) { LM(CurApRefNum) = -1; assignPString(LM(CurApName), toMacRomanFilename(ROMlib_appname), sizeof(LM(CurApName)) - 1); GUEST<THz> saveZone = LM(TheZone); LM(TheZone) = LM(SysZone); finderinfohand fh = (finderinfohand) NewHandle((Size)sizeof(finderinfo) - sizeof(AppFile)); LM(TheZone) = saveZone; LM(AppParmHandle) = (Handle)fh; (*fh)->count = 0; (*fh)->message = ROMlib_print ? appPrint : appOpen; for(int i = 1; i < argc; i++) { AppFile appFile; if(argv_to_appfile(argv[i], &appFile)) { ROMlib_exit = true; INTEGER newcount = (*fh)->count + 1; (*fh)->count = newcount; SetHandleSize((Handle)fh, (char *)&(*fh)->files[newcount] - (char *)*fh); (*fh)->files[(*fh)->count - 1] = appFile; } } } void Executor::CountAppFiles(GUEST<INTEGER> *messagep, GUEST<INTEGER> *countp) /* IMII-57 */ { if(LM(AppParmHandle)) { if(messagep) *messagep = (*(finderinfohand)LM(AppParmHandle))->message; if(countp) *countp = (*(finderinfohand)LM(AppParmHandle))->count; } else *countp = 0; } void Executor::GetAppFiles(INTEGER index, AppFile *filep) /* IMII-58 */ { *filep = (*(finderinfohand)LM(AppParmHandle))->files[index - 1]; } void Executor::ClrAppFiles(INTEGER index) /* IMII-58 */ { if((*(finderinfohand)LM(AppParmHandle))->files[index - 1].fType) { (*(finderinfohand)LM(AppParmHandle))->files[index - 1].fType = 0; (*(finderinfohand)LM(AppParmHandle))->count = (*(finderinfohand)LM(AppParmHandle))->count - 1; } } void Executor::C_GetAppParms(StringPtr namep, GUEST<INTEGER> *rnp, GUEST<Handle> *aphandp) /* IMII-58 */ { str255assign(namep, LM(CurApName)); *rnp = LM(CurApRefNum); *aphandp = LM(AppParmHandle); } static BOOLEAN valid_browser(void) { OSErr err; FInfo finfo; err = GetFInfo(LM(FinderName), LM(BootDrive), &finfo); return !ROMlib_nobrowser && err == noErr && finfo.fdType == TICK("APPL"); } static void launch_browser(void) { /* Set the depth to what was specified on the command line; * if nothing was specified there, set the depth to the maximum * supported bits per pixel. */ SetDepth(LM(MainDevice), (flag_bpp ? std::min(flag_bpp, vdriver->maxBpp()) : vdriver->maxBpp()), 0, 0); Launch(LM(FinderName), LM(BootDrive)); } void Executor::C_ExitToShell() { static char beenhere = false; ALLOCABEGIN #if 1 Point pt; static GUEST<SFTypeList> applonly = { FOURCC('A', 'P', 'P', 'L') }; SFReply reply; struct { char quickbytes[grafSize]; GUEST<GrafPtr> qdthePort; GUEST<LONGINT> tmpA5; } a5space; WindowPeek t_w; int i; if(ROMlib_mods & optionKey) ROMlib_exit = true; /* NOTE: closing drivers is a bad thing in the long run, but for now we're doing it. We actually do it here *and* in reinitialize_things(). We have to do it here since we want the window taken out of the windowlist properly, before we hack it out ourself, but we have to do it in reinitializethings because launch calls that, but doesn't call exittoshell */ for(i = DESK_ACC_MIN; i <= DESK_ACC_MAX; ++i) CloseDriver(-i - 1); empty_timer_queues(); if(LM(WWExist) == EXIST_YES) { /* remove global datastructures associated with each window remaining in the application's window list */ for(t_w = LM(WindowList); t_w; t_w = WINDOW_NEXT_WINDOW(t_w)) pm_window_closed((WindowPtr)t_w); } LM(WindowList) = 0; if(!ROMlib_exit && (!beenhere || strncmp((char *)LM(CurApName) + 1, BROWSER_NAME, LM(CurApName)[0]) != 0)) { beenhere = true; /* if we call `InitWindows ()', we don't want it shouting about 32bit uncleanliness, &c */ size_info.application_p = false; if(LM(QDExist) == EXIST_NO) { EM_A5 = US_TO_SYN68K(&a5space.tmpA5); LM(CurrentA5) = guest_cast<Ptr>(EM_A5); InitGraf((Ptr)&a5space.qdthePort); } InitFonts(); FlushEvents(everyEvent, 0); if(LM(WWExist) == EXIST_NO) InitWindows(); if(LM(TEScrpHandle) == guest_cast<Handle>(-1) || LM(TEScrpHandle) == nullptr) TEInit(); if(LM(DlgFont) == 0 || LM(DlgFont) == -1) InitDialogs((ProcPtr)0); InitCursor(); if(valid_browser()) { /* NOTE: much of the initialization done above isn't really needed here, but I'd prefer to have the same environment when we auto-launch browser as when we choose an app using stdfile */ launch_browser(); } else { pt.h = 100; pt.v = 100; SFGetFile(pt, (StringPtr) "", nullptr, 1, applonly, nullptr, &reply); if(!reply.good) ROMlib_exit = true; else { LM(CurApName)[0] = std::min<uint8_t>(reply.fName[0], 31); BlockMoveData((Ptr)reply.fName + 1, (Ptr)LM(CurApName) + 1, (Size)LM(CurApName)[0]); Launch(LM(CurApName), reply.vRefNum); } } } #endif CloseResFile(0); ROMlib_OurClose(); dcache_invalidate_all(true); if(ROMlib_errorstring) { write(2, ROMlib_errorstring, strlen(ROMlib_errorstring)); gui_abort(); } exit(0); ALLOCAEND /* yeah, right, if exit fails... */ } #define JMPLINSTR 0x4EF9 #define MOVESPINSTR 0x3F3C #define LOADSEGTRAP 0xA9F0 void Executor::C_LoadSeg(INTEGER segno) { Handle newcode; unsigned short offbytes; INTEGER taboff, nentries, savenentries; GUEST<int16_t> *ptr, *saveptr; LM(ResLoad) = -1; /* CricketDraw III's behaviour suggested this */ newcode = GetResource(TICK("CODE"), segno); HLock(newcode); taboff = ((GUEST<INTEGER> *)*newcode)[0]; if((uint16_t)taboff == 0xA89F) /* magic compressed resource signature */ { /* We are totally dead here. We almost certainly can't use * `system_error' to inform the user because the window * manager probably is not yet running. */ ROMlib_launch_failure = (system_version >= 0x700 ? launch_compressed_ge7 : launch_compressed_lt7); C_ExitToShell(); } savenentries = nentries = ((GUEST<INTEGER> *)*newcode)[1]; saveptr = ptr = (GUEST<int16_t> *)((char *)SYN68K_TO_US(EM_A5) + taboff + LM(CurJTOffset)); while(--nentries >= 0) { if(ptr[1] != JMPLINSTR) { offbytes = *ptr; *ptr++ = segno; *ptr++ = JMPLINSTR; *(GUEST<LONGINT> *)ptr = US_TO_SYN68K(*newcode) + offbytes + 4; ptr += 2; } else ptr += 4; } ROMlib_destroy_blocks(US_TO_SYN68K(saveptr), 8L * savenentries, true); } #define SEGNOOFP(p) (((GUEST<INTEGER> *)p)[-1]) static void unpatch(Ptr segstart, Ptr p) { GUEST<INTEGER> *ip; Ptr firstpc; ip = (GUEST<INTEGER> *)p; firstpc = *(GUEST<Ptr> *)(p + 2); ip[1] = ip[-1]; /* the segment number */ ip[-1] = firstpc - segstart - 4; ip[0] = MOVESPINSTR; ip[2] = LOADSEGTRAP; } void Executor::C_UnloadSeg(Ptr addr) { Ptr p, segstart; char *top, *bottom; Handle h; INTEGER segno; if(*(GUEST<INTEGER> *)addr == JMPLINSTR) { segno = SEGNOOFP(addr); h = GetResource(TICK("CODE"), segno); if(!*h) LoadResource(h); segstart = *h; for(p = addr; SEGNOOFP(p) == segno; p += 8) unpatch(segstart, p); bottom = (char *)p; for(p = addr - 8; SEGNOOFP(p) == segno; p -= 8) unpatch(segstart, p); top = (char *)p + 6; /* +8 that we didn't zap, -2 that we went overboard on unpatch (see above) */ ROMlib_destroy_blocks(US_TO_SYN68K(top), bottom - top, false); HUnlock(h); HPurge(h); } } <|endoftext|>
<commit_before>#ifndef SIMPLE_WEB_SERVER_UTILITY_HPP #define SIMPLE_WEB_SERVER_UTILITY_HPP #include "status_code.hpp" #include <iostream> #include <memory> #include <string> #include <unordered_map> namespace SimpleWeb { #ifndef CASE_INSENSITIVE_EQUAL_AND_HASH #define CASE_INSENSITIVE_EQUAL_AND_HASH inline bool case_insensitive_equal(const std::string &str1, const std::string &str2) { return str1.size() == str2.size() && std::equal(str1.begin(), str1.end(), str2.begin(), [](char a, char b) { return tolower(a) == tolower(b); }); } class CaseInsensitiveEqual { public: bool operator()(const std::string &str1, const std::string &str2) const { return case_insensitive_equal(str1, str2); } }; // Based on https://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x/2595226#2595226 class CaseInsensitiveHash { public: size_t operator()(const std::string &str) const { size_t h = 0; std::hash<int> hash; for(auto c : str) h ^= hash(tolower(c)) + 0x9e3779b9 + (h << 6) + (h >> 2); return h; } }; #endif typedef std::unordered_multimap<std::string, std::string, CaseInsensitiveHash, CaseInsensitiveEqual> CaseInsensitiveMultimap; /// Percent encoding and decoding class Percent { public: /// Returns percent-encoded string static std::string encode(const std::string &value) { static auto hex_chars = "0123456789ABCDEF"; std::string result; result.reserve(value.size()); // Minimum size of result for(auto &chr : value) { if(chr == ' ') result += '+'; else if(chr == '!' || chr == '#' || chr == '$' || (chr >= '&' && chr <= ',') || (chr >= '/' && chr <= ';') || chr == '=' || chr == '?' || chr == '@' || chr == '[' || chr == ']') result += std::string("%") + hex_chars[chr >> 4] + hex_chars[chr & 15]; else result += chr; } return result; } /// Returns percent-decoded string static std::string decode(const std::string &value) { std::string result; result.reserve(value.size() / 3 + (value.size() % 3)); // Minimum size of result for(size_t i = 0; i < value.size(); ++i) { auto &chr = value[i]; if(chr == '%' && i + 2 < value.size()) { auto hex = value.substr(i + 1, 2); auto decoded_chr = static_cast<char>(std::strtol(hex.c_str(), nullptr, 16)); result += decoded_chr; i += 2; } else if(chr == '+') result += ' '; else result += chr; } return result; } }; /// Query string creation and parsing class QueryString { public: /// Returns query string created from given field names and values static std::string create(const CaseInsensitiveMultimap &fields) { std::string result; bool first = true; for(auto &field : fields) { result += (!first ? "&" : "") + field.first + '=' + Percent::encode(field.second); first = false; } return result; } /// Returns query keys with percent-decoded values. static CaseInsensitiveMultimap parse(const std::string &query_string) { CaseInsensitiveMultimap result; if(query_string.empty()) return result; size_t name_pos = 0; size_t name_end_pos = -1; size_t value_pos = -1; for(size_t c = 0; c < query_string.size(); ++c) { if(query_string[c] == '&') { auto name = query_string.substr(name_pos, (name_end_pos == std::string::npos ? c : name_end_pos) - name_pos); if(!name.empty()) { auto value = value_pos == std::string::npos ? std::string() : query_string.substr(value_pos, c - value_pos); result.emplace(std::move(name), Percent::decode(value)); } name_pos = c + 1; name_end_pos = -1; value_pos = -1; } else if(query_string[c] == '=') { name_end_pos = c; value_pos = c + 1; } } if(name_pos < query_string.size()) { auto name = query_string.substr(name_pos, name_end_pos - name_pos); if(!name.empty()) { auto value = value_pos >= query_string.size() ? std::string() : query_string.substr(value_pos); result.emplace(std::move(name), Percent::decode(value)); } } return result; } }; class RequestMessage { public: /// Parse request line and header fields static bool parse(std::istream &stream, std::string &method, std::string &path, std::string &query_string, std::string &version, CaseInsensitiveMultimap &header) { header.clear(); std::string line; getline(stream, line); size_t method_end; if((method_end = line.find(' ')) != std::string::npos) { method = line.substr(0, method_end); size_t query_start = std::string::npos; size_t path_and_query_string_end = std::string::npos; for(size_t i = method_end + 1; i < line.size(); ++i) { if(line[i] == '?' && (i + 1) < line.size()) query_start = i + 1; else if(line[i] == ' ') { path_and_query_string_end = i; break; } } if(path_and_query_string_end != std::string::npos) { if(query_start != std::string::npos) { path = line.substr(method_end + 1, query_start - method_end - 2); query_string = line.substr(query_start, path_and_query_string_end - query_start); } else path = line.substr(method_end + 1, path_and_query_string_end - method_end - 1); size_t protocol_end; if((protocol_end = line.find('/', path_and_query_string_end + 1)) != std::string::npos) { if(line.compare(path_and_query_string_end + 1, protocol_end - path_and_query_string_end - 1, "HTTP") != 0) return false; version = line.substr(protocol_end + 1, line.size() - protocol_end - 2); } else return false; getline(stream, line); size_t param_end; while((param_end = line.find(':')) != std::string::npos) { size_t value_start = param_end + 1; if(value_start < line.size()) { if(line[value_start] == ' ') value_start++; if(value_start < line.size()) header.emplace(line.substr(0, param_end), line.substr(value_start, line.size() - value_start - 1)); } getline(stream, line); } } else return false; } else return false; return true; } }; class ResponseMessage { public: /// Parse status line and header fields static bool parse(std::istream &stream, std::string &version, std::string &status_code, CaseInsensitiveMultimap &header) { header.clear(); std::string line; getline(stream, line); size_t version_end = line.find(' '); if(version_end != std::string::npos) { if(5 < line.size()) version = line.substr(5, version_end - 5); else return false; if((version_end + 1) < line.size()) status_code = line.substr(version_end + 1, line.size() - (version_end + 1) - 1); else return false; getline(stream, line); size_t param_end; while((param_end = line.find(':')) != std::string::npos) { size_t value_start = param_end + 1; if((value_start) < line.size()) { if(line[value_start] == ' ') value_start++; if(value_start < line.size()) header.insert(std::make_pair(line.substr(0, param_end), line.substr(value_start, line.size() - value_start - 1))); } getline(stream, line); } } else return false; return true; } }; } #ifdef PTHREAD_RWLOCK_INITIALIZER namespace SimpleWeb { /// Read-preferring R/W lock. /// Uses pthread_rwlock. class SharedMutex { pthread_rwlock_t rwlock; public: class SharedLock { friend class SharedMutex; pthread_rwlock_t &rwlock; SharedLock(pthread_rwlock_t &rwlock) : rwlock(rwlock) { pthread_rwlock_rdlock(&rwlock); } public: ~SharedLock() { pthread_rwlock_unlock(&rwlock); } }; class UniqueLock { friend class SharedMutex; pthread_rwlock_t &rwlock; UniqueLock(pthread_rwlock_t &rwlock) : rwlock(rwlock) { pthread_rwlock_wrlock(&rwlock); } public: ~UniqueLock() { pthread_rwlock_unlock(&rwlock); } }; public: SharedMutex() { pthread_rwlock_init(&rwlock, nullptr); } ~SharedMutex() { pthread_rwlock_destroy(&rwlock); } std::unique_ptr<SharedLock> shared_lock() { return std::unique_ptr<SharedLock>(new SharedLock(rwlock)); } std::unique_ptr<UniqueLock> unique_lock() { return std::unique_ptr<UniqueLock>(new UniqueLock(rwlock)); } }; } // namespace SimpleWeb #else #include <condition_variable> #include <mutex> namespace SimpleWeb { /// Read-preferring R/W lock. /// Based on https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock#Using_a_condition_variable_and_a_mutex pseudocode. /// TODO: Someone that uses Windows should implement Windows specific R/W locks here. class SharedMutex { std::mutex m; std::condition_variable c; int r = 0; bool w = false; public: class SharedLock { friend class SharedMutex; std::condition_variable &c; int &r; std::unique_lock<std::mutex> lock; SharedLock(std::mutex &m, std::condition_variable &c, int &r, bool &w) : c(c), r(r), lock(m) { while(w) c.wait(lock); ++r; lock.unlock(); } public: ~SharedLock() { lock.lock(); --r; if(r == 0) c.notify_all(); lock.unlock(); } }; class UniqueLock { friend class SharedMutex; std::condition_variable &c; bool &w; std::unique_lock<std::mutex> lock; UniqueLock(std::mutex &m, std::condition_variable &c, int &r, bool &w) : c(c), w(w), lock(m) { while(w || r > 0) c.wait(lock); w = true; lock.unlock(); } public: ~UniqueLock() { lock.lock(); w = false; c.notify_all(); lock.unlock(); } }; public: std::unique_ptr<SharedLock> shared_lock() { return std::unique_ptr<SharedLock>(new SharedLock(m, c, r, w)); } std::unique_ptr<UniqueLock> unique_lock() { return std::unique_ptr<UniqueLock>(new UniqueLock(m, c, r, w)); } }; } // namespace SimpleWeb #endif #endif // SIMPLE_WEB_SERVER_UTILITY_HPP <commit_msg>Changed include guards in utility.hpp<commit_after>#ifndef SIMPLE_WEB_UTILITY_HPP #define SIMPLE_WEB_UTILITY_HPP #include "status_code.hpp" #include <iostream> #include <memory> #include <string> #include <unordered_map> namespace SimpleWeb { inline bool case_insensitive_equal(const std::string &str1, const std::string &str2) { return str1.size() == str2.size() && std::equal(str1.begin(), str1.end(), str2.begin(), [](char a, char b) { return tolower(a) == tolower(b); }); } class CaseInsensitiveEqual { public: bool operator()(const std::string &str1, const std::string &str2) const { return case_insensitive_equal(str1, str2); } }; // Based on https://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x/2595226#2595226 class CaseInsensitiveHash { public: size_t operator()(const std::string &str) const { size_t h = 0; std::hash<int> hash; for(auto c : str) h ^= hash(tolower(c)) + 0x9e3779b9 + (h << 6) + (h >> 2); return h; } }; typedef std::unordered_multimap<std::string, std::string, CaseInsensitiveHash, CaseInsensitiveEqual> CaseInsensitiveMultimap; /// Percent encoding and decoding class Percent { public: /// Returns percent-encoded string static std::string encode(const std::string &value) { static auto hex_chars = "0123456789ABCDEF"; std::string result; result.reserve(value.size()); // Minimum size of result for(auto &chr : value) { if(chr == ' ') result += '+'; else if(chr == '!' || chr == '#' || chr == '$' || (chr >= '&' && chr <= ',') || (chr >= '/' && chr <= ';') || chr == '=' || chr == '?' || chr == '@' || chr == '[' || chr == ']') result += std::string("%") + hex_chars[chr >> 4] + hex_chars[chr & 15]; else result += chr; } return result; } /// Returns percent-decoded string static std::string decode(const std::string &value) { std::string result; result.reserve(value.size() / 3 + (value.size() % 3)); // Minimum size of result for(size_t i = 0; i < value.size(); ++i) { auto &chr = value[i]; if(chr == '%' && i + 2 < value.size()) { auto hex = value.substr(i + 1, 2); auto decoded_chr = static_cast<char>(std::strtol(hex.c_str(), nullptr, 16)); result += decoded_chr; i += 2; } else if(chr == '+') result += ' '; else result += chr; } return result; } }; /// Query string creation and parsing class QueryString { public: /// Returns query string created from given field names and values static std::string create(const CaseInsensitiveMultimap &fields) { std::string result; bool first = true; for(auto &field : fields) { result += (!first ? "&" : "") + field.first + '=' + Percent::encode(field.second); first = false; } return result; } /// Returns query keys with percent-decoded values. static CaseInsensitiveMultimap parse(const std::string &query_string) { CaseInsensitiveMultimap result; if(query_string.empty()) return result; size_t name_pos = 0; size_t name_end_pos = -1; size_t value_pos = -1; for(size_t c = 0; c < query_string.size(); ++c) { if(query_string[c] == '&') { auto name = query_string.substr(name_pos, (name_end_pos == std::string::npos ? c : name_end_pos) - name_pos); if(!name.empty()) { auto value = value_pos == std::string::npos ? std::string() : query_string.substr(value_pos, c - value_pos); result.emplace(std::move(name), Percent::decode(value)); } name_pos = c + 1; name_end_pos = -1; value_pos = -1; } else if(query_string[c] == '=') { name_end_pos = c; value_pos = c + 1; } } if(name_pos < query_string.size()) { auto name = query_string.substr(name_pos, name_end_pos - name_pos); if(!name.empty()) { auto value = value_pos >= query_string.size() ? std::string() : query_string.substr(value_pos); result.emplace(std::move(name), Percent::decode(value)); } } return result; } }; class RequestMessage { public: /// Parse request line and header fields static bool parse(std::istream &stream, std::string &method, std::string &path, std::string &query_string, std::string &version, CaseInsensitiveMultimap &header) { header.clear(); std::string line; getline(stream, line); size_t method_end; if((method_end = line.find(' ')) != std::string::npos) { method = line.substr(0, method_end); size_t query_start = std::string::npos; size_t path_and_query_string_end = std::string::npos; for(size_t i = method_end + 1; i < line.size(); ++i) { if(line[i] == '?' && (i + 1) < line.size()) query_start = i + 1; else if(line[i] == ' ') { path_and_query_string_end = i; break; } } if(path_and_query_string_end != std::string::npos) { if(query_start != std::string::npos) { path = line.substr(method_end + 1, query_start - method_end - 2); query_string = line.substr(query_start, path_and_query_string_end - query_start); } else path = line.substr(method_end + 1, path_and_query_string_end - method_end - 1); size_t protocol_end; if((protocol_end = line.find('/', path_and_query_string_end + 1)) != std::string::npos) { if(line.compare(path_and_query_string_end + 1, protocol_end - path_and_query_string_end - 1, "HTTP") != 0) return false; version = line.substr(protocol_end + 1, line.size() - protocol_end - 2); } else return false; getline(stream, line); size_t param_end; while((param_end = line.find(':')) != std::string::npos) { size_t value_start = param_end + 1; if(value_start < line.size()) { if(line[value_start] == ' ') value_start++; if(value_start < line.size()) header.emplace(line.substr(0, param_end), line.substr(value_start, line.size() - value_start - 1)); } getline(stream, line); } } else return false; } else return false; return true; } }; class ResponseMessage { public: /// Parse status line and header fields static bool parse(std::istream &stream, std::string &version, std::string &status_code, CaseInsensitiveMultimap &header) { header.clear(); std::string line; getline(stream, line); size_t version_end = line.find(' '); if(version_end != std::string::npos) { if(5 < line.size()) version = line.substr(5, version_end - 5); else return false; if((version_end + 1) < line.size()) status_code = line.substr(version_end + 1, line.size() - (version_end + 1) - 1); else return false; getline(stream, line); size_t param_end; while((param_end = line.find(':')) != std::string::npos) { size_t value_start = param_end + 1; if((value_start) < line.size()) { if(line[value_start] == ' ') value_start++; if(value_start < line.size()) header.insert(std::make_pair(line.substr(0, param_end), line.substr(value_start, line.size() - value_start - 1))); } getline(stream, line); } } else return false; return true; } }; } // namespace SimpleWeb #ifdef PTHREAD_RWLOCK_INITIALIZER namespace SimpleWeb { /// Read-preferring R/W lock. /// Uses pthread_rwlock. class SharedMutex { pthread_rwlock_t rwlock; public: class SharedLock { friend class SharedMutex; pthread_rwlock_t &rwlock; SharedLock(pthread_rwlock_t &rwlock) : rwlock(rwlock) { pthread_rwlock_rdlock(&rwlock); } public: ~SharedLock() { pthread_rwlock_unlock(&rwlock); } }; class UniqueLock { friend class SharedMutex; pthread_rwlock_t &rwlock; UniqueLock(pthread_rwlock_t &rwlock) : rwlock(rwlock) { pthread_rwlock_wrlock(&rwlock); } public: ~UniqueLock() { pthread_rwlock_unlock(&rwlock); } }; public: SharedMutex() { pthread_rwlock_init(&rwlock, nullptr); } ~SharedMutex() { pthread_rwlock_destroy(&rwlock); } std::unique_ptr<SharedLock> shared_lock() { return std::unique_ptr<SharedLock>(new SharedLock(rwlock)); } std::unique_ptr<UniqueLock> unique_lock() { return std::unique_ptr<UniqueLock>(new UniqueLock(rwlock)); } }; } // namespace SimpleWeb #else #include <condition_variable> #include <mutex> namespace SimpleWeb { /// Read-preferring R/W lock. /// Based on https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock#Using_a_condition_variable_and_a_mutex pseudocode. /// TODO: Someone that uses Windows should implement Windows specific R/W locks here. class SharedMutex { std::mutex m; std::condition_variable c; int r = 0; bool w = false; public: class SharedLock { friend class SharedMutex; std::condition_variable &c; int &r; std::unique_lock<std::mutex> lock; SharedLock(std::mutex &m, std::condition_variable &c, int &r, bool &w) : c(c), r(r), lock(m) { while(w) c.wait(lock); ++r; lock.unlock(); } public: ~SharedLock() { lock.lock(); --r; if(r == 0) c.notify_all(); lock.unlock(); } }; class UniqueLock { friend class SharedMutex; std::condition_variable &c; bool &w; std::unique_lock<std::mutex> lock; UniqueLock(std::mutex &m, std::condition_variable &c, int &r, bool &w) : c(c), w(w), lock(m) { while(w || r > 0) c.wait(lock); w = true; lock.unlock(); } public: ~UniqueLock() { lock.lock(); w = false; c.notify_all(); lock.unlock(); } }; public: std::unique_ptr<SharedLock> shared_lock() { return std::unique_ptr<SharedLock>(new SharedLock(m, c, r, w)); } std::unique_ptr<UniqueLock> unique_lock() { return std::unique_ptr<UniqueLock>(new UniqueLock(m, c, r, w)); } }; } // namespace SimpleWeb #endif #endif // SIMPLE_WEB_UTILITY_HPP <|endoftext|>
<commit_before>#include <glib/gstdio.h> #include <fstream> #include <iostream> #include "settings.h" using namespace AhoViewer; #include "booru/site.h" using namespace AhoViewer::Booru; #include "config.h" #include "imagebox.h" SettingsManager AhoViewer::Settings; SettingsManager::SettingsManager() : ConfigPath(Glib::build_filename(Glib::get_user_config_dir(), PACKAGE)), ConfigFilePath(Glib::build_filename(ConfigPath, PACKAGE ".cfg")), BooruPath(Glib::build_filename(ConfigPath, "booru")), FavoriteTagsPath(Glib::build_filename(ConfigPath, "favorite-tags")), // Defaults {{{ DefaultBools( { { "AutoOpenArchive", true }, { "MangaMode", true }, { "RememberLastFile", true }, { "RememberLastSavePath", true }, { "SaveImageTags", false }, { "SaveThumbnails", true }, { "StartFullscreen", false }, { "StoreRecentFiles", true }, { "SmartNavigation", false }, { "BooruBrowserVisible", true }, { "MenuBarVisible", true }, { "ScrollbarsVisible", true }, { "StatusBarVisible", true }, { "ThumbnailBarVisible", false }, { "HideAll", false }, { "HideAllFullscreen", true }, { "RememberWindowSize", true }, { "RememberWindowPos", true }, }), DefaultInts( { { "ArchiveIndex", -1 }, { "CacheSize", 2 }, { "SlideshowDelay", 5 }, { "CursorHideDelay", 2 }, { "TagViewPosition", 520 }, { "SelectedBooru", 0 }, { "BooruLimit", 50 }, { "BooruWidth", -1 }, { "Volume", 50 }, { "ScrollPosH", -1 }, { "ScrollPosV", -1 } }), DefaultStrings( { { "TitleFormat", "[%i / %c] %f - %p" }, { "AudioSink", "fakesink" }, }), DefaultSites( { std::make_tuple("Danbooru", "https://danbooru.donmai.us", Type::DANBOORU, "", "", 0), std::make_tuple("Gelbooru", "https://gelbooru.com", Type::GELBOORU, "", "", 0), std::make_tuple("Konachan", "https://konachan.com", Type::MOEBOORU, "", "", 6), std::make_tuple("yande.re", "https://yande.re", Type::MOEBOORU, "", "", 0), std::make_tuple("Safebooru", "https://safebooru.org", Type::GELBOORU, "", "", 0), }), DefaultKeybindings( { { "File", { { "OpenFile", "<Primary>o" }, { "Preferences", "p" }, { "Close", "<Primary>w" }, { "Quit", "<Primary>q" }, } }, { "ViewMode", { { "ToggleMangaMode", "g" }, { "AutoFitMode", "a" }, { "FitWidthMode", "w" }, { "FitHeightMode", "h" }, { "ManualZoomMode", "m" }, } }, { "UserInterface", { { "ToggleFullscreen", "f" }, { "ToggleMenuBar", "<Primary>m" }, { "ToggleStatusBar", "<Primary>b" }, { "ToggleScrollbars", "<Primary>l" }, { "ToggleThumbnailBar", "t" }, { "ToggleBooruBrowser", "b" }, { "ToggleHideAll", "i" }, } }, { "Zoom", { { "ZoomIn", "<Primary>equal" }, { "ZoomOut", "<Primary>minus" }, { "ResetZoom", "<Primary>0" }, } }, { "Navigation", { { "NextImage", "Page_Down" }, { "PreviousImage", "Page_Up" }, { "FirstImage", "Home" }, { "LastImage", "End" }, { "ToggleSlideshow", "s" }, } }, { "Scroll", { { "ScrollUp", "Up" }, { "ScrollDown", "Down" }, { "ScrollLeft", "Left" }, { "ScrollRight", "Right" }, } }, { "BooruBrowser", { { "NewTab", "<Primary>t" }, { "SaveImage", "<Primary>s" }, { "SaveImages", "<Primary><Shift>s" }, { "ViewPost", "<Primary><Shift>o" }, { "CopyImageURL", "y" }, { "CopyImageData", "<Primary><Shift>y" }, { "CopyPostURL", "<Primary>y" }, } } }) // }}} { Config.setTabWidth(4); // this is very important if (Glib::file_test(ConfigFilePath, Glib::FILE_TEST_EXISTS)) { try { Config.readFile(ConfigFilePath.c_str()); } catch (const libconfig::ParseException &ex) { std::cerr << "libconfig::Config.readFile: " << ex.what() << std::endl; } } if (!Glib::file_test(BooruPath, Glib::FILE_TEST_EXISTS)) g_mkdir_with_parents(BooruPath.c_str(), 0700); if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS)) { std::ifstream ifs(FavoriteTagsPath); if (ifs) std::copy(std::istream_iterator<std::string>(ifs), std::istream_iterator<std::string>(), std::inserter(m_FavoriteTags, m_FavoriteTags.begin())); } load_keybindings(); } SettingsManager::~SettingsManager() { save_sites(); try { Config.writeFile(ConfigFilePath.c_str()); } catch (const libconfig::FileIOException &ex) { std::cerr << "libconfig::Config.writeFile: " << ex.what() << std::endl; } if (!m_FavoriteTags.empty()) { std::ofstream ofs(FavoriteTagsPath); if (ofs) std::copy(m_FavoriteTags.begin(), m_FavoriteTags.end(), std::ostream_iterator<std::string>(ofs, "\n")); } else if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS)) { g_unlink(FavoriteTagsPath.c_str()); } } bool SettingsManager::get_bool(const std::string &key) const { if (Config.exists(key)) return Config.lookup(key); return DefaultBools.at(key); } int SettingsManager::get_int(const std::string &key) const { if (Config.exists(key)) return Config.lookup(key); return DefaultInts.at(key); } std::string SettingsManager::get_string(const std::string &key) const { if (Config.exists(key)) return static_cast<const char*>(Config.lookup(key)); else if (DefaultStrings.find(key) != DefaultStrings.end()) return DefaultStrings.at(key); return ""; } std::vector<std::shared_ptr<Site>>& SettingsManager::get_sites() { if (m_Sites.size()) { return m_Sites; } else if (Config.exists("Sites")) { const Setting &sites = Config.lookup("Sites"); if (sites.getLength() > 0) { for (size_t i = 0; i < static_cast<size_t>(sites.getLength()); ++i) { const Setting &s = sites[i]; std::string name = s.exists("name") ? s["name"] : "", url = s.exists("url") ? s["url"] : "", username = s.exists("username") ? s["username"] : "", password = s.exists("password") ? s["password"] : ""; int max_cons = 0; s.lookupValue("max_connections", max_cons); // cachesize * 2 + 1 < 6 < max_cons if (max_cons != 0) max_cons = std::max(max_cons, std::min(get_int("CacheSize") * 2 + 1, 6)); bool use_samples = false; s.lookupValue("use_samples", use_samples); m_Sites.push_back( Site::create(name, url, static_cast<Type>(static_cast<int>(s["type"])), username, password, max_cons, use_samples)); } return m_Sites; } } for (const SiteTuple &s : DefaultSites) m_Sites.push_back(Site::create(std::get<0>(s), std::get<1>(s), std::get<2>(s), std::get<3>(s), std::get<4>(s), std::get<5>(s))); return m_Sites; } bool SettingsManager::get_geometry(int &x, int &y, int &w, int &h) const { if (Config.lookupValue("Geometry.x", x) && Config.lookupValue("Geometry.y", y) && Config.lookupValue("Geometry.w", w) && Config.lookupValue("Geometry.h", h)) { return true; } return false; } void SettingsManager::set_geometry(const int x, const int y, const int w, const int h) { if (!Config.exists("Geometry")) Config.getRoot().add("Geometry", Setting::TypeGroup); Setting &geo = Config.lookup("Geometry"); set("x", x, Setting::TypeInt, geo); set("y", y, Setting::TypeInt, geo); set("w", w, Setting::TypeInt, geo); set("h", h, Setting::TypeInt, geo); } std::string SettingsManager::get_keybinding(const std::string &group, const std::string &name) const { return m_Keybindings.at(group).at(name); } // Clears the first (only) binding that has the same value as value // Sets the group and name parameters to those of the binding that was cleared // Returns true if it actually cleared a binding // TODO: Add support for multiple keybindings per action bool SettingsManager::clear_keybinding(const std::string &value, std::string &group, std::string &name) { for (const auto &i : m_Keybindings) { for (const auto &j : i.second) { if (j.second == value) { group = i.first; name = j.first; set_keybinding(group, name, ""); return true; } } } return false; } void SettingsManager::set_keybinding(const std::string &group, const std::string &name, const std::string &value) { if (!Config.exists("Keybindings")) Config.getRoot().add("Keybindings", Setting::TypeGroup); Setting &keys = Config.lookup("Keybindings"); if (!keys.exists(group)) keys.add(group, Setting::TypeGroup); set(name, value, Setting::TypeString, keys[group.c_str()]); m_Keybindings[group][name] = value; } std::string SettingsManager::reset_keybinding(const std::string &group, const std::string &name) { if (Config.exists("Keybindings")) { Setting &keys = Config.lookup("Keybindings"); if (keys.exists(group) && keys[group.c_str()].exists(name)) keys[group.c_str()].remove(name); } return m_Keybindings[group][name] = DefaultKeybindings.at(group).at(name); } Gdk::RGBA SettingsManager::get_background_color() const { if (Config.exists("BackgroundColor")) return Gdk::RGBA(static_cast<const char*>(Config.lookup("BackgroundColor"))); return ImageBox::DefaultBGColor; } void SettingsManager::set_background_color(const Gdk::RGBA &value) { set("BackgroundColor", value.to_string()); } Rating SettingsManager::get_booru_max_rating() const { if (Config.exists("BooruMaxRating")) return Rating(static_cast<int>(Config.lookup("BooruMaxRating"))); return DefaultBooruMaxRating; } void SettingsManager::set_booru_max_rating(const Rating value) { set("BooruMaxRating", static_cast<int>(value)); } ZoomMode SettingsManager::get_zoom_mode() const { if (Config.exists("ZoomMode")) return ZoomMode(static_cast<const char*>(Config.lookup("ZoomMode"))[0]); return DefaultZoomMode; } void SettingsManager::set_zoom_mode(const ZoomMode value) { set("ZoomMode", std::string(1, static_cast<char>(value))); } void SettingsManager::remove(const std::string &key) { if (Config.exists(key)) Config.getRoot().remove(key); } void SettingsManager::load_keybindings() { if (Config.exists("Keybindings")) { Setting &keys = Config.lookup("Keybindings"); for (const std::pair<std::string, std::map<std::string, std::string>> i : DefaultKeybindings) { if (keys.exists(i.first)) { for (const std::pair<std::string, std::string> j : i.second) { if (keys[i.first.c_str()].exists(j.first)) { m_Keybindings[i.first][j.first] = keys[i.first.c_str()][j.first.c_str()].c_str(); } else { m_Keybindings[i.first][j.first] = DefaultKeybindings.at(i.first).at(j.first); } } } else { m_Keybindings[i.first] = DefaultKeybindings.at(i.first); } } } else { m_Keybindings = DefaultKeybindings; } } void SettingsManager::save_sites() { remove("Sites"); Setting &sites = Config.getRoot().add("Sites", Setting::TypeList); for (const std::shared_ptr<Site> &s : m_Sites) { Setting &site = sites.add(Setting::TypeGroup); set("name", s->get_name(), Setting::TypeString, site); set("url", s->get_url(), Setting::TypeString, site); set("type", static_cast<int>(s->get_type()), Setting::TypeInt, site); set("username", s->get_username(), Setting::TypeString, site); #if !defined(HAVE_LIBSECRET) && !defined(_WIN32) set("password", s->get_password(), Setting::TypeString, site); #endif // !defined(HAVE_LIBSECRET) && !defined(_WIN32) set("max_connections", static_cast<int>(s->get_max_connections()), Setting::TypeInt, site); set("use_samples", s->use_samples(), Setting::TypeBoolean, site); } } <commit_msg>settings: Use auto in for loops when loading keybinds<commit_after>#include <glib/gstdio.h> #include <fstream> #include <iostream> #include "settings.h" using namespace AhoViewer; #include "booru/site.h" using namespace AhoViewer::Booru; #include "config.h" #include "imagebox.h" SettingsManager AhoViewer::Settings; SettingsManager::SettingsManager() : ConfigPath(Glib::build_filename(Glib::get_user_config_dir(), PACKAGE)), ConfigFilePath(Glib::build_filename(ConfigPath, PACKAGE ".cfg")), BooruPath(Glib::build_filename(ConfigPath, "booru")), FavoriteTagsPath(Glib::build_filename(ConfigPath, "favorite-tags")), // Defaults {{{ DefaultBools( { { "AutoOpenArchive", true }, { "MangaMode", true }, { "RememberLastFile", true }, { "RememberLastSavePath", true }, { "SaveImageTags", false }, { "SaveThumbnails", true }, { "StartFullscreen", false }, { "StoreRecentFiles", true }, { "SmartNavigation", false }, { "BooruBrowserVisible", true }, { "MenuBarVisible", true }, { "ScrollbarsVisible", true }, { "StatusBarVisible", true }, { "ThumbnailBarVisible", false }, { "HideAll", false }, { "HideAllFullscreen", true }, { "RememberWindowSize", true }, { "RememberWindowPos", true }, }), DefaultInts( { { "ArchiveIndex", -1 }, { "CacheSize", 2 }, { "SlideshowDelay", 5 }, { "CursorHideDelay", 2 }, { "TagViewPosition", 520 }, { "SelectedBooru", 0 }, { "BooruLimit", 50 }, { "BooruWidth", -1 }, { "Volume", 50 }, { "ScrollPosH", -1 }, { "ScrollPosV", -1 } }), DefaultStrings( { { "TitleFormat", "[%i / %c] %f - %p" }, { "AudioSink", "fakesink" }, }), DefaultSites( { std::make_tuple("Danbooru", "https://danbooru.donmai.us", Type::DANBOORU, "", "", 0), std::make_tuple("Gelbooru", "https://gelbooru.com", Type::GELBOORU, "", "", 0), std::make_tuple("Konachan", "https://konachan.com", Type::MOEBOORU, "", "", 6), std::make_tuple("yande.re", "https://yande.re", Type::MOEBOORU, "", "", 0), std::make_tuple("Safebooru", "https://safebooru.org", Type::GELBOORU, "", "", 0), }), DefaultKeybindings( { { "File", { { "OpenFile", "<Primary>o" }, { "Preferences", "p" }, { "Close", "<Primary>w" }, { "Quit", "<Primary>q" }, } }, { "ViewMode", { { "ToggleMangaMode", "g" }, { "AutoFitMode", "a" }, { "FitWidthMode", "w" }, { "FitHeightMode", "h" }, { "ManualZoomMode", "m" }, } }, { "UserInterface", { { "ToggleFullscreen", "f" }, { "ToggleMenuBar", "<Primary>m" }, { "ToggleStatusBar", "<Primary>b" }, { "ToggleScrollbars", "<Primary>l" }, { "ToggleThumbnailBar", "t" }, { "ToggleBooruBrowser", "b" }, { "ToggleHideAll", "i" }, } }, { "Zoom", { { "ZoomIn", "<Primary>equal" }, { "ZoomOut", "<Primary>minus" }, { "ResetZoom", "<Primary>0" }, } }, { "Navigation", { { "NextImage", "Page_Down" }, { "PreviousImage", "Page_Up" }, { "FirstImage", "Home" }, { "LastImage", "End" }, { "ToggleSlideshow", "s" }, } }, { "Scroll", { { "ScrollUp", "Up" }, { "ScrollDown", "Down" }, { "ScrollLeft", "Left" }, { "ScrollRight", "Right" }, } }, { "BooruBrowser", { { "NewTab", "<Primary>t" }, { "SaveImage", "<Primary>s" }, { "SaveImages", "<Primary><Shift>s" }, { "ViewPost", "<Primary><Shift>o" }, { "CopyImageURL", "y" }, { "CopyImageData", "<Primary><Shift>y" }, { "CopyPostURL", "<Primary>y" }, } } }) // }}} { Config.setTabWidth(4); if (Glib::file_test(ConfigFilePath, Glib::FILE_TEST_EXISTS)) { try { Config.readFile(ConfigFilePath.c_str()); } catch (const libconfig::ParseException &ex) { std::cerr << "libconfig::Config.readFile: " << ex.what() << std::endl; } } if (!Glib::file_test(BooruPath, Glib::FILE_TEST_EXISTS)) g_mkdir_with_parents(BooruPath.c_str(), 0700); if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS)) { std::ifstream ifs(FavoriteTagsPath); if (ifs) std::copy(std::istream_iterator<std::string>(ifs), std::istream_iterator<std::string>(), std::inserter(m_FavoriteTags, m_FavoriteTags.begin())); } load_keybindings(); } SettingsManager::~SettingsManager() { save_sites(); try { Config.writeFile(ConfigFilePath.c_str()); } catch (const libconfig::FileIOException &ex) { std::cerr << "libconfig::Config.writeFile: " << ex.what() << std::endl; } if (!m_FavoriteTags.empty()) { std::ofstream ofs(FavoriteTagsPath); if (ofs) std::copy(m_FavoriteTags.begin(), m_FavoriteTags.end(), std::ostream_iterator<std::string>(ofs, "\n")); } else if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS)) { g_unlink(FavoriteTagsPath.c_str()); } } bool SettingsManager::get_bool(const std::string &key) const { if (Config.exists(key)) return Config.lookup(key); return DefaultBools.at(key); } int SettingsManager::get_int(const std::string &key) const { if (Config.exists(key)) return Config.lookup(key); return DefaultInts.at(key); } std::string SettingsManager::get_string(const std::string &key) const { if (Config.exists(key)) return static_cast<const char*>(Config.lookup(key)); else if (DefaultStrings.find(key) != DefaultStrings.end()) return DefaultStrings.at(key); return ""; } std::vector<std::shared_ptr<Site>>& SettingsManager::get_sites() { if (m_Sites.size()) { return m_Sites; } else if (Config.exists("Sites")) { const Setting &sites = Config.lookup("Sites"); if (sites.getLength() > 0) { for (size_t i = 0; i < static_cast<size_t>(sites.getLength()); ++i) { const Setting &s = sites[i]; std::string name = s.exists("name") ? s["name"] : "", url = s.exists("url") ? s["url"] : "", username = s.exists("username") ? s["username"] : "", password = s.exists("password") ? s["password"] : ""; int max_cons = 0; s.lookupValue("max_connections", max_cons); // cachesize * 2 + 1 < 6 < max_cons if (max_cons != 0) max_cons = std::max(max_cons, std::min(get_int("CacheSize") * 2 + 1, 6)); bool use_samples = false; s.lookupValue("use_samples", use_samples); m_Sites.push_back( Site::create(name, url, static_cast<Type>(static_cast<int>(s["type"])), username, password, max_cons, use_samples)); } return m_Sites; } } for (const SiteTuple &s : DefaultSites) m_Sites.push_back(Site::create(std::get<0>(s), std::get<1>(s), std::get<2>(s), std::get<3>(s), std::get<4>(s), std::get<5>(s))); return m_Sites; } bool SettingsManager::get_geometry(int &x, int &y, int &w, int &h) const { if (Config.lookupValue("Geometry.x", x) && Config.lookupValue("Geometry.y", y) && Config.lookupValue("Geometry.w", w) && Config.lookupValue("Geometry.h", h)) { return true; } return false; } void SettingsManager::set_geometry(const int x, const int y, const int w, const int h) { if (!Config.exists("Geometry")) Config.getRoot().add("Geometry", Setting::TypeGroup); Setting &geo = Config.lookup("Geometry"); set("x", x, Setting::TypeInt, geo); set("y", y, Setting::TypeInt, geo); set("w", w, Setting::TypeInt, geo); set("h", h, Setting::TypeInt, geo); } std::string SettingsManager::get_keybinding(const std::string &group, const std::string &name) const { return m_Keybindings.at(group).at(name); } // Clears the first (only) binding that has the same value as value // Sets the group and name parameters to those of the binding that was cleared // Returns true if it actually cleared a binding // TODO: Add support for multiple keybindings per action bool SettingsManager::clear_keybinding(const std::string &value, std::string &group, std::string &name) { for (const auto &i : m_Keybindings) { for (const auto &j : i.second) { if (j.second == value) { group = i.first; name = j.first; set_keybinding(group, name, ""); return true; } } } return false; } void SettingsManager::set_keybinding(const std::string &group, const std::string &name, const std::string &value) { if (!Config.exists("Keybindings")) Config.getRoot().add("Keybindings", Setting::TypeGroup); Setting &keys = Config.lookup("Keybindings"); if (!keys.exists(group)) keys.add(group, Setting::TypeGroup); set(name, value, Setting::TypeString, keys[group.c_str()]); m_Keybindings[group][name] = value; } std::string SettingsManager::reset_keybinding(const std::string &group, const std::string &name) { if (Config.exists("Keybindings")) { Setting &keys = Config.lookup("Keybindings"); if (keys.exists(group) && keys[group.c_str()].exists(name)) keys[group.c_str()].remove(name); } return m_Keybindings[group][name] = DefaultKeybindings.at(group).at(name); } Gdk::RGBA SettingsManager::get_background_color() const { if (Config.exists("BackgroundColor")) return Gdk::RGBA(static_cast<const char*>(Config.lookup("BackgroundColor"))); return ImageBox::DefaultBGColor; } void SettingsManager::set_background_color(const Gdk::RGBA &value) { set("BackgroundColor", value.to_string()); } Rating SettingsManager::get_booru_max_rating() const { if (Config.exists("BooruMaxRating")) return Rating(static_cast<int>(Config.lookup("BooruMaxRating"))); return DefaultBooruMaxRating; } void SettingsManager::set_booru_max_rating(const Rating value) { set("BooruMaxRating", static_cast<int>(value)); } ZoomMode SettingsManager::get_zoom_mode() const { if (Config.exists("ZoomMode")) return ZoomMode(static_cast<const char*>(Config.lookup("ZoomMode"))[0]); return DefaultZoomMode; } void SettingsManager::set_zoom_mode(const ZoomMode value) { set("ZoomMode", std::string(1, static_cast<char>(value))); } void SettingsManager::remove(const std::string &key) { if (Config.exists(key)) Config.getRoot().remove(key); } void SettingsManager::load_keybindings() { if (Config.exists("Keybindings")) { Setting &keys = Config.lookup("Keybindings"); for (auto &i : DefaultKeybindings) { if (keys.exists(i.first)) { for (auto &j : i.second) { if (keys[i.first.c_str()].exists(j.first)) { m_Keybindings[i.first][j.first] = keys[i.first.c_str()][j.first.c_str()].c_str(); } else { m_Keybindings[i.first][j.first] = DefaultKeybindings.at(i.first).at(j.first); } } } else { m_Keybindings[i.first] = DefaultKeybindings.at(i.first); } } } else { m_Keybindings = DefaultKeybindings; } } void SettingsManager::save_sites() { remove("Sites"); Setting &sites = Config.getRoot().add("Sites", Setting::TypeList); for (const std::shared_ptr<Site> &s : m_Sites) { Setting &site = sites.add(Setting::TypeGroup); set("name", s->get_name(), Setting::TypeString, site); set("url", s->get_url(), Setting::TypeString, site); set("type", static_cast<int>(s->get_type()), Setting::TypeInt, site); set("username", s->get_username(), Setting::TypeString, site); #if !defined(HAVE_LIBSECRET) && !defined(_WIN32) set("password", s->get_password(), Setting::TypeString, site); #endif // !defined(HAVE_LIBSECRET) && !defined(_WIN32) set("max_connections", static_cast<int>(s->get_max_connections()), Setting::TypeInt, site); set("use_samples", s->use_samples(), Setting::TypeBoolean, site); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2011 Advanced Micro Devices * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Steve Reinhardt * Gabe Black */ #include "base/misc.hh" #include "sim/core.hh" #include "sim/root.hh" Root *Root::_root = NULL; /* * This function is called periodically by an event in M5 and ensures that * at least as much real time has passed between invocations as simulated time. * If not, the function either sleeps, or if the difference is small enough * spin waits. */ void Root::timeSync() { Time cur_time, diff, period = timeSyncPeriod(); do { cur_time.setTimer(); diff = cur_time - lastTime; Time remainder = period - diff; if (diff < period && remainder > _spinThreshold) { DPRINTF(TimeSync, "Sleeping to sync with real time.\n"); // Sleep until the end of the period, or until a signal. sleep(remainder); // Refresh the current time. cur_time.setTimer(); } } while (diff < period); lastTime = cur_time; schedule(&syncEvent, curTick() + _periodTick); } void Root::timeSyncEnable(bool en) { if (en == _enabled) return; _enabled = en; if (_enabled) { // Get event going. Tick periods = ((curTick() + _periodTick - 1) / _periodTick); Tick nextPeriod = periods * _periodTick; schedule(&syncEvent, nextPeriod); } else { // Stop event. deschedule(&syncEvent); } } /// Configure the period for time sync events. void Root::timeSyncPeriod(Time newPeriod) { bool en = timeSyncEnabled(); _period = newPeriod; _periodTick = _period.nsec() * SimClock::Int::ns + _period.sec() * SimClock::Int::s; timeSyncEnable(en); } /// Set the threshold for time remaining to spin wait. void Root::timeSyncSpinThreshold(Time newThreshold) { bool en = timeSyncEnabled(); _spinThreshold = newThreshold; timeSyncEnable(en); } Root::Root(RootParams *p) : SimObject(p), _enabled(false), _periodTick(p->time_sync_period), syncEvent(this) { uint64_t nsecs = p->time_sync_period / SimClock::Int::ns; _period.set(nsecs / Time::NSEC_PER_SEC, nsecs % Time::NSEC_PER_SEC); nsecs = p->time_sync_spin_threshold / SimClock::Int::ns; _spinThreshold.set(nsecs / Time::NSEC_PER_SEC, nsecs % Time::NSEC_PER_SEC); assert(_root == NULL); _root = this; lastTime.setTimer(); timeSyncEnable(p->time_sync_enable); } Root * RootParams::create() { static bool created = false; if (created) panic("only one root object allowed!"); created = true; return new Root(this); } <commit_msg>TimeSync: Use the new setTick and getTick functions.<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2011 Advanced Micro Devices * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Steve Reinhardt * Gabe Black */ #include "base/misc.hh" #include "sim/root.hh" Root *Root::_root = NULL; /* * This function is called periodically by an event in M5 and ensures that * at least as much real time has passed between invocations as simulated time. * If not, the function either sleeps, or if the difference is small enough * spin waits. */ void Root::timeSync() { Time cur_time, diff, period = timeSyncPeriod(); do { cur_time.setTimer(); diff = cur_time - lastTime; Time remainder = period - diff; if (diff < period && remainder > _spinThreshold) { DPRINTF(TimeSync, "Sleeping to sync with real time.\n"); // Sleep until the end of the period, or until a signal. sleep(remainder); // Refresh the current time. cur_time.setTimer(); } } while (diff < period); lastTime = cur_time; schedule(&syncEvent, curTick() + _periodTick); } void Root::timeSyncEnable(bool en) { if (en == _enabled) return; _enabled = en; if (_enabled) { // Get event going. Tick periods = ((curTick() + _periodTick - 1) / _periodTick); Tick nextPeriod = periods * _periodTick; schedule(&syncEvent, nextPeriod); } else { // Stop event. deschedule(&syncEvent); } } /// Configure the period for time sync events. void Root::timeSyncPeriod(Time newPeriod) { bool en = timeSyncEnabled(); _period = newPeriod; _periodTick = _period.getTick(); timeSyncEnable(en); } /// Set the threshold for time remaining to spin wait. void Root::timeSyncSpinThreshold(Time newThreshold) { bool en = timeSyncEnabled(); _spinThreshold = newThreshold; timeSyncEnable(en); } Root::Root(RootParams *p) : SimObject(p), _enabled(false), _periodTick(p->time_sync_period), syncEvent(this) { _period.setTick(p->time_sync_period); _spinThreshold.setTick(p->time_sync_spin_threshold); assert(_root == NULL); _root = this; lastTime.setTimer(); timeSyncEnable(p->time_sync_enable); } Root * RootParams::create() { static bool created = false; if (created) panic("only one root object allowed!"); created = true; return new Root(this); } <|endoftext|>
<commit_before><commit_msg>Added more input methods to `enum`. These are not yet implemented.<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project 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 HOLDER 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. */ #ifdef WIN32 #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include <conio.h> #include <winsock2.h> typedef int socklen_t; #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #endif #include <iostream> #include <fstream> #include <deque> #include <vector> #include <ctime> #include <event.h> #include <sys/stat.h> #include <zlib.h> #include "logger.h" #include "constants.h" #include "tools.h" #include "user.h" #include "map.h" #include "chat.h" #include "nbt.h" #include "packets.h" extern int setnonblock(int fd); void client_callback(int fd, short ev, void *arg) { User *user = (User *)arg; if(ev & EV_READ) { int read = 1; uint8 *buf = new uint8[2048]; read = recv(fd, (char*)buf, 2048, 0); if(read == 0) { std::cout << "Socket closed properly" << std::endl; //event_del(user->GetEvent()); #ifdef WIN32 closesocket(user->fd); #else close(user->fd); #endif remUser(user->fd); return; } if(read == -1) { std::cout << "Socket had no data to read" << std::endl; return; } user->buffer.addToRead(buf, read); delete[] buf; user->buffer.reset(); while(user->buffer >> (sint8&)user->action) { //Variable len package if(PacketHandler::get().packets[user->action].len == PACKET_VARIABLE_LEN) { //Call specific function int (PacketHandler::*function)(User *) = PacketHandler::get().packets[user->action].function; bool disconnecting = user->action == 0xFF; int curpos = (PacketHandler::get().*function)(user); if(curpos == PACKET_NEED_MORE_DATA) { user->waitForData = true; event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } if(disconnecting) // disconnect -- player gone { return; } } else if(PacketHandler::get().packets[user->action].len == PACKET_DOES_NOT_EXIST) { printf("Unknown action: 0x%x\n", user->action); //event_del(user->GetEvent()); #ifdef WIN32 closesocket(user->fd); #else close(user->fd); #endif remUser(user->fd); } else { if(!user->buffer.haveData(PacketHandler::get().packets[user->action].len)) { user->waitForData = true; event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } //Call specific function int (PacketHandler::*function)(User *) = PacketHandler::get().packets[user->action].function; (PacketHandler::get().*function)(user); } } //End while } int writeLen = user->buffer.getWriteLen(); if(writeLen) { int written = send(fd, (char*)user->buffer.getWrite(), writeLen, 0); if(written == -1) { std::cout << "Error writing to client" << std::endl; //event_del(user->GetEvent()); #ifdef WIN32 closesocket(user->fd); #else close(user->fd); #endif remUser(user->fd); return; } user->buffer.clearWrite(written); if(user->buffer.getWriteLen()) { event_set(user->GetEvent(), fd, EV_WRITE|EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } } event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); } void accept_callback(int fd, short ev, void *arg) { int client_fd; struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len); if(client_fd < 0) { LOG("Client: accept() failed"); return; } User *client = addUser(client_fd, generateEID()); setnonblock(client_fd); event_set(client->GetEvent(), client_fd,EV_WRITE|EV_READ, client_callback, client); event_add(client->GetEvent(), NULL); } <commit_msg>fix for "Error writing to client" -issue<commit_after>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project 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 HOLDER 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. */ #ifdef WIN32 #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include <conio.h> #include <winsock2.h> typedef int socklen_t; #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #endif #include <errno.h> #include <iostream> #include <fstream> #include <deque> #include <vector> #include <ctime> #include <event.h> #include <sys/stat.h> #include <zlib.h> #include "logger.h" #include "constants.h" #include "tools.h" #include "user.h" #include "map.h" #include "chat.h" #include "nbt.h" #include "packets.h" extern int setnonblock(int fd); void client_callback(int fd, short ev, void *arg) { User *user = (User *)arg; if(ev & EV_READ) { int read = 1; uint8 *buf = new uint8[2048]; read = recv(fd, (char*)buf, 2048, 0); if(read == 0) { std::cout << "Socket closed properly" << std::endl; //event_del(user->GetEvent()); #ifdef WIN32 closesocket(user->fd); #else close(user->fd); #endif remUser(user->fd); return; } if(read == -1) { std::cout << "Socket had no data to read" << std::endl; return; } user->buffer.addToRead(buf, read); delete[] buf; user->buffer.reset(); while(user->buffer >> (sint8&)user->action) { //Variable len package if(PacketHandler::get().packets[user->action].len == PACKET_VARIABLE_LEN) { //Call specific function int (PacketHandler::*function)(User *) = PacketHandler::get().packets[user->action].function; bool disconnecting = user->action == 0xFF; int curpos = (PacketHandler::get().*function)(user); if(curpos == PACKET_NEED_MORE_DATA) { user->waitForData = true; event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } if(disconnecting) // disconnect -- player gone { return; } } else if(PacketHandler::get().packets[user->action].len == PACKET_DOES_NOT_EXIST) { printf("Unknown action: 0x%x\n", user->action); //event_del(user->GetEvent()); #ifdef WIN32 closesocket(user->fd); #else close(user->fd); #endif remUser(user->fd); } else { if(!user->buffer.haveData(PacketHandler::get().packets[user->action].len)) { user->waitForData = true; event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } //Call specific function int (PacketHandler::*function)(User *) = PacketHandler::get().packets[user->action].function; (PacketHandler::get().*function)(user); } } //End while } int writeLen = user->buffer.getWriteLen(); if(writeLen) { int written = send(fd, (char*)user->buffer.getWrite(), writeLen, 0); if(written == -1) { if(errno != EAGAIN && errno != EINTR) { std::cout << "Error writing to client" << std::endl; //event_del(user->GetEvent()); #ifdef WIN32 closesocket(user->fd); #else close(user->fd); #endif remUser(user->fd); return; } } else { user->buffer.clearWrite(written); } if(user->buffer.getWriteLen()) { event_set(user->GetEvent(), fd, EV_WRITE|EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } } event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); } void accept_callback(int fd, short ev, void *arg) { int client_fd; struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len); if(client_fd < 0) { LOG("Client: accept() failed"); return; } User *client = addUser(client_fd, generateEID()); setnonblock(client_fd); event_set(client->GetEvent(), client_fd,EV_WRITE|EV_READ, client_callback, client); event_add(client->GetEvent(), NULL); } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdint> #include <cassert> #include <cstring> #include <string> #include <vector> #include <chrono> #include <smmintrin.h> #if defined(HAVE_AVX2_INSTRUCTIONS) || defined(HAVE_AVX512F_INSTRUCTIONS) # include <immintrin.h> #endif #include <utils/sse.cpp> #include <utils/bits.cpp> #include "sse4-strstr.cpp" #ifdef HAVE_AVX2_INSTRUCTIONS # include <utils/avx2.cpp> # include "avx2-strstr.cpp" #endif #ifdef HAVE_AVX512F_INSTRUCTIONS # include "avx512f-strstr.cpp" #endif // ------------------------------------------------------------------------ #include <utils/ansi.cpp> #include "application_base.cpp" class Application final: public ApplicationBase { std::size_t count; public: Application() : count(10) { } bool operator()() { const bool measure_libc = true; const bool measure_stdstring = true; const bool measure_sse4 = true; #ifdef HAVE_AVX2_INSTRUCTIONS const bool measure_avx2 = true; #endif #ifdef HAVE_AVX512F_INSTRUCTIONS const bool measure_avx512f = true; #endif if (measure_libc) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { const char* res = strstr(s.data(), neddle.data()); if (res != nullptr) { return res - s.data(); } else { return std::string::npos; } }; printf("%-20s... ", "std::strstr"); fflush(stdout); measure(find, count); } if (measure_stdstring) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { return s.find(neddle); }; printf("%-20s... ", "std::string::find"); fflush(stdout); measure(find, count); } if (measure_sse4) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { return sse4_strstr(s, neddle); }; printf("%-20s... ", "SSE4"); fflush(stdout); measure(find, count); } #ifdef HAVE_AVX2_INSTRUCTIONS if (measure_avx2) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { return avx2_strstr(s, neddle); }; printf("%-20s... ", "AVX2"); fflush(stdout); measure(find, count); } #endif #ifdef HAVE_AVX512F_INSTRUCTIONS if (measure_avx512f) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { return avx512f_strstr(s, neddle); }; printf("%-20s... ", "AVX512F"); fflush(stdout); measure(find, count); } #endif return true; } void print_help(const char* progname) { std::printf("%s file words\n", progname); std::puts(""); std::puts( "Measure speed of following procedures: " "std::strstr" ", std::string::find" ", SSE4" #ifdef HAVE_AVX2_INSTRUCTIONS ", AVX2" #endif #ifdef HAVE_AVX512F_INSTRUCTIONS ", AVX512F" #endif ); std::puts(""); std::puts("Parameters:"); std::puts(""); std::puts(" file - arbitrary file"); std::puts(" words - list of words in separate lines"); } private: template <typename T_FIND> void measure(T_FIND find, size_t count) { size_t result = 0; const auto t1 = std::chrono::high_resolution_clock::now(); while (count != 0) { for (const auto& word: words) { result += find(file, word); } count--; } const auto t2 = std::chrono::high_resolution_clock::now(); const std::chrono::duration<double> td = t2-t1; printf("reference result = %lu, time = %10.6f s\n", result, td.count()); } }; int main(int argc, char* argv[]) { Application app; if (argc == 3) { try { app.prepare(argv[1], argv[2]); return app() ? EXIT_SUCCESS : EXIT_FAILURE; } catch (ApplicationBase::Error& err) { const auto msg = ansi::seq("Error: ", ansi::RED); printf("%s: %s\n", msg.data(), err.message.data()); return EXIT_FAILURE; } } else { app.print_help(argv[0]); return EXIT_FAILURE; } } <commit_msg>plug new AVX512 procedure into speed util<commit_after>#include <cstdio> #include <cstdint> #include <cassert> #include <cstring> #include <string> #include <vector> #include <chrono> #include <smmintrin.h> #if defined(HAVE_AVX2_INSTRUCTIONS) || defined(HAVE_AVX512F_INSTRUCTIONS) # include <immintrin.h> #endif #include <utils/sse.cpp> #include <utils/bits.cpp> #include "sse4-strstr.cpp" #ifdef HAVE_AVX2_INSTRUCTIONS # include <utils/avx2.cpp> # include "avx2-strstr.cpp" #endif #ifdef HAVE_AVX512F_INSTRUCTIONS # include "avx512f-strstr.cpp" # include "avx512f-strstr-v2.cpp" #endif // ------------------------------------------------------------------------ #include <utils/ansi.cpp> #include "application_base.cpp" class Application final: public ApplicationBase { std::size_t count; public: Application() : count(10) { } bool operator()() { const bool measure_libc = true; const bool measure_stdstring = true; const bool measure_sse4 = true; #ifdef HAVE_AVX2_INSTRUCTIONS const bool measure_avx2 = true; #endif #ifdef HAVE_AVX512F_INSTRUCTIONS const bool measure_avx512f = true; const bool measure_avx512f_v2 = true; #endif if (measure_libc) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { const char* res = strstr(s.data(), neddle.data()); if (res != nullptr) { return res - s.data(); } else { return std::string::npos; } }; printf("%-20s... ", "std::strstr"); fflush(stdout); measure(find, count); } if (measure_stdstring) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { return s.find(neddle); }; printf("%-20s... ", "std::string::find"); fflush(stdout); measure(find, count); } if (measure_sse4) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { return sse4_strstr(s, neddle); }; printf("%-20s... ", "SSE4"); fflush(stdout); measure(find, count); } #ifdef HAVE_AVX2_INSTRUCTIONS if (measure_avx2) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { return avx2_strstr(s, neddle); }; printf("%-20s... ", "AVX2"); fflush(stdout); measure(find, count); } #endif #ifdef HAVE_AVX512F_INSTRUCTIONS if (measure_avx512f) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { return avx512f_strstr(s, neddle); }; printf("%-20s... ", "AVX512F"); fflush(stdout); measure(find, count); } if (measure_avx512f_v2) { auto find = [](const std::string& s, const std::string& neddle) -> size_t { return avx512f_strstr_v2(s, neddle); }; printf("%-20s... ", "AVX512F (v2)"); fflush(stdout); measure(find, count); } #endif return true; } void print_help(const char* progname) { std::printf("%s file words\n", progname); std::puts(""); std::puts( "Measure speed of following procedures: " "std::strstr" ", std::string::find" ", SSE4" #ifdef HAVE_AVX2_INSTRUCTIONS ", AVX2" #endif #ifdef HAVE_AVX512F_INSTRUCTIONS ", AVX512F" #endif ); std::puts(""); std::puts("Parameters:"); std::puts(""); std::puts(" file - arbitrary file"); std::puts(" words - list of words in separate lines"); } private: template <typename T_FIND> void measure(T_FIND find, size_t count) { size_t result = 0; const auto t1 = std::chrono::high_resolution_clock::now(); while (count != 0) { for (const auto& word: words) { result += find(file, word); } count--; } const auto t2 = std::chrono::high_resolution_clock::now(); const std::chrono::duration<double> td = t2-t1; printf("reference result = %lu, time = %10.6f s\n", result, td.count()); } }; int main(int argc, char* argv[]) { Application app; if (argc == 3) { try { app.prepare(argv[1], argv[2]); return app() ? EXIT_SUCCESS : EXIT_FAILURE; } catch (ApplicationBase::Error& err) { const auto msg = ansi::seq("Error: ", ansi::RED); printf("%s: %s\n", msg.data(), err.message.data()); return EXIT_FAILURE; } } else { app.print_help(argv[0]); return EXIT_FAILURE; } } <|endoftext|>
<commit_before>// An implementation of Fujimoto's airport model // Ported from the ROSS airport model (https://github.com/carothersc/ROSS/blob/master/ross/models/airport) // Author: Eric Carver (carverer@mail.uc.edu) #include <vector> #include <memory> #include <random> #include "warped.hpp" #include "airport.hpp" #include "MLCG.h" #include "NegExp.h" #include "tclap/ValueArg.h" WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(AirportEvent) std::vector<std::shared_ptr<warped::Event> > Airport::createInitialEvents() { std::vector<std::shared_ptr<warped::Event> > events; NegativeExpntl depart_expo((double)this->depart_mean_, this->rng_.get()); for (unsigned int i = 0; i < this->num_planes_; i++) { events.emplace_back(new AirportEvent {this->name_, DEPARTURE, (unsigned int)depart_expo()}); } return events; } inline std::string Airport::object_name(const unsigned int object_index) { return std::string("Object ") + std::to_string(object_index); } std::vector<std::shared_ptr<warped::Event> > Airport::receiveEvent(const warped::Event& event) { std::vector<std::shared_ptr<warped::Event> > response_events; auto received_event = static_cast<const AirportEvent&>(event); NegativeExpntl depart_expo((double)this->depart_mean_, this->rng_.get()); NegativeExpntl arrive_expo((double)this->arrive_mean_, this->rng_.get()); std::uniform_int_distribution<unsigned int> rand_airport(0,this->num_airports_-1); switch (received_event.type_) { case DEPARTURE: { this->state_.planes_grounded_--; this->state_.departures_++; // Schedule an arrival at a random airport unsigned int arrival_time = received_event.ts_ + (unsigned int)arrive_expo(); unsigned int destination_index = rand_airport(this->rng_engine_); response_events.emplace_back(new AirportEvent { Airport::object_name(destination_index), ARRIVAL, arrival_time }); break; } case ARRIVAL: { this->state_.arrivals_++; this->state_.planes_grounded_++; // Schedule a departure unsigned int departure_time = received_event.ts_ + (unsigned int)depart_expo(); response_events.emplace_back(new AirportEvent { this->name_, DEPARTURE, departure_time }); break; } } return response_events; } int main(int argc, const char** argv) { unsigned int num_airports = 100; unsigned int mean_ground_time = 50; unsigned int mean_flight_time = 200; unsigned int num_planes = 50; TCLAP::ValueArg<unsigned int> num_airports_arg("n", "num-airports", "Number of airports", false, num_airports, "unsigned int"); TCLAP::ValueArg<unsigned int> mean_ground_time_arg("g", "ground-time", "Mean time of planes waiting to depart", false, mean_ground_time, "unsigned int"); TCLAP::ValueArg<unsigned int> mean_flight_time_arg("f", "flight-time", "Mean flight time", false, mean_flight_time, "unsigned int"); TCLAP::ValueArg<unsigned int> num_planes_arg("p", "num-planes", "Number of planes per airport", false, num_planes, "unsigned int"); std::vector<TCLAP::Arg*> args = {&num_airports_arg, &mean_ground_time_arg, &mean_flight_time_arg, &num_planes_arg}; warped::Simulation airport_sim {"Airport Simulation", argc, argv, args}; num_airports = num_airports_arg.getValue(); mean_ground_time = mean_ground_time_arg.getValue(); mean_flight_time = mean_flight_time_arg.getValue(); num_planes = num_planes_arg.getValue(); std::vector<Airport> objects; for (unsigned int i = 0; i < num_airports; i++) { std::string name = Airport::object_name(i); objects.emplace_back(name, num_airports, num_planes, mean_flight_time, mean_ground_time, i); } std::vector<warped::SimulationObject*> object_pointers; for (auto& o : objects) { object_pointers.push_back(&o); } airport_sim.simulate(object_pointers); unsigned int arrivals = 0; unsigned int departures = 0; unsigned int planes_grounded = 0; for (auto& o : objects) { arrivals += o.state_.arrivals_; departures += o.state_.departures_; planes_grounded += o.state_.planes_grounded_; } std::cout << departures << " total departures" << std::endl; std::cout << arrivals << " total arrivals" << std::endl; std::cout << planes_grounded << " planes grounded" << std::endl; return 0; } <commit_msg>logical feature addition: planes cannot be sent from an airport to itself<commit_after>// An implementation of Fujimoto's airport model // Ported from the ROSS airport model (https://github.com/carothersc/ROSS/blob/master/ross/models/airport) // Author: Eric Carver (carverer@mail.uc.edu) #include <vector> #include <memory> #include <random> #include "warped.hpp" #include "airport.hpp" #include "MLCG.h" #include "NegExp.h" #include "tclap/ValueArg.h" WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(AirportEvent) std::vector<std::shared_ptr<warped::Event> > Airport::createInitialEvents() { std::vector<std::shared_ptr<warped::Event> > events; NegativeExpntl depart_expo((double)this->depart_mean_, this->rng_.get()); for (unsigned int i = 0; i < this->num_planes_; i++) { events.emplace_back(new AirportEvent {this->name_, DEPARTURE, (unsigned int)depart_expo()}); } return events; } inline std::string Airport::object_name(const unsigned int object_index) { return std::string("Object ") + std::to_string(object_index); } std::vector<std::shared_ptr<warped::Event> > Airport::receiveEvent(const warped::Event& event) { std::vector<std::shared_ptr<warped::Event> > response_events; auto received_event = static_cast<const AirportEvent&>(event); NegativeExpntl depart_expo((double)this->depart_mean_, this->rng_.get()); NegativeExpntl arrive_expo((double)this->arrive_mean_, this->rng_.get()); std::uniform_int_distribution<unsigned int> rand_airport(0,this->num_airports_-1); switch (received_event.type_) { case DEPARTURE: { this->state_.planes_grounded_--; this->state_.departures_++; // Schedule an arrival at a random airport unsigned int arrival_time = received_event.ts_ + (unsigned int)arrive_expo(); unsigned int destination_index = rand_airport(this->rng_engine_); while (destination_index == this->index_) { destination_index = rand_airport(this->rng_engine_); } response_events.emplace_back(new AirportEvent { Airport::object_name(destination_index), ARRIVAL, arrival_time }); break; } case ARRIVAL: { this->state_.arrivals_++; this->state_.planes_grounded_++; // Schedule a departure unsigned int departure_time = received_event.ts_ + (unsigned int)depart_expo(); response_events.emplace_back(new AirportEvent { this->name_, DEPARTURE, departure_time }); break; } } return response_events; } int main(int argc, const char** argv) { unsigned int num_airports = 100; unsigned int mean_ground_time = 50; unsigned int mean_flight_time = 200; unsigned int num_planes = 50; TCLAP::ValueArg<unsigned int> num_airports_arg("n", "num-airports", "Number of airports", false, num_airports, "unsigned int"); TCLAP::ValueArg<unsigned int> mean_ground_time_arg("g", "ground-time", "Mean time of planes waiting to depart", false, mean_ground_time, "unsigned int"); TCLAP::ValueArg<unsigned int> mean_flight_time_arg("f", "flight-time", "Mean flight time", false, mean_flight_time, "unsigned int"); TCLAP::ValueArg<unsigned int> num_planes_arg("p", "num-planes", "Number of planes per airport", false, num_planes, "unsigned int"); std::vector<TCLAP::Arg*> args = {&num_airports_arg, &mean_ground_time_arg, &mean_flight_time_arg, &num_planes_arg}; warped::Simulation airport_sim {"Airport Simulation", argc, argv, args}; num_airports = num_airports_arg.getValue(); mean_ground_time = mean_ground_time_arg.getValue(); mean_flight_time = mean_flight_time_arg.getValue(); num_planes = num_planes_arg.getValue(); std::vector<Airport> objects; for (unsigned int i = 0; i < num_airports; i++) { std::string name = Airport::object_name(i); objects.emplace_back(name, num_airports, num_planes, mean_flight_time, mean_ground_time, i); } std::vector<warped::SimulationObject*> object_pointers; for (auto& o : objects) { object_pointers.push_back(&o); } airport_sim.simulate(object_pointers); unsigned int arrivals = 0; unsigned int departures = 0; unsigned int planes_grounded = 0; for (auto& o : objects) { arrivals += o.state_.arrivals_; departures += o.state_.departures_; planes_grounded += o.state_.planes_grounded_; } std::cout << departures << " total departures" << std::endl; std::cout << arrivals << " total arrivals" << std::endl; std::cout << planes_grounded << " planes grounded" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2016 Muhammad Tayyab Akram * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdint> #include <cstring> #include <iostream> #include <list> #include <memory> #include <set> #include <tuple> #include <utility> #include <vector> extern "C" { #include <Source/SFAlbum.h> #include <Source/SFAssert.h> } #include "OpenType/Builder.h" #include "OpenType/GSUB.h" #include "TextProcessorTester.h" using namespace std; using namespace SheenFigure::Tester; using namespace SheenFigure::Tester::OpenType; void TextProcessorTester::testSingleSubstitution() { Builder builder; /* Test the first format. */ { /* Test with unmatching glyph. */ testSubstitution(builder.createSingleSubst({ 0 }, 0), { 1 }, { 1 }); /* Test with zero delta. */ testSubstitution(builder.createSingleSubst({ 1 }, 0), { 1 }, { 1 }); /* Test with positive delta. */ testSubstitution(builder.createSingleSubst({ 1 }, 99), { 1 }, { 100 }); /* Test with negative delta. */ testSubstitution(builder.createSingleSubst({ 100 }, -99), { 100 }, { 1 }); /* Test with opposite delta. */ testSubstitution(builder.createSingleSubst({ 1 }, -1), { 1 }, { 0 }); } /* Test the second format. */ { /* Test with unmatching glyph. */ testSubstitution(builder.createSingleSubst({ {0, 0} }), { 1 }, { 1 }); /* Test with zero glyph. */ testSubstitution(builder.createSingleSubst({ {0, 1} }), { 0 }, { 1 }); /* Test with zero substitution. */ testSubstitution(builder.createSingleSubst({ {1, 0} }), { 1 }, { 0 }); /* Test with same substitution. */ testSubstitution(builder.createSingleSubst({ {1, 1} }), { 1 }, { 1 }); /* Test with a different substitution. */ testSubstitution(builder.createSingleSubst({ {1, 100} }), { 1 }, { 100 }); } } void TextProcessorTester::testMultipleSubstitution() { Builder builder; /* Test with unmatching glyph. */ testSubstitution(builder.createMultipleSubst({ {0, { 1, 2, 3 }} }), { 1 }, { 1 }); /* Test with no glyph. */ testSubstitution(builder.createMultipleSubst({ {1, { }} }), { 1 }, { 1 }); /* Test with zero glyph. */ testSubstitution(builder.createMultipleSubst({ {0, { 1 }} }), { 0 }, { 1 }); /* Test with zero substitution. */ testSubstitution(builder.createMultipleSubst({ {1, { 0 }} }), { 1 }, { 0 }); /* Test with same substitution. */ testSubstitution(builder.createMultipleSubst({ {1, { 1 }} }), { 1 }, { 1 }); /* Test with different single substitution. */ testSubstitution(builder.createMultipleSubst({ {1, { 100 }} }), { 1 }, { 100 }); /* Test with different two substitutions. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 200 }} }), { 1 }, { 100, 200 }); /* Test with different multiple substitutions. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 200, 300 }} }), { 1 }, { 100, 200, 300 }); /* Test with multiple substitutions having input glyph at the start. */ testSubstitution(builder.createMultipleSubst({ {1, { 1, 200, 300 }} }), { 1 }, { 1, 200, 300 }); /* Test with multiple substitutions having input glyph at the middle. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 1, 300 }} }), { 1 }, { 100, 1, 300 }); /* Test with multiple substitutions having input glyph at the end. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 200, 1 }} }), { 1 }, { 100, 200, 1 }); /* Test with multiple substitutions having input glyph everywhere. */ testSubstitution(builder.createMultipleSubst({ {1, { 1, 1, 1 }} }), { 1 }, { 1, 1, 1 }); /* Test with multiple repeating substitutions. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 100, 100 }} }), { 1 }, { 100, 100, 100 }); /* Test with multiple zero substitutions. */ testSubstitution(builder.createMultipleSubst({ {1, { 0, 0, 0 }} }), { 1 }, { 0, 0, 0 }); } void TextProcessorTester::testLigatureSubstitution() { Builder builder; /* Test with unmatching glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 0} }), { 1 }, { 1 }); /* Test with zero glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 0 }, 1} }), { 0 }, { 1 }); /* Test with zero substitution. */ testSubstitution(builder.createLigatureSubst({ {{ 1 }, 0} }), { 1 }, { 0 }); /* Test with same substitution. */ testSubstitution(builder.createLigatureSubst({ {{ 1 }, 1} }), { 1 }, { 1 }); /* Test with different substitution. */ testSubstitution(builder.createLigatureSubst({ {{ 1 }, 100} }), { 1 }, { 100 }); /* Test with two different glyphs. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2 }, 100} }), { 1, 2 }, { 100 }); /* Test with multiple different glyphs. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 100} }), { 1, 2, 3 }, { 100 }); /* Test with multiple glyphs translating to first input glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 1} }), { 1, 2, 3 }, { 1 }); /* Test with multiple glyphs translating to middle input glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 2} }), { 1, 2, 3 }, { 2 }); /* Test with multiple glyphs translating to last input glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 3} }), { 1, 2, 3 }, { 3 }); /* Test with multiple same glyphs translating to itself. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 1, 1 }, 1} }), { 1, 1, 1 }, { 1 }); /* Test with multiple same glyphs translating to a different glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 1, 1 }, 100} }), { 1, 1, 1 }, { 100 }); /* Test with multiple zero glyphs. */ testSubstitution(builder.createLigatureSubst({ {{ 0, 0, 0 }, 100} }), { 0, 0, 0 }, { 100 }); } void TextProcessorTester::testChainContextSubstitution() { Builder builder; /* Test the format 1. */ { /* Test with simple substitution. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 2 }, 1) }; ChainContextSubtable &subtable = builder.createChainContext({ rule_chain_context { { 1, 1, 1 }, { 1, 2, 3 }, { 3, 3, 3 }, { { 1, 1 } } } }); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3 }, referrals.data(), referrals.size()); } /* Test with complex substitutions. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 1, 2, 3, 4, 5, 6 }, 1), &builder.createMultipleSubst({ {2, { 4, 5, 6 }} }), &builder.createLigatureSubst({ {{ 1, 4 }, 10}, {{ 6, 4 }, 20} }) }; ChainContextSubtable &subtable = builder.createChainContext({ rule_chain_context { { 1, 1, 1 }, { 1, 2, 3 }, { 3, 3, 3 }, { { 2, 1 }, { 1, 2 }, { 3, 3 }, { 0, 3 }, { 1, 1 } } } }); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 10, 6, 20, 3, 3, 3 }, referrals.data(), referrals.size()); } } /* Test the format 3. */ { /* Test with simple substitution. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 2 }, 1) }; ChainContextSubtable &subtable = builder.createChainContext( { { 1 }, { 1 }, { 1 } }, { { 1 }, { 2 }, { 3 } }, { { 3 }, { 3 }, { 3 } }, { { 1, 1 } } ); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3 }, referrals.data(), referrals.size()); } /* Test with complex substitutions. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 1, 2, 3, 4, 5, 6 }, 1), &builder.createMultipleSubst({ {2, { 4, 5, 6 }} }), &builder.createLigatureSubst({ {{ 1, 4 }, 10}, {{ 6, 4 }, 20} }) }; ChainContextSubtable &subtable = builder.createChainContext( { { 1 }, { 1 }, { 1 } }, { { 1 }, { 2 }, { 3 } }, { { 3 }, { 3 }, { 3 } }, { { 2, 1 }, { 1, 2 }, { 3, 3 }, { 0, 3 }, { 1, 1 } } ); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 10, 6, 20, 3, 3, 3 }, referrals.data(), referrals.size()); } } } <commit_msg>Added test cases for chain context format 2...<commit_after>/* * Copyright (C) 2016 Muhammad Tayyab Akram * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdint> #include <cstring> #include <iostream> #include <list> #include <memory> #include <set> #include <tuple> #include <utility> #include <vector> extern "C" { #include <Source/SFAlbum.h> #include <Source/SFAssert.h> } #include "OpenType/Builder.h" #include "OpenType/GSUB.h" #include "TextProcessorTester.h" using namespace std; using namespace SheenFigure::Tester; using namespace SheenFigure::Tester::OpenType; void TextProcessorTester::testSingleSubstitution() { Builder builder; /* Test the first format. */ { /* Test with unmatching glyph. */ testSubstitution(builder.createSingleSubst({ 0 }, 0), { 1 }, { 1 }); /* Test with zero delta. */ testSubstitution(builder.createSingleSubst({ 1 }, 0), { 1 }, { 1 }); /* Test with positive delta. */ testSubstitution(builder.createSingleSubst({ 1 }, 99), { 1 }, { 100 }); /* Test with negative delta. */ testSubstitution(builder.createSingleSubst({ 100 }, -99), { 100 }, { 1 }); /* Test with opposite delta. */ testSubstitution(builder.createSingleSubst({ 1 }, -1), { 1 }, { 0 }); } /* Test the second format. */ { /* Test with unmatching glyph. */ testSubstitution(builder.createSingleSubst({ {0, 0} }), { 1 }, { 1 }); /* Test with zero glyph. */ testSubstitution(builder.createSingleSubst({ {0, 1} }), { 0 }, { 1 }); /* Test with zero substitution. */ testSubstitution(builder.createSingleSubst({ {1, 0} }), { 1 }, { 0 }); /* Test with same substitution. */ testSubstitution(builder.createSingleSubst({ {1, 1} }), { 1 }, { 1 }); /* Test with a different substitution. */ testSubstitution(builder.createSingleSubst({ {1, 100} }), { 1 }, { 100 }); } } void TextProcessorTester::testMultipleSubstitution() { Builder builder; /* Test with unmatching glyph. */ testSubstitution(builder.createMultipleSubst({ {0, { 1, 2, 3 }} }), { 1 }, { 1 }); /* Test with no glyph. */ testSubstitution(builder.createMultipleSubst({ {1, { }} }), { 1 }, { 1 }); /* Test with zero glyph. */ testSubstitution(builder.createMultipleSubst({ {0, { 1 }} }), { 0 }, { 1 }); /* Test with zero substitution. */ testSubstitution(builder.createMultipleSubst({ {1, { 0 }} }), { 1 }, { 0 }); /* Test with same substitution. */ testSubstitution(builder.createMultipleSubst({ {1, { 1 }} }), { 1 }, { 1 }); /* Test with different single substitution. */ testSubstitution(builder.createMultipleSubst({ {1, { 100 }} }), { 1 }, { 100 }); /* Test with different two substitutions. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 200 }} }), { 1 }, { 100, 200 }); /* Test with different multiple substitutions. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 200, 300 }} }), { 1 }, { 100, 200, 300 }); /* Test with multiple substitutions having input glyph at the start. */ testSubstitution(builder.createMultipleSubst({ {1, { 1, 200, 300 }} }), { 1 }, { 1, 200, 300 }); /* Test with multiple substitutions having input glyph at the middle. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 1, 300 }} }), { 1 }, { 100, 1, 300 }); /* Test with multiple substitutions having input glyph at the end. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 200, 1 }} }), { 1 }, { 100, 200, 1 }); /* Test with multiple substitutions having input glyph everywhere. */ testSubstitution(builder.createMultipleSubst({ {1, { 1, 1, 1 }} }), { 1 }, { 1, 1, 1 }); /* Test with multiple repeating substitutions. */ testSubstitution(builder.createMultipleSubst({ {1, { 100, 100, 100 }} }), { 1 }, { 100, 100, 100 }); /* Test with multiple zero substitutions. */ testSubstitution(builder.createMultipleSubst({ {1, { 0, 0, 0 }} }), { 1 }, { 0, 0, 0 }); } void TextProcessorTester::testLigatureSubstitution() { Builder builder; /* Test with unmatching glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 0} }), { 1 }, { 1 }); /* Test with zero glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 0 }, 1} }), { 0 }, { 1 }); /* Test with zero substitution. */ testSubstitution(builder.createLigatureSubst({ {{ 1 }, 0} }), { 1 }, { 0 }); /* Test with same substitution. */ testSubstitution(builder.createLigatureSubst({ {{ 1 }, 1} }), { 1 }, { 1 }); /* Test with different substitution. */ testSubstitution(builder.createLigatureSubst({ {{ 1 }, 100} }), { 1 }, { 100 }); /* Test with two different glyphs. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2 }, 100} }), { 1, 2 }, { 100 }); /* Test with multiple different glyphs. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 100} }), { 1, 2, 3 }, { 100 }); /* Test with multiple glyphs translating to first input glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 1} }), { 1, 2, 3 }, { 1 }); /* Test with multiple glyphs translating to middle input glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 2} }), { 1, 2, 3 }, { 2 }); /* Test with multiple glyphs translating to last input glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 2, 3 }, 3} }), { 1, 2, 3 }, { 3 }); /* Test with multiple same glyphs translating to itself. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 1, 1 }, 1} }), { 1, 1, 1 }, { 1 }); /* Test with multiple same glyphs translating to a different glyph. */ testSubstitution(builder.createLigatureSubst({ {{ 1, 1, 1 }, 100} }), { 1, 1, 1 }, { 100 }); /* Test with multiple zero glyphs. */ testSubstitution(builder.createLigatureSubst({ {{ 0, 0, 0 }, 100} }), { 0, 0, 0 }, { 100 }); } void TextProcessorTester::testChainContextSubstitution() { Builder builder; /* Test the format 1. */ { /* Test with simple substitution. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 2 }, 1) }; ChainContextSubtable &subtable = builder.createChainContext({ rule_chain_context { { 1, 1, 1 }, { 1, 2, 3 }, { 3, 3, 3 }, { { 1, 1 } } } }); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3 }, referrals.data(), referrals.size()); } /* Test with complex substitutions. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 1, 2, 3, 4, 5, 6 }, 1), &builder.createMultipleSubst({ {2, { 4, 5, 6 }} }), &builder.createLigatureSubst({ {{ 1, 4 }, 10}, {{ 6, 4 }, 20} }) }; ChainContextSubtable &subtable = builder.createChainContext({ rule_chain_context { { 1, 1, 1 }, { 1, 2, 3 }, { 3, 3, 3 }, { { 2, 1 }, { 1, 2 }, { 3, 3 }, { 0, 3 }, { 1, 1 } } } }); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 10, 6, 20, 3, 3, 3 }, referrals.data(), referrals.size()); } } /* Test the format 2. */ { array<ClassDefTable *, 3> classDefs = { &builder.createClassDef({ { 1, 10, 1 } }), &builder.createClassDef({ { 1, 10, 1 } }), &builder.createClassDef({ { 1, 10, 1 } }), }; /* Test with simple substitution. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 2 }, 1) }; ChainContextSubtable &subtable = builder.createChainContext({ rule_chain_context { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 }, { { 1, 1 } } } }, classDefs); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3 }, referrals.data(), referrals.size()); } /* Test with complex substitutions. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 1, 2, 3, 4, 5, 6 }, 1), &builder.createMultipleSubst({ {2, { 4, 5, 6 }} }), &builder.createLigatureSubst({ {{ 1, 4 }, 10}, {{ 6, 4 }, 20} }) }; ChainContextSubtable &subtable = builder.createChainContext({ rule_chain_context { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 }, { { 2, 1 }, { 1, 2 }, { 3, 3 }, { 0, 3 }, { 1, 1 } } } }, classDefs); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 10, 6, 20, 3, 3, 3 }, referrals.data(), referrals.size()); } } /* Test the format 3. */ { /* Test with simple substitution. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 2 }, 1) }; ChainContextSubtable &subtable = builder.createChainContext( { { 1 }, { 1 }, { 1 } }, { { 1 }, { 2 }, { 3 } }, { { 3 }, { 3 }, { 3 } }, { { 1, 1 } } ); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3 }, referrals.data(), referrals.size()); } /* Test with complex substitutions. */ { vector<LookupSubtable *> referrals = { &builder.createSingleSubst({ 1, 2, 3, 4, 5, 6 }, 1), &builder.createMultipleSubst({ {2, { 4, 5, 6 }} }), &builder.createLigatureSubst({ {{ 1, 4 }, 10}, {{ 6, 4 }, 20} }) }; ChainContextSubtable &subtable = builder.createChainContext( { { 1 }, { 1 }, { 1 } }, { { 1 }, { 2 }, { 3 } }, { { 3 }, { 3 }, { 3 } }, { { 2, 1 }, { 1, 2 }, { 3, 3 }, { 0, 3 }, { 1, 1 } } ); testSubstitution(subtable, { 1, 1, 1, 1, 2, 3, 3, 3, 3 }, { 1, 1, 1, 10, 6, 20, 3, 3, 3 }, referrals.data(), referrals.size()); } } } <|endoftext|>
<commit_before>#ifndef LM_HH #define LM_HH #include <float.h> #include "misc/types.hh" #include "FixedArray.hh" namespace fsalm { class Semiring { public: Semiring() : one(0), zero(-1e30) { } virtual ~Semiring() { } virtual float plus(float a, float b) = 0; virtual float times(float a, float b) = 0; virtual float divide(float a, float b) = 0; virtual bool equal(float a, float b) = 0; float one; float zero; }; class MaxPlusSemiring : public Semiring { public: virtual ~MaxPlusSemiring() { } virtual float plus(float a, float b) { return a < b ? b : a; } virtual float times(float a, float b) { return a + b; } virtual float divide(float a, float b) { return a - b; } virtual bool equal(float a, float b) { return a == b; } }; /** Class for storing ngram language model in a fst format with * backoff arcs. * * INVARIANTS: * * - before trim() there may be nodes without children and bt=0 * * - after trim() only final node has bt=0 and has zero children * * - node n has zero children if limit[n-1] == limit[n] or limit[n] == 0 * * IMPLEMENTATION NOTES: * * - Backoff information is stored in the nodes instead of normal * arcs. Otherwise, creating the arcs in proper order would be * troublesome from ARPA format. * * ASSUMES: * - children of a context are inserted in sorted chunk * - lower order is inserted before higher order */ class LM { public: typedef FixedArray<int> Array; typedef FixedArray<float> FloatArray; Str start_str; Str end_str; Semiring *semiring; LM(); void reset(); const SymbolMap &symbol_map() const { return m_symbol_map; } int start_symbol() const { return m_start_symbol; } int end_symbol() const { return m_end_symbol; } int final_node_id() const { return m_final_node_id; } int empty_node_id() const { return m_empty_node_id; } int initial_node_id() const { return m_initial_node_id; } int order() const { return m_order; } int num_arcs() const { return m_arcs.symbol.num_elems(); } int num_nodes() const { return m_nodes.bo_target.num_elems(); } float final_score() const { return m_final_score; } /** Return the number of explicit children of node. */ int num_children(int node_id) const; /** String describing a vector of symbol indices. */ Str str(const IntVec &vec) const; /** Find context node for given backoff vector by backoffing * further if necessary. * * \note Throws exception if given ngram ends in sentence end * symbol. * * \param vec = candidate context for the backoff * \return node index corresponding to backoff context */ int find_backoff(IntVec vec) const; /** Move to next node through given symbol but do not backoff. * * Finds the arc that starts from given node and has the given * symbol assigned, then returns its target node. * * \param node_id = the node to start from (final node not allowed) * \param symbol = the symbol to search * \param score = float pointer to which the possible score of the arc is ADDED * \return the resulting node (or -1 if explicit arc with symbol not found) */ int walk_no_bo(int node_id, int symbol, float *score = NULL) const; int walk_no_bo(int node_id, const IntVec &vec, float *score = NULL) const; /** Move to next node through given symbols without backoffing. * Same as above, but returns node indices for each symbol in a * vector. */ IntVec walk_no_bo_vec(int node_id, const IntVec &vec, float *score = NULL) const; /** Move to next node through given symbol by backoffing if necessary. * * \param node_id = the node to start from (final node not allowed) * \param symbol = the symbol to traverse through * \param score = float pointer to which the score is ADDED * \return the resulting node */ int walk(int node_id, int symbol, float *score = NULL) const; int walk(int node_id, const IntVec &vec, float *score = NULL) const; void new_arc(int src_node_id, int symbol, int tgt_node_id, float score); void new_ngram(const IntVec &vec, float score, float bo_score); int new_node(); void set_arc(int arc_id, int symbol, int target, float score); void trim(); void quantize(int bits); /** Compute potential of each node (used by push). */ void compute_potential(FloatVec &d); /** Push scores as early as possible. */ void push(); /** Reads the language model in ARPA format. */ void read_arpa(FILE *file, bool show_progress = false); /** Reads the language model in a non-standard format. */ void read(FILE *file); /** Writes the language model in a non-standard format. */ void write(FILE *file) const; /** Write the language model in MIT fst format. */ void write_fst(FILE *file, Str bo_symbol = "<B>") const; /** Write the language model in ATT fsmt format. */ void write_fsmt(FILE *file, Str bo_symbol = "<B>") const; void write_fsmt_node(FILE *file, int n, Str bo_symbol) const; /** Fetch probabilities for all symbols (ignoring non-events). */ void fetch_probs(int node_id, FloatVec &vec); Str debug_str() const; bool debug_check_sum(int node_id) const; bool debug_check_sums() const; bool debug_check_zero_bo() const; private: /** Incoming arc used temporarily by compute_potential() */ struct InArc { InArc() : source(-1), arc_id(-1) { } InArc(int source, int arc_id) : source(source), arc_id(arc_id) { } int source; int arc_id; }; /** Node information */ struct { FloatArray bo_score; Array bo_target; Array limit_arc; //!< Index to one past the last arc that starts from this node. } m_nodes; /** Arc information */ struct { Array symbol; //!< The symbol assigned to the arc. Array target; //!< The target node. FloatArray score; //!< Possible score of the arc. } m_arcs; /** Cache containing information about the last ngram inserted in * the strucure. */ struct { IntVec ctx_vec; //!< Context vector, i.e. all but the last symbol. int ctx_node_id; } m_cache; /** Mapping between language model symbols and indices. */ SymbolMap m_symbol_map; /** Bit array defining non-event symbols. */ BoolVec m_non_event; int m_order; int m_empty_node_id; int m_initial_node_id; int m_final_node_id; int m_start_symbol; int m_end_symbol; float m_final_score; }; }; #endif /* LM_HH */ <commit_msg>Added some Doxygen comments.<commit_after>#ifndef LM_HH #define LM_HH #include <float.h> #include "misc/types.hh" #include "FixedArray.hh" namespace fsalm { class Semiring { public: Semiring() : one(0), zero(-1e30) { } virtual ~Semiring() { } virtual float plus(float a, float b) = 0; virtual float times(float a, float b) = 0; virtual float divide(float a, float b) = 0; virtual bool equal(float a, float b) = 0; float one; float zero; }; class MaxPlusSemiring : public Semiring { public: virtual ~MaxPlusSemiring() { } virtual float plus(float a, float b) { return a < b ? b : a; } virtual float times(float a, float b) { return a + b; } virtual float divide(float a, float b) { return a - b; } virtual bool equal(float a, float b) { return a == b; } }; /** Class for storing ngram language model in a fst format with * backoff arcs. * * INVARIANTS: * * - before trim() there may be nodes without children and bt=0 * * - after trim() only final node has bt=0 and has zero children * * - node n has zero children if limit[n-1] == limit[n] or limit[n] == 0 * * IMPLEMENTATION NOTES: * * - Backoff information is stored in the nodes instead of normal * arcs. Otherwise, creating the arcs in proper order would be * troublesome from ARPA format. * * ASSUMES: * - children of a context are inserted in sorted chunk * - lower order is inserted before higher order */ class LM { public: typedef FixedArray<int> Array; typedef FixedArray<float> FloatArray; Str start_str; Str end_str; Semiring *semiring; LM(); void reset(); const SymbolMap &symbol_map() const { return m_symbol_map; } int start_symbol() const { return m_start_symbol; } int end_symbol() const { return m_end_symbol; } int final_node_id() const { return m_final_node_id; } int empty_node_id() const { return m_empty_node_id; } int initial_node_id() const { return m_initial_node_id; } int order() const { return m_order; } int num_arcs() const { return m_arcs.symbol.num_elems(); } int num_nodes() const { return m_nodes.bo_target.num_elems(); } float final_score() const { return m_final_score; } /** Return the number of explicit children of node. */ int num_children(int node_id) const; /** String describing a vector of symbol indices. */ Str str(const IntVec &vec) const; /** Find context node for given backoff vector by backoffing * further if necessary. * * \note Throws exception if given ngram ends in sentence end * symbol. * * \param vec = candidate context for the backoff * \return node index corresponding to backoff context */ int find_backoff(IntVec vec) const; /** Move to next node through given symbol but do not backoff. * * Finds the arc that starts from given node and has the given * symbol assigned, then returns its target node. * * \param node_id The node to start from (final node not allowed), or * empty_node_id() to search every node(?) * \param symbol The symbol to search for. * \param score Float pointer to which the possible score of the arc is ADDED * \return The resulting node (or -1 if explicit arc with symbol not found). */ int walk_no_bo(int node_id, int symbol, float *score = NULL) const; /** Walks through a list of symbols but does not backoff. * * Finds a path that starts from given node and has the list of symbols * assigned in given order, then returns the target node of the last arc. * * \param node_id The node to start from (final node not allowed), or * empty_node_id() to search every node(?) * \param vec The list of symbols to traverse. * \param score Float pointer to which the possible score of the arc is ADDED * \return The resulting node (or -1 if explicit arc with symbol not found). */ int walk_no_bo(int node_id, const IntVec &vec, float *score = NULL) const; /** Move to next node through given symbols without backoffing. * Same as above, but returns node indices for each symbol in a * vector. */ IntVec walk_no_bo_vec(int node_id, const IntVec &vec, float *score = NULL) const; /** Move to next node through given symbol by backoffing if necessary. * * \param node_id = the node to start from (final node not allowed) * \param symbol = the symbol to traverse through * \param score = float pointer to which the score is ADDED * \return the resulting node */ int walk(int node_id, int symbol, float *score = NULL) const; int walk(int node_id, const IntVec &vec, float *score = NULL) const; void new_arc(int src_node_id, int symbol, int tgt_node_id, float score); void new_ngram(const IntVec &vec, float score, float bo_score); int new_node(); void set_arc(int arc_id, int symbol, int target, float score); void trim(); void quantize(int bits); /** Compute potential of each node (used by push). */ void compute_potential(FloatVec &d); /** Push scores as early as possible. */ void push(); /** Reads the language model in ARPA format. */ void read_arpa(FILE *file, bool show_progress = false); /** Reads the language model in a non-standard format. */ void read(FILE *file); /** Writes the language model in a non-standard format. */ void write(FILE *file) const; /** Write the language model in MIT fst format. */ void write_fst(FILE *file, Str bo_symbol = "<B>") const; /** Write the language model in ATT fsmt format. */ void write_fsmt(FILE *file, Str bo_symbol = "<B>") const; void write_fsmt_node(FILE *file, int n, Str bo_symbol) const; /** Fetch probabilities for all symbols (ignoring non-events). */ void fetch_probs(int node_id, FloatVec &vec); Str debug_str() const; bool debug_check_sum(int node_id) const; bool debug_check_sums() const; bool debug_check_zero_bo() const; private: /** Incoming arc used temporarily by compute_potential() */ struct InArc { InArc() : source(-1), arc_id(-1) { } InArc(int source, int arc_id) : source(source), arc_id(arc_id) { } int source; int arc_id; }; /** Node information */ struct { FloatArray bo_score; Array bo_target; Array limit_arc; //!< Index to one past the last arc that starts from this node. } m_nodes; /** Arc information */ struct { Array symbol; //!< The symbol assigned to the arc. Array target; //!< The target node. FloatArray score; //!< Possible score of the arc. } m_arcs; /** Cache containing information about the last ngram inserted in * the strucure. */ struct { IntVec ctx_vec; //!< Context vector, i.e. all but the last symbol. int ctx_node_id; } m_cache; /** Mapping between language model symbols and indices. */ SymbolMap m_symbol_map; /** Bit array defining non-event symbols. */ BoolVec m_non_event; int m_order; int m_empty_node_id; int m_initial_node_id; int m_final_node_id; int m_start_symbol; int m_end_symbol; float m_final_score; }; }; #endif /* LM_HH */ <|endoftext|>
<commit_before>#include "Camera3D.h" edk::Camera3D::Camera3D(){ // this->start(); this->perspective = false; this->firstPerson=false; } edk::Camera3D::Camera3D(edk::vec3f32 position,edk::vec3f32 lookAt){ this->start(); this->position = position; this->lookAt = lookAt; this->perspective = false; this->firstPerson=false; } edk::Camera3D::Camera3D(edk::float32 pX,edk::float32 pY,edk::float32 pZ,edk::float32 lookX,edk::float32 lookY,edk::float32 lookZ){ this->start(); this->position = edk::vec3f32(pX,pY,pZ); this->lookAt = edk::vec3f32(lookX,lookY,lookZ); this->perspective = false; this->firstPerson=false; } edk::Camera3D::~Camera3D(){ // } void edk::Camera3D::start(){ // this->position = edk::vec3f32(0.f,0.f,-1.f); this->lookAt = edk::vec3f32(0.f,0.f,0.f); this->up = edk::vec3f32(0.f,1.f,0.f); this->size = edk::size2f32(1.f,1.f); this->sizePercent = this->size.width/this->size.height; this->near = 0.0001f; this->far = 1.f; } //Sset witch camera type its using void edk::Camera3D::usePerspective(){ this->perspective=true; } void edk::Camera3D::useOrtho(){ this->perspective=false; } //set the size void edk::Camera3D::setSize(edk::size2f32 size){ // this->size=size*0.5f; this->sizePercent = this->size.width/this->size.height; } void edk::Camera3D::setSize(edk::float32 sizeW,edk::float32 sizeH){ // return this->setSize(edk::size2f32(sizeW,sizeH)); } void edk::Camera3D::setSizeW(edk::float32 width){ this->size.width = width*0.5f; this->sizePercent = this->size.width/this->size.height; } void edk::Camera3D::setSizeH(edk::float32 height){ this->size.height = height*0.5f; this->sizePercent = this->size.width/this->size.height; } //return the size edk::float32 edk::Camera3D::getWidth(){ return this->size.width * 2.f; } edk::float32 edk::Camera3D::getHeight(){ return this->size.height * 2.f; } //set near and far void edk::Camera3D::setNearFar(edk::float32 near,edk::float32 far){ if(far>near){ this->near = near; this->far = far; } else{ this->near = far; this->far = near; } } void edk::Camera3D::setFar(edk::float32 far){ this->setNearFar(0.0001f,far); } //Get near and far edk::float32 edk::Camera3D::getNear(){ return this->near; } edk::float32 edk::Camera3D::getFar(){ return this->far; } //Distance edk::float32 edk::Camera3D::getDistance(){ // return edk::Math::pythagoras3f(this->lookAt.x - this->position.x, this->lookAt.y - this->position.y, this->lookAt.y - this->position.z ); } //set the distance bool edk::Camera3D::setDistance(edk::float32 distance){ if(distance>0.f){ edk::float32 percent = distance / this->getDistance(); //set the distance if(this->firstPerson){ // this->lookAt.x = this->position.x + ((this->lookAt.x-this->position.x) * percent); this->lookAt.y = this->position.y + ((this->lookAt.y-this->position.y) * percent); this->lookAt.z = this->position.z + ((this->lookAt.z-this->position.z) * percent); } else{ // this->position.x = this->lookAt.x + ((this->position.x-this->lookAt.x) * percent); this->position.y = this->lookAt.y + ((this->position.y-this->lookAt.y) * percent); this->position.z = this->lookAt.z + ((this->position.z-this->lookAt.z) * percent); } return true; } return false; } //move the distance bool edk::Camera3D::moveDistance(edk::float32 distance){ return this->setDistance(this->getDistance()+distance); } //return the angle width and height edk::float32 edk::Camera3D::getAngleX(){ if(this->firstPerson){ return edk::Math::getAngle2f(this->lookAt.x-this->position.x,this->lookAt.z-this->position.z); } return edk::Math::getAngle2f(this->position.x-this->lookAt.x,this->position.z-this->lookAt.z); } edk::float32 edk::Camera3D::getAngleY(){ if(this->firstPerson){ return edk::Math::getAngle2f(edk::Math::pythagoras2f(this->lookAt.x-this->position.x,this->lookAt.z-this->position.z),this->lookAt.y-this->position.y); } return edk::Math::getAngle2f(edk::Math::pythagoras2f(this->position.x-this->lookAt.x,this->position.z-this->lookAt.z),this->position.y-this->lookAt.y); } //set the angles void edk::Camera3D::setAngleX(edk::float32 angle){ if(this->firstPerson){ edk::float32 distance = edk::Math::pythagoras2f(this->lookAt.x - this->position.x,this->lookAt.z - this->position.z); this->lookAt.x = edk::Math::rotateXFloat(distance,angle) + this->position.x; this->lookAt.z = edk::Math::rotateYFloat(distance,angle) + this->position.z; } else{ edk::float32 distance = edk::Math::pythagoras2f(this->position.x - this->lookAt.x,this->position.z - this->lookAt.z); this->position.x = edk::Math::rotateXFloat(distance,angle) + this->lookAt.x; this->position.z = edk::Math::rotateYFloat(distance,angle) + this->lookAt.z; } } void edk::Camera3D::setAngleY(edk::float32 angle){ if(this->firstPerson){ edk::float32 angleX = this->getAngleX(); edk::float32 distanceX = edk::Math::pythagoras2f(this->lookAt.x - this->position.x,this->lookAt.z - this->position.z); edk::float32 distanceY = edk::Math::pythagoras2f(distanceX,this->lookAt.y - this->position.y); // distanceX = edk::Math::rotateXFloat(distanceY,angle) + this->position.x; this->lookAt.y = edk::Math::rotateYFloat(distanceY,angle) + this->position.z; // this->lookAt.x = edk::Math::rotateXFloat(distanceX,angleX) + this->position.x; this->lookAt.z = edk::Math::rotateYFloat(distanceX,angleX) + this->position.z; } else{ edk::float32 angleX = this->getAngleX(); edk::float32 distanceX = edk::Math::pythagoras2f(this->position.x - this->lookAt.x,this->position.z - this->lookAt.z); edk::float32 distanceY = edk::Math::pythagoras2f(distanceX,this->position.y - this->lookAt.y); // distanceX = edk::Math::rotateXFloat(distanceY,angle) + this->lookAt.x; this->position.y = edk::Math::rotateYFloat(distanceY,angle) + this->lookAt.z; // this->position.x = edk::Math::rotateXFloat(distanceX,angleX) + this->lookAt.x; this->position.z = edk::Math::rotateYFloat(distanceX,angleX) + this->lookAt.z; } } //move the angles void edk::Camera3D::moveAngleX(edk::float32 angle){ this->setAngleX(angle + this->getAngleX()); } void edk::Camera3D::moveAngleY(edk::float32 angle){ this->setAngleY(angle + this->getAngleY()); } //draw the camera void edk::Camera3D::draw(){ // //test if are NOT using GUmodelview if(!edk::GU::guUsingMatrix(GU_PROJECTION)) //then set to use modelView edk::GU::guUseMatrix(GU_PROJECTION); edk::GU::guLoadIdentity(); // edk::Camera3D::drawAxisOnly(); } void edk::Camera3D::drawAxisOnly(){ if(this->perspective){ edk::GU::guUsePerspective(this->size.height*2.f,this->sizePercent,this->near,this->far); } else{ edk::GU::guUseOrtho(-this->size.width, this->size.width, -this->size.height, this->size.height, this->near,//nea this->far//far ); } /* //update the shaking animations this->animAngle.updateClockAnimation(); if(this->animAngle.isPlaying()){ //calculate the angle of shaking this->up = edk::Math::rotate2f(edk::vec2f32(1,0),(((this->angle + this->animAngle.getClockX())*-1)+360.f)+90); } else{ this->up = edk::Math::rotate2f(edk::vec2f32(1,0),((this->angle*-1)+360.f)+90); } */ //shake position /* this->animPosition.updateClockAnimation(); if(this->animPosition.isPlaying()){ this->tempPosition.x = this->position.x+this->animPosition.getClockX(); this->tempPosition.y = this->position.y+this->animPosition.getClockY(); edk::GU::guLookAt(this->tempPosition.x,this->tempPosition.y,1.f, this->tempPosition.x,this->tempPosition.y,0.f, this->up.x,this->up.y,0.f ); } else{ edk::GU::guLookAt(this->position.x,this->position.y,1.f, this->position.x,this->position.y,0.f, this->up.x,this->up.y,0.f ); } */ edk::GU::guLookAt(this->position.x,this->position.y,this->position.z, this->lookAt.x,this->lookAt.y,this->lookAt.z, this->up.x,this->up.y,this->up.z ); } void edk::Camera3D::drawAxisOnly(edk::float32 seconds){ // } //operator to copy the cameras bool edk::Camera3D::cloneFrom(edk::Camera3D* cam){ // ///TODO return false; } <commit_msg>edk/Camera3D: - Implement the function cloneFrom for clone the camera into another camera.<commit_after>#include "Camera3D.h" edk::Camera3D::Camera3D(){ // this->start(); this->perspective = false; this->firstPerson=false; } edk::Camera3D::Camera3D(edk::vec3f32 position,edk::vec3f32 lookAt){ this->start(); this->position = position; this->lookAt = lookAt; this->perspective = false; this->firstPerson=false; } edk::Camera3D::Camera3D(edk::float32 pX,edk::float32 pY,edk::float32 pZ,edk::float32 lookX,edk::float32 lookY,edk::float32 lookZ){ this->start(); this->position = edk::vec3f32(pX,pY,pZ); this->lookAt = edk::vec3f32(lookX,lookY,lookZ); this->perspective = false; this->firstPerson=false; } edk::Camera3D::~Camera3D(){ // } void edk::Camera3D::start(){ // this->position = edk::vec3f32(0.f,0.f,-1.f); this->lookAt = edk::vec3f32(0.f,0.f,0.f); this->up = edk::vec3f32(0.f,1.f,0.f); this->size = edk::size2f32(1.f,1.f); this->sizePercent = this->size.width/this->size.height; this->near = 0.0001f; this->far = 1.f; } //Sset witch camera type its using void edk::Camera3D::usePerspective(){ this->perspective=true; } void edk::Camera3D::useOrtho(){ this->perspective=false; } //set the size void edk::Camera3D::setSize(edk::size2f32 size){ // this->size=size*0.5f; this->sizePercent = this->size.width/this->size.height; } void edk::Camera3D::setSize(edk::float32 sizeW,edk::float32 sizeH){ // return this->setSize(edk::size2f32(sizeW,sizeH)); } void edk::Camera3D::setSizeW(edk::float32 width){ this->size.width = width*0.5f; this->sizePercent = this->size.width/this->size.height; } void edk::Camera3D::setSizeH(edk::float32 height){ this->size.height = height*0.5f; this->sizePercent = this->size.width/this->size.height; } //return the size edk::float32 edk::Camera3D::getWidth(){ return this->size.width * 2.f; } edk::float32 edk::Camera3D::getHeight(){ return this->size.height * 2.f; } //set near and far void edk::Camera3D::setNearFar(edk::float32 near,edk::float32 far){ if(far>near){ this->near = near; this->far = far; } else{ this->near = far; this->far = near; } } void edk::Camera3D::setFar(edk::float32 far){ this->setNearFar(0.0001f,far); } //Get near and far edk::float32 edk::Camera3D::getNear(){ return this->near; } edk::float32 edk::Camera3D::getFar(){ return this->far; } //Distance edk::float32 edk::Camera3D::getDistance(){ // return edk::Math::pythagoras3f(this->lookAt.x - this->position.x, this->lookAt.y - this->position.y, this->lookAt.y - this->position.z ); } //set the distance bool edk::Camera3D::setDistance(edk::float32 distance){ if(distance>0.f){ edk::float32 percent = distance / this->getDistance(); //set the distance if(this->firstPerson){ // this->lookAt.x = this->position.x + ((this->lookAt.x-this->position.x) * percent); this->lookAt.y = this->position.y + ((this->lookAt.y-this->position.y) * percent); this->lookAt.z = this->position.z + ((this->lookAt.z-this->position.z) * percent); } else{ // this->position.x = this->lookAt.x + ((this->position.x-this->lookAt.x) * percent); this->position.y = this->lookAt.y + ((this->position.y-this->lookAt.y) * percent); this->position.z = this->lookAt.z + ((this->position.z-this->lookAt.z) * percent); } return true; } return false; } //move the distance bool edk::Camera3D::moveDistance(edk::float32 distance){ return this->setDistance(this->getDistance()+distance); } //return the angle width and height edk::float32 edk::Camera3D::getAngleX(){ if(this->firstPerson){ return edk::Math::getAngle2f(this->lookAt.x-this->position.x,this->lookAt.z-this->position.z); } return edk::Math::getAngle2f(this->position.x-this->lookAt.x,this->position.z-this->lookAt.z); } edk::float32 edk::Camera3D::getAngleY(){ if(this->firstPerson){ return edk::Math::getAngle2f(edk::Math::pythagoras2f(this->lookAt.x-this->position.x,this->lookAt.z-this->position.z),this->lookAt.y-this->position.y); } return edk::Math::getAngle2f(edk::Math::pythagoras2f(this->position.x-this->lookAt.x,this->position.z-this->lookAt.z),this->position.y-this->lookAt.y); } //set the angles void edk::Camera3D::setAngleX(edk::float32 angle){ if(this->firstPerson){ edk::float32 distance = edk::Math::pythagoras2f(this->lookAt.x - this->position.x,this->lookAt.z - this->position.z); this->lookAt.x = edk::Math::rotateXFloat(distance,angle) + this->position.x; this->lookAt.z = edk::Math::rotateYFloat(distance,angle) + this->position.z; } else{ edk::float32 distance = edk::Math::pythagoras2f(this->position.x - this->lookAt.x,this->position.z - this->lookAt.z); this->position.x = edk::Math::rotateXFloat(distance,angle) + this->lookAt.x; this->position.z = edk::Math::rotateYFloat(distance,angle) + this->lookAt.z; } } void edk::Camera3D::setAngleY(edk::float32 angle){ if(this->firstPerson){ edk::float32 angleX = this->getAngleX(); edk::float32 distanceX = edk::Math::pythagoras2f(this->lookAt.x - this->position.x,this->lookAt.z - this->position.z); edk::float32 distanceY = edk::Math::pythagoras2f(distanceX,this->lookAt.y - this->position.y); // distanceX = edk::Math::rotateXFloat(distanceY,angle) + this->position.x; this->lookAt.y = edk::Math::rotateYFloat(distanceY,angle) + this->position.z; // this->lookAt.x = edk::Math::rotateXFloat(distanceX,angleX) + this->position.x; this->lookAt.z = edk::Math::rotateYFloat(distanceX,angleX) + this->position.z; } else{ edk::float32 angleX = this->getAngleX(); edk::float32 distanceX = edk::Math::pythagoras2f(this->position.x - this->lookAt.x,this->position.z - this->lookAt.z); edk::float32 distanceY = edk::Math::pythagoras2f(distanceX,this->position.y - this->lookAt.y); // distanceX = edk::Math::rotateXFloat(distanceY,angle) + this->lookAt.x; this->position.y = edk::Math::rotateYFloat(distanceY,angle) + this->lookAt.z; // this->position.x = edk::Math::rotateXFloat(distanceX,angleX) + this->lookAt.x; this->position.z = edk::Math::rotateYFloat(distanceX,angleX) + this->lookAt.z; } } //move the angles void edk::Camera3D::moveAngleX(edk::float32 angle){ this->setAngleX(angle + this->getAngleX()); } void edk::Camera3D::moveAngleY(edk::float32 angle){ this->setAngleY(angle + this->getAngleY()); } //draw the camera void edk::Camera3D::draw(){ // //test if are NOT using GUmodelview if(!edk::GU::guUsingMatrix(GU_PROJECTION)) //then set to use modelView edk::GU::guUseMatrix(GU_PROJECTION); edk::GU::guLoadIdentity(); // edk::Camera3D::drawAxisOnly(); } void edk::Camera3D::drawAxisOnly(){ if(this->perspective){ edk::GU::guUsePerspective(this->size.height*2.f,this->sizePercent,this->near,this->far); } else{ edk::GU::guUseOrtho(-this->size.width, this->size.width, -this->size.height, this->size.height, this->near,//nea this->far//far ); } /* //update the shaking animations this->animAngle.updateClockAnimation(); if(this->animAngle.isPlaying()){ //calculate the angle of shaking this->up = edk::Math::rotate2f(edk::vec2f32(1,0),(((this->angle + this->animAngle.getClockX())*-1)+360.f)+90); } else{ this->up = edk::Math::rotate2f(edk::vec2f32(1,0),((this->angle*-1)+360.f)+90); } */ //shake position /* this->animPosition.updateClockAnimation(); if(this->animPosition.isPlaying()){ this->tempPosition.x = this->position.x+this->animPosition.getClockX(); this->tempPosition.y = this->position.y+this->animPosition.getClockY(); edk::GU::guLookAt(this->tempPosition.x,this->tempPosition.y,1.f, this->tempPosition.x,this->tempPosition.y,0.f, this->up.x,this->up.y,0.f ); } else{ edk::GU::guLookAt(this->position.x,this->position.y,1.f, this->position.x,this->position.y,0.f, this->up.x,this->up.y,0.f ); } */ edk::GU::guLookAt(this->position.x,this->position.y,this->position.z, this->lookAt.x,this->lookAt.y,this->lookAt.z, this->up.x,this->up.y,this->up.z ); } void edk::Camera3D::drawAxisOnly(edk::float32 seconds){ // } //operator to copy the cameras bool edk::Camera3D::cloneFrom(edk::Camera3D* cam){ if(cam){ this->position = cam->position; this->lookAt = cam->lookAt; this->perspective = cam->perspective; this->up = cam->up; this->size = cam->size; this->sizePercent = cam->sizePercent; this->near = cam->near; this->far = cam->far; this->firstPerson = cam->firstPerson; return true; } return false; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/parsers/AbstractDOMParser.hpp> #include <xercesc/dom/DOMImplementation.hpp> #include <xercesc/dom/DOMImplementationLS.hpp> #include <xercesc/dom/DOMImplementationRegistry.hpp> #include <xercesc/dom/DOMBuilder.hpp> #include <xercesc/dom/DOMException.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMNodeList.hpp> #include <xercesc/dom/DOMError.hpp> #include <xercesc/dom/DOMLocator.hpp> #include "DOMCount.hpp" #include <string.h> #include <stdlib.h> #include <fstream.h> // --------------------------------------------------------------------------- // This is a simple program which invokes the DOMParser to build a DOM // tree for the specified input file. It then walks the tree and counts // the number of elements. The element count is then printed. // --------------------------------------------------------------------------- static void usage() { cout << "\nUsage:\n" " DOMCount [options] <XML file | List file>\n\n" "This program invokes the DOMBuilder, builds the DOM tree,\n" "and then prints the number of elements found in each XML file.\n\n" "Options:\n" " -l Indicate the input file is a List File that has a list of xml files.\n" " Default to off (Input file is an XML file).\n" " -v=xxx Validation scheme [always | never | auto*].\n" " -n Enable namespace processing. Defaults to off.\n" " -s Enable schema processing. Defaults to off.\n" " -f Enable full schema constraint checking. Defaults to off.\n" " -locale=ll_CC specify the locale, default: en_US.\n" " -? Show this help.\n\n" " * = Default if not provided explicitly.\n" << endl; } // --------------------------------------------------------------------------- // // Recursively Count up the total number of child Elements under the specified Node. // // --------------------------------------------------------------------------- static int countChildElements(DOMNode *n) { DOMNode *child; int count = 0; if (n) { if (n->getNodeType() == DOMNode::ELEMENT_NODE) count++; for (child = n->getFirstChild(); child != 0; child=child->getNextSibling()) count += countChildElements(child); } return count; } // --------------------------------------------------------------------------- // // main // // --------------------------------------------------------------------------- int main(int argC, char* argV[]) { // Check command line and extract arguments. if (argC < 2) { usage(); return 1; } const char* xmlFile = 0; AbstractDOMParser::ValSchemes valScheme = AbstractDOMParser::Val_Auto; bool doNamespaces = false; bool doSchema = false; bool schemaFullChecking = false; bool doList = false; bool errorOccurred = false; bool recognizeNEL = false; char localeStr[64]; memset(localeStr, 0, sizeof localeStr); int argInd; for (argInd = 1; argInd < argC; argInd++) { // Break out on first parm not starting with a dash if (argV[argInd][0] != '-') break; // Watch for special case help request if (!strcmp(argV[argInd], "-?")) { usage(); return 2; } else if (!strncmp(argV[argInd], "-v=", 3) || !strncmp(argV[argInd], "-V=", 3)) { const char* const parm = &argV[argInd][3]; if (!strcmp(parm, "never")) valScheme = AbstractDOMParser::Val_Never; else if (!strcmp(parm, "auto")) valScheme = AbstractDOMParser::Val_Auto; else if (!strcmp(parm, "always")) valScheme = AbstractDOMParser::Val_Always; else { cerr << "Unknown -v= value: " << parm << endl; return 2; } } else if (!strcmp(argV[argInd], "-n") || !strcmp(argV[argInd], "-N")) { doNamespaces = true; } else if (!strcmp(argV[argInd], "-s") || !strcmp(argV[argInd], "-S")) { doSchema = true; } else if (!strcmp(argV[argInd], "-f") || !strcmp(argV[argInd], "-F")) { schemaFullChecking = true; } else if (!strcmp(argV[argInd], "-l") || !strcmp(argV[argInd], "-L")) { doList = true; } else if (!strcmp(argV[argInd], "-special:nel")) { // turning this on will lead to non-standard compliance behaviour // it will recognize the unicode character 0x85 as new line character // instead of regular character as specified in XML 1.0 // do not turn this on unless really necessary recognizeNEL = true; } else if (!strncmp(argV[argInd], "-locale=", 8)) { // Get out the end of line strcpy(localeStr, &(argV[argInd][8])); } else { cerr << "Unknown option '" << argV[argInd] << "', ignoring it\n" << endl; } } // // There should be only one and only one parameter left, and that // should be the file name. // if (argInd != argC - 1) { usage(); return 1; } // Initialize the XML4C system try { if (strlen(localeStr)) { XMLPlatformUtils::Initialize(localeStr); } else { XMLPlatformUtils::Initialize(); } if (recognizeNEL) { XMLPlatformUtils::recognizeNEL(recognizeNEL); } } catch (const XMLException& toCatch) { cerr << "Error during initialization! :\n" << StrX(toCatch.getMessage()) << endl; return 1; } // Instantiate the DOM parser. static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull }; DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS); DOMBuilder *parser = ((DOMImplementationLS*)impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0); parser->setFeature(XMLUni::fgDOMNamespaces, doNamespaces); parser->setFeature(XMLUni::fgXercesSchema, doSchema); parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking); if (valScheme == AbstractDOMParser::Val_Auto) { parser->setFeature(XMLUni::fgDOMValidateIfSchema, true); } else if (valScheme == AbstractDOMParser::Val_Never) { parser->setFeature(XMLUni::fgDOMValidation, false); } else if (valScheme == AbstractDOMParser::Val_Always) { parser->setFeature(XMLUni::fgDOMValidation, true); } // enable datatype normalization - default is off parser->setFeature(XMLUni::fgDOMDatatypeNormalization, true); // And create our error handler and install it DOMCountErrorHandler errorHandler; parser->setErrorHandler(&errorHandler); // // Get the starting time and kick off the parse of the indicated // file. Catch any exceptions that might propogate out of it. // unsigned long duration; bool more = true; ifstream fin; // the input is a list file if (doList) fin.open(argV[argInd]); if (fin.fail()) { cerr <<"Cannot open the list file: " << argV[argInd] << endl; return 2; } while (more) { char fURI[1000]; //initialize the array to zeros memset(fURI,0,sizeof(fURI)); if (doList) { if (! fin.eof() ) { fin.getline (fURI, sizeof(fURI)); if (!*fURI) continue; else { xmlFile = fURI; cerr << "==Parsing== " << xmlFile << endl; } } else break; } else { xmlFile = argV[argInd]; more = false; } //reset error count first errorHandler.resetErrors(); DOMDocument *doc = 0; try { // reset document pool parser->resetDocumentPool(); const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis(); doc = parser->parseURI(xmlFile); const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis(); duration = endMillis - startMillis; } catch (const XMLException& toCatch) { cerr << "\nError during parsing: '" << xmlFile << "'\n" << "Exception message is: \n" << StrX(toCatch.getMessage()) << "\n" << endl; errorOccurred = true; continue; } catch (const DOMException& toCatch) { const unsigned int maxChars = 2047; XMLCh errText[maxChars + 1]; cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n" << "DOMException code is: " << toCatch.code << endl; if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars)) cerr << "Message is: " << StrX(errText) << endl; errorOccurred = true; continue; } catch (...) { cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n"; errorOccurred = true; continue; } // // Extract the DOM tree, get the list of all the elements and report the // length as the count of elements. // if (errorHandler.getSawErrors()) { cout << "\nErrors occurred, no output available\n" << endl; errorOccurred = true; } else { unsigned int elementCount = 0; if (doc) { elementCount = countChildElements((DOMNode*)doc->getDocumentElement()); // test getElementsByTagName and getLength XMLCh xa[] = {chAsterisk, chNull}; if (elementCount != doc->getElementsByTagName(xa)->getLength()) { cout << "\nErrors occurred, element count is wrong\n" << endl; errorOccurred = true; } } // Print out the stats that we collected and time taken. cout << xmlFile << ": " << duration << " ms (" << elementCount << " elems)." << endl; } } // // Delete the parser itself. Must be done prior to calling Terminate, below. // parser->release(); // And call the termination method XMLPlatformUtils::Terminate(); if (doList) fin.close(); if (errorOccurred) return 4; else return 0; } DOMCountErrorHandler::DOMCountErrorHandler() : fSawErrors(false) { } DOMCountErrorHandler::~DOMCountErrorHandler() { } // --------------------------------------------------------------------------- // DOMCountHandlers: Overrides of the DOM ErrorHandler interface // --------------------------------------------------------------------------- bool DOMCountErrorHandler::handleError(const DOMError& domError) { fSawErrors = true; if (domError.getSeverity() == DOMError::DOM_SEVERITY_WARNING) cerr << "\nWarning at file "; else if (domError.getSeverity() == DOMError::DOM_SEVERITY_ERROR) cerr << "\nError at file "; else cerr << "\nFatal Error at file "; cerr << StrX(domError.getLocation()->getURI()) << ", line " << domError.getLocation()->getLineNumber() << ", char " << domError.getLocation()->getColumnNumber() << "\n Message: " << StrX(domError.getMessage()) << endl; return false; } void DOMCountErrorHandler::resetErrors() { fSawErrors = false; } <commit_msg>[Bug 14955] error validating parser<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/parsers/AbstractDOMParser.hpp> #include <xercesc/dom/DOMImplementation.hpp> #include <xercesc/dom/DOMImplementationLS.hpp> #include <xercesc/dom/DOMImplementationRegistry.hpp> #include <xercesc/dom/DOMBuilder.hpp> #include <xercesc/dom/DOMException.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMNodeList.hpp> #include <xercesc/dom/DOMError.hpp> #include <xercesc/dom/DOMLocator.hpp> #include "DOMCount.hpp" #include <string.h> #include <stdlib.h> #include <fstream.h> // --------------------------------------------------------------------------- // This is a simple program which invokes the DOMParser to build a DOM // tree for the specified input file. It then walks the tree and counts // the number of elements. The element count is then printed. // --------------------------------------------------------------------------- static void usage() { cout << "\nUsage:\n" " DOMCount [options] <XML file | List file>\n\n" "This program invokes the DOMBuilder, builds the DOM tree,\n" "and then prints the number of elements found in each XML file.\n\n" "Options:\n" " -l Indicate the input file is a List File that has a list of xml files.\n" " Default to off (Input file is an XML file).\n" " -v=xxx Validation scheme [always | never | auto*].\n" " -n Enable namespace processing. Defaults to off.\n" " -s Enable schema processing. Defaults to off.\n" " -f Enable full schema constraint checking. Defaults to off.\n" " -locale=ll_CC specify the locale, default: en_US.\n" " -? Show this help.\n\n" " * = Default if not provided explicitly.\n" << endl; } // --------------------------------------------------------------------------- // // Recursively Count up the total number of child Elements under the specified Node. // // --------------------------------------------------------------------------- static int countChildElements(DOMNode *n) { DOMNode *child; int count = 0; if (n) { if (n->getNodeType() == DOMNode::ELEMENT_NODE) count++; for (child = n->getFirstChild(); child != 0; child=child->getNextSibling()) count += countChildElements(child); } return count; } // --------------------------------------------------------------------------- // // main // // --------------------------------------------------------------------------- int main(int argC, char* argV[]) { // Check command line and extract arguments. if (argC < 2) { usage(); return 1; } const char* xmlFile = 0; AbstractDOMParser::ValSchemes valScheme = AbstractDOMParser::Val_Auto; bool doNamespaces = false; bool doSchema = false; bool schemaFullChecking = false; bool doList = false; bool errorOccurred = false; bool recognizeNEL = false; char localeStr[64]; memset(localeStr, 0, sizeof localeStr); int argInd; for (argInd = 1; argInd < argC; argInd++) { // Break out on first parm not starting with a dash if (argV[argInd][0] != '-') break; // Watch for special case help request if (!strcmp(argV[argInd], "-?")) { usage(); return 2; } else if (!strncmp(argV[argInd], "-v=", 3) || !strncmp(argV[argInd], "-V=", 3)) { const char* const parm = &argV[argInd][3]; if (!strcmp(parm, "never")) valScheme = AbstractDOMParser::Val_Never; else if (!strcmp(parm, "auto")) valScheme = AbstractDOMParser::Val_Auto; else if (!strcmp(parm, "always")) valScheme = AbstractDOMParser::Val_Always; else { cerr << "Unknown -v= value: " << parm << endl; return 2; } } else if (!strcmp(argV[argInd], "-n") || !strcmp(argV[argInd], "-N")) { doNamespaces = true; } else if (!strcmp(argV[argInd], "-s") || !strcmp(argV[argInd], "-S")) { doSchema = true; } else if (!strcmp(argV[argInd], "-f") || !strcmp(argV[argInd], "-F")) { schemaFullChecking = true; } else if (!strcmp(argV[argInd], "-l") || !strcmp(argV[argInd], "-L")) { doList = true; } else if (!strcmp(argV[argInd], "-special:nel")) { // turning this on will lead to non-standard compliance behaviour // it will recognize the unicode character 0x85 as new line character // instead of regular character as specified in XML 1.0 // do not turn this on unless really necessary recognizeNEL = true; } else if (!strncmp(argV[argInd], "-locale=", 8)) { // Get out the end of line strcpy(localeStr, &(argV[argInd][8])); } else { cerr << "Unknown option '" << argV[argInd] << "', ignoring it\n" << endl; } } // // There should be only one and only one parameter left, and that // should be the file name. // if (argInd != argC - 1) { usage(); return 1; } // Initialize the XML4C system try { if (strlen(localeStr)) { XMLPlatformUtils::Initialize(localeStr); } else { XMLPlatformUtils::Initialize(); } if (recognizeNEL) { XMLPlatformUtils::recognizeNEL(recognizeNEL); } } catch (const XMLException& toCatch) { cerr << "Error during initialization! :\n" << StrX(toCatch.getMessage()) << endl; return 1; } // Instantiate the DOM parser. static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull }; DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS); DOMBuilder *parser = ((DOMImplementationLS*)impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0); parser->setFeature(XMLUni::fgDOMNamespaces, doNamespaces); parser->setFeature(XMLUni::fgXercesSchema, doSchema); parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking); if (valScheme == AbstractDOMParser::Val_Auto) { parser->setFeature(XMLUni::fgDOMValidateIfSchema, true); } else if (valScheme == AbstractDOMParser::Val_Never) { parser->setFeature(XMLUni::fgDOMValidation, false); } else if (valScheme == AbstractDOMParser::Val_Always) { parser->setFeature(XMLUni::fgDOMValidation, true); } // enable datatype normalization - default is off parser->setFeature(XMLUni::fgDOMDatatypeNormalization, true); // And create our error handler and install it DOMCountErrorHandler errorHandler; parser->setErrorHandler(&errorHandler); // // Get the starting time and kick off the parse of the indicated // file. Catch any exceptions that might propogate out of it. // unsigned long duration; bool more = true; ifstream fin; // the input is a list file if (doList) fin.open(argV[argInd]); if (fin.fail()) { cerr <<"Cannot open the list file: " << argV[argInd] << endl; return 2; } while (more) { char fURI[1000]; //initialize the array to zeros memset(fURI,0,sizeof(fURI)); if (doList) { if (! fin.eof() ) { fin.getline (fURI, sizeof(fURI)); if (!*fURI) continue; else { xmlFile = fURI; cerr << "==Parsing== " << xmlFile << endl; } } else break; } else { xmlFile = argV[argInd]; more = false; } //reset error count first errorHandler.resetErrors(); DOMDocument *doc = 0; try { // reset document pool parser->resetDocumentPool(); const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis(); doc = parser->parseURI(xmlFile); const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis(); duration = endMillis - startMillis; } catch (const XMLException& toCatch) { cerr << "\nError during parsing: '" << xmlFile << "'\n" << "Exception message is: \n" << StrX(toCatch.getMessage()) << "\n" << endl; errorOccurred = true; continue; } catch (const DOMException& toCatch) { const unsigned int maxChars = 2047; XMLCh errText[maxChars + 1]; cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n" << "DOMException code is: " << toCatch.code << endl; if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars)) cerr << "Message is: " << StrX(errText) << endl; errorOccurred = true; continue; } catch (...) { cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n"; errorOccurred = true; continue; } // // Extract the DOM tree, get the list of all the elements and report the // length as the count of elements. // if (errorHandler.getSawErrors()) { cout << "\nErrors occurred, no output available\n" << endl; errorOccurred = true; } else { unsigned int elementCount = 0; if (doc) { elementCount = countChildElements((DOMNode*)doc->getDocumentElement()); // test getElementsByTagName and getLength XMLCh xa[] = {chAsterisk, chNull}; if (elementCount != doc->getElementsByTagName(xa)->getLength()) { cout << "\nErrors occurred, element count is wrong\n" << endl; errorOccurred = true; } } // Print out the stats that we collected and time taken. cout << xmlFile << ": " << duration << " ms (" << elementCount << " elems)." << endl; } } // // Delete the parser itself. Must be done prior to calling Terminate, below. // parser->release(); // And call the termination method XMLPlatformUtils::Terminate(); if (doList) fin.close(); if (errorOccurred) return 4; else return 0; } DOMCountErrorHandler::DOMCountErrorHandler() : fSawErrors(false) { } DOMCountErrorHandler::~DOMCountErrorHandler() { } // --------------------------------------------------------------------------- // DOMCountHandlers: Overrides of the DOM ErrorHandler interface // --------------------------------------------------------------------------- bool DOMCountErrorHandler::handleError(const DOMError& domError) { fSawErrors = true; if (domError.getSeverity() == DOMError::DOM_SEVERITY_WARNING) cerr << "\nWarning at file "; else if (domError.getSeverity() == DOMError::DOM_SEVERITY_ERROR) cerr << "\nError at file "; else cerr << "\nFatal Error at file "; cerr << StrX(domError.getLocation()->getURI()) << ", line " << domError.getLocation()->getLineNumber() << ", char " << domError.getLocation()->getColumnNumber() << "\n Message: " << StrX(domError.getMessage()) << endl; return true; } void DOMCountErrorHandler::resetErrors() { fSawErrors = false; } <|endoftext|>
<commit_before>#include "ActorManager.h" #include "../components/MeshComponent.h" #include "../components/RenderComponent.h" #include "../components/TransformComponent.h" ActorManager::ActorManager() : nextActorID(0), actorXML(nullptr) { this->componentFactory.registerType<MeshComponent>(MeshComponent::componentName); this->componentFactory.registerType<RenderComponent>(RenderComponent::componentName); this->componentFactory.registerType<TransformComponent>(TransformComponent::componentName); } int ActorManager::createActor(const std::string actorPath) { if (!this->actorXML) { this->actorXML = new XMLDocument(); } else { assert("How did we come here?" || false); this->actorXML->Clear(); } this->actorXML->LoadFile(actorPath.c_str()); XMLElement* actorDescription = actorXML->RootElement(); if (actorDescription == nullptr) { printf("Could not find resource: %s\n", actorPath); } return createActor(actorDescription); } int ActorManager::createActor(XMLElement* actorDescriptionRoot) { std::shared_ptr<Actor> actor = std::make_shared<Actor>(this->getNextActorID()); const char* type = actorDescriptionRoot->Attribute("type"); if (!type) { printf("Actor type not specified: Abort actor creation!\n"); return 0; } actor->setActorName(type); // Add components from xml (if it exists a constructor for it) for (XMLElement* node = actorDescriptionRoot->FirstChildElement(); node; node = node->NextSiblingElement()) { std::string name = node->Value(); std::shared_ptr<ActorComponent> component = this->componentFactory.createComponent(name); if (component) { // Add component and set ownership, if it successfully initializes if (component->preInit(node)) { actor->addComponent(name, component); component->owner = actor; } else { printf("ActorComponent \"%s\" in \"%s\" failed to do pre-initialization, and will not be added.\n", name.c_str(), type); } } else { printf("ActorComponent \"%s\" not loaded in Actor \"%s\".\n", name.c_str(), type); } } // execute dependancy injection (let components get pointers to other components) for (auto& component : actor->components) { if (component.second->dependancyInjection() == false) { printf("Dependancy injection failed for %s. Actor creation aborted!\n", type); return 0; } } // now all components should be ready, so we can initialize them for (auto& component : actor->components) { component.second->init(); } // now we are finished with the XMLDocument and can safely delete it delete this->actorXML; return 0; } const int ActorManager::getNextActorID() { int id = this->nextActorID; this->nextActorID += 1; return id; }<commit_msg>Fixed a bug where the member variable actorXML was deleted but not set to nullptr. Caused unwanted behaviour.<commit_after>#include "ActorManager.h" #include "../components/MeshComponent.h" #include "../components/RenderComponent.h" #include "../components/TransformComponent.h" ActorManager::ActorManager() : nextActorID(0), actorXML(nullptr) { this->componentFactory.registerType<MeshComponent>(MeshComponent::componentName); this->componentFactory.registerType<RenderComponent>(RenderComponent::componentName); this->componentFactory.registerType<TransformComponent>(TransformComponent::componentName); } int ActorManager::createActor(const std::string actorPath) { if (!this->actorXML) { this->actorXML = new XMLDocument(); } else { assert("How did we come here?" || false); this->actorXML->Clear(); } this->actorXML->LoadFile(actorPath.c_str()); XMLElement* actorDescription = actorXML->RootElement(); if (actorDescription == nullptr) { printf("Could not find resource: %s\n", actorPath); } return createActor(actorDescription); } int ActorManager::createActor(XMLElement* actorDescriptionRoot) { std::shared_ptr<Actor> actor = std::make_shared<Actor>(this->getNextActorID()); const char* type = actorDescriptionRoot->Attribute("type"); if (!type) { printf("Actor type not specified: Abort actor creation!\n"); return 0; } actor->setActorName(type); // Add components from xml (if it exists a constructor for it) for (XMLElement* node = actorDescriptionRoot->FirstChildElement(); node; node = node->NextSiblingElement()) { std::string name = node->Value(); std::shared_ptr<ActorComponent> component = this->componentFactory.createComponent(name); if (component) { // Add component and set ownership, if it successfully initializes if (component->preInit(node)) { actor->addComponent(name, component); component->owner = actor; } else { printf("ActorComponent \"%s\" in \"%s\" failed to do pre-initialization, and will not be added.\n", name.c_str(), type); } } else { printf("ActorComponent \"%s\" not loaded in Actor \"%s\".\n", name.c_str(), type); } } // execute dependancy injection (let components get pointers to other components) for (auto& component : actor->components) { if (component.second->dependancyInjection() == false) { printf("Dependancy injection failed for %s. Actor creation aborted!\n", type); return 0; } } // now all components should be ready, so we can initialize them for (auto& component : actor->components) { component.second->init(); } // now we are finished with the XMLDocument and can safely delete it delete this->actorXML; this->actorXML = nullptr; return 0; } const int ActorManager::getNextActorID() { int id = this->nextActorID; this->nextActorID += 1; return id; }<|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <numeric> #include <unordered_map> #include <unordered_set> #include "cpp_utils/assert.hpp" #include "summary.hpp" #include "console.hpp" #include "accounts.hpp" #include "compute.hpp" #include "expenses.hpp" #include "earnings.hpp" #include "budget_exception.hpp" #include "config.hpp" using namespace budget; namespace { void month_overview(budget::month month, budget::year year) { // First display overview of the accounts std::vector<std::string> columns; std::vector<std::vector<std::string>> contents; auto sm = start_month(year); columns.push_back("Account"); columns.push_back("Expenses"); columns.push_back("Earnings"); columns.push_back("Balance"); columns.push_back("Local"); std::unordered_map<std::string, budget::money> account_previous; //Fill the table budget::money tot_expenses; budget::money tot_earnings; budget::money tot_balance; budget::money tot_local; for (unsigned short i = sm; i <= month; ++i) { budget::month m = i; for (auto& account : all_accounts(year, m)) { auto total_expenses = accumulate_amount_if(all_expenses(), [account, year, m](budget::expense& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; }); auto total_earnings = accumulate_amount_if(all_earnings(), [account, year, m](budget::earning& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; }); auto balance = account_previous[account.name] + account.amount - total_expenses + total_earnings; auto local_balance = account.amount - total_expenses + total_earnings; if (i == month) { contents.push_back({account.name}); contents.back().push_back(format_money(total_expenses)); contents.back().push_back(format_money(total_earnings)); contents.back().push_back(format_money(balance)); contents.back().push_back(format_money(local_balance)); tot_expenses += total_expenses; tot_earnings += total_earnings; tot_balance += balance; tot_expenses += local_balance; } account_previous[account.name] = balance; } } display_table(columns, contents); } void month_overview(budget::month m) { month_overview(m, local_day().year()); } void month_overview() { month_overview(local_day().month(), local_day().year()); } } // end of anonymous namespace constexpr const std::array<std::pair<const char*, const char*>, 1> budget::module_traits<budget::summary_module>::aliases; void budget::summary_module::load() { load_accounts(); load_expenses(); load_earnings(); } void budget::summary_module::handle(std::vector<std::string>& args) { if (all_accounts().empty()) { throw budget_exception("No accounts defined, you should start by defining some of them"); } if (args.empty() || args.size() == 1) { month_overview(); } else { auto& subcommand = args[1]; if (subcommand == "month") { auto today = local_day(); if (args.size() == 2) { month_overview(); } else if (args.size() == 3) { auto m = budget::month(to_number<unsigned short>(args[2])); if (m > today.month()) { throw budget_exception("Cannot compute the summary of the future"); } month_overview(m); } else if (args.size() == 4) { auto m = budget::month(to_number<unsigned short>(args[2])); auto y = budget::year(to_number<unsigned short>(args[3])); if (y > today.year()) { throw budget_exception("Cannot compute the summary of the future"); } if (y == today.year() && m > today.month()) { throw budget_exception("Cannot compute the summary of the future"); } month_overview(m, y); } else { throw budget_exception("Too many arguments to overview month"); } } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } <commit_msg>Refactor<commit_after>//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <numeric> #include <unordered_map> #include <unordered_set> #include "cpp_utils/assert.hpp" #include "summary.hpp" #include "console.hpp" #include "accounts.hpp" #include "compute.hpp" #include "expenses.hpp" #include "earnings.hpp" #include "budget_exception.hpp" #include "config.hpp" using namespace budget; namespace { std::string account_summary(budget::month month, budget::year year){ std::vector<std::string> columns; std::vector<std::vector<std::string>> contents; auto sm = start_month(year); columns.push_back("Account"); columns.push_back("Expenses"); columns.push_back("Earnings"); columns.push_back("Balance"); columns.push_back("Local"); std::unordered_map<std::string, budget::money> account_previous; //Fill the table budget::money tot_expenses; budget::money tot_earnings; budget::money tot_balance; budget::money tot_local; for (unsigned short i = sm; i <= month; ++i) { budget::month m = i; for (auto& account : all_accounts(year, m)) { auto total_expenses = accumulate_amount_if(all_expenses(), [account, year, m](budget::expense& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; }); auto total_earnings = accumulate_amount_if(all_earnings(), [account, year, m](budget::earning& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; }); auto balance = account_previous[account.name] + account.amount - total_expenses + total_earnings; auto local_balance = account.amount - total_expenses + total_earnings; if (i == month) { contents.push_back({account.name}); contents.back().push_back(format_money(total_expenses)); contents.back().push_back(format_money(total_earnings)); contents.back().push_back(format_money(balance)); contents.back().push_back(format_money(local_balance)); tot_expenses += total_expenses; tot_earnings += total_earnings; tot_balance += balance; tot_expenses += local_balance; } account_previous[account.name] = balance; } } std::stringstream ss; display_table(ss, columns, contents); return ss.str(); } void month_overview(budget::month month, budget::year year) { // First display overview of the accounts auto m_summary = account_summary(month, year); std::cout << m_summary; } void month_overview(budget::month m) { month_overview(m, local_day().year()); } void month_overview() { month_overview(local_day().month(), local_day().year()); } } // end of anonymous namespace constexpr const std::array<std::pair<const char*, const char*>, 1> budget::module_traits<budget::summary_module>::aliases; void budget::summary_module::load() { load_accounts(); load_expenses(); load_earnings(); } void budget::summary_module::handle(std::vector<std::string>& args) { if (all_accounts().empty()) { throw budget_exception("No accounts defined, you should start by defining some of them"); } if (args.empty() || args.size() == 1) { month_overview(); } else { auto& subcommand = args[1]; if (subcommand == "month") { auto today = local_day(); if (args.size() == 2) { month_overview(); } else if (args.size() == 3) { auto m = budget::month(to_number<unsigned short>(args[2])); if (m > today.month()) { throw budget_exception("Cannot compute the summary of the future"); } month_overview(m); } else if (args.size() == 4) { auto m = budget::month(to_number<unsigned short>(args[2])); auto y = budget::year(to_number<unsigned short>(args[3])); if (y > today.year()) { throw budget_exception("Cannot compute the summary of the future"); } if (y == today.year() && m > today.month()) { throw budget_exception("Cannot compute the summary of the future"); } month_overview(m, y); } else { throw budget_exception("Too many arguments to overview month"); } } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } <|endoftext|>
<commit_before><commit_msg>Fixed bug with point lights using shadows.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef ROSETTASTONE_CARD_ENUMS_HPP #define ROSETTASTONE_CARD_ENUMS_HPP #include <string> #include <string_view> namespace RosettaStone { //! \brief An enumerator for identifying the class of the card. enum class CardClass { #define X(a) a, #include "CardClass.def" #undef X }; const std::string CARD_CLASS_STR[] = { #define X(a) #a, #include "CardClass.def" #undef X }; //! \brief An enumerator for identifying the set of the card. enum class CardSet { #define X(a) a, #include "CardSet.def" #undef X }; const std::string CARD_SET_STR[] = { #define X(a) #a, #include "CardSet.def" #undef X }; //! \brief An enumerator for identifying the type of the card. enum class CardType { #define X(a) a, #include "CardType.def" #undef X }; const std::string CARD_TYPE_STR[] = { #define X(a) #a, #include "CardType.def" #undef X }; //! \brief An enumerator for identifying the faction of the card. enum class Faction { #define X(a) a, #include "Faction.def" #undef X }; const std::string FACTION_STR[] = { #define X(a) #a, #include "Faction.def" #undef X }; //! \brief An enumerator for identifying the game tag of the card. enum class GameTag { #define X(a) a, #include "GameTag.def" #undef X }; const std::string GAME_TAG_STR[] = { #define X(a) #a, #include "GameTag.def" #undef X }; //! \brief An enumerator for identifying the play requirement of the card. enum class PlayReq { #define X(a) a, #include "PlayReq.def" #undef X }; const std::string PLAY_REQ_STR[] = { #define X(a) #a, #include "PlayReq.def" #undef X }; //! \brief An enumerator for identifying the race of the card. enum class Race { #define X(a) a, #include "Race.def" #undef X }; const std::string RACE_STR[] = { #define X(a) #a, #include "Race.def" #undef X }; //! \brief An enumerator for identifying the rarity of the card. enum class Rarity { #define X(a) a, #include "Rarity.def" #undef X }; const std::string RARITY_STR[] = { #define X(a) #a, #include "Rarity.def" #undef X }; //! \brief An enumerator for identifying the locale of the card. enum class Locale { UNKNOWN, enUS, enGB, frFR, deDE, koKR, esES, esMX, ruRU, zhTW, zhCN, itIT, ptBR, plPL, ptPT, jaJP, thTH }; //! \brief An enumerator for identifying the mulligan state. enum class Mulligan { INVALID, INPUT, DEALING, WAITING, DONE }; //! \brief An enumerator for identifying the choice type of the card. enum class ChoiceType { INVALID, MULLIGAN, GENERAL }; //! \brief An enumerator for identifying the format type of the card. enum class FormatType { UNKNOWN, WILD, STANDARD }; //! \brief An enumerator for identifying the play state. enum class PlayState { INVALID, PLAYING, WINNING, LOSING, WON, LOST, TIED, DISCONNECTED, CONCEDED }; //! \brief An enumerator for indicating the state of the card. enum class State { INVALID, LOADING, RUNNING, COMPLETE }; //! \brief An enumerator for indicating the game step. enum class Step { INVALID, BEGIN_FIRST, BEGIN_SHUFFLE, BEGIN_DRAW, BEGIN_MULLIGAN, MAIN_BEGIN, MAIN_READY, MAIN_RESOURCE, MAIN_DRAW, MAIN_START, MAIN_ACTION, MAIN_COMBAT, MAIN_END, MAIN_NEXT, FINAL_WRAPUP, FINAL_GAMEOVER, MAIN_CLEANUP, MAIN_START_TRIGGERS }; template <class T> T StrToEnum(const std::string_view&); template <class T> std::string_view EnumToStr(T); #define STR2ENUM(TYPE, ARRAY) \ template <> \ inline TYPE StrToEnum<TYPE>(const std::string_view& str) \ { \ for (std::size_t i = 0; i < (sizeof(ARRAY) / sizeof(ARRAY[0])); ++i) \ { \ if (ARRAY[i] == str) \ { \ return TYPE(i); \ } \ } \ \ return TYPE(0); \ } #define ENUM2STR(TYPE, ARRAY) \ template <> \ inline std::string_view EnumToStr<TYPE>(TYPE v) \ { \ return ARRAY[static_cast<int>(v)]; \ } #define ENUM_AND_STR(TYPE, ARRAY) \ STR2ENUM(TYPE, ARRAY) \ ENUM2STR(TYPE, ARRAY) ENUM_AND_STR(CardClass, CARD_CLASS_STR) ENUM_AND_STR(CardSet, CARD_SET_STR) ENUM_AND_STR(CardType, CARD_TYPE_STR) ENUM_AND_STR(Faction, FACTION_STR) ENUM_AND_STR(GameTag, GAME_TAG_STR) ENUM_AND_STR(PlayReq, PLAY_REQ_STR) ENUM_AND_STR(Race, RACE_STR) ENUM_AND_STR(Rarity, RARITY_STR) } // namespace RosettaStone #endif // ROSETTASTONE_CARD_ENUMS_HPP<commit_msg>refactor: Add enum 'Zone'<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef ROSETTASTONE_CARD_ENUMS_HPP #define ROSETTASTONE_CARD_ENUMS_HPP #include <string> #include <string_view> namespace RosettaStone { //! \brief An enumerator for identifying the class of the card. enum class CardClass { #define X(a) a, #include "CardClass.def" #undef X }; const std::string CARD_CLASS_STR[] = { #define X(a) #a, #include "CardClass.def" #undef X }; //! \brief An enumerator for identifying the set of the card. enum class CardSet { #define X(a) a, #include "CardSet.def" #undef X }; const std::string CARD_SET_STR[] = { #define X(a) #a, #include "CardSet.def" #undef X }; //! \brief An enumerator for identifying the type of the card. enum class CardType { #define X(a) a, #include "CardType.def" #undef X }; const std::string CARD_TYPE_STR[] = { #define X(a) #a, #include "CardType.def" #undef X }; //! \brief An enumerator for identifying the faction of the card. enum class Faction { #define X(a) a, #include "Faction.def" #undef X }; const std::string FACTION_STR[] = { #define X(a) #a, #include "Faction.def" #undef X }; //! \brief An enumerator for identifying the game tag of the card. enum class GameTag { #define X(a) a, #include "GameTag.def" #undef X }; const std::string GAME_TAG_STR[] = { #define X(a) #a, #include "GameTag.def" #undef X }; //! \brief An enumerator for identifying the play requirement of the card. enum class PlayReq { #define X(a) a, #include "PlayReq.def" #undef X }; const std::string PLAY_REQ_STR[] = { #define X(a) #a, #include "PlayReq.def" #undef X }; //! \brief An enumerator for identifying the race of the card. enum class Race { #define X(a) a, #include "Race.def" #undef X }; const std::string RACE_STR[] = { #define X(a) #a, #include "Race.def" #undef X }; //! \brief An enumerator for identifying the rarity of the card. enum class Rarity { #define X(a) a, #include "Rarity.def" #undef X }; const std::string RARITY_STR[] = { #define X(a) #a, #include "Rarity.def" #undef X }; //! \brief An enumerator for identifying the locale of the card. enum class Locale { UNKNOWN, enUS, enGB, frFR, deDE, koKR, esES, esMX, ruRU, zhTW, zhCN, itIT, ptBR, plPL, ptPT, jaJP, thTH }; //! \brief An enumerator for identifying the mulligan state. enum class Mulligan { INVALID, INPUT, DEALING, WAITING, DONE }; //! \brief An enumerator for identifying the choice type of the card. enum class ChoiceType { INVALID, MULLIGAN, GENERAL }; //! \brief An enumerator for identifying the format type of the card. enum class FormatType { UNKNOWN, WILD, STANDARD }; //! \brief An enumerator for identifying the play state. enum class PlayState { INVALID, PLAYING, WINNING, LOSING, WON, LOST, TIED, DISCONNECTED, CONCEDED }; //! \brief An enumerator for indicating the state of the card. enum class State { INVALID, LOADING, RUNNING, COMPLETE }; //! \brief An enumerator for indicating the game step. enum class Step { INVALID, BEGIN_FIRST, BEGIN_SHUFFLE, BEGIN_DRAW, BEGIN_MULLIGAN, MAIN_BEGIN, MAIN_READY, MAIN_RESOURCE, MAIN_DRAW, MAIN_START, MAIN_ACTION, MAIN_COMBAT, MAIN_END, MAIN_NEXT, FINAL_WRAPUP, FINAL_GAMEOVER, MAIN_CLEANUP, MAIN_START_TRIGGERS }; //! \brief An enumerator for indicating the game zone. enum class Zone { INVALID, PLAY, DECK, HAND, GRAVEYARD, REMOVEDFROMGAME, SETASIDE, SECRET }; template <class T> T StrToEnum(const std::string_view&); template <class T> std::string_view EnumToStr(T); #define STR2ENUM(TYPE, ARRAY) \ template <> \ inline TYPE StrToEnum<TYPE>(const std::string_view& str) \ { \ for (std::size_t i = 0; i < (sizeof(ARRAY) / sizeof(ARRAY[0])); ++i) \ { \ if (ARRAY[i] == str) \ { \ return TYPE(i); \ } \ } \ \ return TYPE(0); \ } #define ENUM2STR(TYPE, ARRAY) \ template <> \ inline std::string_view EnumToStr<TYPE>(TYPE v) \ { \ return ARRAY[static_cast<int>(v)]; \ } #define ENUM_AND_STR(TYPE, ARRAY) \ STR2ENUM(TYPE, ARRAY) \ ENUM2STR(TYPE, ARRAY) ENUM_AND_STR(CardClass, CARD_CLASS_STR) ENUM_AND_STR(CardSet, CARD_SET_STR) ENUM_AND_STR(CardType, CARD_TYPE_STR) ENUM_AND_STR(Faction, FACTION_STR) ENUM_AND_STR(GameTag, GAME_TAG_STR) ENUM_AND_STR(PlayReq, PLAY_REQ_STR) ENUM_AND_STR(Race, RACE_STR) ENUM_AND_STR(Rarity, RARITY_STR) } // namespace RosettaStone #endif // ROSETTASTONE_CARD_ENUMS_HPP<|endoftext|>
<commit_before>/************************************************* * SHA-160 Source File * * (C) 1999-2006 The Botan Project * *************************************************/ #include <botan/sha160.h> #include <botan/bit_ops.h> namespace Botan { namespace { /************************************************* * SHA-160 F1 Function * *************************************************/ inline void F1(u32bit A, u32bit& B, u32bit C, u32bit D, u32bit& E, u32bit msg) { E += (D ^ (B & (C ^ D))) + msg + 0x5A827999 + rotate_left(A, 5); B = rotate_left(B, 30); } /************************************************* * SHA-160 F2 Function * *************************************************/ inline void F2(u32bit A, u32bit& B, u32bit C, u32bit D, u32bit& E, u32bit msg) { E += (B ^ C ^ D) + msg + 0x6ED9EBA1 + rotate_left(A, 5); B = rotate_left(B, 30); } /************************************************* * SHA-160 F3 Function * *************************************************/ inline void F3(u32bit A, u32bit& B, u32bit C, u32bit D, u32bit& E, u32bit msg) { E += ((B & C) | ((B | C) & D)) + msg + 0x8F1BBCDC + rotate_left(A, 5); B = rotate_left(B, 30); } /************************************************* * SHA-160 F4 Function * *************************************************/ inline void F4(u32bit A, u32bit& B, u32bit C, u32bit D, u32bit& E, u32bit msg) { E += (B ^ C ^ D) + msg + 0xCA62C1D6 + rotate_left(A, 5); B = rotate_left(B, 30); } } extern "C" void sha160_core(u32bit[5], const byte[64], u32bit[80]); /************************************************* * SHA-160 Compression Function * *************************************************/ void SHA_160::hash(const byte input[]) { sha160_core(digest, input, W); } /************************************************* * Copy out the digest * *************************************************/ void SHA_160::copy_out(byte output[]) { for(u32bit j = 0; j != OUTPUT_LENGTH; ++j) output[j] = get_byte(j % 4, digest[j/4]); } /************************************************* * Clear memory of sensitive data * *************************************************/ void SHA_160::clear() throw() { MDx_HashFunction::clear(); digest[0] = 0x67452301; digest[1] = 0xEFCDAB89; digest[2] = 0x98BADCFE; digest[3] = 0x10325476; digest[4] = 0xC3D2E1F0; } } <commit_msg>Remove the C implementations of the round functions, no longer used<commit_after>/************************************************* * SHA-160 Source File * * (C) 1999-2006 The Botan Project * *************************************************/ #include <botan/sha160.h> #include <botan/bit_ops.h> namespace Botan { extern "C" void sha160_core(u32bit[5], const byte[64], u32bit[80]); /************************************************* * SHA-160 Compression Function * *************************************************/ void SHA_160::hash(const byte input[]) { sha160_core(digest, input, W); } /************************************************* * Copy out the digest * *************************************************/ void SHA_160::copy_out(byte output[]) { for(u32bit j = 0; j != OUTPUT_LENGTH; ++j) output[j] = get_byte(j % 4, digest[j/4]); } /************************************************* * Clear memory of sensitive data * *************************************************/ void SHA_160::clear() throw() { MDx_HashFunction::clear(); digest[0] = 0x67452301; digest[1] = 0xEFCDAB89; digest[2] = 0x98BADCFE; digest[3] = 0x10325476; digest[4] = 0xC3D2E1F0; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: anyrefdg.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:11: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 SC_ANYREFDG_HXX #define SC_ANYREFDG_HXX #ifndef _IMAGEBTN_HXX #include <vcl/imagebtn.hxx> #endif #ifndef _EDIT_HXX #include <vcl/edit.hxx> #endif #ifndef _ACCEL_HXX #include <vcl/accel.hxx> #endif #ifndef _BASEDLGS_HXX #include <sfx2/basedlgs.hxx> #endif class SfxObjectShell; class ScRange; class ScDocument; class ScTabViewShell; class ScAnyRefDlg; class ScRefButton; class ScFormulaCell; class ScCompiler; //============================================================================ class ScRefEdit : public Edit { private: Timer aTimer; ScAnyRefDlg* pAnyRefDlg; // parent dialog BOOL bSilentFocus; // for SilentGrabFocus() DECL_LINK( UpdateHdl, Timer* ); protected: virtual void KeyInput( const KeyEvent& rKEvt ); virtual void GetFocus(); virtual void LoseFocus(); public: ScRefEdit( ScAnyRefDlg* pParent, const ResId& rResId ); ScRefEdit( Window* pParent, const ResId& rResId ); virtual ~ScRefEdit(); void SetRefString( const XubString& rStr ); virtual void SetText( const XubString& rStr ); virtual void Modify(); void StartUpdateData(); void SilentGrabFocus(); // does not update any references void SetRefDialog( ScAnyRefDlg* pDlg ); inline ScAnyRefDlg* GetRefDialog() { return pAnyRefDlg; } }; //============================================================================ class ScRefButton : public ImageButton { private: Image aImgRefStart; /// Start reference input Image aImgRefStartHC; /// Start reference input (high contrast) Image aImgRefDone; /// Stop reference input Image aImgRefDoneHC; /// Stop reference input (high contrast) ScAnyRefDlg* pAnyRefDlg; // parent dialog ScRefEdit* pRefEdit; // zugeordnetes Edit-Control protected: virtual void Click(); virtual void KeyInput( const KeyEvent& rKEvt ); virtual void GetFocus(); virtual void LoseFocus(); public: ScRefButton( ScAnyRefDlg* pParent, const ResId& rResId, ScRefEdit* pEdit ); ScRefButton( Window* pParent, const ResId& rResId ); void SetReferences( ScAnyRefDlg* pDlg, ScRefEdit* pEdit ); void SetStartImage(); void SetEndImage(); inline void DoRef() { Click(); } }; //============================================================================ class ScAnyRefDlg : public SfxModelessDialog { friend class ScRefButton; friend class ScRefEdit; private: SfxBindings* pMyBindings; ScRefEdit* pRefEdit; // aktives Eingabefeld ScRefButton* pRefBtn; // Button dazu String sOldDialogText; // Originaltitel des Dialogfensters Size aOldDialogSize; // Originalgroesse Dialogfenster Point aOldEditPos; // Originalposition des Eingabefeldes Size aOldEditSize; // Originalgroesse des Eingabefeldes Point aOldButtonPos; // Originalpositiuon des Buttons BOOL* pHiddenMarks; // Merkfeld fuer versteckte Controls Accelerator* pAccel; // fuer Enter/Escape BOOL bAccInserted; BOOL bHighLightRef; BOOL bEnableColorRef; ScFormulaCell* pRefCell; ScCompiler* pRefComp; Window* pActiveWin; Timer aTimer; String aDocName; // document on which the dialog was opened DECL_LINK( UpdateFocusHdl, Timer* ); DECL_LINK( AccelSelectHdl, Accelerator* ); protected: BOOL DoClose( USHORT nId ); void EnableSpreadsheets( BOOL bFlag = TRUE, BOOL bChilds = TRUE ); void SetDispatcherLock( BOOL bLock ); virtual long PreNotify( NotifyEvent& rNEvt ); virtual void RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL ); virtual void RefInputDone( BOOL bForced = FALSE ); void ShowSimpleReference( const XubString& rStr ); void ShowFormulaReference( const XubString& rStr ); public: ScAnyRefDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, USHORT nResId); virtual ~ScAnyRefDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ) = 0; virtual void AddRefEntry(); virtual BOOL IsRefInputMode() const; virtual BOOL IsTableLocked() const; virtual BOOL IsDocAllowed( SfxObjectShell* pDocSh ) const; void ShowReference( const XubString& rStr ); void HideReference( BOOL bDoneRefMode = TRUE ); void ToggleCollapsed( ScRefEdit* pEdit, ScRefButton* pButton = NULL ); void ReleaseFocus( ScRefEdit* pEdit, ScRefButton* pButton = NULL ); void ViewShellChanged( ScTabViewShell* pScViewShell ); void SwitchToDocument(); SfxBindings& GetBindings(); virtual void SetActive() = 0; // virtual BOOL Close(); virtual void StateChanged( StateChangedType nStateChange ); }; //============================================================================ #endif // SC_ANYREFDG_HXX <commit_msg>INTEGRATION: CWS calcwarnings (1.8.324); FILE MERGED 2006/12/01 08:53:31 nn 1.8.324.1: #i69284# warning-free: ui, wntmsci10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: anyrefdg.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2007-02-27 13:19:30 $ * * 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 SC_ANYREFDG_HXX #define SC_ANYREFDG_HXX #ifndef _IMAGEBTN_HXX #include <vcl/imagebtn.hxx> #endif #ifndef _EDIT_HXX #include <vcl/edit.hxx> #endif #ifndef _ACCEL_HXX #include <vcl/accel.hxx> #endif #ifndef _BASEDLGS_HXX #include <sfx2/basedlgs.hxx> #endif class SfxObjectShell; class ScRange; class ScDocument; class ScTabViewShell; class ScAnyRefDlg; class ScRefButton; class ScFormulaCell; class ScCompiler; //============================================================================ class ScRefEdit : public Edit { private: Timer aTimer; ScAnyRefDlg* pAnyRefDlg; // parent dialog BOOL bSilentFocus; // for SilentGrabFocus() DECL_LINK( UpdateHdl, Timer* ); protected: virtual void KeyInput( const KeyEvent& rKEvt ); virtual void GetFocus(); virtual void LoseFocus(); public: ScRefEdit( ScAnyRefDlg* pParent, const ResId& rResId ); ScRefEdit( Window* pParent, const ResId& rResId ); virtual ~ScRefEdit(); void SetRefString( const XubString& rStr ); using Edit::SetText; virtual void SetText( const XubString& rStr ); virtual void Modify(); void StartUpdateData(); void SilentGrabFocus(); // does not update any references void SetRefDialog( ScAnyRefDlg* pDlg ); inline ScAnyRefDlg* GetRefDialog() { return pAnyRefDlg; } }; //============================================================================ class ScRefButton : public ImageButton { private: Image aImgRefStart; /// Start reference input Image aImgRefStartHC; /// Start reference input (high contrast) Image aImgRefDone; /// Stop reference input Image aImgRefDoneHC; /// Stop reference input (high contrast) ScAnyRefDlg* pAnyRefDlg; // parent dialog ScRefEdit* pRefEdit; // zugeordnetes Edit-Control protected: virtual void Click(); virtual void KeyInput( const KeyEvent& rKEvt ); virtual void GetFocus(); virtual void LoseFocus(); public: ScRefButton( ScAnyRefDlg* pParent, const ResId& rResId, ScRefEdit* pEdit ); ScRefButton( Window* pParent, const ResId& rResId ); void SetReferences( ScAnyRefDlg* pDlg, ScRefEdit* pEdit ); void SetStartImage(); void SetEndImage(); inline void DoRef() { Click(); } }; //============================================================================ class ScAnyRefDlg : public SfxModelessDialog { friend class ScRefButton; friend class ScRefEdit; private: SfxBindings* pMyBindings; ScRefEdit* pRefEdit; // aktives Eingabefeld ScRefButton* pRefBtn; // Button dazu String sOldDialogText; // Originaltitel des Dialogfensters Size aOldDialogSize; // Originalgroesse Dialogfenster Point aOldEditPos; // Originalposition des Eingabefeldes Size aOldEditSize; // Originalgroesse des Eingabefeldes Point aOldButtonPos; // Originalpositiuon des Buttons BOOL* pHiddenMarks; // Merkfeld fuer versteckte Controls Accelerator* pAccel; // fuer Enter/Escape BOOL bAccInserted; BOOL bHighLightRef; BOOL bEnableColorRef; ScFormulaCell* pRefCell; ScCompiler* pRefComp; Window* pActiveWin; Timer aTimer; String aDocName; // document on which the dialog was opened DECL_LINK( UpdateFocusHdl, Timer* ); DECL_LINK( AccelSelectHdl, Accelerator* ); protected: BOOL DoClose( USHORT nId ); void EnableSpreadsheets( BOOL bFlag = TRUE, BOOL bChilds = TRUE ); void SetDispatcherLock( BOOL bLock ); virtual long PreNotify( NotifyEvent& rNEvt ); virtual void RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL ); virtual void RefInputDone( BOOL bForced = FALSE ); void ShowSimpleReference( const XubString& rStr ); void ShowFormulaReference( const XubString& rStr ); public: ScAnyRefDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, USHORT nResId); virtual ~ScAnyRefDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ) = 0; virtual void AddRefEntry(); virtual BOOL IsRefInputMode() const; virtual BOOL IsTableLocked() const; virtual BOOL IsDocAllowed( SfxObjectShell* pDocSh ) const; void ShowReference( const XubString& rStr ); void HideReference( BOOL bDoneRefMode = TRUE ); void ToggleCollapsed( ScRefEdit* pEdit, ScRefButton* pButton = NULL ); void ReleaseFocus( ScRefEdit* pEdit, ScRefButton* pButton = NULL ); void ViewShellChanged( ScTabViewShell* pScViewShell ); void SwitchToDocument(); SfxBindings& GetBindings(); virtual void SetActive() = 0; // virtual BOOL Close(); virtual void StateChanged( StateChangedType nStateChange ); }; //============================================================================ #endif // SC_ANYREFDG_HXX <|endoftext|>
<commit_before>#include "gvki/Logger.h" #include "gvki/PathSeperator.h" #include <cstdlib> #include <cstdio> #include <cassert> #include <errno.h> #include <iostream> #include <iomanip> #include <sstream> #include "string.h" #include "gvki/Debug.h" #include <sys/stat.h> #ifndef _WIN32 #include <dirent.h> #include <unistd.h> #define MKDIR_FAILS(d) (mkdir(d, 0770) != 0) #define DIR_ALREADY_EXISTS (errno == EEXIST) static void checkDirectoryExists(const char* dirName) { DIR* dh = opendir(dirName); if (dh != NULL) { closedir(dh); return; } ERROR_MSG(strerror(errno) << ". Directory was :" << dirName); exit(1); } #else #include <inttypes.h> #include <Windows.h> #define MKDIR_FAILS(d) (CreateDirectory(ss.str().c_str(), NULL) == 0) #define DIR_ALREADY_EXISTS (GetLastError() == ERROR_ALREADY_EXISTS) static void checkDirectoryExists(const char* dirName) { DWORD ftyp = GetFileAttributesA(dirName); if ((ftyp != INVALID_FILE_ATTRIBUTES) && ftyp & FILE_ATTRIBUTE_DIRECTORY) return; ERROR_MSG(strerror(errno) << ". Directory was :" << dirName); exit(1); } #endif using namespace std; using namespace gvki; // Maximum number of files or directories // that can be created static const int maxFiles = 10000; Logger& Logger::Singleton() { static Logger l; return l; } Logger::Logger() { int count = 0; bool success= false; // FIXME: Reading from the environment probably doesn't belong in here // but it makes implementing the singleton a lot easier std::string directoryPrefix; const char* envTemp = getenv("GVKI_ROOT"); if (envTemp) { DEBUG_MSG("Using GVKI_ROOT value as destination for directories"); checkDirectoryExists(envTemp); directoryPrefix = envTemp; } else { // Use the current working directory DEBUG_MSG("Using current working directory as destination for directories"); // FIXME: Hard-coding this size is gross #define MAX_DIR_LENGTH 1024 #ifndef _WIN32 char cwdArray[MAX_DIR_LENGTH]; char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)/sizeof(char)); if (!cwdResult) #else char cwdResult[MAX_DIR_LENGTH]; if (GetCurrentDirectory(MAX_DIR_LENGTH, cwdResult) == 0) #endif { ERROR_MSG(strerror(errno) << ". Could not read the current working directory"); exit(1); } else directoryPrefix = cwdResult; } directoryPrefix += PATH_SEP "gvki"; DEBUG_MSG("Directory prefix is \"" << directoryPrefix << "\""); // Keep trying a directoryPrefix name with a number as suffix // until we find an available one or we exhaust the maximum // allowed number while (count < maxFiles) { stringstream ss; ss << directoryPrefix << "-" << count; ++count; // Make the directoryPrefix if (MKDIR_FAILS(ss.str().c_str())) { if (!DIR_ALREADY_EXISTS) { ERROR_MSG(strerror(errno) << ". Directory was :" << directoryPrefix); exit(1); } // It already exists, try again continue; } this->directory = ss.str(); success = true; break; } if (!success) { ERROR_MSG("Exhausted available directory names or couldn't create any"); exit(1); } DEBUG_MSG("Directory used for logging is \"" << this->directory << "\""); openLog(); } void Logger::openLog() { // FIXME: We should use mkstemp() or something std::stringstream ss; ss << directory << PATH_SEP << "log.json"; output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate); if (! output->good()) { ERROR_MSG("Failed to create file (" << ss.str() << ") to write log to"); exit(1); } // Start of JSON array *output << "[" << std::endl; } void Logger::closeLog() { // End of JSON array *output << std::endl << "]" << std::endl; output->close(); } Logger::~Logger() { closeLog(); delete output; } void Logger::dump(cl_kernel k) { // Output JSON format defined by // http://multicore.doc.ic.ac.uk/tools/GPUVerify/docs/json_format.html KernelInfo& ki = kernels[k]; static bool isFirst = true; if (!isFirst) { // Emit array element seperator // to seperate from previous dump *output << "," << endl; } isFirst = false; *output << "{" << endl << "\"language\": \"OpenCL\"," << endl; std::string kernelSourceFile = dumpKernelSource(ki); *output << "\"kernel_file\": \"" << kernelSourceFile << "\"," << endl; // FIXME: Teach GPUVerify how to handle non zero global_offset // FIXME: Document this json attribute! // Only emit global_offset if its non zero bool hasNonZeroGlobalOffset = false; for (int index=0; index < ki.globalWorkOffset.size() ; ++index) { if (ki.globalWorkOffset[index] != 0) hasNonZeroGlobalOffset = true; } if (hasNonZeroGlobalOffset) { *output << "\"global_offset\": "; printJSONArray(ki.globalWorkOffset); *output << "," << endl; } *output << "\"global_size\": "; printJSONArray(ki.globalWorkSize); *output << "," << endl; *output << "\"local_size\": "; printJSONArray(ki.localWorkSize); *output << "," << endl; assert( (ki.globalWorkOffset.size() == ki.globalWorkSize.size()) && (ki.globalWorkSize.size() == ki.localWorkSize.size()) && "dimension mismatch"); *output << "\"entry_point\": \"" << ki.entryPointName << "\""; // entry_point might be the last entry is there were no kernel args if (ki.arguments.size() == 0) *output << endl; else { *output << "," << endl << "\"kernel_arguments\": [ " << endl; for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex) { printJSONKernelArgumentInfo(ki.arguments[argIndex]); if (argIndex != (ki.arguments.size() -1)) *output << "," << endl; } *output << endl << "]" << endl; } *output << "}"; } void Logger::printJSONArray(std::vector<size_t>& array) { *output << "[ "; for (int index=0; index < array.size(); ++index) { *output << array[index]; if (index != (array.size() -1)) *output << ", "; } *output << "]"; } void Logger::printJSONKernelArgumentInfo(ArgInfo& ai) { *output << "{"; if (ai.argValue == NULL) { // NULL was passed to clSetKernelArg() // That implies its for unallocated memory *output << "\"type\": \"array\","; // If the arg is for local memory if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler)) { // We assume this means this arguments is for local memory // where size actually means the sizeof the underlying buffer // rather than the size of the type. *output << "\"size\" : " << ai.argSize; } *output << "}"; return; } // FIXME: // Eurgh... the spec says // ``` // If the argument is a buffer object, the arg_value pointer can be NULL or // point to a NULL value in which case a NULL value will be used as the // value for the argument declared as a pointer to __global or __constant // memory in the kernel. ``` // // This makes it impossible (seeing as we don't know which address space // the arguments are in) to work out the argument type once derefencing the // pointer and finding it's equal zero because it could be a scalar constant // (of value 0) or it could be an unintialised array! // Hack: // It's hard to determine what type the argument is. // We can't dereference the void* to check if // it points to cl_mem we previously stored // // In some implementations cl_mem will be a pointer // which poses a risk if a scalar parameter of the same size // as the pointer type. if (ai.argSize == sizeof(cl_mem)) { cl_mem mightBecl_mem = *((cl_mem*) ai.argValue); // We might be reading invalid data now if (buffers.count(mightBecl_mem) == 1) { // We're going to assume it's cl_mem that we saw before *output << "\"type\": \"array\","; BufferInfo& bi = buffers[mightBecl_mem]; *output << "\"size\": " << bi.size << "}"; return; } } // Hack: a similar hack of the image types if (ai.argSize == sizeof(cl_mem)) { cl_mem mightBecl_mem = *((cl_mem*) ai.argValue); // We might be reading invalid data now if (images.count(mightBecl_mem) == 1) { // We're going to assume it's cl_mem that we saw before *output << "\"type\": \"image\"}"; return; } } // Hack: a similar hack for the samplers if (ai.argSize == sizeof(cl_sampler)) { cl_sampler mightBecl_sampler = *((cl_sampler*) ai.argValue); // We might be reading invalid data now if (samplers.count(mightBecl_sampler) == 1) { // We're going to assume it's cl_mem that we saw before *output << "\"type\": \"sampler\"}"; return; } } // I guess it's scalar??? *output << "\"type\": \"scalar\","; *output << " \"value\": \"0x"; // Print the value as hex uint8_t* asByte = (uint8_t*) ai.argValue; // We assume the host is little endian so to print the values // we need to go through the array bytes backwards for (int byteIndex= ai.argSize -1; byteIndex >=0 ; --byteIndex) { *output << std::hex << std::setfill('0') << std::setw(2) << ( (unsigned) asByte[byteIndex]); } *output << "\"" << std::dec; //std::hex is sticky so switch back to decimal *output << "}"; return; } static bool file_exists(std::string& name) { ifstream f(name.c_str()); bool result = f.good(); f.close(); return result; } // Define the strict weak ordering over ProgramInfo instances // Is this correct? bool ProgramInfoCacheCompare::operator() (const ProgramInfo& lhs, const ProgramInfo& rhs) const { // Use the fact that a strict-weak order is already defined over std::vector<> return lhs.sources < rhs.sources; } std::string Logger::dumpKernelSource(KernelInfo& ki) { ProgramInfo& pi = programs[ki.program]; // See if we can used a file that we already printed. // This avoid writing duplicate files. ProgCacheMapTy::iterator it = WrittenKernelFileCache.find(pi); if ( it != WrittenKernelFileCache.end() ) { return it->second; } int count = 0; bool success = false; // FIXME: I really want a std::unique_ptr std::ofstream* kos = 0; std::string theKernelPath; while (count < maxFiles) { stringstream ss; ss << ki.entryPointName << "." << count << ".cl"; ++count; std::string withDir = (directory + PATH_SEP) + ss.str(); if (!file_exists(withDir)) { kos = new std::ofstream(withDir.c_str()); if (!kos->good()) { kos->close(); delete kos; continue; } success = true; theKernelPath = ss.str(); break; } } if (!success) { ERROR_MSG("Failed to log kernel output"); return std::string("FIXME"); } // Write kernel source for (vector<string>::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b) { *kos << *b; } // Urgh this is bad, need RAII! kos->close(); delete kos; // Store in cache assert(WrittenKernelFileCache.count(pi) == 0 && "ProgramInfo already in cache!"); WrittenKernelFileCache[pi] = theKernelPath; return theKernelPath; } <commit_msg>Attempt to emit "compile_flags" key and value in JSON output. This has not been tested because the OpenCL implementation is broken on my machine. Hopefully if it is broken TravisCI will catch it.<commit_after>#include "gvki/Logger.h" #include "gvki/PathSeperator.h" #include <cstdlib> #include <cstdio> #include <cassert> #include <errno.h> #include <iostream> #include <iomanip> #include <sstream> #include "string.h" #include "gvki/Debug.h" #include <sys/stat.h> #ifndef _WIN32 #include <dirent.h> #include <unistd.h> #define MKDIR_FAILS(d) (mkdir(d, 0770) != 0) #define DIR_ALREADY_EXISTS (errno == EEXIST) static void checkDirectoryExists(const char* dirName) { DIR* dh = opendir(dirName); if (dh != NULL) { closedir(dh); return; } ERROR_MSG(strerror(errno) << ". Directory was :" << dirName); exit(1); } #else #include <inttypes.h> #include <Windows.h> #define MKDIR_FAILS(d) (CreateDirectory(ss.str().c_str(), NULL) == 0) #define DIR_ALREADY_EXISTS (GetLastError() == ERROR_ALREADY_EXISTS) static void checkDirectoryExists(const char* dirName) { DWORD ftyp = GetFileAttributesA(dirName); if ((ftyp != INVALID_FILE_ATTRIBUTES) && ftyp & FILE_ATTRIBUTE_DIRECTORY) return; ERROR_MSG(strerror(errno) << ". Directory was :" << dirName); exit(1); } #endif using namespace std; using namespace gvki; // Maximum number of files or directories // that can be created static const int maxFiles = 10000; Logger& Logger::Singleton() { static Logger l; return l; } Logger::Logger() { int count = 0; bool success= false; // FIXME: Reading from the environment probably doesn't belong in here // but it makes implementing the singleton a lot easier std::string directoryPrefix; const char* envTemp = getenv("GVKI_ROOT"); if (envTemp) { DEBUG_MSG("Using GVKI_ROOT value as destination for directories"); checkDirectoryExists(envTemp); directoryPrefix = envTemp; } else { // Use the current working directory DEBUG_MSG("Using current working directory as destination for directories"); // FIXME: Hard-coding this size is gross #define MAX_DIR_LENGTH 1024 #ifndef _WIN32 char cwdArray[MAX_DIR_LENGTH]; char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)/sizeof(char)); if (!cwdResult) #else char cwdResult[MAX_DIR_LENGTH]; if (GetCurrentDirectory(MAX_DIR_LENGTH, cwdResult) == 0) #endif { ERROR_MSG(strerror(errno) << ". Could not read the current working directory"); exit(1); } else directoryPrefix = cwdResult; } directoryPrefix += PATH_SEP "gvki"; DEBUG_MSG("Directory prefix is \"" << directoryPrefix << "\""); // Keep trying a directoryPrefix name with a number as suffix // until we find an available one or we exhaust the maximum // allowed number while (count < maxFiles) { stringstream ss; ss << directoryPrefix << "-" << count; ++count; // Make the directoryPrefix if (MKDIR_FAILS(ss.str().c_str())) { if (!DIR_ALREADY_EXISTS) { ERROR_MSG(strerror(errno) << ". Directory was :" << directoryPrefix); exit(1); } // It already exists, try again continue; } this->directory = ss.str(); success = true; break; } if (!success) { ERROR_MSG("Exhausted available directory names or couldn't create any"); exit(1); } DEBUG_MSG("Directory used for logging is \"" << this->directory << "\""); openLog(); } void Logger::openLog() { // FIXME: We should use mkstemp() or something std::stringstream ss; ss << directory << PATH_SEP << "log.json"; output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate); if (! output->good()) { ERROR_MSG("Failed to create file (" << ss.str() << ") to write log to"); exit(1); } // Start of JSON array *output << "[" << std::endl; } void Logger::closeLog() { // End of JSON array *output << std::endl << "]" << std::endl; output->close(); } Logger::~Logger() { closeLog(); delete output; } void Logger::dump(cl_kernel k) { // Output JSON format defined by // http://multicore.doc.ic.ac.uk/tools/GPUVerify/docs/json_format.html KernelInfo& ki = kernels[k]; assert( programs.count(ki.program) == 1 && "cl_program missing"); ProgramInfo& pi = programs[ki.program]; static bool isFirst = true; if (!isFirst) { // Emit array element seperator // to seperate from previous dump *output << "," << endl; } isFirst = false; *output << "{" << endl << "\"language\": \"OpenCL\"," << endl; std::string kernelSourceFile = dumpKernelSource(ki); *output << "\"kernel_file\": \"" << kernelSourceFile << "\"," << endl; // FIXME: Teach GPUVerify how to handle non zero global_offset // FIXME: Document this json attribute! // Only emit global_offset if its non zero bool hasNonZeroGlobalOffset = false; for (int index=0; index < ki.globalWorkOffset.size() ; ++index) { if (ki.globalWorkOffset[index] != 0) hasNonZeroGlobalOffset = true; } if (hasNonZeroGlobalOffset) { *output << "\"global_offset\": "; printJSONArray(ki.globalWorkOffset); *output << "," << endl; } *output << "\"global_size\": "; printJSONArray(ki.globalWorkSize); *output << "," << endl; *output << "\"local_size\": "; printJSONArray(ki.localWorkSize); *output << "," << endl; *output << "\"compiler_flags\": \"" << pi.compileFlags << "\"," << endl; assert( (ki.globalWorkOffset.size() == ki.globalWorkSize.size()) && (ki.globalWorkSize.size() == ki.localWorkSize.size()) && "dimension mismatch"); *output << "\"entry_point\": \"" << ki.entryPointName << "\""; // entry_point might be the last entry is there were no kernel args if (ki.arguments.size() == 0) *output << endl; else { *output << "," << endl << "\"kernel_arguments\": [ " << endl; for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex) { printJSONKernelArgumentInfo(ki.arguments[argIndex]); if (argIndex != (ki.arguments.size() -1)) *output << "," << endl; } *output << endl << "]" << endl; } *output << "}"; } void Logger::printJSONArray(std::vector<size_t>& array) { *output << "[ "; for (int index=0; index < array.size(); ++index) { *output << array[index]; if (index != (array.size() -1)) *output << ", "; } *output << "]"; } void Logger::printJSONKernelArgumentInfo(ArgInfo& ai) { *output << "{"; if (ai.argValue == NULL) { // NULL was passed to clSetKernelArg() // That implies its for unallocated memory *output << "\"type\": \"array\","; // If the arg is for local memory if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler)) { // We assume this means this arguments is for local memory // where size actually means the sizeof the underlying buffer // rather than the size of the type. *output << "\"size\" : " << ai.argSize; } *output << "}"; return; } // FIXME: // Eurgh... the spec says // ``` // If the argument is a buffer object, the arg_value pointer can be NULL or // point to a NULL value in which case a NULL value will be used as the // value for the argument declared as a pointer to __global or __constant // memory in the kernel. ``` // // This makes it impossible (seeing as we don't know which address space // the arguments are in) to work out the argument type once derefencing the // pointer and finding it's equal zero because it could be a scalar constant // (of value 0) or it could be an unintialised array! // Hack: // It's hard to determine what type the argument is. // We can't dereference the void* to check if // it points to cl_mem we previously stored // // In some implementations cl_mem will be a pointer // which poses a risk if a scalar parameter of the same size // as the pointer type. if (ai.argSize == sizeof(cl_mem)) { cl_mem mightBecl_mem = *((cl_mem*) ai.argValue); // We might be reading invalid data now if (buffers.count(mightBecl_mem) == 1) { // We're going to assume it's cl_mem that we saw before *output << "\"type\": \"array\","; BufferInfo& bi = buffers[mightBecl_mem]; *output << "\"size\": " << bi.size << "}"; return; } } // Hack: a similar hack of the image types if (ai.argSize == sizeof(cl_mem)) { cl_mem mightBecl_mem = *((cl_mem*) ai.argValue); // We might be reading invalid data now if (images.count(mightBecl_mem) == 1) { // We're going to assume it's cl_mem that we saw before *output << "\"type\": \"image\"}"; return; } } // Hack: a similar hack for the samplers if (ai.argSize == sizeof(cl_sampler)) { cl_sampler mightBecl_sampler = *((cl_sampler*) ai.argValue); // We might be reading invalid data now if (samplers.count(mightBecl_sampler) == 1) { // We're going to assume it's cl_mem that we saw before *output << "\"type\": \"sampler\"}"; return; } } // I guess it's scalar??? *output << "\"type\": \"scalar\","; *output << " \"value\": \"0x"; // Print the value as hex uint8_t* asByte = (uint8_t*) ai.argValue; // We assume the host is little endian so to print the values // we need to go through the array bytes backwards for (int byteIndex= ai.argSize -1; byteIndex >=0 ; --byteIndex) { *output << std::hex << std::setfill('0') << std::setw(2) << ( (unsigned) asByte[byteIndex]); } *output << "\"" << std::dec; //std::hex is sticky so switch back to decimal *output << "}"; return; } static bool file_exists(std::string& name) { ifstream f(name.c_str()); bool result = f.good(); f.close(); return result; } // Define the strict weak ordering over ProgramInfo instances // Is this correct? bool ProgramInfoCacheCompare::operator() (const ProgramInfo& lhs, const ProgramInfo& rhs) const { // Use the fact that a strict-weak order is already defined over std::vector<> return lhs.sources < rhs.sources; } std::string Logger::dumpKernelSource(KernelInfo& ki) { ProgramInfo& pi = programs[ki.program]; // See if we can used a file that we already printed. // This avoid writing duplicate files. ProgCacheMapTy::iterator it = WrittenKernelFileCache.find(pi); if ( it != WrittenKernelFileCache.end() ) { return it->second; } int count = 0; bool success = false; // FIXME: I really want a std::unique_ptr std::ofstream* kos = 0; std::string theKernelPath; while (count < maxFiles) { stringstream ss; ss << ki.entryPointName << "." << count << ".cl"; ++count; std::string withDir = (directory + PATH_SEP) + ss.str(); if (!file_exists(withDir)) { kos = new std::ofstream(withDir.c_str()); if (!kos->good()) { kos->close(); delete kos; continue; } success = true; theKernelPath = ss.str(); break; } } if (!success) { ERROR_MSG("Failed to log kernel output"); return std::string("FIXME"); } // Write kernel source for (vector<string>::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b) { *kos << *b; } // Urgh this is bad, need RAII! kos->close(); delete kos; // Store in cache assert(WrittenKernelFileCache.count(pi) == 0 && "ProgramInfo already in cache!"); WrittenKernelFileCache[pi] = theKernelPath; return theKernelPath; } <|endoftext|>
<commit_before>#define DEFINE_GLOBALS #include"all_defines.hpp" #ifndef single_threaded bool single_threaded; #endif class Symbol; Symbol* symbol_sym; Symbol* symbol_int; Symbol* symbol_char; Symbol* symbol_cons; Symbol* symbol_pid; Symbol* symbol_fn; Symbol* symbol_string; Symbol* symbol_unspecified; Symbol* symbol_float; Symbol* symbol_array; Symbol* symbol_table; Symbol* symbol_container; Symbol* symbol_bytecode; Symbol* symbol_iport; Symbol* symbol_oport; Symbol* symbol_binobj; Symbol* symbol_call_star; #include"symbols.hpp" boost::scoped_ptr<SymbolsTable> symbols; void initialize_globals(void) { symbols.reset(new SymbolsTable()); symbol_sym = symbols->lookup("<hl>sym"); symbol_sym = symbols->lookup("<hl>int"); symbol_sym = symbols->lookup("<hl>char"); symbol_cons = symbols->lookup("<hl>cons"); symbol_pid = symbols->lookup("<hl>pid"); symbol_fn = symbols->lookup("<hl>fn"); symbol_string = symbols->lookup("<hl>string"); symbol_unspecified = symbols->lookup("<hl>unspecified"); symbol_float = symbols->lookup("<hl>float"); symbol_array = symbols->lookup("<hl>array"); symbol_table = symbols->lookup("<hl>table"); symbol_container = symbols->lookup("<hl>container"); symbol_bytecode = symbols->lookup("<hl>bytecode"); symbol_iport = symbols->lookup("<hl>iport"); symbol_oport = symbols->lookup("<hl>oport"); symbol_binobj = symbols->lookup("<hl>binobj"); symbol_call_star = symbols->lookup("<hl>call-star"); } <commit_msg>src/globals.cpp: corrected name of <hl>call*<commit_after>#define DEFINE_GLOBALS #include"all_defines.hpp" #ifndef single_threaded bool single_threaded; #endif class Symbol; Symbol* symbol_sym; Symbol* symbol_int; Symbol* symbol_char; Symbol* symbol_cons; Symbol* symbol_pid; Symbol* symbol_fn; Symbol* symbol_string; Symbol* symbol_unspecified; Symbol* symbol_float; Symbol* symbol_array; Symbol* symbol_table; Symbol* symbol_container; Symbol* symbol_bytecode; Symbol* symbol_iport; Symbol* symbol_oport; Symbol* symbol_binobj; Symbol* symbol_call_star; #include"symbols.hpp" boost::scoped_ptr<SymbolsTable> symbols; void initialize_globals(void) { symbols.reset(new SymbolsTable()); symbol_sym = symbols->lookup("<hl>sym"); symbol_sym = symbols->lookup("<hl>int"); symbol_sym = symbols->lookup("<hl>char"); symbol_cons = symbols->lookup("<hl>cons"); symbol_pid = symbols->lookup("<hl>pid"); symbol_fn = symbols->lookup("<hl>fn"); symbol_string = symbols->lookup("<hl>string"); symbol_unspecified = symbols->lookup("<hl>unspecified"); symbol_float = symbols->lookup("<hl>float"); symbol_array = symbols->lookup("<hl>array"); symbol_table = symbols->lookup("<hl>table"); symbol_container = symbols->lookup("<hl>container"); symbol_bytecode = symbols->lookup("<hl>bytecode"); symbol_iport = symbols->lookup("<hl>iport"); symbol_oport = symbols->lookup("<hl>oport"); symbol_binobj = symbols->lookup("<hl>binobj"); symbol_call_star = symbols->lookup("<hl>call*"); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkCorrelativeStatistics.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. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkToolkits.h" #include "vtkCorrelativeStatistics.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkTable.h" #include "vtkVariantArray.h" #include <vtkstd/set> // = Start Private Implementation ======================================= class vtkCorrelativeStatisticsPrivate { public: vtkCorrelativeStatisticsPrivate(); ~vtkCorrelativeStatisticsPrivate(); vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> > ColumnPairs; }; vtkCorrelativeStatisticsPrivate::vtkCorrelativeStatisticsPrivate() { } vtkCorrelativeStatisticsPrivate::~vtkCorrelativeStatisticsPrivate() { } // = End Private Implementation ========================================= vtkCxxRevisionMacro(vtkCorrelativeStatistics, "1.4"); vtkStandardNewMacro(vtkCorrelativeStatistics); // ---------------------------------------------------------------------- vtkCorrelativeStatistics::vtkCorrelativeStatistics() { this->Internals = new vtkCorrelativeStatisticsPrivate; } // ---------------------------------------------------------------------- vtkCorrelativeStatistics::~vtkCorrelativeStatistics() { delete this->Internals; } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::PrintSelf( ostream &os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::ResetColumnPairs() { this->Internals->ColumnPairs.clear(); } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::AddColumnPair( vtkIdType idxColX, vtkIdType idxColY ) { vtkstd::pair<vtkIdType,vtkIdType> idxPair( idxColX, idxColY ); this->Internals->ColumnPairs.insert( idxPair ); } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::ExecuteLearn( vtkTable* dataset, vtkTable* output, bool finalize ) { vtkIdType nCol = dataset->GetNumberOfColumns(); if ( ! nCol ) { vtkWarningMacro( "Dataset table does not have any columns. Doing nothing." ); this->SampleSize = 0; return; } this->SampleSize = dataset->GetNumberOfRows(); if ( ! this->SampleSize ) { vtkWarningMacro( "Dataset table does not have any rows. Doing nothing." ); return; } vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Column X" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Column Y" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); if ( finalize ) { vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Mean X" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Mean Y" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Variance X" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Variance Y" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Covariance" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "SlopeYX" ); output->AddColumn( doubleCol ); doubleCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Linear Correlation" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Intersect YX" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Slope XY" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Intersect XY" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Correlation" ); output->AddColumn( doubleCol ); doubleCol->Delete(); } else { vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum y" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x2" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum y2" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum xy" ); output->AddColumn( doubleCol ); doubleCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Cardinality" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); } for ( vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> >::iterator it = this->Internals->ColumnPairs.begin(); it != this->Internals->ColumnPairs.end(); ++ it ) { vtkIdType idX = it->first; if ( idX >= nCol ) { vtkWarningMacro( "Dataset table does not have a column with index "<<idX<<". Ignoring this pair." ); continue; } vtkIdType idY = it->second; if ( idY >= nCol ) { vtkWarningMacro( "Dataset table does not have a column with index "<<idY<<". Ignoring this pair." ); continue; } double x = 0.; double y = 0.; double sx = 0.; double sy = 0.; double sx2 = 0.; double sy2 = 0.; double sxy = 0.; for ( vtkIdType r = 0; r < this->SampleSize; ++ r ) { x = dataset->GetValue( r, idX ).ToDouble(); y = dataset->GetValue( r, idY ).ToDouble(); sx += x; sy += y; sx2 += x * x; sy2 += y * y; sxy += x * y; } vtkVariantArray* row = vtkVariantArray::New(); if ( finalize ) { row->SetNumberOfValues( 13 ); double correlations[5]; int res = this->CalculateFromSums( this->SampleSize, sx, sy, sx2, sy2, sxy, correlations ); row->SetValue( 0, idX ); row->SetValue( 1, idY ); row->SetValue( 2, sx ); row->SetValue( 3, sy ); row->SetValue( 4, sx2 ); row->SetValue( 5, sy2 ); row->SetValue( 6, sxy ); row->SetValue( 7, res ); for ( int i = 0; i < 5; ++ i ) { row->SetValue( i + 8, correlations[i] ); } } else { row->SetNumberOfValues( 8 ); row->SetValue( 0, idX ); row->SetValue( 1, idY ); row->SetValue( 2, sx ); row->SetValue( 3, sy ); row->SetValue( 4, sx2 ); row->SetValue( 5, sy2 ); row->SetValue( 6, sxy ); row->SetValue( 7, this->SampleSize ); } output->InsertNextRow( row ); row->Delete(); } return; } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::ExecuteValidate( vtkTable*, vtkTable*, vtkTable* ) { // Not implemented for this statistical engine } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::ExecuteEvince( vtkTable* dataset, vtkTable* params, vtkTable* output) { vtkIdType nColD = dataset->GetNumberOfColumns(); if ( ! nColD ) { vtkWarningMacro( "Dataset table does not have any columns. Doing nothing." ); return; } vtkIdType nRowD = dataset->GetNumberOfRows(); if ( ! nRowD ) { vtkWarningMacro( "Dataset table does not have any rows. Doing nothing." ); return; } vtkIdType nColP = params->GetNumberOfColumns(); if ( nColP != 8 ) { vtkWarningMacro( "Parameter table has " << nColP << " != 8 columns. Doing nothing." ); return; } vtkIdType nRowP = params->GetNumberOfRows(); if ( ! nRowP ) { vtkWarningMacro( "Parameter table does not have any rows. Doing nothing." ); return; } vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Column X" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Column Y" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Row" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Relative PDF" ); output->AddColumn( doubleCol ); doubleCol->Delete(); vtkVariantArray* row = vtkVariantArray::New(); row->SetNumberOfValues( 4 ); for ( vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> >::iterator it = this->Internals->ColumnPairs.begin(); it != this->Internals->ColumnPairs.end(); ++ it ) { vtkIdType idX = it->first; if ( idX >= nColD ) { vtkWarningMacro( "Dataset table does not have a column with index "<<idX<<". Ignoring it." ); continue; } vtkIdType idY = it->second; if ( idY >= nColD ) { vtkWarningMacro( "Dataset table does not have a column with index "<<idY<<". Ignoring it." ); continue; } bool unfound = true; for ( int i = 0; i < nRowP; ++ i ) { vtkIdType c1 = params->GetValue( i, 0 ).ToInt(); vtkIdType c2 = params->GetValue( i, 1 ).ToInt(); if ( ( c1 == it->first && c2 == it->second ) || ( c2 == it->first && c1 == it->second ) ) { unfound = false; double varX = params->GetValue( i, 4 ).ToDouble(); double varY = params->GetValue( i, 5 ).ToDouble(); double covr = params->GetValue( i, 6 ).ToDouble(); double d = varX * varY - covr * covr; if ( d <= 0. ) { vtkWarningMacro( "Incorrect parameters for column pair (" <<c1 <<", " <<c2 <<"): variance/covariance matrix has non-positive determinant." ); continue; } double nominalX = params->GetValue( i, 2 ).ToDouble(); double nominalY = params->GetValue( i, 3 ).ToDouble(); double thresPDF = params->GetValue( i, 7 ).ToDouble(); double eFac = -.5 / d; covr *= 2.; if ( c2 == it->first ) { vtkIdType tmp = idX; idX = idY; idY = tmp; } double x, y, rPDF; for ( vtkIdType r = 0; r < nRowD; ++ r ) { x = dataset->GetValue( r, idX ).ToDouble() - nominalX; y = dataset->GetValue( r, idY ).ToDouble() - nominalY; rPDF = exp( eFac * ( varY * x * x - covr * x * y + varX * y * y ) ); if ( rPDF < thresPDF ) { row->SetValue( 0, idX ); row->SetValue( 1, idY ); row->SetValue( 2, r ); row->SetValue( 3, rPDF ); output->InsertNextRow( row ); } } break; } } if ( unfound ) { vtkWarningMacro( "Parameter table does not a row for dataset table column pair (" <<it->first <<", " <<it->second <<"). Ignoring it." ); continue; } } row->Delete(); return; } // ---------------------------------------------------------------------- int vtkCorrelativeStatistics::CalculateFromSums( int n, double& sx, double& sy, double& sx2, double& sy2, double& sxy, double* correlations ) { if ( n < 2 ) { return -1; } double nd = static_cast<double>( n ); // (unbiased) estimation of the means sx /= nd; sy /= nd; if ( n == 1 ) { sx2 = sy2 = sxy = 0.; return 0; } // (unbiased) estimation of the variances and covariance double f = 1. / ( nd - 1. ); sx2 = ( sx2 - sx * sx * nd ) * f; sy2 = ( sy2 - sy * sy * nd ) * f; sxy = ( sxy - sx * sy * nd ) * f; // linear regression if ( sx2 > 0. && sy2 > 0. ) { // variable Y on variable X: // slope correlations[0] = sxy / sx2; // intersect correlations[1] = sy - correlations[0] * sx; // variable X on variable Y: // slope correlations[2] = sxy / sy2; // intersect correlations[3] = sx - correlations[2] * sy; // correlation coefficient double d = sx2 * sy2; if ( d > 0 ) { correlations[4] = sxy / sqrt( d ); return 0; } else { correlations[4] = 0.; return 1; } } else { correlations[0] = 0.; correlations[1] = 0.; correlations[2] = 0.; correlations[3] = 0.; correlations[4] = 0.; return 1; } } <commit_msg>BUG: when columns of interest are changed, Modified() must be called.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkCorrelativeStatistics.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. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkToolkits.h" #include "vtkCorrelativeStatistics.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkTable.h" #include "vtkVariantArray.h" #include <vtkstd/set> // = Start Private Implementation ======================================= class vtkCorrelativeStatisticsPrivate { public: vtkCorrelativeStatisticsPrivate(); ~vtkCorrelativeStatisticsPrivate(); vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> > ColumnPairs; }; vtkCorrelativeStatisticsPrivate::vtkCorrelativeStatisticsPrivate() { } vtkCorrelativeStatisticsPrivate::~vtkCorrelativeStatisticsPrivate() { } // = End Private Implementation ========================================= vtkCxxRevisionMacro(vtkCorrelativeStatistics, "1.5"); vtkStandardNewMacro(vtkCorrelativeStatistics); // ---------------------------------------------------------------------- vtkCorrelativeStatistics::vtkCorrelativeStatistics() { this->Internals = new vtkCorrelativeStatisticsPrivate; } // ---------------------------------------------------------------------- vtkCorrelativeStatistics::~vtkCorrelativeStatistics() { delete this->Internals; } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::PrintSelf( ostream &os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::ResetColumnPairs() { this->Internals->ColumnPairs.clear(); this->Modified(); } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::AddColumnPair( vtkIdType idxColX, vtkIdType idxColY ) { vtkstd::pair<vtkIdType,vtkIdType> idxPair( idxColX, idxColY ); this->Internals->ColumnPairs.insert( idxPair ); this->Modified(); } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::ExecuteLearn( vtkTable* dataset, vtkTable* output, bool finalize ) { vtkIdType nCol = dataset->GetNumberOfColumns(); if ( ! nCol ) { vtkWarningMacro( "Dataset table does not have any columns. Doing nothing." ); this->SampleSize = 0; return; } this->SampleSize = dataset->GetNumberOfRows(); if ( ! this->SampleSize ) { vtkWarningMacro( "Dataset table does not have any rows. Doing nothing." ); return; } vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Column X" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Column Y" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); if ( finalize ) { vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Mean X" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Mean Y" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Variance X" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Variance Y" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Covariance" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "SlopeYX" ); output->AddColumn( doubleCol ); doubleCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Linear Correlation" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Intersect YX" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Slope XY" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Intersect XY" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Correlation" ); output->AddColumn( doubleCol ); doubleCol->Delete(); } else { vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum y" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x2" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum y2" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum xy" ); output->AddColumn( doubleCol ); doubleCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Cardinality" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); } for ( vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> >::iterator it = this->Internals->ColumnPairs.begin(); it != this->Internals->ColumnPairs.end(); ++ it ) { vtkIdType idX = it->first; if ( idX >= nCol ) { vtkWarningMacro( "Dataset table does not have a column with index "<<idX<<". Ignoring this pair." ); continue; } vtkIdType idY = it->second; if ( idY >= nCol ) { vtkWarningMacro( "Dataset table does not have a column with index "<<idY<<". Ignoring this pair." ); continue; } double x = 0.; double y = 0.; double sx = 0.; double sy = 0.; double sx2 = 0.; double sy2 = 0.; double sxy = 0.; for ( vtkIdType r = 0; r < this->SampleSize; ++ r ) { x = dataset->GetValue( r, idX ).ToDouble(); y = dataset->GetValue( r, idY ).ToDouble(); sx += x; sy += y; sx2 += x * x; sy2 += y * y; sxy += x * y; } vtkVariantArray* row = vtkVariantArray::New(); if ( finalize ) { row->SetNumberOfValues( 13 ); double correlations[5]; int res = this->CalculateFromSums( this->SampleSize, sx, sy, sx2, sy2, sxy, correlations ); row->SetValue( 0, idX ); row->SetValue( 1, idY ); row->SetValue( 2, sx ); row->SetValue( 3, sy ); row->SetValue( 4, sx2 ); row->SetValue( 5, sy2 ); row->SetValue( 6, sxy ); row->SetValue( 7, res ); for ( int i = 0; i < 5; ++ i ) { row->SetValue( i + 8, correlations[i] ); } } else { row->SetNumberOfValues( 8 ); row->SetValue( 0, idX ); row->SetValue( 1, idY ); row->SetValue( 2, sx ); row->SetValue( 3, sy ); row->SetValue( 4, sx2 ); row->SetValue( 5, sy2 ); row->SetValue( 6, sxy ); row->SetValue( 7, this->SampleSize ); } output->InsertNextRow( row ); row->Delete(); } return; } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::ExecuteValidate( vtkTable*, vtkTable*, vtkTable* ) { // Not implemented for this statistical engine } // ---------------------------------------------------------------------- void vtkCorrelativeStatistics::ExecuteEvince( vtkTable* dataset, vtkTable* params, vtkTable* output) { vtkIdType nColD = dataset->GetNumberOfColumns(); if ( ! nColD ) { vtkWarningMacro( "Dataset table does not have any columns. Doing nothing." ); return; } vtkIdType nRowD = dataset->GetNumberOfRows(); if ( ! nRowD ) { vtkWarningMacro( "Dataset table does not have any rows. Doing nothing." ); return; } vtkIdType nColP = params->GetNumberOfColumns(); if ( nColP != 8 ) { vtkWarningMacro( "Parameter table has " << nColP << " != 8 columns. Doing nothing." ); return; } vtkIdType nRowP = params->GetNumberOfRows(); if ( ! nRowP ) { vtkWarningMacro( "Parameter table does not have any rows. Doing nothing." ); return; } vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Column X" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Column Y" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Row" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Relative PDF" ); output->AddColumn( doubleCol ); doubleCol->Delete(); vtkVariantArray* row = vtkVariantArray::New(); row->SetNumberOfValues( 4 ); for ( vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> >::iterator it = this->Internals->ColumnPairs.begin(); it != this->Internals->ColumnPairs.end(); ++ it ) { vtkIdType idX = it->first; if ( idX >= nColD ) { vtkWarningMacro( "Dataset table does not have a column with index "<<idX<<". Ignoring it." ); continue; } vtkIdType idY = it->second; if ( idY >= nColD ) { vtkWarningMacro( "Dataset table does not have a column with index "<<idY<<". Ignoring it." ); continue; } bool unfound = true; for ( int i = 0; i < nRowP; ++ i ) { vtkIdType c1 = params->GetValue( i, 0 ).ToInt(); vtkIdType c2 = params->GetValue( i, 1 ).ToInt(); if ( ( c1 == it->first && c2 == it->second ) || ( c2 == it->first && c1 == it->second ) ) { unfound = false; double varX = params->GetValue( i, 4 ).ToDouble(); double varY = params->GetValue( i, 5 ).ToDouble(); double covr = params->GetValue( i, 6 ).ToDouble(); double d = varX * varY - covr * covr; if ( d <= 0. ) { vtkWarningMacro( "Incorrect parameters for column pair (" <<c1 <<", " <<c2 <<"): variance/covariance matrix has non-positive determinant." ); continue; } double nominalX = params->GetValue( i, 2 ).ToDouble(); double nominalY = params->GetValue( i, 3 ).ToDouble(); double thresPDF = params->GetValue( i, 7 ).ToDouble(); double eFac = -.5 / d; covr *= 2.; if ( c2 == it->first ) { vtkIdType tmp = idX; idX = idY; idY = tmp; } double x, y, rPDF; for ( vtkIdType r = 0; r < nRowD; ++ r ) { x = dataset->GetValue( r, idX ).ToDouble() - nominalX; y = dataset->GetValue( r, idY ).ToDouble() - nominalY; rPDF = exp( eFac * ( varY * x * x - covr * x * y + varX * y * y ) ); if ( rPDF < thresPDF ) { row->SetValue( 0, idX ); row->SetValue( 1, idY ); row->SetValue( 2, r ); row->SetValue( 3, rPDF ); output->InsertNextRow( row ); } } break; } } if ( unfound ) { vtkWarningMacro( "Parameter table does not a row for dataset table column pair (" <<it->first <<", " <<it->second <<"). Ignoring it." ); continue; } } row->Delete(); return; } // ---------------------------------------------------------------------- int vtkCorrelativeStatistics::CalculateFromSums( int n, double& sx, double& sy, double& sx2, double& sy2, double& sxy, double* correlations ) { if ( n < 2 ) { return -1; } double nd = static_cast<double>( n ); // (unbiased) estimation of the means sx /= nd; sy /= nd; if ( n == 1 ) { sx2 = sy2 = sxy = 0.; return 0; } // (unbiased) estimation of the variances and covariance double f = 1. / ( nd - 1. ); sx2 = ( sx2 - sx * sx * nd ) * f; sy2 = ( sy2 - sy * sy * nd ) * f; sxy = ( sxy - sx * sy * nd ) * f; // linear regression if ( sx2 > 0. && sy2 > 0. ) { // variable Y on variable X: // slope correlations[0] = sxy / sx2; // intersect correlations[1] = sy - correlations[0] * sx; // variable X on variable Y: // slope correlations[2] = sxy / sy2; // intersect correlations[3] = sx - correlations[2] * sy; // correlation coefficient double d = sx2 * sy2; if ( d > 0 ) { correlations[4] = sxy / sqrt( d ); return 0; } else { correlations[4] = 0.; return 1; } } else { correlations[0] = 0.; correlations[1] = 0.; correlations[2] = 0.; correlations[3] = 0.; correlations[4] = 0.; return 1; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: areasdlg.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: dr $ $Date: 2001-05-23 15:05:18 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_AREASDLG_HXX #define SC_AREASDLG_HXX #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef SC_ANYREFDG_HXX #include <anyrefdg.hxx> #endif class ScDocument; class ScViewData; class ScRangeUtil; class ScRangeItem; //============================================================================ class ScPrintAreasDlg : public ScAnyRefDlg { public: ScPrintAreasDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent ); ~ScPrintAreasDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ); virtual void AddRefEntry(); virtual BOOL IsTableLocked() const; virtual void SetActive(); virtual void Deactivate(); virtual BOOL Close(); private: ListBox aLbPrintArea; FixedLine aFlPrintArea; ScRefEdit aEdPrintArea; ScRefButton aRbPrintArea; ListBox aLbRepeatRow; FixedLine aFlRepeatRow; ScRefEdit aEdRepeatRow; ScRefButton aRbRepeatRow; ListBox aLbRepeatCol; FixedLine aFlRepeatCol; ScRefEdit aEdRepeatCol; ScRefButton aRbRepeatCol; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; BOOL bDlgLostFocus; ScRefEdit* pRefInputEdit; ScDocument* pDoc; ScViewData* pViewData; USHORT nCurTab; #ifdef _AREASDLG_CXX private: void Impl_Reset(); BOOL Impl_CheckRefStrings(); void Impl_FillLists(); BOOL Impl_GetItem( Edit* pEd, SfxStringItem& rItem ); // Handler: DECL_LINK( Impl_SelectHdl, ListBox* ); DECL_LINK( Impl_ModifyHdl, ScRefEdit* ); DECL_LINK( Impl_BtnHdl, PushButton* ); DECL_LINK( Impl_GetFocusHdl, Control* ); #endif }; #endif <commit_msg>INTEGRATION: CWS rowlimit (1.2.332); FILE MERGED 2004/01/13 20:04:08 er 1.2.332.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/************************************************************************* * * $RCSfile: areasdlg.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:30:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_AREASDLG_HXX #define SC_AREASDLG_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef SC_ANYREFDG_HXX #include <anyrefdg.hxx> #endif class ScDocument; class ScViewData; class ScRangeUtil; class ScRangeItem; //============================================================================ class ScPrintAreasDlg : public ScAnyRefDlg { public: ScPrintAreasDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent ); ~ScPrintAreasDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ); virtual void AddRefEntry(); virtual BOOL IsTableLocked() const; virtual void SetActive(); virtual void Deactivate(); virtual BOOL Close(); private: ListBox aLbPrintArea; FixedLine aFlPrintArea; ScRefEdit aEdPrintArea; ScRefButton aRbPrintArea; ListBox aLbRepeatRow; FixedLine aFlRepeatRow; ScRefEdit aEdRepeatRow; ScRefButton aRbRepeatRow; ListBox aLbRepeatCol; FixedLine aFlRepeatCol; ScRefEdit aEdRepeatCol; ScRefButton aRbRepeatCol; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; BOOL bDlgLostFocus; ScRefEdit* pRefInputEdit; ScDocument* pDoc; ScViewData* pViewData; SCTAB nCurTab; #ifdef _AREASDLG_CXX private: void Impl_Reset(); BOOL Impl_CheckRefStrings(); void Impl_FillLists(); BOOL Impl_GetItem( Edit* pEd, SfxStringItem& rItem ); // Handler: DECL_LINK( Impl_SelectHdl, ListBox* ); DECL_LINK( Impl_ModifyHdl, ScRefEdit* ); DECL_LINK( Impl_BtnHdl, PushButton* ); DECL_LINK( Impl_GetFocusHdl, Control* ); #endif }; #endif <|endoftext|>
<commit_before>#include "gorgone.h" using namespace cv; using namespace ofxCv; int accum = 0; void gorgone::setup() { ofSetLogLevel(OF_LOG_NOTICE); masterIp = "Mac-Pro-de-10-52.local"; appName = "gorgone-1"; parseCmdLineOptions(); vidGrabber.setup(filename); svgInterp.setup(); jamoma.setup((void*) this, appName, masterIp); motionDetector.setup(&jamoma); irisDetector.setJamomaRef(&jamoma); counter = 0; } void gorgone::exit(){ setPwm(0); #ifdef TARGET_RASPBERRY_PI vidGrabber.led.switchOffIR(); #endif } void gorgone::update() { ofLogVerbose("gorgone") << ofGetFrameRate() << " fps" << endl; vidGrabber.update(); if ( vidGrabber.isFrameNew() ){ frame = vidGrabber.getFrame(); if ( bMotion ){ motionDetector.update(frame); } if( bTracking ){ if ( frame.cols == 0 ) return; cv::Mat gray; if ( frame.channels() == 1 ){ gray = frame.clone(); } else { cv::cvtColor(frame, gray, CV_RGB2GRAY); } ofLogVerbose("gorgone") << "new frame to process : " << gray.cols << "x" << gray.rows << endl; irisDetector.updateBool(gray); } } Mat img = irisDetector.getIrisCode(); if( irisDetector.newCode ) { bComputeCode=false; jamoma.mComputeIrisCodeParameter.set("value", bComputeCode); svgInterp.coeff.clear(); ofLogNotice("gorgone") << "code image resolution : " << img.cols << "x" << img.rows << endl; uchar* p; for (int i = 0; i < img.rows; i++ ){ float avg=0; p=img.ptr<uchar>(i); for (int j = 0; j < img.cols; j++ ){ avg+=p[j] / 255.; } avg/=img.cols; svgInterp.coeff.push_back(avg); } irisDetector.newCode = false; TTValue v, w; for (int i = 0; i<svgInterp.coeff.size(); i++){ v.push_back(svgInterp.coeff[i]); } jamoma.mTrackingIrisCodeReturn.set("value", v); w.push_back(irisDetector.blobArea); jamoma.mTrackingIrisBlobAreaReturn.set("value",w); } if (bComputeCode && !irisDetector.isThreadRunning() ) { irisDetector.start(); } } void gorgone::draw() { //vidGrabber.draw(0,0); drawMat(frame,0,0); if ( svgInterp.updateBool() ){ TTValue x,y; ofPolyline line = svgInterp.interpolatedLine; // ofLogNotice("gorgone") << "update drawing with " << line.size() << "points" << endl; for (int i=0; i<line.size(); i++){ x.push_back(line[i].x); y.push_back(line[i].y); } jamoma.mDrawingShapeXReturn.set("value", x); jamoma.mDrawingShapeYReturn.set("value", y); } if ( bTracking ) { ofDrawBitmapStringHighlight("eye tracking", 10, 400); irisDetector.drawEyes(); } if ( bDisplaying ) { ofDrawBitmapStringHighlight("laser drawing", 200, 400); svgInterp.draw(); } if ( bMotion ){ ofDrawBitmapStringHighlight("motion detection", 400, 400); } } void gorgone::keyPressed(int key) { ofLogVerbose("gorgone") << "keypressed : " << key << endl; switch (key){ case 's': irisDetector.save(); break; case ' ': irisDetector.reset(); break; case 'c': bComputeCode=true; break; case 'm': bMotion = !bMotion; break; case 't': bTracking = !bTracking; if ( bTracking ) irisDetector.reset(); #ifdef TARGET_RASPBERRY_PI if ( bTracking ) vidGrabber.led.switchOnIR(); else vidGrabber.led.switchOffIR(); #endif break; case 'd': bDisplaying = !bDisplaying; break; #ifdef TARGET_RASPBERRY_PI case 'i': vidGrabber.led.switchOnIR(); break; case 'o': vidGrabber.led.switchOffIR(); break; case 'w': vidGrabber.led.switchOnWhite(); break; case 'x': vidGrabber.led.switchOffWhite(); break; #endif case 357 : // arrow up svgInterp.selectedId = counter++; break; case 359: // arrow down svgInterp.selectedId = counter--; break; default : break; } } void gorgone::messageReceived(ofMessage& message) { } void gorgone::parseCmdLineOptions(){ vector<string> keys = ofxArgParser::allKeys(); for (int i = 0; i < keys.size(); i++) { if ( keys[i] == "f" ) filename = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "name" ) appName = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "masterIp" ) masterIp = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "verbose" ) { // vebose level, value : 0..5, default 1 (OF_LOG_NOTICE) int logLevel; istringstream( ofxArgParser::getValue(keys[i]) ) >> logLevel; ofSetLogLevel((ofLogLevel) logLevel); } ofLogNotice("gorgone") << "key: " << keys[i] << ", value: " << ofxArgParser::getValue(keys[i]) << endl; } } void gorgone::setPwm(float pc){ #ifdef TARGET_RASPBERRY_PI ofstream file; file.open("/dev/servoblaster", ios::in); file << "0=" << pc << "%" << endl; file.close(); #endif } <commit_msg>reduce irisCode size<commit_after>#include "gorgone.h" using namespace cv; using namespace ofxCv; int accum = 0; void gorgone::setup() { ofSetLogLevel(OF_LOG_NOTICE); masterIp = "Mac-Pro-de-10-52.local"; appName = "gorgone-1"; parseCmdLineOptions(); vidGrabber.setup(filename); svgInterp.setup(); jamoma.setup((void*) this, appName, masterIp); motionDetector.setup(&jamoma); irisDetector.setJamomaRef(&jamoma); counter = 0; } void gorgone::exit(){ setPwm(0); #ifdef TARGET_RASPBERRY_PI vidGrabber.led.switchOffIR(); #endif } void gorgone::update() { ofLogVerbose("gorgone") << ofGetFrameRate() << " fps" << endl; vidGrabber.update(); if ( vidGrabber.isFrameNew() ){ frame = vidGrabber.getFrame(); if ( bMotion ){ motionDetector.update(frame); } if( bTracking ){ if ( frame.cols == 0 ) return; cv::Mat gray; if ( frame.channels() == 1 ){ gray = frame.clone(); } else { cv::cvtColor(frame, gray, CV_RGB2GRAY); } ofLogVerbose("gorgone") << "new frame to process : " << gray.cols << "x" << gray.rows << endl; irisDetector.updateBool(gray); } } Mat tmp = irisDetector.getIrisCode(); Mat img; resize(tmp, img, Size(tmp.cols, tmp.rows/4.)); if( irisDetector.newCode ) { bComputeCode=false; jamoma.mComputeIrisCodeParameter.set("value", bComputeCode); svgInterp.coeff.clear(); ofLogNotice("gorgone") << "code image resolution : " << img.cols << "x" << img.rows << endl; uchar* p; for (int i = 0; i < img.rows; i++ ){ float avg=0; p=img.ptr<uchar>(i); for (int j = 0; j < img.cols; j++ ){ avg+=p[j] / 255.; } avg/=img.cols; svgInterp.coeff.push_back(avg); } irisDetector.newCode = false; TTValue v, w; for (int i = 0; i<svgInterp.coeff.size(); i++){ v.push_back(svgInterp.coeff[i]); } jamoma.mTrackingIrisCodeReturn.set("value", v); w.push_back(irisDetector.blobArea); jamoma.mTrackingIrisBlobAreaReturn.set("value",w); } if (bComputeCode && !irisDetector.isThreadRunning() ) { irisDetector.start(); } } void gorgone::draw() { //vidGrabber.draw(0,0); drawMat(frame,0,0); if ( svgInterp.updateBool() ){ TTValue x,y; ofPolyline line = svgInterp.interpolatedLine; // ofLogNotice("gorgone") << "update drawing with " << line.size() << "points" << endl; for (int i=0; i<line.size(); i++){ x.push_back(line[i].x); y.push_back(line[i].y); } jamoma.mDrawingShapeXReturn.set("value", x); jamoma.mDrawingShapeYReturn.set("value", y); } if ( bTracking ) { ofDrawBitmapStringHighlight("eye tracking", 10, 400); irisDetector.drawEyes(); } if ( bDisplaying ) { ofDrawBitmapStringHighlight("laser drawing", 200, 400); svgInterp.draw(); } if ( bMotion ){ ofDrawBitmapStringHighlight("motion detection", 400, 400); } } void gorgone::keyPressed(int key) { ofLogVerbose("gorgone") << "keypressed : " << key << endl; switch (key){ case 's': irisDetector.save(); break; case ' ': irisDetector.reset(); break; case 'c': bComputeCode=true; break; case 'm': bMotion = !bMotion; break; case 't': bTracking = !bTracking; if ( bTracking ) irisDetector.reset(); #ifdef TARGET_RASPBERRY_PI if ( bTracking ) vidGrabber.led.switchOnIR(); else vidGrabber.led.switchOffIR(); #endif break; case 'd': bDisplaying = !bDisplaying; break; #ifdef TARGET_RASPBERRY_PI case 'i': vidGrabber.led.switchOnIR(); break; case 'o': vidGrabber.led.switchOffIR(); break; case 'w': vidGrabber.led.switchOnWhite(); break; case 'x': vidGrabber.led.switchOffWhite(); break; #endif case 357 : // arrow up svgInterp.selectedId = counter++; break; case 359: // arrow down svgInterp.selectedId = counter--; break; default : break; } } void gorgone::messageReceived(ofMessage& message) { } void gorgone::parseCmdLineOptions(){ vector<string> keys = ofxArgParser::allKeys(); for (int i = 0; i < keys.size(); i++) { if ( keys[i] == "f" ) filename = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "name" ) appName = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "masterIp" ) masterIp = ofxArgParser::getValue(keys[i]); else if ( keys[i] == "verbose" ) { // vebose level, value : 0..5, default 1 (OF_LOG_NOTICE) int logLevel; istringstream( ofxArgParser::getValue(keys[i]) ) >> logLevel; ofSetLogLevel((ofLogLevel) logLevel); } ofLogNotice("gorgone") << "key: " << keys[i] << ", value: " << ofxArgParser::getValue(keys[i]) << endl; } } void gorgone::setPwm(float pc){ #ifdef TARGET_RASPBERRY_PI ofstream file; file.open("/dev/servoblaster", ios::in); file << "0=" << pc << "%" << endl; file.close(); #endif } <|endoftext|>
<commit_before>//===---- IncludeInserterTest.cpp - clang-tidy ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "../clang-tidy/IncludeInserter.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "ClangTidyTest.h" #include "gtest/gtest.h" namespace clang { namespace tidy { namespace { class IncludeInserterCheckBase : public ClangTidyCheck { public: using ClangTidyCheck::ClangTidyCheck; void registerPPCallbacks(CompilerInstance &Compiler) override { Inserter.reset(new IncludeInserter(Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeSorter::IS_Google)); Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks()); } void registerMatchers(ast_matchers::MatchFinder *Finder) override { Finder->addMatcher(ast_matchers::declStmt().bind("stmt"), this); } void check(const ast_matchers::MatchFinder::MatchResult &Result) override { auto Fixit = Inserter->CreateIncludeInsertion(Result.SourceManager->getMainFileID(), HeaderToInclude(), IsAngledInclude()); if (Fixit) { diag(Result.Nodes.getStmtAs<DeclStmt>("stmt")->getLocStart(), "foo, bar") << *Fixit; } // Second include should yield no Fixit. Fixit = Inserter->CreateIncludeInsertion(Result.SourceManager->getMainFileID(), HeaderToInclude(), IsAngledInclude()); EXPECT_FALSE(Fixit); } virtual StringRef HeaderToInclude() const = 0; virtual bool IsAngledInclude() const = 0; std::unique_ptr<IncludeInserter> Inserter; }; class NonSystemHeaderInserterCheck : public IncludeInserterCheckBase { public: using IncludeInserterCheckBase::IncludeInserterCheckBase; StringRef HeaderToInclude() const override { return "path/to/header.h"; } bool IsAngledInclude() const override { return false; } }; class CXXSystemIncludeInserterCheck : public IncludeInserterCheckBase { public: using IncludeInserterCheckBase::IncludeInserterCheckBase; StringRef HeaderToInclude() const override { return "set"; } bool IsAngledInclude() const override { return true; } }; template <typename Check> std::string runCheckOnCode(StringRef Code, StringRef Filename, size_t NumWarningsExpected) { std::vector<ClangTidyError> Errors; return test::runCheckOnCode<Check>(Code, &Errors, Filename, None, ClangTidyOptions(), {// Main file include {"devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.h", "\n"}, // Non system headers {"path/to/a/header.h", "\n"}, {"path/to/z/header.h", "\n"}, {"path/to/header.h", "\n"}, // Fake system headers. {"stdlib.h", "\n"}, {"unistd.h", "\n"}, {"list", "\n"}, {"map", "\n"}, {"set", "\n"}, {"vector", "\n"}}); EXPECT_EQ(NumWarningsExpected, Errors.size()); } TEST(IncludeInserterTest, InsertAfterLastNonSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" #include "path/to/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_input2.cc", 1)); } TEST(IncludeInserterTest, InsertBeforeFirstNonSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/z/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/header.h" #include "path/to/z/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_input2.cc", 1)); } TEST(IncludeInserterTest, InsertBetweenNonSystemIncludes) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" #include "path/to/z/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" #include "path/to/header.h" #include "path/to/z/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_input2.cc", 1)); } TEST(IncludeInserterTest, NonSystemIncludeAlreadyIncluded) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" #include "path/to/header.h" #include "path/to/z/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PreCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_input2.cc", 0)); } TEST(IncludeInserterTest, InsertNonSystemIncludeAfterLastCXXSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertNonSystemIncludeAfterMainFileInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include "path/to/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeAfterLastCXXSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include <set> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeBeforeFirstCXXSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <vector> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <set> #include <vector> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeBetweenCXXSystemIncludes) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <map> #include <vector> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <map> #include <set> #include <vector> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeAfterMainFileInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <set> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeAfterCSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <stdlib.h> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <stdlib.h> #include <set> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } } // namespace } // namespace tidy } // namespace clang <commit_msg>Do not use inheriting constructors.<commit_after>//===---- IncludeInserterTest.cpp - clang-tidy ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "../clang-tidy/IncludeInserter.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "ClangTidyTest.h" #include "gtest/gtest.h" namespace clang { namespace tidy { namespace { class IncludeInserterCheckBase : public ClangTidyCheck { public: IncludeInserterCheckBase(StringRef CheckName, ClangTidyContext *Context) : ClangTidyCheck(CheckName, Context) {} void registerPPCallbacks(CompilerInstance &Compiler) override { Inserter.reset(new IncludeInserter(Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeSorter::IS_Google)); Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks()); } void registerMatchers(ast_matchers::MatchFinder *Finder) override { Finder->addMatcher(ast_matchers::declStmt().bind("stmt"), this); } void check(const ast_matchers::MatchFinder::MatchResult &Result) override { auto Fixit = Inserter->CreateIncludeInsertion(Result.SourceManager->getMainFileID(), HeaderToInclude(), IsAngledInclude()); if (Fixit) { diag(Result.Nodes.getStmtAs<DeclStmt>("stmt")->getLocStart(), "foo, bar") << *Fixit; } // Second include should yield no Fixit. Fixit = Inserter->CreateIncludeInsertion(Result.SourceManager->getMainFileID(), HeaderToInclude(), IsAngledInclude()); EXPECT_FALSE(Fixit); } virtual StringRef HeaderToInclude() const = 0; virtual bool IsAngledInclude() const = 0; std::unique_ptr<IncludeInserter> Inserter; }; class NonSystemHeaderInserterCheck : public IncludeInserterCheckBase { public: NonSystemHeaderInserterCheck(StringRef CheckName, ClangTidyContext *Context) : IncludeInserterCheckBase(CheckName, Context) {} StringRef HeaderToInclude() const override { return "path/to/header.h"; } bool IsAngledInclude() const override { return false; } }; class CXXSystemIncludeInserterCheck : public IncludeInserterCheckBase { public: CXXSystemIncludeInserterCheck(StringRef CheckName, ClangTidyContext *Context) : IncludeInserterCheckBase(CheckName, Context) {} StringRef HeaderToInclude() const override { return "set"; } bool IsAngledInclude() const override { return true; } }; template <typename Check> std::string runCheckOnCode(StringRef Code, StringRef Filename, size_t NumWarningsExpected) { std::vector<ClangTidyError> Errors; return test::runCheckOnCode<Check>(Code, &Errors, Filename, None, ClangTidyOptions(), {// Main file include {"devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.h", "\n"}, // Non system headers {"path/to/a/header.h", "\n"}, {"path/to/z/header.h", "\n"}, {"path/to/header.h", "\n"}, // Fake system headers. {"stdlib.h", "\n"}, {"unistd.h", "\n"}, {"list", "\n"}, {"map", "\n"}, {"set", "\n"}, {"vector", "\n"}}); EXPECT_EQ(NumWarningsExpected, Errors.size()); } TEST(IncludeInserterTest, InsertAfterLastNonSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" #include "path/to/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_input2.cc", 1)); } TEST(IncludeInserterTest, InsertBeforeFirstNonSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/z/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/header.h" #include "path/to/z/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_input2.cc", 1)); } TEST(IncludeInserterTest, InsertBetweenNonSystemIncludes) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" #include "path/to/z/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" #include "path/to/header.h" #include "path/to/z/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_input2.cc", 1)); } TEST(IncludeInserterTest, NonSystemIncludeAlreadyIncluded) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" #include "path/to/header.h" #include "path/to/z/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PreCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_input2.cc", 0)); } TEST(IncludeInserterTest, InsertNonSystemIncludeAfterLastCXXSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertNonSystemIncludeAfterMainFileInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include "path/to/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<NonSystemHeaderInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeAfterLastCXXSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <list> #include <map> #include <set> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeBeforeFirstCXXSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <vector> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <set> #include <vector> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeBetweenCXXSystemIncludes) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <map> #include <vector> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <map> #include <set> #include <vector> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeAfterMainFileInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <set> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } TEST(IncludeInserterTest, InsertCXXSystemIncludeAfterCSystemInclude) { const char *PreCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <stdlib.h> #include "path/to/a/header.h" void foo() { int a = 0; })"; const char *PostCode = R"( #include "devtools/cymbal/clang_tidy/tests/insert_includes_test_header.h" #include <stdlib.h> #include <set> #include "path/to/a/header.h" void foo() { int a = 0; })"; EXPECT_EQ(PostCode, runCheckOnCode<CXXSystemIncludeInserterCheck>( PreCode, "devtools/cymbal/clang_tidy/tests/" "insert_includes_test_header.cc", 1)); } } // namespace } // namespace tidy } // namespace clang <|endoftext|>
<commit_before>#include <arpc.h> #include <modlogger.h> #include <misc_utils.h> #include <dhash_types.h> #include <dhash_common.h> #include <merkle_sync_prot.h> #include <merkle.h> #include <maint_prot.h> #include "maint_policy.h" // {{{ Globals static char *logfname; static char *localdatapath; static vec<ptr<maintainer> > maintainers; enum maint_mode_t { MAINT_CARBONITE, MAINT_PASSINGTONE, } maint_mode; struct maint_mode_desc { maint_mode_t m; char *cmdline; maintainer_producer_t producer; } maint_modes[] = { { MAINT_CARBONITE, "carbonite", wrap (carbonite::produce_maintainer) }, { MAINT_PASSINGTONE, "passingtone", wrap (passingtone::produce_maintainer) } }; enum sync_mode_t { SYNC_MERKLE, SYNC_TIME } sync_mode; struct sync_mode_desc { sync_mode_t m; char *cmdline; syncer_producer_t producer; } sync_modes[] = { { SYNC_MERKLE, "merkle", wrap (merkle_sync::produce_syncer) } }; // }}} // {{{ General utility functions template<class VS, class S> static S select_mode (const char *arg, const VS *modes, int nmodes) { int i; S m = modes[0].m; for (i = 0; i < nmodes; i++) { if (strcmp (arg, modes[i].cmdline) == 0) { m = modes[i].m; break; } } if (i == nmodes) { strbuf s; for (i = 0; i < nmodes; i++) s << " " << modes[i].cmdline; fatal << "allowed modes are" << s << "\n"; } return m; } static void halt () { warnx << "Exiting on command.\n"; while (maintainers.size ()) { maintainers.pop_back (); } exit (0); } void start_logs () { static int logfd (-1); // XXX please don't call setlogfd or change errfd anywhere else... if (logfname) { if (logfd >= 0) close (logfd); logfd = open (logfname, O_RDWR | O_CREAT, 0666); if (logfd < 0) fatal << "Could not open log file " << logfd << " for appending.\n"; lseek (logfd, 0, SEEK_END); errfd = logfd; modlogger::setlogfd (logfd); } } static void usage () { warnx << "Usage: " << progname << "\t[-C maintd-ctlsock]\n" << "\t[-d localdatapath]\n" << "\t[-L logfilename]\n" << "\t[-m maintmode]\n" << "\t[-s syncmode]\n" << "\t[-t]\n"; exit (1); } // }}} // {{{ Remote-side RPC handling static void srvaccept (int fd); static void sync_dispatch (ptr<asrv> srv, svccb *sbp); static void init_remote_server (const net_address &addr) { in_addr laddr; inet_aton (addr.hostname, &laddr); int tcpfd = inetsocket (SOCK_STREAM, addr.port-1, ntohl (laddr.s_addr)); if (tcpfd < 0) fatal ("binding TCP addr %s port %d: %m\n", addr.hostname.cstr (), addr.port-1); int ret = listen (tcpfd, 5); if (ret < 0) fatal ("listen (%d, 5): %m\n", tcpfd); fdcb (tcpfd, selread, wrap (&srvaccept, tcpfd)); warn << "Listening for sync requests on " << addr.hostname << ":" << addr.port-1 << ".\n"; } static void srvaccept (int lfd) { sockaddr_un sun; bzero (&sun, sizeof (sun)); socklen_t sunlen = sizeof (sun); int fd = accept (lfd, reinterpret_cast<sockaddr *> (&sun), &sunlen); if (fd < 0) { warn ("accept: unexpected EOF: %m\n"); return; } ref<axprt_stream> c = axprt_stream::alloc (fd, 1024*1025); // XXX should accept for whatever the chosen syncmode wants. ptr<asrv> s = asrv::alloc (c, merklesync_program_1); s->setcb (wrap (&sync_dispatch, s)); } static void sync_dispatch (ptr<asrv> srv, svccb *sbp) { if (!sbp) { srv->setcb (NULL); srv = NULL; return; } bool ok = false; syncdest_t *discrim = sbp->Xtmpl getarg<syncdest_t> (); for (size_t i = 0; i < maintainers.size (); i++) { // maintainer takes some time to get local db info from adbd; // must check for valid localtree before dispatching if (maintainers[i]->sync->sync_program ().progno == sbp->prog () && maintainers[i]->sync->ctype == discrim->ctype && maintainers[i]->host.vnode_num == (int) discrim->vnode && maintainers[i]->localtree () != NULL) { ok = true; ptr<merkle_tree> t = maintainers[i]->localtree (); maintainers[i]->sync->dispatch (t, sbp); break; } } if (!ok) sbp->reject (PROC_UNAVAIL); } // }}} // {{{ Control-side RPC execution void do_setmaint (svccb *sbp) { maint_setmaintarg *arg = sbp->Xtmpl getarg<maint_setmaintarg> (); for (unsigned int i = 0; i < maintainers.size (); i++) { if (arg->enable) { maintainers[i]->start (arg->delay); } else { maintainers[i]->stop (); } } sbp->replyref (arg->enable); } void do_initspace (svccb *sbp) { maint_dhashinfo_t *arg = sbp->Xtmpl getarg<maint_dhashinfo_t> (); maint_status res (MAINTPROC_OK); chord_node host = arg->host; dhash_ctype ctype = arg->ctype; // Check that we don't already have a maintainer for this host/ctype for (unsigned int i = 0; i < maintainers.size (); i++) { if (maintainers[i]->host.r.hostname == host.r.hostname && maintainers[i]->host.r.port == host.r.port && maintainers[i]->host.vnode_num == host.vnode_num && maintainers[i]->ctype == ctype) { res = MAINTPROC_ERR; sbp->replyref (res); return; } } ptr<syncer> s = sync_modes[sync_mode].producer (ctype); ptr<maintainer> m = maint_modes[maint_mode].producer (localdatapath, arg, s); maintainers.push_back (m); sbp->replyref (res); } void do_listen (svccb *sbp) { static bool initialized (false); maint_status res (MAINTPROC_OK); net_address *addr = sbp->Xtmpl getarg<net_address> (); if (!initialized) { init_remote_server (*addr); initialized = true; } else { res = MAINTPROC_ERR; } sbp->replyref (res); } void do_getrepairs (svccb *sbp) { maint_getrepairsarg *arg = sbp->Xtmpl getarg<maint_getrepairsarg> (); maint_getrepairsres *res = sbp->Xtmpl getarg<maint_getrepairsres> (); chord_node host = arg->host; dhash_ctype ctype = arg->ctype; ptr<maintainer> m = NULL; for (unsigned int i = 0; i < maintainers.size (); i++) { if (maintainers[i]->host.r.hostname == host.r.hostname && maintainers[i]->host.r.port == host.r.port && maintainers[i]->host.vnode_num == host.vnode_num && maintainers[i]->ctype == ctype) { m = maintainers[i]; } } if (!m) { res->status = MAINTPROC_ERR; sbp->reply (res); return; } m->getrepairs (arg->start, arg->thresh, arg->count, res->repairs); sbp->reply (res); } // }}} // {{{ Control-side RPC accept and dispatch static void accept_cb (int lfd); void dispatch (ref<axprt_stream> s, ptr<asrv> a, svccb *sbp); static void listen_unix (str sock_name) { unlink (sock_name); int clntfd = unixsocket (sock_name); if (clntfd < 0) fatal << "Error creating socket (UNIX)" << strerror (errno) << "\n"; if (listen (clntfd, 128) < 0) { fatal ("Error from listen: %m\n"); close (clntfd); } else { fdcb (clntfd, selread, wrap (accept_cb, clntfd)); } } static void accept_cb (int lfd) { sockaddr_un sun; bzero (&sun, sizeof (sun)); socklen_t sunlen = sizeof (sun); int fd = accept (lfd, reinterpret_cast<sockaddr *> (&sun), &sunlen); if (fd < 0) fatal ("EOF\n"); ref<axprt_stream> x = axprt_stream::alloc (fd, 1024*1025); ptr<asrv> a = asrv::alloc (x, maint_program_1); a->setcb (wrap (dispatch, x, a)); } void dispatch (ref<axprt_stream> s, ptr<asrv> a, svccb *sbp) { if (sbp == NULL) { warn << "EOF from client\n"; a = NULL; return; } switch (sbp->proc ()) { case MAINTPROC_NULL: sbp->reply (NULL); break; case MAINTPROC_SETMAINT: do_setmaint (sbp); break; case MAINTPROC_INITSPACE: do_initspace (sbp); break; case MAINTPROC_LISTEN: do_listen (sbp); break; case MAINTPROC_GETREPAIRS: do_getrepairs (sbp); break; default: warn << "unknown procedure: " << sbp->proc () << "\n"; sbp->reject (PROC_UNAVAIL); } return; } // }}} int main (int argc, char **argv) { str ctlsock = "/tmp/maint-sock"; char ch; setprogname (argv[0]); random_init (); localdatapath = "./maintdata/"; maint_mode = MAINT_CARBONITE; sync_mode = SYNC_MERKLE; while ((ch = getopt (argc, argv, "C:d:L:m:s:t"))!=-1) switch (ch) { case 'C': ctlsock = optarg; break; case 'd': localdatapath = optarg; break; case 'L': logfname = optarg; break; case 'm': maint_mode = select_mode<maint_mode_desc, maint_mode_t> (optarg, maint_modes, sizeof (maint_modes)/sizeof (maint_modes[0])); break; case 's': sync_mode = select_mode<sync_mode_desc, sync_mode_t> (optarg, sync_modes, sizeof (sync_modes)/sizeof (sync_modes[0])); break; case 't': modlogger::setmaxprio (modlogger::TRACE); break; default: usage (); break; } start_logs (); warn << "Starting up " << maint_modes[maint_mode].cmdline << " maintenance, syncing with " << sync_modes[sync_mode].cmdline << ".\n"; { struct stat sb; if (stat (localdatapath, &sb) < 0) { if (errno != ENOENT || (mkdir (localdatapath, 0755) < 0 && errno != EEXIST)) fatal ("%s: %m\n", localdatapath); if (stat (localdatapath, &sb) < 0) fatal ("stat (%s): %m\n", localdatapath); warn << "Created " << localdatapath << " for maintenance state.\n"; } if (!S_ISDIR (sb.st_mode)) fatal ("%s: not a directory\n", localdatapath); } listen_unix (ctlsock); sigcb (SIGHUP, wrap (&start_logs)); sigcb (SIGINT, wrap (&halt)); sigcb (SIGTERM, wrap (&halt)); amain (); } // vim: foldmethod=marker <commit_msg>Correct initialization of maint_getrepairsres in maintd.<commit_after>#include <arpc.h> #include <modlogger.h> #include <misc_utils.h> #include <dhash_types.h> #include <dhash_common.h> #include <merkle_sync_prot.h> #include <merkle.h> #include <maint_prot.h> #include "maint_policy.h" // {{{ Globals static char *logfname; static char *localdatapath; static vec<ptr<maintainer> > maintainers; enum maint_mode_t { MAINT_CARBONITE, MAINT_PASSINGTONE, } maint_mode; struct maint_mode_desc { maint_mode_t m; char *cmdline; maintainer_producer_t producer; } maint_modes[] = { { MAINT_CARBONITE, "carbonite", wrap (carbonite::produce_maintainer) }, { MAINT_PASSINGTONE, "passingtone", wrap (passingtone::produce_maintainer) } }; enum sync_mode_t { SYNC_MERKLE, SYNC_TIME } sync_mode; struct sync_mode_desc { sync_mode_t m; char *cmdline; syncer_producer_t producer; } sync_modes[] = { { SYNC_MERKLE, "merkle", wrap (merkle_sync::produce_syncer) } }; // }}} // {{{ General utility functions template<class VS, class S> static S select_mode (const char *arg, const VS *modes, int nmodes) { int i; S m = modes[0].m; for (i = 0; i < nmodes; i++) { if (strcmp (arg, modes[i].cmdline) == 0) { m = modes[i].m; break; } } if (i == nmodes) { strbuf s; for (i = 0; i < nmodes; i++) s << " " << modes[i].cmdline; fatal << "allowed modes are" << s << "\n"; } return m; } static void halt () { warnx << "Exiting on command.\n"; while (maintainers.size ()) { maintainers.pop_back (); } exit (0); } void start_logs () { static int logfd (-1); // XXX please don't call setlogfd or change errfd anywhere else... if (logfname) { if (logfd >= 0) close (logfd); logfd = open (logfname, O_RDWR | O_CREAT, 0666); if (logfd < 0) fatal << "Could not open log file " << logfd << " for appending.\n"; lseek (logfd, 0, SEEK_END); errfd = logfd; modlogger::setlogfd (logfd); } } static void usage () { warnx << "Usage: " << progname << "\t[-C maintd-ctlsock]\n" << "\t[-d localdatapath]\n" << "\t[-L logfilename]\n" << "\t[-m maintmode]\n" << "\t[-s syncmode]\n" << "\t[-t]\n"; exit (1); } // }}} // {{{ Remote-side RPC handling static void srvaccept (int fd); static void sync_dispatch (ptr<asrv> srv, svccb *sbp); static void init_remote_server (const net_address &addr) { in_addr laddr; inet_aton (addr.hostname, &laddr); int tcpfd = inetsocket (SOCK_STREAM, addr.port-1, ntohl (laddr.s_addr)); if (tcpfd < 0) fatal ("binding TCP addr %s port %d: %m\n", addr.hostname.cstr (), addr.port-1); int ret = listen (tcpfd, 5); if (ret < 0) fatal ("listen (%d, 5): %m\n", tcpfd); fdcb (tcpfd, selread, wrap (&srvaccept, tcpfd)); warn << "Listening for sync requests on " << addr.hostname << ":" << addr.port-1 << ".\n"; } static void srvaccept (int lfd) { sockaddr_un sun; bzero (&sun, sizeof (sun)); socklen_t sunlen = sizeof (sun); int fd = accept (lfd, reinterpret_cast<sockaddr *> (&sun), &sunlen); if (fd < 0) { warn ("accept: unexpected EOF: %m\n"); return; } ref<axprt_stream> c = axprt_stream::alloc (fd, 1024*1025); // XXX should accept for whatever the chosen syncmode wants. ptr<asrv> s = asrv::alloc (c, merklesync_program_1); s->setcb (wrap (&sync_dispatch, s)); } static void sync_dispatch (ptr<asrv> srv, svccb *sbp) { if (!sbp) { srv->setcb (NULL); srv = NULL; return; } bool ok = false; syncdest_t *discrim = sbp->Xtmpl getarg<syncdest_t> (); for (size_t i = 0; i < maintainers.size (); i++) { // maintainer takes some time to get local db info from adbd; // must check for valid localtree before dispatching if (maintainers[i]->sync->sync_program ().progno == sbp->prog () && maintainers[i]->sync->ctype == discrim->ctype && maintainers[i]->host.vnode_num == (int) discrim->vnode && maintainers[i]->localtree () != NULL) { ok = true; ptr<merkle_tree> t = maintainers[i]->localtree (); maintainers[i]->sync->dispatch (t, sbp); break; } } if (!ok) sbp->reject (PROC_UNAVAIL); } // }}} // {{{ Control-side RPC execution void do_setmaint (svccb *sbp) { maint_setmaintarg *arg = sbp->Xtmpl getarg<maint_setmaintarg> (); for (unsigned int i = 0; i < maintainers.size (); i++) { if (arg->enable) { maintainers[i]->start (arg->delay); } else { maintainers[i]->stop (); } } sbp->replyref (arg->enable); } void do_initspace (svccb *sbp) { maint_dhashinfo_t *arg = sbp->Xtmpl getarg<maint_dhashinfo_t> (); maint_status res (MAINTPROC_OK); chord_node host = arg->host; dhash_ctype ctype = arg->ctype; // Check that we don't already have a maintainer for this host/ctype for (unsigned int i = 0; i < maintainers.size (); i++) { if (maintainers[i]->host.r.hostname == host.r.hostname && maintainers[i]->host.r.port == host.r.port && maintainers[i]->host.vnode_num == host.vnode_num && maintainers[i]->ctype == ctype) { res = MAINTPROC_ERR; sbp->replyref (res); return; } } ptr<syncer> s = sync_modes[sync_mode].producer (ctype); ptr<maintainer> m = maint_modes[maint_mode].producer (localdatapath, arg, s); maintainers.push_back (m); sbp->replyref (res); } void do_listen (svccb *sbp) { static bool initialized (false); maint_status res (MAINTPROC_OK); net_address *addr = sbp->Xtmpl getarg<net_address> (); if (!initialized) { init_remote_server (*addr); initialized = true; } else { res = MAINTPROC_ERR; } sbp->replyref (res); } void do_getrepairs (svccb *sbp) { maint_getrepairsarg *arg = sbp->Xtmpl getarg<maint_getrepairsarg> (); maint_getrepairsres *res = sbp->Xtmpl getres<maint_getrepairsres> (); res->status = MAINTPROC_OK; chord_node host = arg->host; dhash_ctype ctype = arg->ctype; ptr<maintainer> m = NULL; for (unsigned int i = 0; i < maintainers.size (); i++) { if (maintainers[i]->host.r.hostname == host.r.hostname && maintainers[i]->host.r.port == host.r.port && maintainers[i]->host.vnode_num == host.vnode_num && maintainers[i]->ctype == ctype) { m = maintainers[i]; } } if (!m) { res->status = MAINTPROC_ERR; sbp->reply (res); return; } m->getrepairs (arg->start, arg->thresh, arg->count, res->repairs); sbp->reply (res); } // }}} // {{{ Control-side RPC accept and dispatch static void accept_cb (int lfd); void dispatch (ref<axprt_stream> s, ptr<asrv> a, svccb *sbp); static void listen_unix (str sock_name) { unlink (sock_name); int clntfd = unixsocket (sock_name); if (clntfd < 0) fatal << "Error creating socket (UNIX)" << strerror (errno) << "\n"; if (listen (clntfd, 128) < 0) { fatal ("Error from listen: %m\n"); close (clntfd); } else { fdcb (clntfd, selread, wrap (accept_cb, clntfd)); } } static void accept_cb (int lfd) { sockaddr_un sun; bzero (&sun, sizeof (sun)); socklen_t sunlen = sizeof (sun); int fd = accept (lfd, reinterpret_cast<sockaddr *> (&sun), &sunlen); if (fd < 0) fatal ("EOF\n"); ref<axprt_stream> x = axprt_stream::alloc (fd, 1024*1025); ptr<asrv> a = asrv::alloc (x, maint_program_1); a->setcb (wrap (dispatch, x, a)); } void dispatch (ref<axprt_stream> s, ptr<asrv> a, svccb *sbp) { if (sbp == NULL) { warn << "EOF from client\n"; a = NULL; return; } switch (sbp->proc ()) { case MAINTPROC_NULL: sbp->reply (NULL); break; case MAINTPROC_SETMAINT: do_setmaint (sbp); break; case MAINTPROC_INITSPACE: do_initspace (sbp); break; case MAINTPROC_LISTEN: do_listen (sbp); break; case MAINTPROC_GETREPAIRS: do_getrepairs (sbp); break; default: warn << "unknown procedure: " << sbp->proc () << "\n"; sbp->reject (PROC_UNAVAIL); } return; } // }}} int main (int argc, char **argv) { str ctlsock = "/tmp/maint-sock"; char ch; setprogname (argv[0]); random_init (); localdatapath = "./maintdata/"; maint_mode = MAINT_CARBONITE; sync_mode = SYNC_MERKLE; while ((ch = getopt (argc, argv, "C:d:L:m:s:t"))!=-1) switch (ch) { case 'C': ctlsock = optarg; break; case 'd': localdatapath = optarg; break; case 'L': logfname = optarg; break; case 'm': maint_mode = select_mode<maint_mode_desc, maint_mode_t> (optarg, maint_modes, sizeof (maint_modes)/sizeof (maint_modes[0])); break; case 's': sync_mode = select_mode<sync_mode_desc, sync_mode_t> (optarg, sync_modes, sizeof (sync_modes)/sizeof (sync_modes[0])); break; case 't': modlogger::setmaxprio (modlogger::TRACE); break; default: usage (); break; } start_logs (); warn << "Starting up " << maint_modes[maint_mode].cmdline << " maintenance, syncing with " << sync_modes[sync_mode].cmdline << ".\n"; { struct stat sb; if (stat (localdatapath, &sb) < 0) { if (errno != ENOENT || (mkdir (localdatapath, 0755) < 0 && errno != EEXIST)) fatal ("%s: %m\n", localdatapath); if (stat (localdatapath, &sb) < 0) fatal ("stat (%s): %m\n", localdatapath); warn << "Created " << localdatapath << " for maintenance state.\n"; } if (!S_ISDIR (sb.st_mode)) fatal ("%s: not a directory\n", localdatapath); } listen_unix (ctlsock); sigcb (SIGHUP, wrap (&start_logs)); sigcb (SIGINT, wrap (&halt)); sigcb (SIGTERM, wrap (&halt)); amain (); } // vim: foldmethod=marker <|endoftext|>
<commit_before>// AdvGfx.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "AdvGfx.h" #include "objLoader.h" #include "Raytracer.h" #include <fstream> #include <iostream> #include <string> #include <GLM\glm.hpp> #include <GLM\ext.hpp> namespace AdvGfxCore { using namespace std; void getErrors() { GLenum error = glGetError(); while (error) { cout << gluErrorString(error) << endl; error = glGetError(); } } static string textFileRead(const char *fileName) { string fileString = string(); // A string for storing the file contents string line = string(); // A string for holding the current line ifstream file(fileName); // Open an input stream with the selected file if (file.is_open()) { // If the file opened successfully while (!file.eof()) { // While we are not at the end of the file getline(file, line); // Get the current line fileString.append(line); // Append the line to our file string fileString.append("\n"); // Appand a new line character } file.close(); // Close the file } return fileString; // Return our string } static bool validateProgram(GLuint program) { const unsigned int BUFFER_SIZE = 512; char buffer[BUFFER_SIZE]; memset(buffer, 0, BUFFER_SIZE); GLsizei length = 0; glGetProgramInfoLog(program, BUFFER_SIZE, &length, buffer); // Ask OpenGL to give us the log associated with the program if (length > 0) // If we have any information to display { cout << "Program " << program << " link error: " << buffer << endl; // Output the information return false; } glValidateProgram(program); // Get OpenGL to try validating the program GLint status; glGetProgramiv(program, GL_VALIDATE_STATUS, &status); // Find out if the shader program validated correctly if (status == GL_FALSE) // If there was a problem validating { cout << "Error validating shader " << program << endl; // Output which program had the error return false; } return true; } glm::vec3 movement; GLuint prog; GLuint projLoc; GLuint viewLoc; GLuint modelLoc; camera c; glm::mat4 modelMatrix; float xChange = 0, yChange = 0, zChange = 0; clock_t lastDraw = clock(); Model* model = NULL; Model* model2 = NULL; GLuint texture; void Init(int w, int h) { glClearColor(.1f, .2f, .3f, 1.f); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); prog = glCreateProgram(); GLuint vert = glCreateShader(GL_VERTEX_SHADER); GLuint frag = glCreateShader(GL_FRAGMENT_SHADER); string v = textFileRead("rayShader.vert"); string f = textFileRead("rayShader.frag"); const char* vArr = v.c_str(); const char* fArr = f.c_str(); glShaderSource(vert, 1, &vArr, 0); glShaderSource(frag, 1, &fArr, 0); glCompileShaderARB(vert); glCompileShaderARB(frag); GLint compiled; glGetObjectParameterivARB(vert, GL_COMPILE_STATUS, &compiled); if (compiled) { glGetObjectParameterivARB(frag, GL_COMPILE_STATUS, &compiled); if (compiled) { //continue; } else { const unsigned int BUFFER_SIZE = 512; char buffer[BUFFER_SIZE]; memset(buffer, 0, BUFFER_SIZE); GLsizei length = 0; glGetShaderInfoLog(frag, BUFFER_SIZE, &length, buffer); cout << buffer << endl; } } glAttachShader(prog, frag); glAttachShader(prog, vert); glLinkProgram(prog); validateProgram(prog); projLoc = glGetUniformLocation(prog, "projection"); viewLoc = glGetUniformLocation(prog, "view"); modelLoc = glGetUniformLocation(prog, "model"); ResetCamera(); c.projectionMatrix = glm::perspective(60.0f, (float)w / h, 0.1f, 100.f); //glm::mat4 viewMatrix = glm::translate(glm::mat4(1.0f), viewVec); modelMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(0.01f, 0.01f, 0.01f)); glUseProgram(prog); glUniformMatrix4fv(projLoc, 1, false, &c.projectionMatrix[0][0]); //glUniformMatrix4fv(viewLoc, 1, false, &viewMatrix[0][0]); glUniformMatrix4fv(modelLoc, 1, false, &modelMatrix[0][0]); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); getErrors(); } void Draw() { RayTracer r; pixel *pixels = r.shootRay(c); clock_t startDraw = clock(); // Draw the pixels GLuint quad_vertexArrayID; glGenVertexArrays(1, &quad_vertexArrayID); glBindVertexArray(quad_vertexArrayID); static const GLfloat g_quad_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; GLuint quad_vertexBuffer; glGenBuffers(1, &quad_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW); pixel p; p.r = 255; p.a = 255; p.b = 0; p.g = 0; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixels); glDrawArrays(GL_TRIANGLES, 0, 2); getErrors(); /* float duration = (startDraw - lastDraw) / (float)CLOCKS_PER_SEC; //viewVec += glm::vec3(xChange * duration, yChange * duration, zChange * duration); glm::vec3 finalMovement = 10 * duration * movement; finalMovement = glm::rotateX(finalMovement, -(c.xRot)); finalMovement = glm::rotateY(finalMovement, -c.yRot); c.viewVec += finalMovement; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); c.viewMatrix = glm::mat4(1.0f); c.viewMatrix = glm::rotate(c.viewMatrix, c.xRot, glm::vec3(1.f, 0.f, 0.f)); c.viewMatrix = glm::rotate(c.viewMatrix, c.yRot, glm::vec3(0.f, 1.f, 0.f)); c.viewMatrix = glm::translate(c.viewMatrix, -(c.viewVec)); //modelMatrix = glm::rotate(modelMatrix, (float)duration * 50, 0.f, 1.f, 0.f); glUniformMatrix4fv(viewLoc, 1, false, &c.viewMatrix[0][0]); glUniformMatrix4fv(modelLoc, 1, false, &modelMatrix[0][0]); if(model) model->draw(); //getErrors(); lastDraw = startDraw; xChange = yChange = zChange = 0;*/ } void Resize(int width, int height) { glm::mat4 projectionMatrix = glm::perspective(60.0f, (float)width / height, 0.1f, 100.f); glUniformMatrix4fv(projLoc, 1, false, &projectionMatrix[0][0]); glViewport(0, 0, width, height); } void MoveCamera(float x, float y, float z) { xChange = x; yChange = y; zChange = z; } void MoveCamera(Movement m, bool stop) { switch (m) { case AdvGfxCore::Up: movement.y = (float)((int)!stop) * 1; break; case AdvGfxCore::Down: movement.y = (float)((int)!stop) * -1; break; case AdvGfxCore::Left: movement.x = (float)((int)!stop) * -1; break; case AdvGfxCore::Right: movement.x = (float)((int)!stop) * 1; break; case AdvGfxCore::Forward: movement.z = (float)((int)!stop) * -1; break; case AdvGfxCore::Backward: movement.z = (float)((int)!stop) * 1; break; } } void RotateCamera(int x, int y) { c.xRot -= y; c.yRot -= x; } void ResetCamera() { c.viewVec = glm::vec3(0.0f, 0.0f, 5.0f); c.xRot = 0.f; c.yRot = 0.f; } unsigned int getFileLength(ifstream& file) { if (!file.good()) return 0; int pos = file.tellg(); file.seekg(0, ios::end); int len = file.tellg(); file.seekg(ios::beg); cout << len << '\n'; return len; } const char** constructArray(ifstream& file, int length) { char* arr = new char[length + 1]; if (file.is_open()) { int i = 0; while (file.good()) { arr[i++] = file.get(); // gets char from line } arr[i] = 0; } file.close(); const char* returnArray = arr; return &returnArray; } void load(const char* path) { if(model) delete model; model = loadModel(path, prog); } }<commit_msg>niks maar moet committen omdat ie anders moeilijk doet<commit_after>// AdvGfx.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "AdvGfx.h" #include "objLoader.h" #include "Raytracer.h" #include <fstream> #include <iostream> #include <string> #include <GLM\glm.hpp> #include <GLM\ext.hpp> namespace AdvGfxCore { using namespace std; void getErrors() { GLenum error = glGetError(); while (error) { cout << gluErrorString(error) << endl; error = glGetError(); } } static string textFileRead(const char *fileName) { string fileString = string(); // A string for storing the file contents string line = string(); // A string for holding the current line ifstream file(fileName); // Open an input stream with the selected file if (file.is_open()) { // If the file opened successfully while (!file.eof()) { // While we are not at the end of the file getline(file, line); // Get the current line fileString.append(line); // Append the line to our file string fileString.append("\n"); // Appand a new line character } file.close(); // Close the file } return fileString; // Return our string } static bool validateProgram(GLuint program) { const unsigned int BUFFER_SIZE = 512; char buffer[BUFFER_SIZE]; memset(buffer, 0, BUFFER_SIZE); GLsizei length = 0; glGetProgramInfoLog(program, BUFFER_SIZE, &length, buffer); // Ask OpenGL to give us the log associated with the program if (length > 0) // If we have any information to display { cout << "Program " << program << " link error: " << buffer << endl; // Output the information return false; } glValidateProgram(program); // Get OpenGL to try validating the program GLint status; glGetProgramiv(program, GL_VALIDATE_STATUS, &status); // Find out if the shader program validated correctly if (status == GL_FALSE) // If there was a problem validating { cout << "Error validating shader " << program << endl; // Output which program had the error return false; } return true; } glm::vec3 movement; GLuint prog; GLuint projLoc; GLuint viewLoc; GLuint modelLoc; camera c; glm::mat4 modelMatrix; float xChange = 0, yChange = 0, zChange = 0; clock_t lastDraw = clock(); Model* model = NULL; Model* model2 = NULL; GLuint texture; void Init(int w, int h) { glClearColor(.1f, .2f, .3f, 1.f); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); prog = glCreateProgram(); GLuint vert = glCreateShader(GL_VERTEX_SHADER); GLuint frag = glCreateShader(GL_FRAGMENT_SHADER); string v = textFileRead("rayShader.vert"); string f = textFileRead("rayShader.frag"); const char* vArr = v.c_str(); const char* fArr = f.c_str(); glShaderSource(vert, 1, &vArr, 0); glShaderSource(frag, 1, &fArr, 0); glCompileShaderARB(vert); glCompileShaderARB(frag); GLint compiled; glGetObjectParameterivARB(vert, GL_COMPILE_STATUS, &compiled); if (compiled) { glGetObjectParameterivARB(frag, GL_COMPILE_STATUS, &compiled); if (compiled) { //continue; } else { const unsigned int BUFFER_SIZE = 512; char buffer[BUFFER_SIZE]; memset(buffer, 0, BUFFER_SIZE); GLsizei length = 0; glGetShaderInfoLog(frag, BUFFER_SIZE, &length, buffer); cout << buffer << endl; } } glAttachShader(prog, frag); glAttachShader(prog, vert); glLinkProgram(prog); validateProgram(prog); projLoc = glGetUniformLocation(prog, "projection"); viewLoc = glGetUniformLocation(prog, "view"); modelLoc = glGetUniformLocation(prog, "model"); ResetCamera(); c.projectionMatrix = glm::perspective(60.0f, (float)w / h, 0.1f, 100.f); //glm::mat4 viewMatrix = glm::translate(glm::mat4(1.0f), viewVec); modelMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(0.01f, 0.01f, 0.01f)); glUseProgram(prog); glUniformMatrix4fv(projLoc, 1, false, &c.projectionMatrix[0][0]); //glUniformMatrix4fv(viewLoc, 1, false, &viewMatrix[0][0]); glUniformMatrix4fv(modelLoc, 1, false, &modelMatrix[0][0]); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); getErrors(); } void Draw() { RayTracer r; pixel *pixels = r.shootRay(c); clock_t startDraw = clock(); // Draw the pixels GLuint quad_vertexArrayID; glGenVertexArrays(1, &quad_vertexArrayID); glBindVertexArray(quad_vertexArrayID); static const GLfloat g_quad_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; GLuint quad_vertexBuffer; glGenBuffers(1, &quad_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW); pixel p; p.r = 255; p.a = 255; p.b = 0; p.g = 0; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1280, 720, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glDrawArrays(GL_TRIANGLES, 0, 2); getErrors(); /* float duration = (startDraw - lastDraw) / (float)CLOCKS_PER_SEC; //viewVec += glm::vec3(xChange * duration, yChange * duration, zChange * duration); glm::vec3 finalMovement = 10 * duration * movement; finalMovement = glm::rotateX(finalMovement, -(c.xRot)); finalMovement = glm::rotateY(finalMovement, -c.yRot); c.viewVec += finalMovement; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); c.viewMatrix = glm::mat4(1.0f); c.viewMatrix = glm::rotate(c.viewMatrix, c.xRot, glm::vec3(1.f, 0.f, 0.f)); c.viewMatrix = glm::rotate(c.viewMatrix, c.yRot, glm::vec3(0.f, 1.f, 0.f)); c.viewMatrix = glm::translate(c.viewMatrix, -(c.viewVec)); //modelMatrix = glm::rotate(modelMatrix, (float)duration * 50, 0.f, 1.f, 0.f); glUniformMatrix4fv(viewLoc, 1, false, &c.viewMatrix[0][0]); glUniformMatrix4fv(modelLoc, 1, false, &modelMatrix[0][0]); if(model) model->draw(); //getErrors(); lastDraw = startDraw; xChange = yChange = zChange = 0;*/ } void Resize(int width, int height) { glm::mat4 projectionMatrix = glm::perspective(60.0f, (float)width / height, 0.1f, 100.f); glUniformMatrix4fv(projLoc, 1, false, &projectionMatrix[0][0]); glViewport(0, 0, width, height); } void MoveCamera(float x, float y, float z) { xChange = x; yChange = y; zChange = z; } void MoveCamera(Movement m, bool stop) { switch (m) { case AdvGfxCore::Up: movement.y = (float)((int)!stop) * 1; break; case AdvGfxCore::Down: movement.y = (float)((int)!stop) * -1; break; case AdvGfxCore::Left: movement.x = (float)((int)!stop) * -1; break; case AdvGfxCore::Right: movement.x = (float)((int)!stop) * 1; break; case AdvGfxCore::Forward: movement.z = (float)((int)!stop) * -1; break; case AdvGfxCore::Backward: movement.z = (float)((int)!stop) * 1; break; } } void RotateCamera(int x, int y) { c.xRot -= y; c.yRot -= x; } void ResetCamera() { c.viewVec = glm::vec3(0.0f, 0.0f, 5.0f); c.xRot = 0.f; c.yRot = 0.f; } unsigned int getFileLength(ifstream& file) { if (!file.good()) return 0; int pos = file.tellg(); file.seekg(0, ios::end); int len = file.tellg(); file.seekg(ios::beg); cout << len << '\n'; return len; } const char** constructArray(ifstream& file, int length) { char* arr = new char[length + 1]; if (file.is_open()) { int i = 0; while (file.good()) { arr[i++] = file.get(); // gets char from line } arr[i] = 0; } file.close(); const char* returnArray = arr; return &returnArray; } void load(const char* path) { if(model) delete model; model = loadModel(path, prog); } }<|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2008 Kevin Ottens <ervin@kde.org> Copyright 2008, 2009 Mario Bensi <nef@ipsquad.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <akonadi/control.h> #include <akonadi/itemcreatejob.h> #include <akonadi/itemmodel.h> #include <boost/shared_ptr.hpp> #include <kcal/todo.h> #include <KDE/KAction> #include <KDE/KActionCollection> #include <KDE/KConfigGroup> #include <KDE/KDebug> #include <KDE/KIcon> #include <KDE/KLineEdit> #include <KDE/KLocale> #include <KDE/KTabWidget> #include <QtGui/QDockWidget> #include <QtGui/QStackedWidget> #include <QtGui/QHeaderView> #include <QtGui/QToolBar> #include <QtGui/QVBoxLayout> #include "actionlistmodel.h" #include "actionlistview.h" #include "configdialog.h" #include "contextsmodel.h" #include "globalmodel.h" #include "globalsettings.h" #include "librarymodel.h" #include "projectsmodel.h" #include "todocategoriesmodel.h" #include "todoflatmodel.h" #include "todotreemodel.h" #include "sidebar.h" typedef boost::shared_ptr<KCal::Incidence> IncidencePtr; MainWindow::MainWindow(QWidget *parent) : KXmlGuiWindow(parent) { Akonadi::Control::start(); setupCentralWidget(); setupSideBar(); setupActions(); setupGUI(); restoreColumnState(); applySettings(); actionCollection()->action("project_mode")->trigger(); } void MainWindow::setupCentralWidget() { QWidget *centralWidget = new QWidget(this); centralWidget->setLayout(new QVBoxLayout(centralWidget)); m_view = new ActionListView(centralWidget); centralWidget->layout()->addWidget(m_view); m_actionList = new ActionListModel(this); m_view->setModel(m_actionList); m_actionList->setSourceModel(GlobalModel::todoFlat()); m_addActionEdit = new KLineEdit(centralWidget); centralWidget->layout()->addWidget(m_addActionEdit); m_addActionEdit->setClickMessage(i18n("Type and press enter to add an action")); m_addActionEdit->setClearButtonShown(true); connect(m_addActionEdit, SIGNAL(returnPressed()), this, SLOT(onAddActionRequested())); setCentralWidget(centralWidget); } void MainWindow::setupSideBar() { m_sidebar = new SideBar(this, actionCollection()); connect(m_sidebar, SIGNAL(projectChanged(const QModelIndex&)), this, SLOT(onProjectChanged(const QModelIndex&))); connect(m_sidebar, SIGNAL(contextChanged(const QModelIndex&)), this, SLOT(onContextChanged(const QModelIndex&))); QDockWidget *dock = new QDockWidget(this); dock->setObjectName("SideBar"); dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable); dock->setWidget(m_sidebar); addDockWidget(Qt::LeftDockWidgetArea, dock); } void MainWindow::setupActions() { KActionCollection *ac = actionCollection(); QActionGroup *modeGroup = new QActionGroup(this); modeGroup->setExclusive(true); KAction *action = ac->addAction("project_mode", m_sidebar, SLOT(switchToProjectMode())); action->setText(i18n("Project Mode")); action->setIcon(KIcon("view-pim-tasks")); action->setCheckable(true); modeGroup->addAction(action); action = ac->addAction("context_mode", m_sidebar, SLOT(switchToContextMode())); action->setText(i18n("Context Mode")); action->setIcon(KIcon("view-pim-notes")); action->setCheckable(true); modeGroup->addAction(action); ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog())); ac->addAction(KStandardAction::Quit, this, SLOT(close())); } void MainWindow::collectionClicked(const Akonadi::Collection &collection) { GlobalModel::todoFlat()->setCollection(collection); } void MainWindow::onProjectChanged(const QModelIndex &current) { delete m_actionList; m_actionList = new ActionListModel(this); m_view->setModel(m_actionList); if (GlobalModel::projectsLibrary()->isInbox(current)) { m_actionList->setSourceModel(GlobalModel::todoFlat()); m_actionList->setMode(ActionListModel::NoProjectMode); } else { m_actionList->setSourceModel(GlobalModel::todoTree()); m_actionList->setMode(ActionListModel::ProjectMode); QModelIndex projIndex = GlobalModel::projectsLibrary()->mapToSource(current); QModelIndex focusIndex = GlobalModel::projects()->mapToSource(projIndex); m_actionList->setSourceFocusIndex(focusIndex); } } void MainWindow::onContextChanged(const QModelIndex &current) { delete m_actionList; m_actionList = new ActionListModel(this); m_view->setModel(m_actionList); if (GlobalModel::contextsLibrary()->isInbox(current)) { m_actionList->setSourceModel(GlobalModel::todoFlat()); m_actionList->setMode(ActionListModel::NoContextMode); } else { m_actionList->setSourceModel(GlobalModel::todoCategories()); m_actionList->setMode(ActionListModel::ContextMode); QModelIndex catIndex = GlobalModel::contextsLibrary()->mapToSource(current); QModelIndex focusIndex = GlobalModel::contexts()->mapToSource(catIndex); m_actionList->setSourceFocusIndex(focusIndex); } } void MainWindow::onAddActionRequested() { QString summary = m_addActionEdit->text().trimmed(); m_addActionEdit->setText(QString()); if (summary.isEmpty()) return; QModelIndex current = m_actionList->mapToSource(m_view->currentIndex()); int type = current.sibling(current.row(), TodoFlatModel::RowType).data().toInt(); if (type==TodoFlatModel::StandardTodo) { current = current.parent(); } QString parentRemoteId; if (m_actionList->sourceModel()==GlobalModel::todoTree()) { QModelIndex parentIndex = current.sibling(current.row(), TodoFlatModel::RemoteId); parentRemoteId = GlobalModel::todoTree()->data(parentIndex).toString(); } QString category; if (m_actionList->sourceModel()==GlobalModel::todoCategories()) { QModelIndex categoryIndex = current.sibling(current.row(), TodoFlatModel::Summary); category = GlobalModel::todoCategories()->data(categoryIndex).toString(); } KCal::Todo *todo = new KCal::Todo(); todo->setSummary(summary); if (!parentRemoteId.isEmpty()) { todo->setRelatedToUid(parentRemoteId); } if (!category.isEmpty()) { todo->setCategories(category); } IncidencePtr incidence(todo); Akonadi::Item item; item.setMimeType("application/x-vnd.akonadi.calendar.todo"); item.setPayload<IncidencePtr>(incidence); Akonadi::Collection collection = GlobalModel::todoFlat()->collection(); Akonadi::ItemCreateJob *job = new Akonadi::ItemCreateJob(item, collection); job->start(); } void MainWindow::closeEvent(QCloseEvent *event) { saveColumnsState(); KXmlGuiWindow::closeEvent(event); } void MainWindow::saveAutoSaveSettings() { saveColumnsState(); KXmlGuiWindow::saveAutoSaveSettings(); } void MainWindow::saveColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); QByteArray state = m_view->header()->saveState(); cg.writeEntry("MainHeaderState", state.toBase64()); } void MainWindow::restoreColumnState() { KConfigGroup cg = autoSaveConfigGroup(); QByteArray state; if (cg.hasKey("MainHeaderState")) { state = cg.readEntry("MainHeaderState", state); m_view->header()->restoreState(QByteArray::fromBase64(state)); } } void MainWindow::showConfigDialog() { if (KConfigDialog::showDialog("settings")) { return; } ConfigDialog *dialog = new ConfigDialog(this, "settings", GlobalSettings::self()); connect(dialog, SIGNAL(settingsChanged(const QString&)), this, SLOT(applySettings())); dialog->show(); } void MainWindow::applySettings() { Akonadi::Collection collection(GlobalSettings::collectionId()); GlobalModel::todoFlat()->setCollection(collection); } <commit_msg>Fetch the collection first to be sure all the attributes got properly loaded.<commit_after>/* This file is part of Zanshin Todo. Copyright 2008 Kevin Ottens <ervin@kde.org> Copyright 2008, 2009 Mario Bensi <nef@ipsquad.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <akonadi/control.h> #include <akonadi/collectionfetchjob.h> #include <akonadi/itemcreatejob.h> #include <akonadi/itemmodel.h> #include <boost/shared_ptr.hpp> #include <kcal/todo.h> #include <KDE/KAction> #include <KDE/KActionCollection> #include <KDE/KConfigGroup> #include <KDE/KDebug> #include <KDE/KIcon> #include <KDE/KLineEdit> #include <KDE/KLocale> #include <KDE/KTabWidget> #include <QtGui/QDockWidget> #include <QtGui/QStackedWidget> #include <QtGui/QHeaderView> #include <QtGui/QToolBar> #include <QtGui/QVBoxLayout> #include "actionlistmodel.h" #include "actionlistview.h" #include "configdialog.h" #include "contextsmodel.h" #include "globalmodel.h" #include "globalsettings.h" #include "librarymodel.h" #include "projectsmodel.h" #include "todocategoriesmodel.h" #include "todoflatmodel.h" #include "todotreemodel.h" #include "sidebar.h" typedef boost::shared_ptr<KCal::Incidence> IncidencePtr; MainWindow::MainWindow(QWidget *parent) : KXmlGuiWindow(parent) { Akonadi::Control::start(); setupCentralWidget(); setupSideBar(); setupActions(); setupGUI(); restoreColumnState(); applySettings(); actionCollection()->action("project_mode")->trigger(); } void MainWindow::setupCentralWidget() { QWidget *centralWidget = new QWidget(this); centralWidget->setLayout(new QVBoxLayout(centralWidget)); m_view = new ActionListView(centralWidget); centralWidget->layout()->addWidget(m_view); m_actionList = new ActionListModel(this); m_view->setModel(m_actionList); m_actionList->setSourceModel(GlobalModel::todoFlat()); m_addActionEdit = new KLineEdit(centralWidget); centralWidget->layout()->addWidget(m_addActionEdit); m_addActionEdit->setClickMessage(i18n("Type and press enter to add an action")); m_addActionEdit->setClearButtonShown(true); connect(m_addActionEdit, SIGNAL(returnPressed()), this, SLOT(onAddActionRequested())); setCentralWidget(centralWidget); } void MainWindow::setupSideBar() { m_sidebar = new SideBar(this, actionCollection()); connect(m_sidebar, SIGNAL(projectChanged(const QModelIndex&)), this, SLOT(onProjectChanged(const QModelIndex&))); connect(m_sidebar, SIGNAL(contextChanged(const QModelIndex&)), this, SLOT(onContextChanged(const QModelIndex&))); QDockWidget *dock = new QDockWidget(this); dock->setObjectName("SideBar"); dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable); dock->setWidget(m_sidebar); addDockWidget(Qt::LeftDockWidgetArea, dock); } void MainWindow::setupActions() { KActionCollection *ac = actionCollection(); QActionGroup *modeGroup = new QActionGroup(this); modeGroup->setExclusive(true); KAction *action = ac->addAction("project_mode", m_sidebar, SLOT(switchToProjectMode())); action->setText(i18n("Project Mode")); action->setIcon(KIcon("view-pim-tasks")); action->setCheckable(true); modeGroup->addAction(action); action = ac->addAction("context_mode", m_sidebar, SLOT(switchToContextMode())); action->setText(i18n("Context Mode")); action->setIcon(KIcon("view-pim-notes")); action->setCheckable(true); modeGroup->addAction(action); ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog())); ac->addAction(KStandardAction::Quit, this, SLOT(close())); } void MainWindow::collectionClicked(const Akonadi::Collection &collection) { GlobalModel::todoFlat()->setCollection(collection); } void MainWindow::onProjectChanged(const QModelIndex &current) { delete m_actionList; m_actionList = new ActionListModel(this); m_view->setModel(m_actionList); if (GlobalModel::projectsLibrary()->isInbox(current)) { m_actionList->setSourceModel(GlobalModel::todoFlat()); m_actionList->setMode(ActionListModel::NoProjectMode); } else { m_actionList->setSourceModel(GlobalModel::todoTree()); m_actionList->setMode(ActionListModel::ProjectMode); QModelIndex projIndex = GlobalModel::projectsLibrary()->mapToSource(current); QModelIndex focusIndex = GlobalModel::projects()->mapToSource(projIndex); m_actionList->setSourceFocusIndex(focusIndex); } } void MainWindow::onContextChanged(const QModelIndex &current) { delete m_actionList; m_actionList = new ActionListModel(this); m_view->setModel(m_actionList); if (GlobalModel::contextsLibrary()->isInbox(current)) { m_actionList->setSourceModel(GlobalModel::todoFlat()); m_actionList->setMode(ActionListModel::NoContextMode); } else { m_actionList->setSourceModel(GlobalModel::todoCategories()); m_actionList->setMode(ActionListModel::ContextMode); QModelIndex catIndex = GlobalModel::contextsLibrary()->mapToSource(current); QModelIndex focusIndex = GlobalModel::contexts()->mapToSource(catIndex); m_actionList->setSourceFocusIndex(focusIndex); } } void MainWindow::onAddActionRequested() { QString summary = m_addActionEdit->text().trimmed(); m_addActionEdit->setText(QString()); if (summary.isEmpty()) return; QModelIndex current = m_actionList->mapToSource(m_view->currentIndex()); int type = current.sibling(current.row(), TodoFlatModel::RowType).data().toInt(); if (type==TodoFlatModel::StandardTodo) { current = current.parent(); } QString parentRemoteId; if (m_actionList->sourceModel()==GlobalModel::todoTree()) { QModelIndex parentIndex = current.sibling(current.row(), TodoFlatModel::RemoteId); parentRemoteId = GlobalModel::todoTree()->data(parentIndex).toString(); } QString category; if (m_actionList->sourceModel()==GlobalModel::todoCategories()) { QModelIndex categoryIndex = current.sibling(current.row(), TodoFlatModel::Summary); category = GlobalModel::todoCategories()->data(categoryIndex).toString(); } KCal::Todo *todo = new KCal::Todo(); todo->setSummary(summary); if (!parentRemoteId.isEmpty()) { todo->setRelatedToUid(parentRemoteId); } if (!category.isEmpty()) { todo->setCategories(category); } IncidencePtr incidence(todo); Akonadi::Item item; item.setMimeType("application/x-vnd.akonadi.calendar.todo"); item.setPayload<IncidencePtr>(incidence); Akonadi::Collection collection = GlobalModel::todoFlat()->collection(); Akonadi::ItemCreateJob *job = new Akonadi::ItemCreateJob(item, collection); job->start(); } void MainWindow::closeEvent(QCloseEvent *event) { saveColumnsState(); KXmlGuiWindow::closeEvent(event); } void MainWindow::saveAutoSaveSettings() { saveColumnsState(); KXmlGuiWindow::saveAutoSaveSettings(); } void MainWindow::saveColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); QByteArray state = m_view->header()->saveState(); cg.writeEntry("MainHeaderState", state.toBase64()); } void MainWindow::restoreColumnState() { KConfigGroup cg = autoSaveConfigGroup(); QByteArray state; if (cg.hasKey("MainHeaderState")) { state = cg.readEntry("MainHeaderState", state); m_view->header()->restoreState(QByteArray::fromBase64(state)); } } void MainWindow::showConfigDialog() { if (KConfigDialog::showDialog("settings")) { return; } ConfigDialog *dialog = new ConfigDialog(this, "settings", GlobalSettings::self()); connect(dialog, SIGNAL(settingsChanged(const QString&)), this, SLOT(applySettings())); dialog->show(); } void MainWindow::applySettings() { Akonadi::Collection collection(GlobalSettings::collectionId()); Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(collection, Akonadi::CollectionFetchJob::Base); job->exec(); GlobalModel::todoFlat()->setCollection(job->collections().first()); } <|endoftext|>
<commit_before>#include <iostream> class Base { public: virtual void func(int x) { std::cout << "Base::func(int)" << '\n' << "x = " << x << '\n'; } }; class Sub : public Base { public: void func(int x) // <=> virtual void func(int x) { std::cout << "Sub::func(int)" << '\n' << "x = " << ++x << '\n'; } }; void test(Base& x) { x.func(5); } int main() { Base bc; Sub sc; test(bc); test(sc); sc.Base::func(10); sc.func(10); Base& rbc = bc; rbc.func(20); Sub& rsc = sc; rsc.func(20); return 0; } <commit_msg>derived<commit_after>#include <iostream> class Base { public: virtual void func(int x) { std::cout << "Base::func(int)" << '\n' << "x = " << x << '\n'; } }; class Sub : public Base { public: void func(int x) // <=> virtual void func(int x) { std::cout << "Sub::func(int)" << '\n' << "x = " << ++x << '\n'; } }; int main() { Base bc; Sub sc; Base& rbc = bc; Base& rsc = sc; rbc.func(20); rsc.func(20); sc.Base::func(10); sc.func(10); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 Alec Thomas <alec@swapoff.org> * All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. * * Author: Alec Thomas <alec@swapoff.org> */ // http://docs.python.org/2/extending/extending.html #include <pybind11/pybind11.h> #include <pybind11/eval.h> #include <cassert> #include <string> #include <iostream> #include <sstream> #include "entityx/python/PythonScript.hpp" #include "entityx/python/PythonSystem.h" #include "entityx/python/config.h" namespace py = pybind11; namespace entityx { namespace python { class PythonEntityXLogger { public: PythonEntityXLogger() {} explicit PythonEntityXLogger(PythonSystem::LoggerFunction logger) : logger_(logger) {} ~PythonEntityXLogger() { flush(true); } void write(const std::string &text) { line_ += text; flush(); } private: void flush(bool force = false) { size_t offset; while ( (offset = line_.find('\n')) != std::string::npos ) { std::string text = line_.substr(0, offset); logger_(text); line_ = line_.substr(offset + 1); } if ( force && line_.size() ) { logger_(line_); line_ = ""; } } PythonSystem::LoggerFunction logger_; std::string line_; }; /** * Base class for Python entities. */ /*FIXME(SMA): Doesn't work :(. I've ported it to Python entityx/__init__.py struct PythonEntity { explicit PythonEntity(Entity& e) : _entity(e) { assert(_entity.valid()); } virtual ~PythonEntity() {} explicit PythonEntity(const PythonEntity &) = delete; operator Entity () const { return _entity; } void destroy() { _entity.destroy(); } virtual void update(float dt) {} Entity::Id _entity_id() const { assert(_entity.valid()); return _entity.id(); } bool valid() const { return _entity.valid(); } Entity _entity; };*/ static std::string Entity_Id_repr(Entity::Id id) { std::stringstream repr; repr << "<Entity::Id " << id.index() << "." << id.version() << ">"; return repr.str(); } Entity EntityManager_new_entity(EntityManager& entity_manager, py::object self) { Entity entity = entity_manager.create(); entity.assign<PythonScript>(self); return entity; } namespace _py_entityx { PYBIND11_PLUGIN(_entityx) { py::module m("_entityx"); py::class_<PythonEntityXLogger>(m, "Logger") // no init .def("write", &PythonEntityXLogger::write); py::class_<Entity>(m, "_Entity") .def(py::init<EntityManager*, Entity::Id>()) .def_property_readonly("id", &Entity::id) .def("valid", &Entity::valid) .def("destroy", &Entity::destroy); //FIXME(SMA): I really have no clue none of these are working... //py::class_<PythonEntity>(m, "Entity") //.def_readwrite("entity", &PythonEntity::_entity, py::return_value_policy::reference); //.def_property_readonly("id", &PythonEntity::_entity_id) //.def("valid", &PythonEntity::valid) //.def("update", &PythonEntity::update) //.def("destroy", &PythonEntity::destroy); //py::implicitly_convertible<PythonEntity, Entity>(); py::class_<Entity::Id>(m, "EntityId") // no init .def_property_readonly("id", &Entity::Id::id) .def_property_readonly("index", &Entity::Id::index) .def_property_readonly("version", &Entity::Id::version) .def("__repr__", &Entity_Id_repr); py::class_<PythonScript>(m, "PythonScript") .def(py::init<py::object>()) .def("assign_to", &assign_to<PythonScript>) .def_static("get_component", &get_component<PythonScript>, py::return_value_policy::reference); py::class_<EntityManager>(m, "EntityManager") // no init .def("new_entity", &EntityManager_new_entity, py::return_value_policy::copy); return m.ptr(); } } // namespace _py_entityx static void log_to_stderr(const std::string &text) { std::cerr << "python stderr: " << text << std::endl; } static void log_to_stdout(const std::string &text) { std::cout << "python stdout: " << text << std::endl; } // PythonSystem below here bool PythonSystem::initialized_ = false; PythonSystem::PythonSystem(EntityManager& entity_manager) : em_(entity_manager), stdout_(log_to_stdout), stderr_(log_to_stderr) { Py_Initialize(); if ( !initialized_ ) { initialize_python_module(); initialized_ = true; } } PythonSystem::~PythonSystem() { // TODO(SMA): Look into cleaning up our module. //try { // py::object entityx = py::module::import("_entityx"); // entityx.attr("_entity_manager"); // entityx.attr("_event_manager").del(); // py::object sys = py::module::import("sys"); // sys.attr("stdout").del(); // sys.attr("stderr").del(); // py::object gc = py::module::import("gc"); // gc.attr("collect")(); //} //catch ( ... ) { // PyErr_Print(); // PyErr_Clear(); // throw; //} // FIXME: It would be good to do this, but it is not supported by boost::python: // http://www.boost.org/doc/libs/1_53_0/libs/python/todo.html#pyfinalize-safety // Py_Finalize(); } void PythonSystem::add_installed_library_path() { add_path(ENTITYX_INSTALLED_PYTHON_PACKAGE_DIR); } void PythonSystem::add_path(const std::string &path) { python_paths_.push_back(path); } void PythonSystem::initialize_python_module() { _py_entityx::pybind11_init(); } void PythonSystem::configure(EventManager& ev) { ev.subscribe<ComponentAddedEvent<PythonScript>>(*this); try { py::object main_module = py::module::import("__main__"); py::object main_namespace = main_module.attr("__dict__"); // Initialize logging. py::object sys = py::module::import("sys"); sys.attr("stdout") = PythonEntityXLogger(stdout_); sys.attr("stderr") = PythonEntityXLogger(stderr_); // Add paths to interpreter sys.path for ( auto path : python_paths_ ) { py::str dir(path.c_str()); sys.attr("path").attr("insert")(0, dir); } py::object entityx = py::module::import("_entityx"); entityx.attr("_entity_manager") = &em_; } catch ( const py::error_already_set& e ) { // TODO(SMA) : Really!? fix this. Should handle execption e better here. PyErr_SetString(PyExc_RuntimeError, e.what()); PyErr_Print(); PyErr_Clear(); throw; } } void PythonSystem::update(EntityManager & em, EventManager & events, TimeDelta dt) { em.each<PythonScript>( [=](Entity entity, PythonScript& python) { try { // Access PythonEntity and call Update. python.object.attr("update")(dt); } catch ( const py::error_already_set& e ) { // TODO(SMA) : Really!? fix this. Should handle execption e better here. PyErr_SetString(PyExc_RuntimeError, e.what()); PyErr_Print(); PyErr_Clear(); throw; } }); } void PythonSystem::log_to(LoggerFunction sout, LoggerFunction serr) { stdout_ = sout; stderr_ = serr; } void PythonSystem::receive(const ComponentAddedEvent<PythonScript> &event) { // If the component was created in C++ it won't have a Python object // associated with it. Create one. if ( !event.component->object ) { try { // TODO(SMA): use system.importer and import objects while always "hot reloading" them. // this might be a -little- inefficent, try to measure cost here. py::object importer = py::module::import("entityx.importer"); py::object import_f = importer.attr("reload"); py::object module = import_f.call(event.component->module); py::object cls = module.attr(event.component->cls.c_str()); py::object from_raw_entity = cls.attr("_from_raw_entity"); py::list args; if ( py::len(event.component->args) != 0 ) { args.append(event.component->args); } py::kwargs kwargs; kwargs["entity"] = Entity(event.entity); // Access PythonEntity and call Update. ComponentHandle<PythonScript> scripthandle = event.component; scripthandle->object = from_raw_entity.operator()<py::return_value_policy::reference_internal>(*args, **kwargs); } catch ( const py::error_already_set& e ) { PyErr_SetString(PyExc_RuntimeError, e.what()); PyErr_Print(); PyErr_Clear(); throw; } } } } // namespace python } // namespace entityx <commit_msg>Remove depercated use of call.<commit_after>/* * Copyright (C) 2013 Alec Thomas <alec@swapoff.org> * All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. * * Author: Alec Thomas <alec@swapoff.org> */ // http://docs.python.org/2/extending/extending.html #include <pybind11/pybind11.h> #include <pybind11/eval.h> #include <cassert> #include <string> #include <iostream> #include <sstream> #include "entityx/python/PythonScript.hpp" #include "entityx/python/PythonSystem.h" #include "entityx/python/config.h" namespace py = pybind11; namespace entityx { namespace python { class PythonEntityXLogger { public: PythonEntityXLogger() {} explicit PythonEntityXLogger(PythonSystem::LoggerFunction logger) : logger_(logger) {} ~PythonEntityXLogger() { flush(true); } void write(const std::string &text) { line_ += text; flush(); } private: void flush(bool force = false) { size_t offset; while ( (offset = line_.find('\n')) != std::string::npos ) { std::string text = line_.substr(0, offset); logger_(text); line_ = line_.substr(offset + 1); } if ( force && line_.size() ) { logger_(line_); line_ = ""; } } PythonSystem::LoggerFunction logger_; std::string line_; }; /** * Base class for Python entities. */ /*FIXME(SMA): Doesn't work :(. I've ported it to Python entityx/__init__.py struct PythonEntity { explicit PythonEntity(Entity& e) : _entity(e) { assert(_entity.valid()); } virtual ~PythonEntity() {} explicit PythonEntity(const PythonEntity &) = delete; operator Entity () const { return _entity; } void destroy() { _entity.destroy(); } virtual void update(float dt) {} Entity::Id _entity_id() const { assert(_entity.valid()); return _entity.id(); } bool valid() const { return _entity.valid(); } Entity _entity; };*/ static std::string Entity_Id_repr(Entity::Id id) { std::stringstream repr; repr << "<Entity::Id " << id.index() << "." << id.version() << ">"; return repr.str(); } Entity EntityManager_new_entity(EntityManager& entity_manager, py::object self) { Entity entity = entity_manager.create(); entity.assign<PythonScript>(self); return entity; } namespace _py_entityx { PYBIND11_PLUGIN(_entityx) { py::module m("_entityx"); py::class_<PythonEntityXLogger>(m, "Logger") // no init .def("write", &PythonEntityXLogger::write); py::class_<Entity>(m, "_Entity") .def(py::init<EntityManager*, Entity::Id>()) .def_property_readonly("id", &Entity::id) .def("valid", &Entity::valid) .def("destroy", &Entity::destroy); //FIXME(SMA): I really have no clue none of these are working... //py::class_<PythonEntity>(m, "Entity") //.def_readwrite("entity", &PythonEntity::_entity, py::return_value_policy::reference); //.def_property_readonly("id", &PythonEntity::_entity_id) //.def("valid", &PythonEntity::valid) //.def("update", &PythonEntity::update) //.def("destroy", &PythonEntity::destroy); //py::implicitly_convertible<PythonEntity, Entity>(); py::class_<Entity::Id>(m, "EntityId") // no init .def_property_readonly("id", &Entity::Id::id) .def_property_readonly("index", &Entity::Id::index) .def_property_readonly("version", &Entity::Id::version) .def("__repr__", &Entity_Id_repr); py::class_<PythonScript>(m, "PythonScript") .def(py::init<py::object>()) .def("assign_to", &assign_to<PythonScript>) .def_static("get_component", &get_component<PythonScript>, py::return_value_policy::reference); py::class_<EntityManager>(m, "EntityManager") // no init .def("new_entity", &EntityManager_new_entity, py::return_value_policy::copy); return m.ptr(); } } // namespace _py_entityx static void log_to_stderr(const std::string &text) { std::cerr << "python stderr: " << text << std::endl; } static void log_to_stdout(const std::string &text) { std::cout << "python stdout: " << text << std::endl; } // PythonSystem below here bool PythonSystem::initialized_ = false; PythonSystem::PythonSystem(EntityManager& entity_manager) : em_(entity_manager), stdout_(log_to_stdout), stderr_(log_to_stderr) { Py_Initialize(); if ( !initialized_ ) { initialize_python_module(); initialized_ = true; } } PythonSystem::~PythonSystem() { // TODO(SMA): Look into cleaning up our module. //try { // py::object entityx = py::module::import("_entityx"); // entityx.attr("_entity_manager"); // entityx.attr("_event_manager").del(); // py::object sys = py::module::import("sys"); // sys.attr("stdout").del(); // sys.attr("stderr").del(); // py::object gc = py::module::import("gc"); // gc.attr("collect")(); //} //catch ( ... ) { // PyErr_Print(); // PyErr_Clear(); // throw; //} // FIXME: It would be good to do this, but it is not supported by boost::python: // http://www.boost.org/doc/libs/1_53_0/libs/python/todo.html#pyfinalize-safety // Py_Finalize(); } void PythonSystem::add_installed_library_path() { add_path(ENTITYX_INSTALLED_PYTHON_PACKAGE_DIR); } void PythonSystem::add_path(const std::string &path) { python_paths_.push_back(path); } void PythonSystem::initialize_python_module() { _py_entityx::pybind11_init(); } void PythonSystem::configure(EventManager& ev) { ev.subscribe<ComponentAddedEvent<PythonScript>>(*this); try { py::object main_module = py::module::import("__main__"); py::object main_namespace = main_module.attr("__dict__"); // Initialize logging. py::object sys = py::module::import("sys"); sys.attr("stdout") = PythonEntityXLogger(stdout_); sys.attr("stderr") = PythonEntityXLogger(stderr_); // Add paths to interpreter sys.path for ( auto path : python_paths_ ) { py::str dir(path.c_str()); sys.attr("path").attr("insert")(0, dir); } py::object entityx = py::module::import("_entityx"); entityx.attr("_entity_manager") = &em_; } catch ( const py::error_already_set& e ) { // TODO(SMA) : Really!? fix this. Should handle execption e better here. PyErr_SetString(PyExc_RuntimeError, e.what()); PyErr_Print(); PyErr_Clear(); throw; } } void PythonSystem::update(EntityManager & em, EventManager & events, TimeDelta dt) { em.each<PythonScript>( [=](Entity entity, PythonScript& python) { try { // Access PythonEntity and call Update. python.object.attr("update")(dt); } catch ( const py::error_already_set& e ) { // TODO(SMA) : Really!? fix this. Should handle execption e better here. PyErr_SetString(PyExc_RuntimeError, e.what()); PyErr_Print(); PyErr_Clear(); throw; } }); } void PythonSystem::log_to(LoggerFunction sout, LoggerFunction serr) { stdout_ = sout; stderr_ = serr; } void PythonSystem::receive(const ComponentAddedEvent<PythonScript> &event) { // If the component was created in C++ it won't have a Python object // associated with it. Create one. if ( !event.component->object ) { try { // TODO(SMA): use system.importer and import objects while always "hot reloading" them. // this might be a -little- inefficent, try to measure cost here. py::object importer = py::module::import("entityx.importer"); py::object import_f = importer.attr("reload"); py::object module = import_f(event.component->module); py::object cls = module.attr(event.component->cls.c_str()); py::object from_raw_entity = cls.attr("_from_raw_entity"); py::list args; if ( py::len(event.component->args) != 0 ) { args.append(event.component->args); } py::kwargs kwargs; kwargs["entity"] = Entity(event.entity); // Access PythonEntity and call Update. ComponentHandle<PythonScript> scripthandle = event.component; scripthandle->object = from_raw_entity.operator()<py::return_value_policy::reference_internal>(*args, **kwargs); } catch ( const py::error_already_set& e ) { PyErr_SetString(PyExc_RuntimeError, e.what()); PyErr_Print(); PyErr_Clear(); throw; } } } } // namespace python } // namespace entityx <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: spinbutton.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-04-02 10:57:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef FORMS_SOURCE_COMPONENT_SPINBUTTON_HXX #define FORMS_SOURCE_COMPONENT_SPINBUTTON_HXX #ifndef _FORMS_FORMCOMPONENT_HXX_ #include "FormComponent.hxx" #endif #ifndef FORMS_MODULE_HXX #include "formsmodule.hxx" #endif //........................................................................ namespace frm { //........................................................................ //==================================================================== //= OSpinButtonModel //==================================================================== class OSpinButtonModel :public OBoundControlModel ,public ::comphelper::OAggregationArrayUsageHelper< OSpinButtonModel > { private: // <properties> sal_Int32 m_nDefaultSpinValue; // </properties> protected: DECLARE_DEFAULT_LEAF_XTOR( OSpinButtonModel ); // XServiceInfo DECLARE_SERVICE_REGISTRATION( OSpinButtonModel ); // XPersistObject DECLARE_XPERSISTOBJECT(); // XCloneable DECLARE_XCLONEABLE(); // XPropertyState virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 _nHandle ) const; // XPropertySet and related helpers ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException); ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual void fillProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps ) const; // OPropertySetHelper virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& _rValue, sal_Int32 _nHandle ) const; virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue ) throw ( ::com::sun::star::uno::Exception ); 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 ); // OBoundControlModel virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual ::com::sun::star::uno::Any translateExternalValueToControlValue( ); virtual ::com::sun::star::uno::Any translateControlValueToExternalValue( ); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); // XCoponent and related helpers virtual void SAL_CALL disposing(); IMPLEMENT_INFO_SERVICE() }; //........................................................................ } // namespacefrm //........................................................................ #endif // FORMS_SOURCE_COMPONENT_SPINBUTTON_HXX <commit_msg>INTEGRATION: CWS frmcontrols02 (1.2.6); FILE MERGED 2004/02/02 07:47:57 fs 1.2.6.1: functionality moved to another include file<commit_after>/************************************************************************* * * $RCSfile: spinbutton.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-04-13 11:16:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef FORMS_SOURCE_COMPONENT_SPINBUTTON_HXX #define FORMS_SOURCE_COMPONENT_SPINBUTTON_HXX #ifndef _FORMS_FORMCOMPONENT_HXX_ #include "FormComponent.hxx" #endif #ifndef FRM_MODULE_HXX #include "frm_module.hxx" #endif //........................................................................ namespace frm { //........................................................................ //==================================================================== //= OSpinButtonModel //==================================================================== class OSpinButtonModel :public OBoundControlModel ,public ::comphelper::OAggregationArrayUsageHelper< OSpinButtonModel > { private: // <properties> sal_Int32 m_nDefaultSpinValue; // </properties> protected: DECLARE_DEFAULT_LEAF_XTOR( OSpinButtonModel ); // XServiceInfo DECLARE_SERVICE_REGISTRATION( OSpinButtonModel ); // XPersistObject DECLARE_XPERSISTOBJECT(); // XCloneable DECLARE_XCLONEABLE(); // XPropertyState virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 _nHandle ) const; // XPropertySet and related helpers ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException); ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual void fillProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps ) const; // OPropertySetHelper virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& _rValue, sal_Int32 _nHandle ) const; virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue ) throw ( ::com::sun::star::uno::Exception ); 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 ); // OBoundControlModel virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual ::com::sun::star::uno::Any translateExternalValueToControlValue( ); virtual ::com::sun::star::uno::Any translateControlValueToExternalValue( ); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); // XCoponent and related helpers virtual void SAL_CALL disposing(); IMPLEMENT_INFO_SERVICE() }; //........................................................................ } // namespacefrm //........................................................................ #endif // FORMS_SOURCE_COMPONENT_SPINBUTTON_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pivotsh.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-05-10 16:07:56 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include "scitems.hxx" #include <svx/srchitem.hxx> #include <sfx2/app.hxx> #include <sfx2/objface.hxx> #include <sfx2/objsh.hxx> #include <sfx2/request.hxx> #include <svtools/whiter.hxx> #include <vcl/msgbox.hxx> #include "sc.hrc" #include "pivotsh.hxx" #include "tabvwsh.hxx" #include "docsh.hxx" #include "scresid.hxx" #include "document.hxx" #include "dpobject.hxx" #include "dpshttab.hxx" #include "dbdocfun.hxx" #include "uiitems.hxx" //CHINA001 #include "pfiltdlg.hxx" #include "scabstdlg.hxx" //CHINA001 //------------------------------------------------------------------------ #define ScPivotShell #include "scslots.hxx" //------------------------------------------------------------------------ TYPEINIT1( ScPivotShell, SfxShell ); SFX_IMPL_INTERFACE(ScPivotShell, SfxShell, ScResId(SCSTR_PIVOTSHELL)) { SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_PIVOT) ); } //------------------------------------------------------------------------ ScPivotShell::ScPivotShell( ScTabViewShell* pViewSh ) : SfxShell(pViewSh), pViewShell( pViewSh ) { SetPool( &pViewSh->GetPool() ); SetUndoManager( pViewSh->GetViewData()->GetSfxDocShell()->GetUndoManager() ); SetHelpId( HID_SCSHELL_PIVOTSH ); SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Pivot"))); } //------------------------------------------------------------------------ ScPivotShell::~ScPivotShell() { } //------------------------------------------------------------------------ void ScPivotShell::Execute( SfxRequest& rReq ) { switch ( rReq.GetSlot() ) { case SID_PIVOT_RECALC: pViewShell->RecalcPivotTable(); break; case SID_PIVOT_KILL: pViewShell->DeletePivotTable(); break; case SID_DP_FILTER: { ScDPObject* pDPObj = GetCurrDPObject(); if( pDPObj ) { ScQueryParam aQueryParam; USHORT nSrcTab = 0; const ScSheetSourceDesc* pDesc = pDPObj->GetSheetDesc(); DBG_ASSERT( pDesc, "no sheet source for DP filter dialog" ); if( pDesc ) { aQueryParam = pDesc->aQueryParam; nSrcTab = pDesc->aSourceRange.aStart.Tab(); } ScViewData* pViewData = pViewShell->GetViewData(); SfxItemSet aArgSet( pViewShell->GetPool(), SCITEM_QUERYDATA, SCITEM_QUERYDATA ); aArgSet.Put( ScQueryItem( SCITEM_QUERYDATA, pViewData, &aQueryParam ) ); //CHINA001 ScPivotFilterDlg* pDlg = new ScPivotFilterDlg( //CHINA001 pViewShell->GetDialogParent(), aArgSet, nSrcTab ); ScAbstractDialogFactory* pFact = ScAbstractDialogFactory::Create(); DBG_ASSERT(pFact, "ScAbstractFactory create fail!");//CHINA001 AbstractScPivotFilterDlg* pDlg = pFact->CreateScPivotFilterDlg( pViewShell->GetDialogParent(), aArgSet, nSrcTab, ResId(RID_SCDLG_PIVOTFILTER)); DBG_ASSERT(pDlg, "Dialog create fail!");//CHINA001 if( pDlg->Execute() == RET_OK ) { ScSheetSourceDesc aNewDesc; if( pDesc ) aNewDesc = *pDesc; const ScQueryItem& rQueryItem = pDlg->GetOutputItem(); aNewDesc.aQueryParam = rQueryItem.GetQueryData(); ScDPObject aNewObj( *pDPObj ); aNewObj.SetSheetDesc( aNewDesc ); ScDBDocFunc aFunc( *pViewData->GetDocShell() ); aFunc.DataPilotUpdate( pDPObj, &aNewObj, TRUE, FALSE ); pViewData->GetView()->CursorPosChanged(); // shells may be switched } delete pDlg; } } break; } } //------------------------------------------------------------------------ void __EXPORT ScPivotShell::GetState( SfxItemSet& rSet ) { ScDocShell* pDocSh = pViewShell->GetViewData()->GetDocShell(); ScDocument* pDoc = pDocSh->GetDocument(); BOOL bDisable = pDocSh->IsReadOnly() || pDoc->GetChangeTrack(); SfxWhichIter aIter(rSet); USHORT nWhich = aIter.FirstWhich(); while (nWhich) { switch (nWhich) { case SID_PIVOT_RECALC: case SID_PIVOT_KILL: { //! move ReadOnly check to idl flags if ( bDisable ) { rSet.DisableItem( nWhich ); } } break; case SID_DP_FILTER: { ScDPObject* pDPObj = GetCurrDPObject(); if( bDisable || !pDPObj || !pDPObj->IsSheetData() ) rSet.DisableItem( nWhich ); } break; } nWhich = aIter.NextWhich(); } } //------------------------------------------------------------------------ ScDPObject* ScPivotShell::GetCurrDPObject() { const ScViewData& rViewData = *pViewShell->GetViewData(); return rViewData.GetDocument()->GetDPAtCursor( rViewData.GetCurX(), rViewData.GetCurY(), rViewData.GetTabNo() ); } <commit_msg>INTEGRATION: CWS rowlimit (1.3.310); FILE MERGED 2004/01/16 17:43:02 er 1.3.310.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/************************************************************************* * * $RCSfile: pivotsh.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-06-04 12:04:08 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include "scitems.hxx" #include <svx/srchitem.hxx> #include <sfx2/app.hxx> #include <sfx2/objface.hxx> #include <sfx2/objsh.hxx> #include <sfx2/request.hxx> #include <svtools/whiter.hxx> #include <vcl/msgbox.hxx> #include "sc.hrc" #include "pivotsh.hxx" #include "tabvwsh.hxx" #include "docsh.hxx" #include "scresid.hxx" #include "document.hxx" #include "dpobject.hxx" #include "dpshttab.hxx" #include "dbdocfun.hxx" #include "uiitems.hxx" //CHINA001 #include "pfiltdlg.hxx" #include "scabstdlg.hxx" //CHINA001 //------------------------------------------------------------------------ #define ScPivotShell #include "scslots.hxx" //------------------------------------------------------------------------ TYPEINIT1( ScPivotShell, SfxShell ); SFX_IMPL_INTERFACE(ScPivotShell, SfxShell, ScResId(SCSTR_PIVOTSHELL)) { SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_PIVOT) ); } //------------------------------------------------------------------------ ScPivotShell::ScPivotShell( ScTabViewShell* pViewSh ) : SfxShell(pViewSh), pViewShell( pViewSh ) { SetPool( &pViewSh->GetPool() ); SetUndoManager( pViewSh->GetViewData()->GetSfxDocShell()->GetUndoManager() ); SetHelpId( HID_SCSHELL_PIVOTSH ); SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Pivot"))); } //------------------------------------------------------------------------ ScPivotShell::~ScPivotShell() { } //------------------------------------------------------------------------ void ScPivotShell::Execute( SfxRequest& rReq ) { switch ( rReq.GetSlot() ) { case SID_PIVOT_RECALC: pViewShell->RecalcPivotTable(); break; case SID_PIVOT_KILL: pViewShell->DeletePivotTable(); break; case SID_DP_FILTER: { ScDPObject* pDPObj = GetCurrDPObject(); if( pDPObj ) { ScQueryParam aQueryParam; SCTAB nSrcTab = 0; const ScSheetSourceDesc* pDesc = pDPObj->GetSheetDesc(); DBG_ASSERT( pDesc, "no sheet source for DP filter dialog" ); if( pDesc ) { aQueryParam = pDesc->aQueryParam; nSrcTab = pDesc->aSourceRange.aStart.Tab(); } ScViewData* pViewData = pViewShell->GetViewData(); SfxItemSet aArgSet( pViewShell->GetPool(), SCITEM_QUERYDATA, SCITEM_QUERYDATA ); aArgSet.Put( ScQueryItem( SCITEM_QUERYDATA, pViewData, &aQueryParam ) ); //CHINA001 ScPivotFilterDlg* pDlg = new ScPivotFilterDlg( //CHINA001 pViewShell->GetDialogParent(), aArgSet, nSrcTab ); ScAbstractDialogFactory* pFact = ScAbstractDialogFactory::Create(); DBG_ASSERT(pFact, "ScAbstractFactory create fail!");//CHINA001 AbstractScPivotFilterDlg* pDlg = pFact->CreateScPivotFilterDlg( pViewShell->GetDialogParent(), aArgSet, nSrcTab, ResId(RID_SCDLG_PIVOTFILTER)); DBG_ASSERT(pDlg, "Dialog create fail!");//CHINA001 if( pDlg->Execute() == RET_OK ) { ScSheetSourceDesc aNewDesc; if( pDesc ) aNewDesc = *pDesc; const ScQueryItem& rQueryItem = pDlg->GetOutputItem(); aNewDesc.aQueryParam = rQueryItem.GetQueryData(); ScDPObject aNewObj( *pDPObj ); aNewObj.SetSheetDesc( aNewDesc ); ScDBDocFunc aFunc( *pViewData->GetDocShell() ); aFunc.DataPilotUpdate( pDPObj, &aNewObj, TRUE, FALSE ); pViewData->GetView()->CursorPosChanged(); // shells may be switched } delete pDlg; } } break; } } //------------------------------------------------------------------------ void __EXPORT ScPivotShell::GetState( SfxItemSet& rSet ) { ScDocShell* pDocSh = pViewShell->GetViewData()->GetDocShell(); ScDocument* pDoc = pDocSh->GetDocument(); BOOL bDisable = pDocSh->IsReadOnly() || pDoc->GetChangeTrack(); SfxWhichIter aIter(rSet); USHORT nWhich = aIter.FirstWhich(); while (nWhich) { switch (nWhich) { case SID_PIVOT_RECALC: case SID_PIVOT_KILL: { //! move ReadOnly check to idl flags if ( bDisable ) { rSet.DisableItem( nWhich ); } } break; case SID_DP_FILTER: { ScDPObject* pDPObj = GetCurrDPObject(); if( bDisable || !pDPObj || !pDPObj->IsSheetData() ) rSet.DisableItem( nWhich ); } break; } nWhich = aIter.NextWhich(); } } //------------------------------------------------------------------------ ScDPObject* ScPivotShell::GetCurrDPObject() { const ScViewData& rViewData = *pViewShell->GetViewData(); return rViewData.GetDocument()->GetDPAtCursor( rViewData.GetCurX(), rViewData.GetCurY(), rViewData.GetTabNo() ); } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2014 Lunarg, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <stdio.h> #include <string> #include "vktrace_common.h" #include "vktrace_tracelog.h" #include "vktrace_filelike.h" #include "vktrace_trace_packet_utils.h" #include "vkreplay_main.h" #include "vkreplay_factory.h" #include "vkreplay_seq.h" #include "vkreplay_window.h" vkreplayer_settings replaySettings = { NULL, 1, -1, -1, NULL }; vktrace_SettingInfo g_settings_info[] = { { "t", "TraceFile", VKTRACE_SETTING_STRING, &replaySettings.pTraceFilePath, &replaySettings.pTraceFilePath, TRUE, "The trace file to replay."}, { "l", "NumLoops", VKTRACE_SETTING_UINT, &replaySettings.numLoops, &replaySettings.numLoops, TRUE, "The number of times to replay the trace file or loop range." }, { "lsf", "LoopStartFrame", VKTRACE_SETTING_INT, &replaySettings.loopStartFrame, &replaySettings.loopStartFrame, TRUE, "The start frame number of the loop range." }, { "lef", "LoopEndFrame", VKTRACE_SETTING_INT, &replaySettings.loopEndFrame, &replaySettings.loopEndFrame, TRUE, "The end frame number of the loop range." }, { "s", "Screenshot", VKTRACE_SETTING_STRING, &replaySettings.screenshotList, &replaySettings.screenshotList, TRUE, "Comma separated list of frames to take a take snapshots of"}, }; vktrace_SettingGroup g_replaySettingGroup = { "vkreplay", sizeof(g_settings_info) / sizeof(g_settings_info[0]), &g_settings_info[0] }; namespace vktrace_replay { int main_loop(Sequencer &seq, vktrace_trace_packet_replay_library *replayerArray[], vkreplayer_settings settings) { int err = 0; vktrace_trace_packet_header *packet; unsigned int res; vktrace_trace_packet_replay_library *replayer; vktrace_trace_packet_message* msgPacket; struct seqBookmark startingPacket; bool trace_running = true; int prevFrameNumber = -1; while (settings.numLoops > 0) { while ((packet = seq.get_next_packet()) != NULL && trace_running) { switch (packet->packet_id) { case VKTRACE_TPI_MESSAGE: msgPacket = vktrace_interpret_body_as_trace_packet_message(packet); vktrace_LogAlways("Packet %lu: Traced Message (%s): %s", packet->global_packet_index, vktrace_LogLevelToShortString(msgPacket->type), msgPacket->message); break; case VKTRACE_TPI_MARKER_CHECKPOINT: break; case VKTRACE_TPI_MARKER_API_BOUNDARY: break; case VKTRACE_TPI_MARKER_API_GROUP_BEGIN: break; case VKTRACE_TPI_MARKER_API_GROUP_END: break; case VKTRACE_TPI_MARKER_TERMINATE_PROCESS: break; //TODO processing code for all the above cases default: { if (packet->tracer_id >= VKTRACE_MAX_TRACER_ID_ARRAY_SIZE || packet->tracer_id == VKTRACE_TID_RESERVED) { vktrace_LogError("Tracer_id from packet num packet %d invalid.", packet->packet_id); continue; } replayer = replayerArray[packet->tracer_id]; if (replayer == NULL) { vktrace_LogWarning("Tracer_id %d has no valid replayer.", packet->tracer_id); continue; } if (packet->packet_id >= VKTRACE_TPI_BEGIN_API_HERE) { // replay the API packet res = replayer->Replay(replayer->Interpret(packet)); if (res != VKTRACE_REPLAY_SUCCESS) { vktrace_LogError("Failed to replay packet_id %d.",packet->packet_id); return -1; } // frame control logic int frameNumber = replayer->GetFrameNumber(); if (prevFrameNumber != frameNumber) { prevFrameNumber = frameNumber; if (settings.loopStartFrame == -1 || frameNumber == settings.loopStartFrame) { // record the location of looping start packet seq.record_bookmark(); seq.get_bookmark(startingPacket); } if (frameNumber == settings.loopEndFrame) { trace_running = false; } } } else { vktrace_LogError("Bad packet type id=%d, index=%d.", packet->packet_id, packet->global_packet_index); return -1; } } } } settings.numLoops--; seq.set_bookmark(startingPacket); trace_running = true; if (replayer != NULL) { replayer->ResetFrameNumber(); } } return err; } } // namespace vktrace_replay using namespace vktrace_replay; void loggingCallback(VktraceLogLevel level, const char* pMessage) { switch(level) { case VKTRACE_LOG_ALWAYS: printf("%s\n", pMessage); break; case VKTRACE_LOG_DEBUG: printf("Debug: %s\n", pMessage); break; case VKTRACE_LOG_ERROR: printf("Error: %s\n", pMessage); break; case VKTRACE_LOG_WARNING: printf("Warning: %s\n", pMessage); break; case VKTRACE_LOG_VERBOSE: printf("Verbose: %s\n", pMessage); break; default: printf("%s\n", pMessage); break; } #if defined(_DEBUG) #if defined(WIN32) OutputDebugString(pMessage); #endif #endif } extern "C" int main(int argc, char **argv) { int err = 0; vktrace_SettingGroup* pAllSettings = NULL; unsigned int numAllSettings = 0; vktrace_LogSetCallback(loggingCallback); vktrace_LogSetLevel(VKTRACE_LOG_LEVEL_MAXIMUM); // apply settings from cmd-line args if (vktrace_SettingGroup_init_from_cmdline(&g_replaySettingGroup, argc, argv, &replaySettings.pTraceFilePath) != 0) { // invalid options specified if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return err; } // merge settings so that new settings will get written into the settings file vktrace_SettingGroup_merge(&g_replaySettingGroup, &pAllSettings, &numAllSettings); // Set up environment for screenshot if (replaySettings.screenshotList != NULL) { // Set env var that communicates list to ScreenShot layer vktrace_set_global_var("_VK_SCREENSHOT", replaySettings.screenshotList); } else { vktrace_set_global_var("_VK_SCREENSHOT",""); } // open trace file and read in header char* pTraceFile = replaySettings.pTraceFilePath; vktrace_trace_file_header fileHeader; FILE *tracefp; if (pTraceFile != NULL && strlen(pTraceFile) > 0) { tracefp = fopen(pTraceFile, "rb"); if (tracefp == NULL) { vktrace_LogError("Cannot open trace file: '%s'.", pTraceFile); return 1; } } else { vktrace_LogError("No trace file specified."); vktrace_SettingGroup_print(&g_replaySettingGroup); if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return 1; } FileLike* traceFile = vktrace_FileLike_create_file(tracefp); if (vktrace_FileLike_ReadRaw(traceFile, &fileHeader, sizeof(fileHeader)) == false) { vktrace_LogError("Unable to read header from file."); if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } VKTRACE_DELETE(traceFile); return 1; } // Make sure trace file version is supported if (fileHeader.trace_file_version < VKTRACE_TRACE_FILE_VERSION_MINIMUM_COMPATIBLE) { vktrace_LogError("Trace file version %u is older than minimum compatible version (%u).\nYou'll need to make a new trace file, or use an older replayer.", fileHeader.trace_file_version, VKTRACE_TRACE_FILE_VERSION_MINIMUM_COMPATIBLE); } // load any API specific driver libraries and init replayer objects uint8_t tidApi = VKTRACE_TID_RESERVED; vktrace_trace_packet_replay_library* replayer[VKTRACE_MAX_TRACER_ID_ARRAY_SIZE]; ReplayFactory makeReplayer; Display disp(1024, 768, 0, false); for (int i = 0; i < VKTRACE_MAX_TRACER_ID_ARRAY_SIZE; i++) { replayer[i] = NULL; } for (int i = 0; i < fileHeader.tracer_count; i++) { uint8_t tracerId = fileHeader.tracer_id_array[i].id; tidApi = tracerId; const VKTRACE_TRACER_REPLAYER_INFO* pReplayerInfo = &(gs_tracerReplayerInfo[tracerId]); if (pReplayerInfo->tracerId != tracerId) { vktrace_LogError("Replayer info for TracerId (%d) failed consistency check.", tracerId); assert(!"TracerId in VKTRACE_TRACER_REPLAYER_INFO does not match the requested tracerId. The array needs to be corrected."); } else if (pReplayerInfo->needsReplayer == TRUE) { // Have our factory create the necessary replayer replayer[tracerId] = makeReplayer.Create(tracerId); if (replayer[tracerId] == NULL) { // replayer failed to be created if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return err; } // merge the replayer's settings into the list of all settings so that we can output a comprehensive settings file later on. vktrace_SettingGroup_merge(replayer[tracerId]->GetSettings(), &pAllSettings, &numAllSettings); // update the replayer with the loaded settings replayer[tracerId]->UpdateFromSettings(pAllSettings, numAllSettings); replayer[tracerId]->SetLogCallback(loggingCallback); replayer[tracerId]->SetLogLevel(VKTRACE_LOG_LEVEL_MAXIMUM); // Initialize the replayer err = replayer[tracerId]->Initialize(&disp, &replaySettings); if (err) { vktrace_LogError("Couldn't Initialize replayer for TracerId %d.", tracerId); if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return err; } } } if (tidApi == VKTRACE_TID_RESERVED) { vktrace_LogError("No API specified in tracefile for replaying."); if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return -1; } // main loop Sequencer sequencer(traceFile); err = vktrace_replay::main_loop(sequencer, replayer, replaySettings); for (int i = 0; i < VKTRACE_MAX_TRACER_ID_ARRAY_SIZE; i++) { if (replayer[i] != NULL) { replayer[i]->Deinitialize(); makeReplayer.Destroy(&replayer[i]); } } if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return err; } <commit_msg>Remove the extra space before main_loop<commit_after>/************************************************************************** * * Copyright 2014 Lunarg, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <stdio.h> #include <string> #include "vktrace_common.h" #include "vktrace_tracelog.h" #include "vktrace_filelike.h" #include "vktrace_trace_packet_utils.h" #include "vkreplay_main.h" #include "vkreplay_factory.h" #include "vkreplay_seq.h" #include "vkreplay_window.h" vkreplayer_settings replaySettings = { NULL, 1, -1, -1, NULL }; vktrace_SettingInfo g_settings_info[] = { { "t", "TraceFile", VKTRACE_SETTING_STRING, &replaySettings.pTraceFilePath, &replaySettings.pTraceFilePath, TRUE, "The trace file to replay."}, { "l", "NumLoops", VKTRACE_SETTING_UINT, &replaySettings.numLoops, &replaySettings.numLoops, TRUE, "The number of times to replay the trace file or loop range." }, { "lsf", "LoopStartFrame", VKTRACE_SETTING_INT, &replaySettings.loopStartFrame, &replaySettings.loopStartFrame, TRUE, "The start frame number of the loop range." }, { "lef", "LoopEndFrame", VKTRACE_SETTING_INT, &replaySettings.loopEndFrame, &replaySettings.loopEndFrame, TRUE, "The end frame number of the loop range." }, { "s", "Screenshot", VKTRACE_SETTING_STRING, &replaySettings.screenshotList, &replaySettings.screenshotList, TRUE, "Comma separated list of frames to take a take snapshots of"}, }; vktrace_SettingGroup g_replaySettingGroup = { "vkreplay", sizeof(g_settings_info) / sizeof(g_settings_info[0]), &g_settings_info[0] }; namespace vktrace_replay { int main_loop(Sequencer &seq, vktrace_trace_packet_replay_library *replayerArray[], vkreplayer_settings settings) { int err = 0; vktrace_trace_packet_header *packet; unsigned int res; vktrace_trace_packet_replay_library *replayer; vktrace_trace_packet_message* msgPacket; struct seqBookmark startingPacket; bool trace_running = true; int prevFrameNumber = -1; while (settings.numLoops > 0) { while ((packet = seq.get_next_packet()) != NULL && trace_running) { switch (packet->packet_id) { case VKTRACE_TPI_MESSAGE: msgPacket = vktrace_interpret_body_as_trace_packet_message(packet); vktrace_LogAlways("Packet %lu: Traced Message (%s): %s", packet->global_packet_index, vktrace_LogLevelToShortString(msgPacket->type), msgPacket->message); break; case VKTRACE_TPI_MARKER_CHECKPOINT: break; case VKTRACE_TPI_MARKER_API_BOUNDARY: break; case VKTRACE_TPI_MARKER_API_GROUP_BEGIN: break; case VKTRACE_TPI_MARKER_API_GROUP_END: break; case VKTRACE_TPI_MARKER_TERMINATE_PROCESS: break; //TODO processing code for all the above cases default: { if (packet->tracer_id >= VKTRACE_MAX_TRACER_ID_ARRAY_SIZE || packet->tracer_id == VKTRACE_TID_RESERVED) { vktrace_LogError("Tracer_id from packet num packet %d invalid.", packet->packet_id); continue; } replayer = replayerArray[packet->tracer_id]; if (replayer == NULL) { vktrace_LogWarning("Tracer_id %d has no valid replayer.", packet->tracer_id); continue; } if (packet->packet_id >= VKTRACE_TPI_BEGIN_API_HERE) { // replay the API packet res = replayer->Replay(replayer->Interpret(packet)); if (res != VKTRACE_REPLAY_SUCCESS) { vktrace_LogError("Failed to replay packet_id %d.",packet->packet_id); return -1; } // frame control logic int frameNumber = replayer->GetFrameNumber(); if (prevFrameNumber != frameNumber) { prevFrameNumber = frameNumber; if (settings.loopStartFrame == -1 || frameNumber == settings.loopStartFrame) { // record the location of looping start packet seq.record_bookmark(); seq.get_bookmark(startingPacket); } if (frameNumber == settings.loopEndFrame) { trace_running = false; } } } else { vktrace_LogError("Bad packet type id=%d, index=%d.", packet->packet_id, packet->global_packet_index); return -1; } } } } settings.numLoops--; seq.set_bookmark(startingPacket); trace_running = true; if (replayer != NULL) { replayer->ResetFrameNumber(); } } return err; } } // namespace vktrace_replay using namespace vktrace_replay; void loggingCallback(VktraceLogLevel level, const char* pMessage) { switch(level) { case VKTRACE_LOG_ALWAYS: printf("%s\n", pMessage); break; case VKTRACE_LOG_DEBUG: printf("Debug: %s\n", pMessage); break; case VKTRACE_LOG_ERROR: printf("Error: %s\n", pMessage); break; case VKTRACE_LOG_WARNING: printf("Warning: %s\n", pMessage); break; case VKTRACE_LOG_VERBOSE: printf("Verbose: %s\n", pMessage); break; default: printf("%s\n", pMessage); break; } #if defined(_DEBUG) #if defined(WIN32) OutputDebugString(pMessage); #endif #endif } extern "C" int main(int argc, char **argv) { int err = 0; vktrace_SettingGroup* pAllSettings = NULL; unsigned int numAllSettings = 0; vktrace_LogSetCallback(loggingCallback); vktrace_LogSetLevel(VKTRACE_LOG_LEVEL_MAXIMUM); // apply settings from cmd-line args if (vktrace_SettingGroup_init_from_cmdline(&g_replaySettingGroup, argc, argv, &replaySettings.pTraceFilePath) != 0) { // invalid options specified if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return err; } // merge settings so that new settings will get written into the settings file vktrace_SettingGroup_merge(&g_replaySettingGroup, &pAllSettings, &numAllSettings); // Set up environment for screenshot if (replaySettings.screenshotList != NULL) { // Set env var that communicates list to ScreenShot layer vktrace_set_global_var("_VK_SCREENSHOT", replaySettings.screenshotList); } else { vktrace_set_global_var("_VK_SCREENSHOT",""); } // open trace file and read in header char* pTraceFile = replaySettings.pTraceFilePath; vktrace_trace_file_header fileHeader; FILE *tracefp; if (pTraceFile != NULL && strlen(pTraceFile) > 0) { tracefp = fopen(pTraceFile, "rb"); if (tracefp == NULL) { vktrace_LogError("Cannot open trace file: '%s'.", pTraceFile); return 1; } } else { vktrace_LogError("No trace file specified."); vktrace_SettingGroup_print(&g_replaySettingGroup); if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return 1; } FileLike* traceFile = vktrace_FileLike_create_file(tracefp); if (vktrace_FileLike_ReadRaw(traceFile, &fileHeader, sizeof(fileHeader)) == false) { vktrace_LogError("Unable to read header from file."); if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } VKTRACE_DELETE(traceFile); return 1; } // Make sure trace file version is supported if (fileHeader.trace_file_version < VKTRACE_TRACE_FILE_VERSION_MINIMUM_COMPATIBLE) { vktrace_LogError("Trace file version %u is older than minimum compatible version (%u).\nYou'll need to make a new trace file, or use an older replayer.", fileHeader.trace_file_version, VKTRACE_TRACE_FILE_VERSION_MINIMUM_COMPATIBLE); } // load any API specific driver libraries and init replayer objects uint8_t tidApi = VKTRACE_TID_RESERVED; vktrace_trace_packet_replay_library* replayer[VKTRACE_MAX_TRACER_ID_ARRAY_SIZE]; ReplayFactory makeReplayer; Display disp(1024, 768, 0, false); for (int i = 0; i < VKTRACE_MAX_TRACER_ID_ARRAY_SIZE; i++) { replayer[i] = NULL; } for (int i = 0; i < fileHeader.tracer_count; i++) { uint8_t tracerId = fileHeader.tracer_id_array[i].id; tidApi = tracerId; const VKTRACE_TRACER_REPLAYER_INFO* pReplayerInfo = &(gs_tracerReplayerInfo[tracerId]); if (pReplayerInfo->tracerId != tracerId) { vktrace_LogError("Replayer info for TracerId (%d) failed consistency check.", tracerId); assert(!"TracerId in VKTRACE_TRACER_REPLAYER_INFO does not match the requested tracerId. The array needs to be corrected."); } else if (pReplayerInfo->needsReplayer == TRUE) { // Have our factory create the necessary replayer replayer[tracerId] = makeReplayer.Create(tracerId); if (replayer[tracerId] == NULL) { // replayer failed to be created if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return err; } // merge the replayer's settings into the list of all settings so that we can output a comprehensive settings file later on. vktrace_SettingGroup_merge(replayer[tracerId]->GetSettings(), &pAllSettings, &numAllSettings); // update the replayer with the loaded settings replayer[tracerId]->UpdateFromSettings(pAllSettings, numAllSettings); replayer[tracerId]->SetLogCallback(loggingCallback); replayer[tracerId]->SetLogLevel(VKTRACE_LOG_LEVEL_MAXIMUM); // Initialize the replayer err = replayer[tracerId]->Initialize(&disp, &replaySettings); if (err) { vktrace_LogError("Couldn't Initialize replayer for TracerId %d.", tracerId); if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return err; } } } if (tidApi == VKTRACE_TID_RESERVED) { vktrace_LogError("No API specified in tracefile for replaying."); if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return -1; } // main loop Sequencer sequencer(traceFile); err = vktrace_replay::main_loop(sequencer, replayer, replaySettings); for (int i = 0; i < VKTRACE_MAX_TRACER_ID_ARRAY_SIZE; i++) { if (replayer[i] != NULL) { replayer[i]->Deinitialize(); makeReplayer.Destroy(&replayer[i]); } } if (pAllSettings != NULL) { vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings); } return err; } <|endoftext|>
<commit_before>#include "Model.h" using namespace std; using namespace Eigen; const string to_string(const FieldStrength& f) { static const string f3{"3T"}, f7{"7T"}, fu{"User"}; switch (f) { case FieldStrength::Three: return f3; case FieldStrength::Seven: return f7; case FieldStrength::User: return fu; } } /*****************************************************************************/ /* Base Class */ /*****************************************************************************/ string Model::to_string(const Scale &p) { static const string sn{"None"}, snm{"Normalised to Mean"}; switch (p) { case Scale::None: return sn; case Scale::ToMean: return snm; } } ArrayXcd Model::scale(const ArrayXcd &s) const { ArrayXcd scaled(s.size()); switch (m_scaling) { case Scale::None: scaled = s; break; case Scale::ToMean: scaled = s / s.abs().mean(); break; } return s; } VectorXcd Model::MultiEcho(cvecd &, carrd &) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SPGR(cvecd &params, carrd &a, cdbl TR) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SPGRFinite(cvecd &params, carrd &a, cdbl TR, cdbl T_rf, cdbl TE) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::MPRAGE(cvecd &params, cdbl a, cdbl TR, const int N, cvecd &TI, cdbl TD) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::AFI(cvecd &p, cdbl a, cdbl TR1, cdbl TR2) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SSFP(cvecd &params, carrd &a, cdbl TR, cdbl phi) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SSFPEllipse(cvecd &params, carrd &a, cdbl TR) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SSFPFinite(cvecd &params, carrd &a, cdbl TR, cdbl T_rf, cdbl phi) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } /*****************************************************************************/ /* Single Component DESPOT */ /*****************************************************************************/ string SCD::Name() const { return "1C"; } size_t SCD::nParameters() const { return 5; } const vector<string> &SCD::Names() const { static vector<string> n{"PD", "T1", "T2", "f0", "B1"}; return n; } ArrayXXd SCD::Bounds(const FieldStrength f, cdbl TR) const { size_t nP = nParameters(); ArrayXXd b(nP, 2); switch (f) { case FieldStrength::Three: b << 1.0, 1.0, 0.1, 4.5, 0.010, 2.500, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::Seven: b << 1.0, 1.0, 0.1, 4.5, 0.010, 2.500, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::User: b.setZero(); break; } return b; } bool SCD::ValidParameters(cvecd &params) const { // Negative T1/T2 makes no sense if ((params[1] <= 0.) || (params[2] <= 0.)) return false; else return true; } VectorXcd SCD::MultiEcho(cvecd &p, carrd &TE) const { return scale(One_MultiEcho(TE, p[0], p[2])); } VectorXcd SCD::SPGR(cvecd &p, carrd &a, cdbl TR) const { return scale(One_SPGR(a, TR, p[0], p[1], p[4])); } VectorXcd SCD::SPGRFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl TE) const { return scale(One_SSFP_Finite(a, true, TR, Trf, TE, 0, p[0], p[1], p[2], p[3], p[4])); } VectorXcd SCD::MPRAGE(cvecd &p, cdbl a, cdbl TR, const int N, cvecd &TI, cdbl TD) const { return scale(MP_RAGE(a, TR, N, TI, TD, p[0], p[1], p[4])); } VectorXcd SCD::AFI(cvecd &p, cdbl a, cdbl TR1, cdbl TR2) const { return scale(One_AFI(a, TR1, TR2, p[0], p[1], p[4])); } VectorXcd SCD::SSFP(cvecd &p, carrd &a, cdbl TR, cdbl phi) const { return scale(One_SSFP(a, TR, phi, p[0], p[1], p[2], p[3], p[4])); } VectorXcd SCD::SSFPFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl phi) const { return scale(One_SSFP_Finite(a, false, TR, Trf, 0., phi, p[0], p[1], p[2], p[3], p[4])); } VectorXcd SCD::SSFPEllipse(cvecd &p, carrd &a, cdbl TR) const { return scale(One_SSFP_Ellipse(a, TR, p[0], p[1], p[2], p[3], p[4])); } /*****************************************************************************/ /* Two Component DESPOT */ /*****************************************************************************/ string MCD2::Name() const { return "2C"; } size_t MCD2::nParameters() const { return 9; } const vector<string> & MCD2::Names() const { static vector<string> n{"PD", "T1_a", "T2_a", "T1_b", "T2_b", "tau_a", "f_a", "f0", "B1"}; return n; } ArrayXXd MCD2::Bounds(const FieldStrength f, cdbl TR) const { size_t nP = nParameters(); ArrayXXd b(nP, 2); switch (f) { case FieldStrength::Three: b << 1.0, 1.0, 0.3, 0.65, 0.001, 0.030, 0.5, 4.5, 0.05, 0.165, 0.025, 0.60, 0.0, 0.35, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::Seven: b << 1.0, 1.0, 0.4, 0.8, 0.001, 0.025, 0.7, 4.5, 0.05, 0.165, 0.025, 0.60, 0.0, 0.35, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::User: b.setZero(); break; } return b; } bool MCD2::ValidParameters(cvecd &params) const { // Negative T1/T2 makes no sense if ((params[1] <= 0.) || (params[2] <= 0.)) return false; else { if ((params[1] < params[3]) && (params[2] < params[4]) && (params[6] <= 1.0)) return true; else return false; } } VectorXcd MCD2::SPGR(cvecd &p, carrd &a, cdbl TR) const { return scale(Two_SPGR(a, TR, p[0], p[1], p[3], p[5], p[6], p[8])); } VectorXcd MCD2::SPGRFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl TE) const { return scale(Two_SSFP_Finite(a, true, TR, Trf, TE, 0, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[7], p[8])); } VectorXcd MCD2::SSFP(cvecd &p, carrd &a, cdbl TR, cdbl phi) const { return scale(Two_SSFP(a, TR, phi, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[7], p[8])); } VectorXcd MCD2::SSFPFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl phi) const { return scale(Two_SSFP_Finite(a, false, TR, Trf, 0., phi, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[7], p[8])); } /*****************************************************************************/ /* Three Component DESPOT */ /*****************************************************************************/ string MCD3::Name() const { return "3C"; } size_t MCD3::nParameters() const { return 12; } const vector<string> & MCD3::Names() const { static vector<string> n{"PD", "T1_a", "T2_a", "T1_b", "T2_b", "T1_c", "T2_c", "tau_a", "f_a", "f_c", "f0", "B1"}; return n; } ArrayXXd MCD3::Bounds(const FieldStrength f, cdbl TR) const { size_t nP = nParameters(); ArrayXXd b(nP, 2); switch (f) { case FieldStrength::Three: b << 1.0, 1.0, 0.3, 0.65, 0.001, 0.030, 0.5, 1.5, 0.05, 0.165, 3.0, 4.5, 0.5, 1.5, 0.025, 0.60, 0.0, 0.35, 0.0, 1.0, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::Seven: b << 1.0, 1.0, 0.4, 0.90, 0.001, 0.025, 0.8, 2.0, 0.04, 0.140, 3.0, 4.5, 0.5, 1.5, 0.025, 0.60, 0.0, 0.35, 0.0, 1.0, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::User: b.setZero(); break; } return b; } bool MCD3::ValidParameters(cvecd &params) const { // Negative T1/T2 makes no sense if ((params[1] <= 0.) || (params[2] <= 0.)) return false; else { if ((params[1] < params[3]) && (params[2] < params[4]) && (params[3] < params[5]) && (params[4] < params[6]) && ((params[8] + params[9]) <= 1.0)) return true; else return false; } } VectorXcd MCD3::SPGR(cvecd &p, carrd &a, cdbl TR) const { return scale(Three_SPGR(a, TR, p[0], p[1], p[3], p[5], p[7], p[8], p[9], p[11])); } VectorXcd MCD3::SPGRFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl TE) const { return scale(Three_SSFP_Finite(a, true, TR, Trf, TE, 0, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[10], p[10], p[11])); } VectorXcd MCD3::SSFP(cvecd &p, carrd &a, cdbl TR, cdbl phi) const { return scale(Three_SSFP(a, TR, phi, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[10], p[10], p[11])); } VectorXcd MCD3::SSFPFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl phi) const { return scale(Three_SSFP_Finite(a, false, TR, Trf, 0., phi, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[10], p[10], p[11])); } <commit_msg>Changed output filenames for mcdespot.<commit_after>#include "Model.h" using namespace std; using namespace Eigen; const string to_string(const FieldStrength& f) { static const string f3{"3T"}, f7{"7T"}, fu{"User"}; switch (f) { case FieldStrength::Three: return f3; case FieldStrength::Seven: return f7; case FieldStrength::User: return fu; } } /*****************************************************************************/ /* Base Class */ /*****************************************************************************/ string Model::to_string(const Scale &p) { static const string sn{"None"}, snm{"Normalised to Mean"}; switch (p) { case Scale::None: return sn; case Scale::ToMean: return snm; } } ArrayXcd Model::scale(const ArrayXcd &s) const { ArrayXcd scaled(s.size()); switch (m_scaling) { case Scale::None: scaled = s; break; case Scale::ToMean: scaled = s / s.abs().mean(); break; } return s; } VectorXcd Model::MultiEcho(cvecd &, carrd &) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SPGR(cvecd &params, carrd &a, cdbl TR) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SPGRFinite(cvecd &params, carrd &a, cdbl TR, cdbl T_rf, cdbl TE) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::MPRAGE(cvecd &params, cdbl a, cdbl TR, const int N, cvecd &TI, cdbl TD) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::AFI(cvecd &p, cdbl a, cdbl TR1, cdbl TR2) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SSFP(cvecd &params, carrd &a, cdbl TR, cdbl phi) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SSFPEllipse(cvecd &params, carrd &a, cdbl TR) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } VectorXcd Model::SSFPFinite(cvecd &params, carrd &a, cdbl TR, cdbl T_rf, cdbl phi) const { throw(logic_error(std::string(__PRETTY_FUNCTION__) + " not implemented.")); } /*****************************************************************************/ /* Single Component DESPOT */ /*****************************************************************************/ string SCD::Name() const { return "1C"; } size_t SCD::nParameters() const { return 5; } const vector<string> &SCD::Names() const { static vector<string> n{"PD", "T1", "T2", "f0", "B1"}; return n; } ArrayXXd SCD::Bounds(const FieldStrength f, cdbl TR) const { size_t nP = nParameters(); ArrayXXd b(nP, 2); switch (f) { case FieldStrength::Three: b << 1.0, 1.0, 0.1, 4.5, 0.010, 2.500, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::Seven: b << 1.0, 1.0, 0.1, 4.5, 0.010, 2.500, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::User: b.setZero(); break; } return b; } bool SCD::ValidParameters(cvecd &params) const { // Negative T1/T2 makes no sense if ((params[1] <= 0.) || (params[2] <= 0.)) return false; else return true; } VectorXcd SCD::MultiEcho(cvecd &p, carrd &TE) const { return scale(One_MultiEcho(TE, p[0], p[2])); } VectorXcd SCD::SPGR(cvecd &p, carrd &a, cdbl TR) const { return scale(One_SPGR(a, TR, p[0], p[1], p[4])); } VectorXcd SCD::SPGRFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl TE) const { return scale(One_SSFP_Finite(a, true, TR, Trf, TE, 0, p[0], p[1], p[2], p[3], p[4])); } VectorXcd SCD::MPRAGE(cvecd &p, cdbl a, cdbl TR, const int N, cvecd &TI, cdbl TD) const { return scale(MP_RAGE(a, TR, N, TI, TD, p[0], p[1], p[4])); } VectorXcd SCD::AFI(cvecd &p, cdbl a, cdbl TR1, cdbl TR2) const { return scale(One_AFI(a, TR1, TR2, p[0], p[1], p[4])); } VectorXcd SCD::SSFP(cvecd &p, carrd &a, cdbl TR, cdbl phi) const { return scale(One_SSFP(a, TR, phi, p[0], p[1], p[2], p[3], p[4])); } VectorXcd SCD::SSFPFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl phi) const { return scale(One_SSFP_Finite(a, false, TR, Trf, 0., phi, p[0], p[1], p[2], p[3], p[4])); } VectorXcd SCD::SSFPEllipse(cvecd &p, carrd &a, cdbl TR) const { return scale(One_SSFP_Ellipse(a, TR, p[0], p[1], p[2], p[3], p[4])); } /*****************************************************************************/ /* Two Component DESPOT */ /*****************************************************************************/ string MCD2::Name() const { return "2C"; } size_t MCD2::nParameters() const { return 9; } const vector<string> & MCD2::Names() const { static vector<string> n{"PD", "T1_m", "T2_m", "T1_ie", "T2_ie", "tau_m", "f_m", "f0", "B1"}; return n; } ArrayXXd MCD2::Bounds(const FieldStrength f, cdbl TR) const { size_t nP = nParameters(); ArrayXXd b(nP, 2); switch (f) { case FieldStrength::Three: b << 1.0, 1.0, 0.3, 0.65, 0.001, 0.030, 0.5, 1.5, 0.05, 0.165, 0.025, 0.6, 0.0, 0.35, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::Seven: b << 1.0, 1.0, 0.4, 0.8, 0.001, 0.025, 0.7, 2.5, 0.05, 0.165, 0.025, 0.6, 0.0, 0.35, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::User: b.setZero(); break; } return b; } bool MCD2::ValidParameters(cvecd &params) const { // Negative T1/T2 makes no sense if ((params[1] <= 0.) || (params[2] <= 0.)) return false; else { if ((params[1] < params[3]) && (params[2] < params[4]) && (params[6] <= 1.0)) return true; else return false; } } VectorXcd MCD2::SPGR(cvecd &p, carrd &a, cdbl TR) const { return scale(Two_SPGR(a, TR, p[0], p[1], p[3], p[5], p[6], p[8])); } VectorXcd MCD2::SPGRFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl TE) const { return scale(Two_SSFP_Finite(a, true, TR, Trf, TE, 0, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[7], p[8])); } VectorXcd MCD2::SSFP(cvecd &p, carrd &a, cdbl TR, cdbl phi) const { return scale(Two_SSFP(a, TR, phi, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[7], p[8])); } VectorXcd MCD2::SSFPFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl phi) const { return scale(Two_SSFP_Finite(a, false, TR, Trf, 0., phi, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[7], p[8])); } /*****************************************************************************/ /* Three Component DESPOT */ /*****************************************************************************/ string MCD3::Name() const { return "3C"; } size_t MCD3::nParameters() const { return 12; } const vector<string> & MCD3::Names() const { static vector<string> n{"PD", "T1_m", "T2_m", "T1_ie", "T2_ie", "T1_csf", "T2_csf", "tau_m", "f_m", "f_csf", "f0", "B1"}; return n; } ArrayXXd MCD3::Bounds(const FieldStrength f, cdbl TR) const { size_t nP = nParameters(); ArrayXXd b(nP, 2); switch (f) { case FieldStrength::Three: b << 1.0, 1.0, 0.3, 0.65, 0.001, 0.030, 0.5, 1.5, 0.05, 0.165, 3.0, 4.5, 0.5, 1.5, 0.025, 0.60, 0.0, 0.35, 0.0, 1.0, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::Seven: b << 1.0, 1.0, 0.4, 0.90, 0.001, 0.025, 0.8, 2.0, 0.04, 0.140, 3.0, 4.5, 0.5, 1.5, 0.025, 0.60, 0.0, 0.35, 0.0, 1.0, -0.5/TR, 0.5/TR, 1.0, 1.0; break; case FieldStrength::User: b.setZero(); break; } return b; } bool MCD3::ValidParameters(cvecd &params) const { // Negative T1/T2 makes no sense if ((params[1] <= 0.) || (params[2] <= 0.)) return false; else { if ((params[1] < params[3]) && (params[2] < params[4]) && (params[3] < params[5]) && (params[4] < params[6]) && ((params[8] + params[9]) <= 1.0)) return true; else return false; } } VectorXcd MCD3::SPGR(cvecd &p, carrd &a, cdbl TR) const { return scale(Three_SPGR(a, TR, p[0], p[1], p[3], p[5], p[7], p[8], p[9], p[11])); } VectorXcd MCD3::SPGRFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl TE) const { return scale(Three_SSFP_Finite(a, true, TR, Trf, TE, 0, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[10], p[10], p[11])); } VectorXcd MCD3::SSFP(cvecd &p, carrd &a, cdbl TR, cdbl phi) const { return scale(Three_SSFP(a, TR, phi, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[10], p[10], p[11])); } VectorXcd MCD3::SSFPFinite(cvecd &p, carrd &a, cdbl TR, cdbl Trf, cdbl phi) const { return scale(Three_SSFP_Finite(a, false, TR, Trf, 0., phi, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[10], p[10], p[11])); } <|endoftext|>
<commit_before> /*******************************************************************/ /* 3d_toolbar.cpp: construction des tool bars de la frame visu 3d */ /*******************************************************************/ #include "fctsys.h" #include "macros.h" #include "bitmaps3d.h" #include "bitmaps.h" #include "id.h" #define BITMAP wxBitmap #include "3d_viewer.h" /*********************************************/ void WinEDA3D_DrawFrame::ReCreateHToolbar(void) /*********************************************/ { if ( m_HToolBar != NULL ) { // simple mise a jour de la liste des fichiers anciens SetToolbars(); return; } m_HToolBar = new WinEDA_Toolbar(TOOLBAR_MAIN, this, ID_H_TOOLBAR, TRUE); SetToolBar(m_HToolBar); // Set up toolbar m_HToolBar->AddTool(ID_RELOAD3D_BOARD, wxEmptyString, BITMAP(import3d_xpm), _("Reload board")); #ifdef __WINDOWS__ // do not work properly under linux m_HToolBar->AddSeparator(); m_HToolBar->AddTool(ID_TOOL_SCREENCOPY_TOCLIBBOARD, wxEmptyString, BITMAP(copy_button), _("Copy 3D Image to Clipboard")); #endif m_HToolBar->AddSeparator(); m_HToolBar->AddTool(ID_ZOOM_PLUS_BUTT, wxEmptyString, BITMAP(zoom_in_xpm), _("zoom + (F1)")); m_HToolBar->AddTool(ID_ZOOM_MOINS_BUTT, wxEmptyString, BITMAP(zoom_out_xpm), _("zoom - (F2)")); m_HToolBar->AddTool(ID_ZOOM_REDRAW_BUTT, wxEmptyString, BITMAP(repaint_xpm), _("redraw (F3)")); m_HToolBar->AddTool(ID_ZOOM_PAGE_BUTT, wxEmptyString, BITMAP(zoom_optimal_xpm), _("auto zoom")); m_HToolBar->AddSeparator(); m_HToolBar->AddTool(ID_ROTATE3D_X_NEG, wxEmptyString, BITMAP(rotate_neg_X_xpm), _("Rotate X <-") ); m_HToolBar->AddTool(ID_ROTATE3D_X_POS, wxEmptyString, BITMAP(rotate_pos_X_xpm), _("Rotate X ->") ); m_HToolBar->AddSeparator(); m_HToolBar->AddTool(ID_ROTATE3D_Y_NEG, wxEmptyString, BITMAP(rotate_neg_Y_xpm), _("Rotate Y <-") ); m_HToolBar->AddTool(ID_ROTATE3D_Y_POS, wxEmptyString, BITMAP(rotate_pos_Y_xpm), _("Rotate Y ->") ); m_HToolBar->AddSeparator(); m_HToolBar->AddTool(ID_ROTATE3D_Z_NEG, wxEmptyString, BITMAP(rotate_neg_Z_xpm), _("Rotate Z <-") ); m_HToolBar->AddTool(ID_ROTATE3D_Z_POS, wxEmptyString, BITMAP(rotate_pos_Z_xpm), _("Rotate Z ->") ); m_HToolBar->AddSeparator(); m_HToolBar->AddTool(ID_MOVE3D_LEFT, wxEmptyString, BITMAP(left_xpm), _("Move left <-") ); m_HToolBar->AddTool(ID_MOVE3D_RIGHT, wxEmptyString, BITMAP(right_xpm), _("Move right ->") ); m_HToolBar->AddTool(ID_MOVE3D_UP, wxEmptyString, BITMAP(up_xpm), _("Move Up ^") ); m_HToolBar->AddTool(ID_MOVE3D_DOWN, wxEmptyString, BITMAP(down_xpm), _("Move Down") ); m_HToolBar->Realize(); // SetToolbars(); } /*********************************************/ void WinEDA3D_DrawFrame::ReCreateVToolbar(void) /*********************************************/ { } /**********************************************/ void WinEDA3D_DrawFrame::ReCreateMenuBar(void) /**********************************************/ { wxMenuBar *menuBar = new wxMenuBar; wxMenu *fileMenu = new wxMenu; menuBar->Append(fileMenu, _("&File") ); fileMenu->Append(ID_MENU_SCREENCOPY_PNG, _("Create Image (png format)")); fileMenu->Append(ID_MENU_SCREENCOPY_JPEG, _("Create Image (jpeg format)")); fileMenu->AppendSeparator(); fileMenu->Append(wxID_EXIT, _("&Exit")); wxMenu *referencesMenu = new wxMenu; menuBar->Append(referencesMenu, _("&Preferences") ); ADD_MENUITEM(referencesMenu, ID_MENU3D_BGCOLOR_SELECTION, _("Choose background color"), palette_xpm) SetMenuBar(menuBar); } /*****************************************/ void WinEDA3D_DrawFrame::SetToolbars(void) /*****************************************/ { } <commit_msg>beautified and account for changed macros.h<commit_after>/*******************************************************************/ /* 3d_toolbar.cpp: construction des tool bars de la frame visu 3d */ /*******************************************************************/ #include "fctsys.h" #include "macros.h" #include "bitmaps3d.h" #include "bitmaps.h" #include "id.h" #define BITMAP wxBitmap #include "3d_viewer.h" /*********************************************/ void WinEDA3D_DrawFrame::ReCreateHToolbar() /*********************************************/ { if( m_HToolBar != NULL ) { // simple mise a jour de la liste des fichiers anciens SetToolbars(); return; } m_HToolBar = new WinEDA_Toolbar( TOOLBAR_MAIN, this, ID_H_TOOLBAR, TRUE ); SetToolBar( m_HToolBar ); // Set up toolbar m_HToolBar->AddTool( ID_RELOAD3D_BOARD, wxEmptyString, BITMAP( import3d_xpm ), _( "Reload board" ) ); #ifdef __WINDOWS__ // do not work properly under linux m_HToolBar-> AddSeparator(); m_HToolBar->AddTool( ID_TOOL_SCREENCOPY_TOCLIBBOARD, wxEmptyString, BITMAP( copy_button ), _( "Copy 3D Image to Clipboard" ) ); #endif m_HToolBar->AddSeparator(); m_HToolBar->AddTool( ID_ZOOM_PLUS_BUTT, wxEmptyString, BITMAP( zoom_in_xpm ), _( "zoom + (F1)" ) ); m_HToolBar->AddTool( ID_ZOOM_MOINS_BUTT, wxEmptyString, BITMAP( zoom_out_xpm ), _( "zoom - (F2)" ) ); m_HToolBar->AddTool( ID_ZOOM_REDRAW_BUTT, wxEmptyString, BITMAP( repaint_xpm ), _( "redraw (F3)" ) ); m_HToolBar->AddTool( ID_ZOOM_PAGE_BUTT, wxEmptyString, BITMAP( zoom_optimal_xpm ), _( "auto zoom" ) ); m_HToolBar->AddSeparator(); m_HToolBar->AddTool( ID_ROTATE3D_X_NEG, wxEmptyString, BITMAP( rotate_neg_X_xpm ), _( "Rotate X <-" ) ); m_HToolBar->AddTool( ID_ROTATE3D_X_POS, wxEmptyString, BITMAP( rotate_pos_X_xpm ), _( "Rotate X ->" ) ); m_HToolBar->AddSeparator(); m_HToolBar->AddTool( ID_ROTATE3D_Y_NEG, wxEmptyString, BITMAP( rotate_neg_Y_xpm ), _( "Rotate Y <-" ) ); m_HToolBar->AddTool( ID_ROTATE3D_Y_POS, wxEmptyString, BITMAP( rotate_pos_Y_xpm ), _( "Rotate Y ->" ) ); m_HToolBar->AddSeparator(); m_HToolBar->AddTool( ID_ROTATE3D_Z_NEG, wxEmptyString, BITMAP( rotate_neg_Z_xpm ), _( "Rotate Z <-" ) ); m_HToolBar->AddTool( ID_ROTATE3D_Z_POS, wxEmptyString, BITMAP( rotate_pos_Z_xpm ), _( "Rotate Z ->" ) ); m_HToolBar->AddSeparator(); m_HToolBar->AddTool( ID_MOVE3D_LEFT, wxEmptyString, BITMAP( left_xpm ), _( "Move left <-" ) ); m_HToolBar->AddTool( ID_MOVE3D_RIGHT, wxEmptyString, BITMAP( right_xpm ), _( "Move right ->" ) ); m_HToolBar->AddTool( ID_MOVE3D_UP, wxEmptyString, BITMAP( up_xpm ), _( "Move Up ^" ) ); m_HToolBar->AddTool( ID_MOVE3D_DOWN, wxEmptyString, BITMAP( down_xpm ), _( "Move Down" ) ); m_HToolBar->Realize(); // SetToolbars(); } /*********************************************/ void WinEDA3D_DrawFrame::ReCreateVToolbar() /*********************************************/ { } /**********************************************/ void WinEDA3D_DrawFrame::ReCreateMenuBar() /**********************************************/ { wxMenuBar* menuBar = new wxMenuBar; wxMenu* fileMenu = new wxMenu; menuBar->Append( fileMenu, _( "&File" ) ); fileMenu->Append( ID_MENU_SCREENCOPY_PNG, _( "Create Image (png format)" ) ); fileMenu->Append( ID_MENU_SCREENCOPY_JPEG, _( "Create Image (jpeg format)" ) ); fileMenu->AppendSeparator(); fileMenu->Append( wxID_EXIT, _( "&Exit" ) ); wxMenu* referencesMenu = new wxMenu; menuBar->Append( referencesMenu, _( "&Preferences" ) ); ADD_MENUITEM( referencesMenu, ID_MENU3D_BGCOLOR_SELECTION, _( "Choose background color" ), palette_xpm ); SetMenuBar( menuBar ); } /*****************************************/ void WinEDA3D_DrawFrame::SetToolbars() /*****************************************/ { } <|endoftext|>