text
stringlengths
54
60.6k
<commit_before>08de11f5-2748-11e6-bc87-e0f84713e7b8<commit_msg>I'm done<commit_after>08e9adc2-2748-11e6-b464-e0f84713e7b8<|endoftext|>
<commit_before>59426848-5216-11e5-b27e-6c40088e03e4<commit_msg>594957ca-5216-11e5-9918-6c40088e03e4<commit_after>594957ca-5216-11e5-9918-6c40088e03e4<|endoftext|>
<commit_before>ed4ce0a6-327f-11e5-a4e9-9cf387a8033e<commit_msg>ed52adcf-327f-11e5-bf51-9cf387a8033e<commit_after>ed52adcf-327f-11e5-bf51-9cf387a8033e<|endoftext|>
<commit_before>5b4162eb-2e4f-11e5-afa1-28cfe91dbc4b<commit_msg>5b48fe80-2e4f-11e5-b89f-28cfe91dbc4b<commit_after>5b48fe80-2e4f-11e5-b89f-28cfe91dbc4b<|endoftext|>
<commit_before>67c19ec2-2e4f-11e5-99f7-28cfe91dbc4b<commit_msg>67c8b5e1-2e4f-11e5-bde3-28cfe91dbc4b<commit_after>67c8b5e1-2e4f-11e5-bde3-28cfe91dbc4b<|endoftext|>
<commit_before>7879d332-2d53-11e5-baeb-247703a38240<commit_msg>787a5244-2d53-11e5-baeb-247703a38240<commit_after>787a5244-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>7720354e-2d53-11e5-baeb-247703a38240<commit_msg>7720b2a8-2d53-11e5-baeb-247703a38240<commit_after>7720b2a8-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>#include <iostream> #include <chrono> #include <random> #include <vector> #include <cmath> #include <SFML/System.hpp> #include <SFML/Graphics.hpp> std::mt19937 generator; std::uniform_real_distribution<double> heightDist(0, 1); std::uniform_int_distribution<int> startDist(-10000, 10000); sf::Vector2u size; std::vector<double> heights; void divideSquare(unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4); int main(int argc, char** argv) { if(argc != 3) { std::cerr << "Incorrect # of args, must be 2.\n"; return 1; } size = {static_cast<unsigned>(std::stoi(argv[1])), static_cast<unsigned>(std::stoi(argv[2]))}; // resize vector to correct size heights.resize(size.x * size.y); // seed generator generator.seed(std::chrono::system_clock::now().time_since_epoch().count()); // begin the recursive algo! divideSquare(0, 0, size.x, size.y, -1, -1, -1, -1); // make the image sf::Image heightMap; heightMap.create(size.x, size.y, {255, 255, 255}); // fill the image for(unsigned i = 0; i < size.x * size.y; i++) { double heightVal = heights[i]; int r = 255.d * heightVal; int g = 255.d * heightVal; int b = 255.d * heightVal; heightMap.setPixel(i % size.x, i / size.y, {r, g, b}); } heightMap.saveToFile("img" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()) + ".png"); return 0; } void divideSquare(unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4) { // get corners double topLeft, topRight, botLeft, botRight; if(c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1) { topLeft = heightDist(generator); topRight = heightDist(generator); botLeft = heightDist(generator); botRight = heightDist(generator); } else { topLeft = c1; topRight = c2; botLeft = c3; botRight = c4; } // get midpoints on edges double topEdge, leftEdge, rightEdge, botEdge; topEdge = (topLeft + topRight) / 2; leftEdge = (topLeft + botLeft) / 2; rightEdge = (topRight + botRight) / 2; botEdge = (botLeft + botRight) / 2; // middle point of the square double middle = (topLeft + topRight + botLeft + botRight) / 4; // assign values // corners heights[x % size.x + y / size.y] = topLeft; heights[x % size.x + (w - 1) + y / size.y] = topRight; heights[x % size.x + y / size.y + (h - 1)] = botLeft; heights[x % size.x + (w - 1) + y / size.y + (h - 1)] = botRight; // midpoints heights[x % size.x + ((w - 1) / 2) + y / size.y] = topEdge; heights[x % size.x + y / size.y + ((h - 1) / 2)] = leftEdge; heights[x % size.x + (w - 1) + y / size.y + ((h - 1) / 2)] = rightEdge; heights[x % size.x + ((w - 1) / 2) + y / size.y + (h - 1)] = botEdge; heights[x % size.x + ((w - 1) / 2) + y / size.y + ((h - 1) / 2)] = middle; // if we're too small to continue if(!(w > 2 || h > 2)) return; divideSquare(x, y, w / 2, h / 2, topLeft, topEdge, leftEdge, middle); // top left quad divideSquare(x + w / 2, y, w / 2, h / 2, topEdge, topRight, middle, rightEdge); // top right quad divideSquare(x, y + h / 2, w / 2, h / 2, leftEdge, middle, botLeft, botEdge); // bot left quad divideSquare(x + w / 2, y + h / 2, w / 2, h / 2, middle, rightEdge, botEdge, botRight); // bot right quad }<commit_msg>Fixed algo to pick the right pixel to color.<commit_after>#include <iostream> #include <chrono> #include <random> #include <vector> #include <SFML/System/Vector2.hpp> #include <SFML/Graphics/Image.hpp> bool done = false; std::mt19937 generator; std::uniform_real_distribution<double> heightDist(0, 1); std::uniform_int_distribution<int> startDist(-10000, 10000); sf::Vector2u size; std::vector<double> heights; void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4); int main(int argc, char** argv) { if(argc != 3) { std::cerr << "Incorrect # of args, must be 2.\n"; return 1; } size = {static_cast<unsigned>(std::stoi(argv[1])), static_cast<unsigned>(std::stoi(argv[2]))}; // resize vector to correct size heights.resize(size.x * size.y, 0); // seed generator generator.seed(std::chrono::system_clock::now().time_since_epoch().count()); // make the image sf::Image heightMap; heightMap.create(size.x, size.y); // begin the recursive algo! divideSquare(true, 0, 0, size.x, size.y, -1, -1, -1, -1); // fill the image for(unsigned i = 0; i < size.x * size.y; i++) { sf::Uint8 r = 255.0 * heights[i]; sf::Uint8 g = 255.0 * heights[i]; sf::Uint8 b = 255.0 * heights[i]; heightMap.setPixel(i % size.x, i / size.y, {r, g, b}); } heightMap.saveToFile("img" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()) + ".png"); return 0; } void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4) { // get corners double topLeft, topRight, botLeft, botRight; if((c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1) || first) { topLeft = heightDist(generator); topRight = heightDist(generator); botLeft = heightDist(generator); botRight = heightDist(generator); } else { topLeft = c1; topRight = c2; botLeft = c3; botRight = c4; } // get midpoints on edges double topEdge, leftEdge, rightEdge, botEdge; if(first) { topEdge = heightDist(generator); leftEdge = heightDist(generator); rightEdge = heightDist(generator); botEdge = heightDist(generator); } else { topEdge = (topLeft + topRight) / 2.0; leftEdge = (topLeft + botLeft) / 2.0; rightEdge = (topRight + botRight) / 2.0; botEdge = (botLeft + botRight) / 2.0; } // middle point of the square, add a random amount to keep the map less uniform double middle; if(first) middle = heightDist(generator); else middle = (topLeft + topRight + botLeft + botRight + heightDist(generator)) / 5.0; // assign values // corners heights[(x % size.x) + (y % size.y) * size.x] = topLeft; heights[(x + w) % size.x + (y % size.y) * size.x] = topRight; heights[(x % size.x) + ((y + h) % size.y) * size.x] = botLeft; heights[(x + w) % size.x + ((y + h) % size.y) * size.x] = botRight; // midpoints heights[(x + (w / 2)) % size.x + (y % size.y) * size.x] = topEdge; heights[(x % size.x) + ((y + (h / 2)) % size.y) * size.x] = leftEdge; heights[(x + w) % size.x + ((y + (h / 2)) % size.y) * size.x] = rightEdge; heights[(x + (w / 2)) % size.x + ((y + h) % size.y) * size.x] = botEdge; heights[(x + (w / 2)) % size.x + ((y + (h / 2)) % size.y) * size.x] = middle; // if we're too small to continue if(!(w > 1 || h > 1)) return; divideSquare(false, x, y, w / 2.0, h / 2.0, topLeft, topEdge, leftEdge, middle); // top left quad divideSquare(false, x + w / 2.0, y, w / 2.0, h / 2.0, topEdge, topRight, middle, rightEdge); // top right quad divideSquare(false, x, y + h / 2.0, w / 2.0, h / 2.0, leftEdge, middle, botLeft, botEdge); // bot left quad divideSquare(false, x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0, middle, rightEdge, botEdge, botRight); // bot right quad } <|endoftext|>
<commit_before>1cb39194-2e4f-11e5-b8ef-28cfe91dbc4b<commit_msg>1cbc1800-2e4f-11e5-b45b-28cfe91dbc4b<commit_after>1cbc1800-2e4f-11e5-b45b-28cfe91dbc4b<|endoftext|>
<commit_before>9101ad16-2d14-11e5-af21-0401358ea401<commit_msg>9101ad17-2d14-11e5-af21-0401358ea401<commit_after>9101ad17-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>f12f1630-327f-11e5-b116-9cf387a8033e<commit_msg>f13716c7-327f-11e5-a822-9cf387a8033e<commit_after>f13716c7-327f-11e5-a822-9cf387a8033e<|endoftext|>
<commit_before>#include "include/input/input.hpp" #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> int main() { cv::Mat image; cv::namedWindow("BGR Feed", cv::WINDOW_AUTOSIZE); cv::namedWindow("Depth Feed", cv::WINDOW_AUTOSIZE); cv::namedWindow("IR Feed", cv::WINDOW_AUTOSIZE); Input *input = new Input(); input->getBGR(image); cv::imshow("BGR Feed", image); input->getDepth(image); cv::imshow("Depth Feed", image); input->getIR(image); cv::imshow("IR Feed", image); return 0; } <commit_msg>Delete main.cpp<commit_after><|endoftext|>
<commit_before>7986359a-2d53-11e5-baeb-247703a38240<commit_msg>7986b8b2-2d53-11e5-baeb-247703a38240<commit_after>7986b8b2-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <string> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> using namespace std; //function to convert a vector of char * to a //char * [] for use as an execvp argument char ** conv_vec(vector<char*> v) { //create a char * [] of proper size char ** t = new char* [v.size() + 1]; //counter to keep track of the position //for entering char* unsigned i = 0; for (; i < v.size(); ++i) { //first make char[] entry of the right length t[i] = new char[strlen(v.at(i))]; //then copy the entire string from the vector //into the char *[] strcpy(t[i], v.at(i)); } //set the last position to a null character t[i] = '\0'; return t; } char ** get_command(string& a, int& flag) { //first make a copy of the command string //so that we can check what delimiter strtok //stopped at char * copy = new char [a.length() + 1]; strcpy(copy, a.c_str()); //create a vector because we do not know //how many tokens are in the command entered vector<char *> temp; //create an empty char * [] to return. It can //either be empty if there is no input or //filled later when we convert the vector //into an array char ** vec = NULL; //bool done = false; //set a starting position to reference when //finding the position of the delimiter found char * begin = copy; //take the first token char * token = strtok(copy, " ;|&"); //for position of delimiter unsigned int pos; while (token != 0) { // cout << token << endl; //the position of the delimiter with respect //to the beginning of the array pos = token - begin + strlen(token); //put the token at the end of the vector temp.push_back(token); //to find out which delimiter was found //if it was the end, it will not go through this if (pos < a.size()) { //store delimiter character found char delim = a.at(pos); // cout << delim << endl; if (delim != ' ' || (pos + 1 < a.size() && (a.at(pos + 1) == '&' || a.at(pos + 1) == '|'))) { //if it was not ' ' then we have reached a //delimiter that indicates the end of the //command so we are done. Convert //the vector into the proper char * [] vec = conv_vec(temp); // for (unsigned i = 0; vec[i] != 0; ++i) // { // cout << i << endl; // cout << vec[i] << endl; // } //remember to get rid of the dynamically allocated delete copy; if (delim == '|' || (pos + 1 < a.size() && a.at(pos + 1) == '|')) { //set flag bit flag = 1; } else if (delim == '&' || (pos + 1 < a.size() && a.at(pos + 1) == '&')) { //set flag bit to 2 flag = 2; } else { //then it was ; so set flag bit to 0 flag = 0; } cout << flag << endl; a = a.substr(pos + 1, a.size() - pos + 1); return vec; } } token = strtok(NULL, " ;|&"); } a = ""; vec = conv_vec(temp); delete copy; flag = 0; return vec; } void display_prompt() { char host[15]; int host_flag = gethostname(host, sizeof host); if(host_flag == -1) { perror("gethostname"); } char *login = getlogin(); if (login == 0) { perror("getlogin"); } cout << login << '@' << host << "$ "; } int main() { int flag = 0; while (1) { display_prompt(); string command; getline(cin, command); while(flag != 0 || command != "") { char ** argv = get_command(command, flag); cout << command << endl; cout << flag << endl; if (strcmp(argv[0], "exit") == 0) { return 0; } for (int i = 0; argv[i] != 0; ++i) { cout << argv[i] << endl; } int fork_flag = fork(); if (fork_flag == -1) { perror("fork"); return 1; } else if (fork_flag == 0) { int execvp_flag = execvp(argv[0], argv); if (execvp_flag == -1) { perror("execvp"); // return 1; } } int wait_flag = wait(NULL); if (wait_flag == -1) { perror("wait"); if (flag == 2) { break; } // return 1; } if (flag == 1) { break; } } } return 0; } <commit_msg>uncommented the return 1 to see if there was any error<commit_after>#include <iostream> #include <vector> #include <string> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> using namespace std; //function to convert a vector of char * to a //char * [] for use as an execvp argument char ** conv_vec(vector<char*> v) { //create a char * [] of proper size char ** t = new char* [v.size() + 1]; //counter to keep track of the position //for entering char* unsigned i = 0; for (; i < v.size(); ++i) { //first make char[] entry of the right length t[i] = new char[strlen(v.at(i))]; //then copy the entire string from the vector //into the char *[] strcpy(t[i], v.at(i)); } //set the last position to a null character t[i] = '\0'; return t; } char ** get_command(string& a, int& flag) { //first make a copy of the command string //so that we can check what delimiter strtok //stopped at char * copy = new char [a.length() + 1]; strcpy(copy, a.c_str()); //create a vector because we do not know //how many tokens are in the command entered vector<char *> temp; //create an empty char * [] to return. It can //either be empty if there is no input or //filled later when we convert the vector //into an array char ** vec = NULL; //bool done = false; //set a starting position to reference when //finding the position of the delimiter found char * begin = copy; //take the first token char * token = strtok(copy, " ;|&"); //for position of delimiter unsigned int pos; while (token != 0) { // cout << token << endl; //the position of the delimiter with respect //to the beginning of the array pos = token - begin + strlen(token); //put the token at the end of the vector temp.push_back(token); //to find out which delimiter was found //if it was the end, it will not go through this if (pos < a.size()) { //store delimiter character found char delim = a.at(pos); // cout << delim << endl; if (delim != ' ' || (pos + 1 < a.size() && (a.at(pos + 1) == '&' || a.at(pos + 1) == '|'))) { //if it was not ' ' then we have reached a //delimiter that indicates the end of the //command so we are done. Convert //the vector into the proper char * [] vec = conv_vec(temp); // for (unsigned i = 0; vec[i] != 0; ++i) // { // cout << i << endl; // cout << vec[i] << endl; // } //remember to get rid of the dynamically allocated delete copy; if (delim == '|' || (pos + 1 < a.size() && a.at(pos + 1) == '|')) { //set flag bit flag = 1; } else if (delim == '&' || (pos + 1 < a.size() && a.at(pos + 1) == '&')) { //set flag bit to 2 flag = 2; } else { //then it was ; so set flag bit to 0 flag = 0; } cout << flag << endl; a = a.substr(pos + 1, a.size() - pos + 1); return vec; } } token = strtok(NULL, " ;|&"); } a = ""; vec = conv_vec(temp); delete copy; flag = 0; return vec; } void display_prompt() { char host[15]; int host_flag = gethostname(host, sizeof host); if(host_flag == -1) { perror("gethostname"); } char *login = getlogin(); if (login == 0) { perror("getlogin"); } cout << login << '@' << host << "$ "; } int main() { int flag = 0; while (1) { display_prompt(); string command; getline(cin, command); while(flag != 0 || command != "") { char ** argv = get_command(command, flag); cout << command << endl; cout << flag << endl; if (strcmp(argv[0], "exit") == 0) { return 0; } for (int i = 0; argv[i] != 0; ++i) { cout << argv[i] << endl; } int fork_flag = fork(); if (fork_flag == -1) { perror("fork"); return 1; } else if (fork_flag == 0) { int execvp_flag = execvp(argv[0], argv); if (execvp_flag == -1) { perror("execvp"); return 1; } } int wait_flag = wait(NULL); if (wait_flag == -1) { perror("wait"); if (flag == 2) { break; } // return 1; } if (flag == 1) { break; } } } return 0; } <|endoftext|>
<commit_before><commit_msg>Main socket-forking<commit_after>/*Main*/ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> #include <stdlib.h> #include <netdb.h> #define BUFFER_SIZE 1024 using namespace std; int main() { //Create a listener socket int sock = socket(PF_INET, SOCK_STREAM, 0); if (sock < 0) { cerr << "Failed to create a listener socket. Exiting..." << endl; exit(EXIT_FAILURE); } //Socket address struct struct sockaddr_in server; server.sin_family = PF_INET; server.sin_addr.s_addr = INADDR_ANY; //Assign port unsigned short port = 8765; server.sin_port = htons(port); //Bind socket to address int serverSize = sizeof(server); if (bind(sock, (struct sockaddr *)&server, serverSize) < 0) { cerr << "Failed to bind socket. Exiting..." << endl; exit(EXIT_FAILURE); } //Listen for up to SOMAXCONN clients listen(sock, 128); cout << "Listening on port " << port << endl; struct sockaddr_in client; int clientSize = sizeof(client); int pid; char buffer[BUFFER_SIZE]; while (1) { int newsock = accept(sock, (struct sockaddr *)&client, (socklen_t*)&clientSize); //Get hostname char hostName[NI_MAXHOST]; struct in_addr ipv4addr; inet_pton(AF_INET, inet_ntoa(client.sin_addr), &ipv4addr); if (getnameinfo(client, clientSize, hostName, sizeof(hostName), NULL, 0, NI_NAMEREQD) != 0) { cout << "Received incoming connection from unresolved host" << endl; } else { cout << "Received incoming connection from " << hostName << endl; } //Fork the new socket pid = fork(); //Client fork doesn't exist if (pid < 0) { cerr << "Could not fork client socket. Exiting..." << endl; exit(EXIT_FAILURE); } //Client thread else if (pid == 0) { int n; do { n = 0; //***TEMP*** } while (n > 0); cout << "Client closed its socket....terminating" << endl; } //Server else { close(newsock); } } close(sock); return EXIT_SUCCESS; }<|endoftext|>
<commit_before>dd324f94-313a-11e5-9440-3c15c2e10482<commit_msg>dd3882cc-313a-11e5-bc13-3c15c2e10482<commit_after>dd3882cc-313a-11e5-bc13-3c15c2e10482<|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <list> #include "opencv.hpp" using namespace cv; using namespace std; using namespace flann; static const double PI = 3.1415926536; struct Options { int threshold; double subsample; // 0..1 -> size on load float minLineLength; float relativeLengthTolerance; int percentStarsRequired; float starDistCutoff; }; struct Star { double x, y; double r; Star(double x, double y, double r) { this->x = x; this->y = y; this->r = r; } Star(const Star &s) : x(s.x), y(s.y), r(s.r) { } }; struct Blob { double x, y; double S; }; Blob operator+(const Blob & l, const Blob & r) { Blob q; q.S = l.S + r.S; q.x = (l.S*l.x + r.S*r.x) / q.S; q.y = (l.S*l.y + r.S*r.y) / q.S; } Blob & operator+=(Blob & blob, const Blob & x) { double S = blob.S + x.S; blob.x = (blob.S*blob.x + x.S*x.x) / S; blob.y = (blob.S*blob.y + x.S*x.y) / S; blob.S = S; } bool operator<(const Star & l, const Star & r) { if (l.r < r.r) return true; if (l.r > r.r) return false; return (l.x < r.x); } typedef vector<Star> Stars; typedef vector<Blob> Blobs; void die(const string & msg) { cerr << "Error: " << msg << endl; exit(1); } inline double sqr(double x) { return x*x; } Point2f controlPoint(const Point2f & u, const Point2f & v) { double dx = v.x - u.x; double dy = v.y - u.y; return Point2f(u.x - dy, u.y + dx); } struct Line { Star a, b; double length; Line(const Star & a_, const Star & b_) : a(a_), b(b_) { length = sqrt(sqr(a.x-b.x) + sqr(a.y - b.y)); } Line(const Line& x) : a(x.a), b(x.b), length(x.length) { } }; bool operator<(const Line & l, const Line & r) { return (l.length < r.length); } void getLines(const Stars & stars, vector<Line> & lines) { for (int i = 0; i < stars.size(); ++i) { for (int j = i+1; j < stars.size(); ++j) { lines.push_back(Line(stars[i], stars[j])); } } } Mat getLineTransform(const Line & a, const Line & b) { Point2f xp[3], yp[3]; xp[0] = Point2f(a.a.x, a.a.y); xp[1] = Point2f(a.b.x, a.b.y); xp[2] = controlPoint(xp[0], xp[1]); yp[0] = Point2f(b.a.x, b.a.y); yp[1] = Point2f(b.b.x, b.b.y); yp[2] = controlPoint(yp[0], yp[1]); return getAffineTransform(xp, yp); } struct ScanItem { Blob blob; int l, r; ScanItem(int _l, int _r, const Blob & _b) : l(_l), r(_r), blob(_b) {} }; double evaluate(const Mat & trans, const Stars & xs, Index_<double> & yindex, const Options & opt) { Mat q(3, xs.size(), CV_64F); for (int x = 0; x < xs.size(); ++x) { q.at<double>(0, x) = xs[x].x; q.at<double>(1, x) = xs[x].y; q.at<double>(2, x) = 1; } Mat query = trans * q; Mat indices(xs.size(), 1, CV_32S), dists(xs.size(), 1, CV_32F); yindex.knnSearch(query.t(), indices, dists, 1, SearchParams()); int cnt = 0; double sum = 0; for (int i = 0; i < dists.rows; ++i) { float dist = dists.at<float>(i, 0); if (dist < opt.starDistCutoff) { ++cnt; sum += dist; } } if (cnt < opt.percentStarsRequired * xs.size() / 100) { // cout << "Not enough stars: " << cnt << endl; return 0; } return opt.starDistCutoff - sum/cnt; } bool getTransform(const Stars & xs, const Stars & ys, Mat & bestTrans, const Options & opt) { // precompute NN search index Mat ymat(ys.size(), 2, CV_64F); for (int y = 0; y < ys.size(); ++y) { ymat.at<double>(y, 0) = ys[y].x; ymat.at<double>(y, 1) = ys[y].y; } Index_<double> yindex(ymat, AutotunedIndexParams()); // find all lines vector<Line> xl, yl; getLines(xs, xl); getLines(ys, yl); // sort the lines sort(xl.rbegin(), xl.rend()); sort(yl.begin(), yl.end()); // cout << "X lines: " << xl.size() << ", Y lines: " << yl.size() << endl; bestTrans = Mat::eye(2, 3, CV_64F); double bestScore = 0; int bestOfs = 0; for (int i = 0; i < xl.size(); ++i) { const Line & xline = xl[i]; double xlen = xline.length; if (xlen < opt.minLineLength) break; // bisect -> find estimate int lo = 0; int hi = yl.size() - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (xlen < yl[mid].length) hi = mid; else lo = mid+1; } // find upper && lower bound int estimate = lo; int estlo = estimate, esthi = estimate; double tolerance = xlen * opt.relativeLengthTolerance; while (estlo >= 0 && yl[estlo].length + tolerance >= xlen) --estlo; while (esthi < yl.size() && yl[esthi].length - tolerance <= xlen) ++esthi; hi = lo+1; // cout << " within (" << estlo-estimate << "," << esthi-estimate << ")" << endl; while (lo > estlo || hi < esthi) { if (lo > estlo) { Mat trans = getLineTransform(xline, yl[lo]); double score = evaluate(trans, xs, yindex, opt); if (score > bestScore) { bestScore = score; bestTrans = trans; bestOfs = lo - estimate; } } if (hi < esthi) { Mat trans = getLineTransform(xline, yl[hi]); double score = evaluate(trans, xs, yindex, opt); if (score > bestScore) { bestScore = score; bestTrans = trans; bestOfs = hi - estimate; } } --lo; ++hi; } } cout << "Best score is " << opt.starDistCutoff-bestScore << " at offset " << bestOfs << endl; return (bestScore > 0); }; void findBlobs(const Mat & mat, Blobs & blobs) { /* namedWindow("foo"); imshow("foo", mat); waitKey(1000); */ //cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl; list<ScanItem> scan, newscan; for (int y = 0; y < mat.rows; ++y) { const uint8_t * row = mat.ptr<uint8_t>(y); list<ScanItem>::iterator it = scan.begin(); int l = 0; for (int x = 0; x < mat.cols; ++x) { // skip blanks while (it != scan.end() && it->r < x) { blobs.push_back(it->blob); ++it; } // find the end of the white segment while (x < mat.cols && row[x]) ++x; // if white segment found if (row[l]) { //cout << "rowscan at " << l << ".." << x << "," << y << endl; Blob cur = {(x+l-1)/2.0, y, x-l}; while (it != scan.end() && it->l < x) { cur += it->blob; ++it; } newscan.push_back(ScanItem(l,x-1,cur)); } l = ++x; } scan = newscan; newscan.clear(); } for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it) { blobs.push_back(it->blob); } } void findStars(const Mat & srcimg, Stars & stars, int thresh) { // threshold the image Mat image; threshold(srcimg, image, thresh, 255, THRESH_BINARY); // find the blobs Blobs blobs; findBlobs(image, blobs); // traverse the blobs stars.clear(); for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it) { stars.push_back(Star(it->x, it->y, sqrt(it->S / PI))); } } inline uint8_t clamp(int x) { return (x < 0) ? 0 : ((x > 255) ? 255 : x); } #define FOREACH(st) \ for (int y = 0; y < mat.rows; ++y) \ { \ uint8_t * row = mat.ptr<uint8_t>(y); \ const uint8_t * end = row + mat.cols; \ while (row < end) { \ st; \ ++row; \ } \ } void normalize(Mat & mat) { int sum = 0; FOREACH(sum += *row); int N = mat.rows * mat.cols; int avg = sum / N; int sqdiff = 0; FOREACH(sqdiff += (avg-*row) * (avg-*row)); int var = sqdiff / N; int sigma = lround(sqrt(var)); FOREACH(*row = clamp(255 * ((int) *row - (int) avg) / (16 * sigma))); } Mat merge(const vector<string> & fn, int a, int b, const Options & opt) { if (a+1 >= b) { cout << "Loading " << fn[a] << endl; Mat full = imread(fn[a], CV_LOAD_IMAGE_GRAYSCALE); Mat subsampled; resize(full, subsampled, Size(0,0), opt.subsample, opt.subsample); normalize(subsampled); return subsampled; } // merge recursively int mid = (a + b) / 2; Mat l = merge(fn, a, mid, opt); Mat r = merge(fn, mid, b, opt); // align the images Stars lstars, rstars; findStars(l, lstars, opt.threshold); findStars(r, rstars, opt.threshold); Mat trans; bool ret = getTransform(lstars, rstars, trans, opt); if (!ret) { cout << "Could not align images!" << endl; return l; // no transform could be found -> return (arbitrarily) the left child } // remap Mat lremap; warpAffine(l, lremap, trans, r.size()); // merge return (0.5*lremap + 0.5*r); } int main(int argc, char ** argv) { char ** end = argv + argc; ++argv; // skip the name of the executable // some default options Options opt; opt.threshold = 128; opt.subsample = 0.3; opt.minLineLength = 100; opt.percentStarsRequired = 50; opt.relativeLengthTolerance = 0.05; opt.starDistCutoff = 100; // get the options while (argv < end) { // end of options if (**argv != '-') break; string opt = *argv++; // no options will follow if (opt == "--") break; die("unknown option " + opt); } // get the list of images vector<string> imgNames; while (argv < end) imgNames.push_back(*argv++); // perform some sanity checks if (imgNames.size() < 2) die("no point in aligning less than two images"); // stack the images Mat stack = merge(imgNames, 0, imgNames.size(), opt); namedWindow("preview"); imshow("preview", stack); waitKey(0); return 0; } <commit_msg>Threshold autodetection.<commit_after>#include <iostream> #include <string> #include <vector> #include <list> #include "opencv.hpp" using namespace cv; using namespace std; using namespace flann; static const double PI = 3.1415926536; struct Options { int threshold; double subsample; // 0..1 -> size on load float minLineLength; float relativeLengthTolerance; int percentStarsRequired; float starDistCutoff; int starCount; }; struct Star { double x, y; double r; Star(double x, double y, double r) { this->x = x; this->y = y; this->r = r; } Star(const Star &s) : x(s.x), y(s.y), r(s.r) { } }; struct Blob { double x, y; double S; }; Blob operator+(const Blob & l, const Blob & r) { Blob q; q.S = l.S + r.S; q.x = (l.S*l.x + r.S*r.x) / q.S; q.y = (l.S*l.y + r.S*r.y) / q.S; } Blob & operator+=(Blob & blob, const Blob & x) { double S = blob.S + x.S; blob.x = (blob.S*blob.x + x.S*x.x) / S; blob.y = (blob.S*blob.y + x.S*x.y) / S; blob.S = S; } bool operator<(const Star & l, const Star & r) { if (l.r < r.r) return true; if (l.r > r.r) return false; return (l.x < r.x); } typedef vector<Star> Stars; typedef vector<Blob> Blobs; void die(const string & msg) { cerr << "Error: " << msg << endl; exit(1); } inline double sqr(double x) { return x*x; } Point2f controlPoint(const Point2f & u, const Point2f & v) { double dx = v.x - u.x; double dy = v.y - u.y; return Point2f(u.x - dy, u.y + dx); } struct Line { Star a, b; double length; Line(const Star & a_, const Star & b_) : a(a_), b(b_) { length = sqrt(sqr(a.x-b.x) + sqr(a.y - b.y)); } Line(const Line& x) : a(x.a), b(x.b), length(x.length) { } }; bool operator<(const Line & l, const Line & r) { return (l.length < r.length); } void getLines(const Stars & stars, vector<Line> & lines) { for (int i = 0; i < stars.size(); ++i) { for (int j = i+1; j < stars.size(); ++j) { lines.push_back(Line(stars[i], stars[j])); } } } Mat getLineTransform(const Line & a, const Line & b) { Point2f xp[3], yp[3]; xp[0] = Point2f(a.a.x, a.a.y); xp[1] = Point2f(a.b.x, a.b.y); xp[2] = controlPoint(xp[0], xp[1]); yp[0] = Point2f(b.a.x, b.a.y); yp[1] = Point2f(b.b.x, b.b.y); yp[2] = controlPoint(yp[0], yp[1]); return getAffineTransform(xp, yp); } struct ScanItem { Blob blob; int l, r; ScanItem(int _l, int _r, const Blob & _b) : l(_l), r(_r), blob(_b) {} }; double evaluate(const Mat & trans, const Stars & xs, Index_<double> & yindex, const Options & opt) { Mat q(3, xs.size(), CV_64F); for (int x = 0; x < xs.size(); ++x) { q.at<double>(0, x) = xs[x].x; q.at<double>(1, x) = xs[x].y; q.at<double>(2, x) = 1; } Mat query = trans * q; Mat indices(xs.size(), 1, CV_32S), dists(xs.size(), 1, CV_32F); yindex.knnSearch(query.t(), indices, dists, 1, SearchParams()); int cnt = 0; double sum = 0; for (int i = 0; i < dists.rows; ++i) { float dist = dists.at<float>(i, 0); if (dist < opt.starDistCutoff) { ++cnt; sum += dist; } } if (cnt < opt.percentStarsRequired * xs.size() / 100) { // cout << "Not enough stars: " << cnt << endl; return 0; } return opt.starDistCutoff - sum/cnt; } bool getTransform(const Stars & xs, const Stars & ys, Mat & bestTrans, const Options & opt) { // precompute NN search index Mat ymat(ys.size(), 2, CV_64F); for (int y = 0; y < ys.size(); ++y) { ymat.at<double>(y, 0) = ys[y].x; ymat.at<double>(y, 1) = ys[y].y; } Index_<double> yindex(ymat, AutotunedIndexParams()); // find all lines vector<Line> xl, yl; getLines(xs, xl); getLines(ys, yl); // sort the lines sort(xl.rbegin(), xl.rend()); sort(yl.begin(), yl.end()); // cout << "X lines: " << xl.size() << ", Y lines: " << yl.size() << endl; bestTrans = Mat::eye(2, 3, CV_64F); double bestScore = 0; int bestOfs = 0; for (int i = 0; i < xl.size(); ++i) { const Line & xline = xl[i]; double xlen = xline.length; if (xlen < opt.minLineLength) break; // bisect -> find estimate int lo = 0; int hi = yl.size() - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (xlen < yl[mid].length) hi = mid; else lo = mid+1; } // find upper && lower bound int estimate = lo; int estlo = estimate, esthi = estimate; double tolerance = xlen * opt.relativeLengthTolerance; while (estlo >= 0 && yl[estlo].length + tolerance >= xlen) --estlo; while (esthi < yl.size() && yl[esthi].length - tolerance <= xlen) ++esthi; hi = lo+1; // cout << " within (" << estlo-estimate << "," << esthi-estimate << ")" << endl; while (lo > estlo || hi < esthi) { if (lo > estlo) { Mat trans = getLineTransform(xline, yl[lo]); double score = evaluate(trans, xs, yindex, opt); if (score > bestScore) { bestScore = score; bestTrans = trans; bestOfs = lo - estimate; } } if (hi < esthi) { Mat trans = getLineTransform(xline, yl[hi]); double score = evaluate(trans, xs, yindex, opt); if (score > bestScore) { bestScore = score; bestTrans = trans; bestOfs = hi - estimate; } } --lo; ++hi; } } cout << "Best score is " << opt.starDistCutoff-bestScore << " at offset " << bestOfs << endl; return (bestScore > 0); }; void findBlobs(const Mat & mat, Blobs & blobs) { /* namedWindow("foo"); imshow("foo", mat); waitKey(1000); */ //cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl; list<ScanItem> scan, newscan; for (int y = 0; y < mat.rows; ++y) { const uint8_t * row = mat.ptr<uint8_t>(y); list<ScanItem>::iterator it = scan.begin(); int l = 0; for (int x = 0; x < mat.cols; ++x) { // skip blanks while (it != scan.end() && it->r < x) { blobs.push_back(it->blob); ++it; } // find the end of the white segment while (x < mat.cols && row[x]) ++x; // if white segment found if (row[l]) { //cout << "rowscan at " << l << ".." << x << "," << y << endl; Blob cur = {(x+l-1)/2.0, y, x-l}; while (it != scan.end() && it->l < x) { cur += it->blob; ++it; } newscan.push_back(ScanItem(l,x-1,cur)); } l = ++x; } scan = newscan; newscan.clear(); } for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it) { blobs.push_back(it->blob); } } void findStars(const Mat & srcimg, Stars & stars, int thresh) { // threshold the image Mat image; threshold(srcimg, image, thresh, 255, THRESH_BINARY); // find the blobs Blobs blobs; findBlobs(image, blobs); // traverse the blobs stars.clear(); for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it) { stars.push_back(Star(it->x, it->y, sqrt(it->S / PI))); } } inline uint8_t clamp(int x) { return (x < 0) ? 0 : ((x > 255) ? 255 : x); } #define FOREACH(st) \ for (int y = 0; y < mat.rows; ++y) \ { \ uint8_t * row = mat.ptr<uint8_t>(y); \ const uint8_t * end = row + mat.cols; \ while (row < end) { \ st; \ ++row; \ } \ } void normalize(Mat & mat) { int sum = 0; FOREACH(sum += *row); int N = mat.rows * mat.cols; int avg = sum / N; int sqdiff = 0; FOREACH(sqdiff += (avg-*row) * (avg-*row)); int var = sqdiff / N; int sigma = lround(sqrt(var)); FOREACH(*row = clamp(255 * ((int) *row - (int) avg) / (16 * sigma))); } Mat merge(const vector<string> & fn, int a, int b, Options & opt) { if (a+1 >= b) { cout << "Loading " << fn[a] << endl; Mat full = imread(fn[a], CV_LOAD_IMAGE_GRAYSCALE); Mat subsampled; resize(full, subsampled, Size(0,0), opt.subsample, opt.subsample); normalize(subsampled); return subsampled; } // merge recursively int mid = (a + b) / 2; Mat l = merge(fn, a, mid, opt); Mat r = merge(fn, mid, b, opt); // align the images Stars lstars, rstars; if (opt.threshold == -1) { // autodetect threshold lstars.clear(); int thresh = 128; int cnt = 0; while (true) { findStars(l, lstars, thresh); cnt = lstars.size(); if (abs(cnt - opt.starCount) < opt.starCount/5) break; else if (cnt < opt.starCount) thresh = thresh / 2; else thresh = (thresh + 255) / 2; if (opt.threshold == thresh) { cerr << "Warning: could not estimate threshold." << endl; break; } else { opt.threshold = thresh; } } cout << "Threshold auto-estimated at " << opt.threshold << endl; } else { findStars(l, lstars, opt.threshold); } findStars(r, rstars, opt.threshold); Mat trans; bool ret = getTransform(lstars, rstars, trans, opt); if (!ret) { cout << "Could not align images!" << endl; return l; // no transform could be found -> return (arbitrarily) the left child } // remap Mat lremap; warpAffine(l, lremap, trans, r.size()); // merge return (0.5*lremap + 0.5*r); } int main(int argc, char ** argv) { char ** end = argv + argc; ++argv; // skip the name of the executable // some default options Options opt; opt.threshold = -1; // autodetect opt.subsample = 0.5; opt.minLineLength = 100; opt.percentStarsRequired = 50; opt.relativeLengthTolerance = 0.05; opt.starDistCutoff = 100; opt.starCount = 15; // get the options while (argv < end) { // end of options if (**argv != '-') break; string opt = *argv++; // no options will follow if (opt == "--") break; die("unknown option " + opt); } // get the list of images vector<string> imgNames; while (argv < end) imgNames.push_back(*argv++); // perform some sanity checks if (imgNames.size() < 2) die("no point in aligning less than two images"); // stack the images Mat stack = merge(imgNames, 0, imgNames.size(), opt); namedWindow("preview"); imshow("preview", stack); waitKey(0); return 0; } <|endoftext|>
<commit_before>6ef88bc6-2fa5-11e5-b7ea-00012e3d3f12<commit_msg>6efa6082-2fa5-11e5-8008-00012e3d3f12<commit_after>6efa6082-2fa5-11e5-8008-00012e3d3f12<|endoftext|>
<commit_before>6b722424-2fa5-11e5-85b0-00012e3d3f12<commit_msg>6b73f8e4-2fa5-11e5-b9e4-00012e3d3f12<commit_after>6b73f8e4-2fa5-11e5-b9e4-00012e3d3f12<|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <stdint.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" void rasterize_triangle_fixed16_8( uint32_t* fb, uint32_t fb_width, uint32_t x0, uint32_t y0, uint32_t z0, uint32_t x1, uint32_t y1, uint32_t z1, uint32_t x2, uint32_t y2, uint32_t z2) { // window coordinates' bounding box uint32_t x_min = x0, x_max = x0; if (x1 < x_min) x_min = x1; if (x2 < x_min) x_min = x2; if (x1 > x_max) x_max = x1; if (x2 > x_max) x_max = x2; uint32_t y_min = y0, y_max = y0; if (y1 < y_min) y_min = y1; if (y2 < y_min) y_min = y2; if (y1 > y_max) y_max = y1; if (y2 > y_max) y_max = y2; // barycentric coordinates of top left corner coordinate // | x y z | // | vx vy 0 | // | ux uy 0 | // = z(vx*uy - vy*ux) int32_t min_bary0 = ((int64_t)(x2 - x1) * (y_min - y1) - (int64_t)(y2 - y1) * (x_min - x1)) >> 8; int32_t min_bary1 = ((int64_t)(x0 - x2) * (y_min - y2) - (int64_t)(y0 - y2) * (x_min - x2)) >> 8; int32_t min_bary2 = ((int64_t)(x1 - x0) * (y_min - y0) - (int64_t)(y1 - y0) * (x_min - x0)) >> 8; // derivative of barycentric coordinates in x and y int32_t dbary0dx = y1 - y2; int32_t dbary0dy = x2 - x1; int32_t dbary1dx = y2 - y0; int32_t dbary1dy = x0 - x2; int32_t dbary2dx = y0 - y1; int32_t dbary2dy = x1 - x0; // minimum/maximum pixel coordinates uint32_t x_min_px = x_min >> 8; uint32_t x_max_px = x_max >> 8; uint32_t y_min_px = y_min >> 8; uint32_t y_max_px = y_max >> 8; // these variables move forward with every y int32_t curr_bary0_row = min_bary0; int32_t curr_bary1_row = min_bary1; int32_t curr_bary2_row = min_bary2; uint32_t* curr_px_row = fb; // fill pixels inside the window coordinate bounding box that are inside all three edges' half-planes for (uint32_t y_px = y_min_px; y_px <= y_max_px; y_px++) { // these variables move forward with every x int32_t curr_bary0 = curr_bary0_row; int32_t curr_bary1 = curr_bary1_row; int32_t curr_bary2 = curr_bary2_row; uint32_t* curr_px = curr_px_row; // fill pixels in this row for (uint32_t x_px = x_min_px; x_px <= x_max_px; x_px++) { // TODO: Handle top-left rule if (curr_bary0 < 0 && curr_bary1 < 0 && curr_bary2 < 0) { *curr_px = 0xFFFFFF00; } // move to next pixel in x direction curr_px += 1; curr_bary0 += dbary0dx; curr_bary1 += dbary1dx; curr_bary2 += dbary2dx; } // move to the start of the next row curr_px_row += fb_width; curr_bary0_row += dbary0dy; curr_bary1_row += dbary1dy; curr_bary2_row += dbary2dy; } } int main() { int fbwidth = 640; int fbheight = 480; uint32_t* fb = (uint32_t*)malloc(fbwidth * fbheight * sizeof(uint32_t)); // fill with background color for (int i = 0; i < fbwidth * fbheight; i++) { fb[i] = 0x00000000; } // rasterize a triangle rasterize_triangle_fixed16_8( fb, fbwidth, 0 << 8, 0 << 8, 0 << 8, 0 << 8, 100 << 8, 0 << 8, 100 << 8, 100 << 8, 0 << 8); // convert framebuffer from bgra to rgba for stbi_image_write for (int i = 0; i < fbwidth * fbheight; i++) { uint32_t src = fb[i]; uint8_t* dst = (uint8_t*)fb + i * 4; dst[0] = (uint8_t)((src & 0x00FF0000) >> 16); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x000000FF) >> 0); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } if (!stbi_write_png("output.png", fbwidth, fbheight, 4, fb, fbwidth * 4)) { fprintf(stderr, "Failed to write image\n"); exit(1); } system("output.png"); free(fb); return 0; }<commit_msg>handle top-left edges<commit_after>#include <stdio.h> #include <stdlib.h> #include <stdint.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" uint32_t g_Color; void rasterize_triangle_fixed16_8( uint32_t* fb, uint32_t fb_width, uint32_t x0, uint32_t y0, uint32_t z0, uint32_t x1, uint32_t y1, uint32_t z1, uint32_t x2, uint32_t y2, uint32_t z2) { // window coordinates' bounding box uint32_t x_min = x0, x_max = x0; if (x1 < x_min) x_min = x1; if (x2 < x_min) x_min = x2; if (x1 > x_max) x_max = x1; if (x2 > x_max) x_max = x2; uint32_t y_min = y0, y_max = y0; if (y1 < y_min) y_min = y1; if (y2 < y_min) y_min = y2; if (y1 > y_max) y_max = y1; if (y2 > y_max) y_max = y2; // barycentric coordinates of top left corner coordinate // | x y z | // | vx vy 0 | // | ux uy 0 | // = z(vx*uy - vy*ux) int32_t min_bary0 = ((int64_t)(x2 - x1) * (y_min - y1) - (int64_t)(y2 - y1) * (x_min - x1)) >> 8; int32_t min_bary1 = ((int64_t)(x0 - x2) * (y_min - y2) - (int64_t)(y0 - y2) * (x_min - x2)) >> 8; int32_t min_bary2 = ((int64_t)(x1 - x0) * (y_min - y0) - (int64_t)(y1 - y0) * (x_min - x0)) >> 8; // offset barycentrics of non top-left edges, which ever so slightly removes them from the rasterization if ((y1 != y2 || x1 > x2) && (y1 < y2)) min_bary0 -= 1; if ((y2 != y0 || x2 > x0) && (y2 < y0)) min_bary1 -= 1; if ((y0 != y1 || x0 > x1) && (y0 < y1)) min_bary2 -= 1; // derivative of barycentric coordinates in x and y int32_t dbary0dx = y1 - y2; int32_t dbary0dy = x2 - x1; int32_t dbary1dx = y2 - y0; int32_t dbary1dy = x0 - x2; int32_t dbary2dx = y0 - y1; int32_t dbary2dy = x1 - x0; // minimum/maximum pixel center coordinates (center sample locations) uint32_t x_min_center = (x_min & 0xFFFFFF00) | 0x7F; uint32_t x_max_center = (x_max & 0xFFFFFF00) | 0x7F; uint32_t y_min_center = (y_min & 0xFFFFFF00) | 0x7F; uint32_t y_max_center = (y_max & 0xFFFFFF00) | 0x7F; // these variables move forward with every y int32_t curr_bary0_row = min_bary0; int32_t curr_bary1_row = min_bary1; int32_t curr_bary2_row = min_bary2; uint32_t* curr_px_row = fb; // fill pixels inside the window coordinate bounding box that are inside all three edges' half-planes for (uint32_t y_px = y_min_center; y_px <= y_max_center; y_px += 0x100) { // these variables move forward with every x int32_t curr_bary0 = curr_bary0_row; int32_t curr_bary1 = curr_bary1_row; int32_t curr_bary2 = curr_bary2_row; uint32_t* curr_px = curr_px_row; // fill pixels in this row for (uint32_t x_px = x_min_center; x_px <= x_max_center; x_px += 0x100) { if (curr_bary0 >= 0 && curr_bary1 >= 0 && curr_bary2 >= 0) { *curr_px += g_Color; } // move to next pixel in x direction curr_bary0 += dbary0dx; curr_bary1 += dbary1dx; curr_bary2 += dbary2dx; curr_px += 1; } // move to the start of the next row curr_bary0_row += dbary0dy; curr_bary1_row += dbary1dy; curr_bary2_row += dbary2dy; curr_px_row += fb_width; } } int main() { int fbwidth = 256; int fbheight = 256; uint32_t* fb = (uint32_t*)malloc(fbwidth * fbheight * sizeof(uint32_t)); // fill with background color for (int i = 0; i < fbwidth * fbheight; i++) { fb[i] = 0x00000000; } // rasterize triangles g_Color = 0xFFFFFF00; rasterize_triangle_fixed16_8( fb, fbwidth, 0 << 8, 0 << 8, 0, 100 << 8, 100 << 8, 0, 0 << 8, 100 << 8, 0); g_Color = 0xFFFF00FF; rasterize_triangle_fixed16_8( fb, fbwidth, 0 << 8, 0 << 8, 0, 100 << 8, 0 << 8, 0, 100 << 8, 100 << 8, 0); // convert framebuffer from bgra to rgba for stbi_image_write for (int i = 0; i < fbwidth * fbheight; i++) { uint32_t src = fb[i]; uint8_t* dst = (uint8_t*)fb + i * 4; dst[0] = (uint8_t)((src & 0x00FF0000) >> 16); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x000000FF) >> 0); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } if (!stbi_write_png("output.png", fbwidth, fbheight, 4, fb, fbwidth * 4)) { fprintf(stderr, "Failed to write image\n"); exit(1); } system("output.png"); free(fb); return 0; }<|endoftext|>
<commit_before>15a33310-585b-11e5-a2ae-6c40088e03e4<commit_msg>15a9e0f0-585b-11e5-89a8-6c40088e03e4<commit_after>15a9e0f0-585b-11e5-89a8-6c40088e03e4<|endoftext|>
<commit_before> #include <string> /// Some documentation struct s{ std::string i; }; int main(int argc, char *argv[]){ int b = 1; b++; void* p; int* c = new int(2); char dir[1024]; strcpy(dir, argv[1]); sprintf(dir, argv[1]); } <commit_msg>added missing header<commit_after> #include <cstring> #include <string> /// Some documentation struct s{ std::string i; }; int main(int argc, char *argv[]){ int b = 1; b++; void* p; int* c = new int(2); char dir[1024]; std::strcpy(dir, argv[1]); std::sprintf(dir, argv[1]); } <|endoftext|>
<commit_before>83000dca-2d15-11e5-af21-0401358ea401<commit_msg>83000dcb-2d15-11e5-af21-0401358ea401<commit_after>83000dcb-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <iostream> #include <cmath> ///@todo only needed for example formula, maybe remove later #include "CalculatorBase.h" #include "OptSimulatedAnnealing.h" class MyCalculator : public CalculatorBase { public: MyCalculator() { } void calculate(OptValue &optValue) const ///@todo make static for easier usage (may not work like this[static] or at least not help) { #ifdef DEBUG std::cout << "DEBUG: in MyCalculator" << std::endl; #endif optValue.result = pow(optValue.get_parameter("X"),2); #ifdef DEBUG std::cout << "DEBUG: result: " << optValue.result << std::endl; #endif } }; using namespace std; int main() { std::vector<OptBoundary> optBoundaries; unsigned int maxCalculations = 100; OptTarget optTarget = APPROACH; T coolingFactor = 0.9; T startChance = 0.25; OptBoundary optBoundary(-3.0, 10.0, "X"); optBoundaries.push_back(optBoundary); MyCalculator myCalculator; OptSimulatedAnnealing opt(optBoundaries, maxCalculations, &myCalculator, optTarget, 3.0, coolingFactor, startChance); OptBase::run_optimisations(1); return 0; } <commit_msg>changed the test to better test approach<commit_after>#include <iostream> #include <cmath> ///@todo only needed for example formula, maybe remove later #include "CalculatorBase.h" #include "OptSimulatedAnnealing.h" class MyCalculator : public CalculatorBase { public: MyCalculator() { } void calculate(OptValue &optValue) const ///@todo make static for easier usage (may not work like this[static] or at least not help) { #ifdef DEBUG std::cout << "DEBUG: in MyCalculator" << std::endl; #endif optValue.result = pow(optValue.get_parameter("X"),2); #ifdef DEBUG std::cout << "DEBUG: result: " << optValue.result << std::endl; #endif } }; using namespace std; int main() { std::vector<OptBoundary> optBoundaries; unsigned int maxCalculations = 1000; OptTarget optTarget = APPROACH; T coolingFactor = 0.995; T startChance = 0.25; OptBoundary optBoundary(-3.0, 10.0, "X"); optBoundaries.push_back(optBoundary); MyCalculator myCalculator; OptSimulatedAnnealing opt(optBoundaries, maxCalculations, &myCalculator, optTarget, 3.0, coolingFactor, startChance); OptBase::run_optimisations(1); return 0; } <|endoftext|>
<commit_before>dca43db0-313a-11e5-bf73-3c15c2e10482<commit_msg>dcaac4fd-313a-11e5-85ab-3c15c2e10482<commit_after>dcaac4fd-313a-11e5-85ab-3c15c2e10482<|endoftext|>
<commit_before>67de9d24-2fa5-11e5-bcea-00012e3d3f12<commit_msg>67e0c006-2fa5-11e5-b02f-00012e3d3f12<commit_after>67e0c006-2fa5-11e5-b02f-00012e3d3f12<|endoftext|>
<commit_before>a2eff5f0-327f-11e5-9c57-9cf387a8033e<commit_msg>a2f63533-327f-11e5-9df5-9cf387a8033e<commit_after>a2f63533-327f-11e5-9df5-9cf387a8033e<|endoftext|>
<commit_before>bdfd90ae-35ca-11e5-a30c-6c40088e03e4<commit_msg>be04fef4-35ca-11e5-941f-6c40088e03e4<commit_after>be04fef4-35ca-11e5-941f-6c40088e03e4<|endoftext|>
<commit_before>f5a74aa6-585a-11e5-9322-6c40088e03e4<commit_msg>f5ae130c-585a-11e5-a570-6c40088e03e4<commit_after>f5ae130c-585a-11e5-a570-6c40088e03e4<|endoftext|>
<commit_before>76fec8d1-2749-11e6-a52d-e0f84713e7b8<commit_msg>Did ANOTHER thing<commit_after>770e0391-2749-11e6-9716-e0f84713e7b8<|endoftext|>
<commit_before>86936ff3-2d15-11e5-af21-0401358ea401<commit_msg>86936ff4-2d15-11e5-af21-0401358ea401<commit_after>86936ff4-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>face98e2-585a-11e5-a0a4-6c40088e03e4<commit_msg>fad5531a-585a-11e5-9191-6c40088e03e4<commit_after>fad5531a-585a-11e5-9191-6c40088e03e4<|endoftext|>
<commit_before>#include "AnimSymLoader.h" #include "FilepathHelper.h" #include "EasyAnimLoader.h" #include "SpineAnimLoader.h" #include <sprite2/AnimSymbol.h> #include <json/json.h> #include <fstream> #include <string.h> namespace gum { AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym, bool flatten, const SymbolLoader* sym_loader, const SpriteLoader* spr_loader) : m_sym(sym) , m_spr_loader(spr_loader) , m_sym_loader(sym_loader) , m_flatten(flatten) { if (m_sym) { m_sym->AddReference(); } } AnimSymLoader::~AnimSymLoader() { if (m_sym) { m_sym->RemoveReference(); } } void AnimSymLoader::LoadJson(const std::string& filepath) { if (!m_sym) { return; } std::string dir = FilepathHelper::Dir(filepath); Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); if (val.isMember("skeleton") && val["skeleton"].isMember("spine")) { SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader); loader.LoadJson(val, dir, filepath); } else { EasyAnimLoader loader(m_sym, m_flatten, m_spr_loader); loader.LoadJson(val, dir); } if (m_flatten) { m_sym->BuildFlatten(NULL); } else { m_sym->LoadCopy(); } } void AnimSymLoader::LoadBin(const simp::NodeAnimation* node) { EasyAnimLoader loader(m_sym, m_flatten, m_spr_loader); loader.LoadBin(node); if (m_flatten) { m_sym->BuildFlatten(NULL); } else { m_sym->LoadCopy(); } } }<commit_msg>[FIXED] up s2, BuildCurr()<commit_after>#include "AnimSymLoader.h" #include "FilepathHelper.h" #include "EasyAnimLoader.h" #include "SpineAnimLoader.h" #include <sprite2/AnimSymbol.h> #include <json/json.h> #include <fstream> #include <string.h> namespace gum { AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym, bool flatten, const SymbolLoader* sym_loader, const SpriteLoader* spr_loader) : m_sym(sym) , m_spr_loader(spr_loader) , m_sym_loader(sym_loader) , m_flatten(flatten) { if (m_sym) { m_sym->AddReference(); } } AnimSymLoader::~AnimSymLoader() { if (m_sym) { m_sym->RemoveReference(); } } void AnimSymLoader::LoadJson(const std::string& filepath) { if (!m_sym) { return; } std::string dir = FilepathHelper::Dir(filepath); Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); if (val.isMember("skeleton") && val["skeleton"].isMember("spine")) { SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader); loader.LoadJson(val, dir, filepath); } else { EasyAnimLoader loader(m_sym, m_flatten, m_spr_loader); loader.LoadJson(val, dir); } if (m_flatten) { m_sym->BuildFlatten(NULL); } else { m_sym->LoadCopy(); } m_sym->BuildCurr(); } void AnimSymLoader::LoadBin(const simp::NodeAnimation* node) { EasyAnimLoader loader(m_sym, m_flatten, m_spr_loader); loader.LoadBin(node); if (m_flatten) { m_sym->BuildFlatten(NULL); } else { m_sym->LoadCopy(); } m_sym->BuildCurr(); } }<|endoftext|>
<commit_before>5e691cb8-ad5c-11e7-aa66-ac87a332f658<commit_msg>TODO: Add a beter commit message<commit_after>5ee17e38-ad5c-11e7-a086-ac87a332f658<|endoftext|>
<commit_before>/****************************************************************/ /* */ /* */ /****************************************************************/ #include "Electrocardio.h" template<> InputParameters validParams<Electrocardio>() { InputParameters params = validParams<Material>(); params.addRequiredCoupledVar("vmem","Membrane potential needed as input for ion channel model"); //! @todo: For ion channel models that need the diffusion current, have to fetch the value of Imem somehow return params; } Electrocardio::Electrocardio(const std::string & name, InputParameters parameters) : Material(name, parameters), _Iion(declareProperty<Real>("Iion")), _gates(declareProperty<std::vector<Real> >("gates")), _gates_old(declarePropertyOld<std::vector<Real> >("gates")), // coupled variables _vmem(coupledValue("vmem")) { // Create pointer to a Bernus model object using the factory class _ionmodel = IionmodelFactory::factory(IionmodelFactory::BERNUS); } void Electrocardio::initQpStatefulProperties() { // initialize local gate variable vector _ionmodel->initialize(&(_gates[_qp])); } /** * @todo documentation */ void Electrocardio::computeQpProperties() { // Compute ionforcing _Iion[_qp] = _ionmodel->ionforcing(_vmem[_qp], &(_gates_old[_qp])); // Copy old values into _gates as initial value for (int i=0; i<_ionmodel->get_ngates(); i++) { _gates[_qp][i] = _gates_old[_qp][i]; } // Perform one Rush-Larsen time step to propagate forward gating variables _ionmodel->rush_larsen_step(_vmem[_qp], _dt, &(_gates[_qp])); /** * The mono domain equations reads * * V_t + div( G grad(V)) = I_ion(V) * * where G is a conductivity tensor, I_ion the current [unit Ampere] generated by the membrane potential V [unit Volt]. * The ODE for the membrane states S reads * * S_t = Z(V,S) * * with V being the membrane potential. * The dependance of I_ion on V and the evolution of the state variables S is given by some membrane model, e.g. Bernus. * * In propag, the following names are used * * Vmem = V = membrane potential = variable in reaction-diffusion PDE * Iion = I_ion(V) = ion current = reaction term in PDE * Imem = diffusion current = div( G grad(V)) * yyy = S = cell states = variable in the ODE */ } <commit_msg>avoiding warning messages about being unable to output gates material parameter<commit_after>#include "Electrocardio.h" template<> InputParameters validParams<Electrocardio>() { InputParameters params = validParams<Material>(); params.addRequiredCoupledVar("vmem","Membrane potential needed as input for ion channel model"); //! @todo: For ion channel models that need the diffusion current, have to fetch the value of Imem somehow // we restrict output to Imem to avoid warnings about gates being impossible to be used in output std::vector<std::string> output_properties; output_properties.push_back("Iion"); params.set<std::vector<std::string> >("output_properties") = output_properties; return params; } Electrocardio::Electrocardio(const std::string & name, InputParameters parameters) : Material(name, parameters), _Iion(declareProperty<Real>("Iion")), _gates(declareProperty<std::vector<Real> >("gates")), _gates_old(declarePropertyOld<std::vector<Real> >("gates")), // coupled variables _vmem(coupledValue("vmem")) { // Create pointer to a Bernus model object using the factory class _ionmodel = IionmodelFactory::factory(IionmodelFactory::BERNUS); } void Electrocardio::initQpStatefulProperties() { // initialize local gate variable vector _ionmodel->initialize(&(_gates[_qp])); } /** * @todo documentation */ void Electrocardio::computeQpProperties() { // Compute ionforcing _Iion[_qp] = _ionmodel->ionforcing(_vmem[_qp], &(_gates_old[_qp])); // Copy old values into _gates as initial value for (int i=0; i<_ionmodel->get_ngates(); i++) { _gates[_qp][i] = _gates_old[_qp][i]; } // Perform one Rush-Larsen time step to propagate forward gating variables _ionmodel->rush_larsen_step(_vmem[_qp], _dt, &(_gates[_qp])); /** * The mono domain equations reads * * V_t + div( G grad(V)) = I_ion(V) * * where G is a conductivity tensor, I_ion the current [unit Ampere] generated by the membrane potential V [unit Volt]. * The ODE for the membrane states S reads * * S_t = Z(V,S) * * with V being the membrane potential. * The dependance of I_ion on V and the evolution of the state variables S is given by some membrane model, e.g. Bernus. * * In propag, the following names are used * * Vmem = V = membrane potential = variable in reaction-diffusion PDE * Iion = I_ion(V) = ion current = reaction term in PDE * Imem = diffusion current = div( G grad(V)) * yyy = S = cell states = variable in the ODE */ } <|endoftext|>
<commit_before>7789028a-2e3a-11e5-95bf-c03896053bdd<commit_msg>779560ca-2e3a-11e5-aeaf-c03896053bdd<commit_after>779560ca-2e3a-11e5-aeaf-c03896053bdd<|endoftext|>
<commit_before>#pragma once #include "stdafx.h" #include "utilities/lua_state_wrapper.h" #include "hypersomnia_gui.h" #include "misc/vector_wrapper.h" #include "misc/stream.h" #include <chrono> #include <ctime> void callback_textbox::set_command_callback(luabind::object callback) { //luabind::object callbackobj = *callback; textbox_object.command_callback = [callback](std::wstring& wstr) { luabind::call_function<void>(callback, augs::misc::towchar_vec(wstr)); }; } augs::misc::vector_wrapper<wchar_t> get_local_time() { auto now = std::chrono::system_clock::now(); auto now_c = std::chrono::system_clock::to_time_t(now); auto tm = std::localtime(&now_c); return augs::misc::towchar_vec (L'[' + augs::misc::wstr<int>(tm->tm_hour) + L':' + augs::misc::wstr<int>(tm->tm_min) + L':' + augs::misc::wstr<int>(tm->tm_sec) + L']'); } void callback_rect::set_focus_callback(luabind::object callback) { rect_obj.focus_callback = [callback]() { luabind::call_function<void>(callback); }; } void callback_rect::set_lpressed_callback(luabind::object callback) { rect_obj.lpressed_callback = [callback]() { luabind::call_function<void>(callback); }; } void callback_rect::set_hover_callback(luabind::object callback) { rect_obj.hover_callback = [callback]() { luabind::call_function<void>(callback); }; } void callback_rect::set_blur_callback(luabind::object callback) { rect_obj.blur_callback = [callback]() { luabind::call_function<void>(callback); }; } void callback_textbox::append_text(augs::graphics::gui::text::fstr& str, bool set_default_font) { auto prev_caret_pos = textbox_object.editor.get_caret_pos(); auto prev_caret_sel = textbox_object.editor.get_selection_offset(); textbox_object.editor.set_caret_end(false); if (set_default_font) { auto def_style = textbox_object.editor.get_default_style(); for (auto& c : str) { c.font_used = def_style.f; } } textbox_object.editor.insert(str); textbox_object.editor.set_caret(prev_caret_pos, false); textbox_object.editor.set_selection_offset(prev_caret_sel); } using namespace graphics::gui; stylesheet::style* resolve_attr(stylesheet& subject, std::string a) { if (a == "released") { return &subject.released; } else if (a == "focused") { return &subject.focused; } else if (a == "hovered") { return &subject.hovered; } else if (a == "pushed") { return &subject.pushed; } return nullptr; } void set_color(stylesheet& subject, std::string attr, augs::graphics::pixel_32 rgba) { auto* s = resolve_attr(subject, attr); if (s) s->color.set(rgba); } void set_border(stylesheet& subject, std::string attr, int w, augs::graphics::pixel_32 rgba) { auto* s = resolve_attr(subject, attr); if (s) s->border.set(solid_stroke(w, material(rgba))); } template <typename... Args> void invokem (Args...) { } template<typename Signature> struct setter_wrapper; template<typename Ret, typename First, typename... Args> struct setter_wrapper<Ret (First, Args...)> { template <typename T, stylesheet& get_style(T&), Ret setter_func(First, Args...)> static Ret setter(T& subject, Args... arguments) { return setter_func(get_style(subject), arguments...); } }; #define wrap_set(_s, _g, _t) setter_wrapper<decltype(_s)>::setter<_t, _g, _s> stylesheet& get_textbox_style(callback_textbox& c) { return c.textbox_object.styles; } stylesheet& get_rect_style(callback_rect& c) { return c.rect_obj.styles; } void hypersomnia_gui::bind(augs::lua_state_wrapper& wrapper) { callback_textbox a; invokem(a.textbox_object.styles, "aaa", augs::graphics::pixel_32(1, 1, 1, 1)); //setter_wrapper<decltype(set_color)>::invoke(a, "aaa", augs::graphics::pixel_32(1, 1, 1, 1)); (a, "aaa", augs::graphics::pixel_32(1, 1, 1, 1)); luabind::module(wrapper.raw)[ luabind::class_<hypersomnia_gui>("hypersomnia_gui") .def(luabind::constructor<augs::window::glwindow&>()) .def("poll_events", &poll_events) .def("setup", &setup) .def("blur", &blur) .def("draw_call", &draw_call), luabind::class_<callback_textbox>("callback_textbox") .def(luabind::constructor<hypersomnia_gui&>()) .def("append_text", &callback_textbox::append_text) .def("setup", &callback_textbox::setup) .def("set_caret", &callback_textbox::set_caret) .def("backspace", &callback_textbox::backspace) .def("view_caret", &callback_textbox::view_caret) .def("remove_line", &callback_textbox::remove_line) .def("is_focused", &callback_textbox::is_focused) .def("focus", &callback_textbox::focus) .def("get_length", &callback_textbox::get_length) .def("draw", &callback_textbox::draw) .def("clear_text", &callback_textbox::clear_text) .def("is_clean", &callback_textbox::is_clean) .def("set_area", &callback_textbox::set_area) .def("get_text_bbox", &callback_textbox::get_text_bbox) .def("set_alpha_range", &callback_textbox::set_alpha_range) .def("set_command_callback", &callback_textbox::set_command_callback), luabind::def("get_local_time", get_local_time), luabind::def("set_color", wrap_set(set_color, get_textbox_style, callback_textbox)), luabind::def("set_color", wrap_set(set_color, get_rect_style, callback_rect)), luabind::def("set_border", wrap_set(set_border, get_textbox_style, callback_textbox)), luabind::def("set_border", wrap_set(set_border, get_rect_style, callback_rect)), luabind::class_<callback_rect>("callback_rect") .def(luabind::constructor<hypersomnia_gui&>()) .def("setup", &callback_rect::setup) .def("focus", &callback_rect::focus) .def("set_focus_callback", &callback_rect::set_focus_callback) .def("set_lpressed_callback", &callback_rect::set_lpressed_callback) .def("set_hover_callback", &callback_rect::set_hover_callback) .def("set_blur_callback", &callback_rect::set_blur_callback) ]; }<commit_msg>corrected time formatting<commit_after>#pragma once #include "stdafx.h" #include "utilities/lua_state_wrapper.h" #include "hypersomnia_gui.h" #include "misc/vector_wrapper.h" #include "misc/stream.h" #include <chrono> #include <ctime> void callback_textbox::set_command_callback(luabind::object callback) { //luabind::object callbackobj = *callback; textbox_object.command_callback = [callback](std::wstring& wstr) { luabind::call_function<void>(callback, augs::misc::towchar_vec(wstr)); }; } augs::misc::vector_wrapper<wchar_t> get_local_time() { auto now = std::chrono::system_clock::now(); auto now_c = std::chrono::system_clock::to_time_t(now); auto tm = std::localtime(&now_c); auto hours = augs::misc::wstr<int>(tm->tm_hour); auto mins = augs::misc::wstr<int>(tm->tm_min); auto secs = augs::misc::wstr<int>(tm->tm_sec); if (tm->tm_hour < 10) hours = L'0' + hours; if (tm->tm_min < 10) mins = L'0' + mins; if (tm->tm_sec < 10) secs = L'0' + secs; return augs::misc::towchar_vec (L'[' + hours + L':' + mins + L':' + secs + L']'); } void callback_rect::set_focus_callback(luabind::object callback) { rect_obj.focus_callback = [callback]() { luabind::call_function<void>(callback); }; } void callback_rect::set_lpressed_callback(luabind::object callback) { rect_obj.lpressed_callback = [callback]() { luabind::call_function<void>(callback); }; } void callback_rect::set_hover_callback(luabind::object callback) { rect_obj.hover_callback = [callback]() { luabind::call_function<void>(callback); }; } void callback_rect::set_blur_callback(luabind::object callback) { rect_obj.blur_callback = [callback]() { luabind::call_function<void>(callback); }; } void callback_textbox::append_text(augs::graphics::gui::text::fstr& str, bool set_default_font) { auto prev_caret_pos = textbox_object.editor.get_caret_pos(); auto prev_caret_sel = textbox_object.editor.get_selection_offset(); textbox_object.editor.set_caret_end(false); if (set_default_font) { auto def_style = textbox_object.editor.get_default_style(); for (auto& c : str) { c.font_used = def_style.f; } } textbox_object.editor.insert(str); textbox_object.editor.set_caret(prev_caret_pos, false); textbox_object.editor.set_selection_offset(prev_caret_sel); } using namespace graphics::gui; stylesheet::style* resolve_attr(stylesheet& subject, std::string a) { if (a == "released") { return &subject.released; } else if (a == "focused") { return &subject.focused; } else if (a == "hovered") { return &subject.hovered; } else if (a == "pushed") { return &subject.pushed; } return nullptr; } void set_color(stylesheet& subject, std::string attr, augs::graphics::pixel_32 rgba) { auto* s = resolve_attr(subject, attr); if (s) s->color.set(rgba); } void set_border(stylesheet& subject, std::string attr, int w, augs::graphics::pixel_32 rgba) { auto* s = resolve_attr(subject, attr); if (s) s->border.set(solid_stroke(w, material(rgba))); } template <typename... Args> void invokem (Args...) { } template<typename Signature> struct setter_wrapper; template<typename Ret, typename First, typename... Args> struct setter_wrapper<Ret (First, Args...)> { template <typename T, stylesheet& get_style(T&), Ret setter_func(First, Args...)> static Ret setter(T& subject, Args... arguments) { return setter_func(get_style(subject), arguments...); } }; #define wrap_set(_s, _g, _t) setter_wrapper<decltype(_s)>::setter<_t, _g, _s> stylesheet& get_textbox_style(callback_textbox& c) { return c.textbox_object.styles; } stylesheet& get_rect_style(callback_rect& c) { return c.rect_obj.styles; } void hypersomnia_gui::bind(augs::lua_state_wrapper& wrapper) { callback_textbox a; invokem(a.textbox_object.styles, "aaa", augs::graphics::pixel_32(1, 1, 1, 1)); //setter_wrapper<decltype(set_color)>::invoke(a, "aaa", augs::graphics::pixel_32(1, 1, 1, 1)); (a, "aaa", augs::graphics::pixel_32(1, 1, 1, 1)); luabind::module(wrapper.raw)[ luabind::class_<hypersomnia_gui>("hypersomnia_gui") .def(luabind::constructor<augs::window::glwindow&>()) .def("poll_events", &poll_events) .def("setup", &setup) .def("blur", &blur) .def("draw_call", &draw_call), luabind::class_<callback_textbox>("callback_textbox") .def(luabind::constructor<hypersomnia_gui&>()) .def("append_text", &callback_textbox::append_text) .def("setup", &callback_textbox::setup) .def("set_caret", &callback_textbox::set_caret) .def("backspace", &callback_textbox::backspace) .def("view_caret", &callback_textbox::view_caret) .def("remove_line", &callback_textbox::remove_line) .def("is_focused", &callback_textbox::is_focused) .def("focus", &callback_textbox::focus) .def("get_length", &callback_textbox::get_length) .def("draw", &callback_textbox::draw) .def("clear_text", &callback_textbox::clear_text) .def("is_clean", &callback_textbox::is_clean) .def("set_area", &callback_textbox::set_area) .def("get_text_bbox", &callback_textbox::get_text_bbox) .def("set_alpha_range", &callback_textbox::set_alpha_range) .def("set_command_callback", &callback_textbox::set_command_callback), luabind::def("get_local_time", get_local_time), luabind::def("set_color", wrap_set(set_color, get_textbox_style, callback_textbox)), luabind::def("set_color", wrap_set(set_color, get_rect_style, callback_rect)), luabind::def("set_border", wrap_set(set_border, get_textbox_style, callback_textbox)), luabind::def("set_border", wrap_set(set_border, get_rect_style, callback_rect)), luabind::class_<callback_rect>("callback_rect") .def(luabind::constructor<hypersomnia_gui&>()) .def("setup", &callback_rect::setup) .def("focus", &callback_rect::focus) .def("set_focus_callback", &callback_rect::set_focus_callback) .def("set_lpressed_callback", &callback_rect::set_lpressed_callback) .def("set_hover_callback", &callback_rect::set_hover_callback) .def("set_blur_callback", &callback_rect::set_blur_callback) ]; }<|endoftext|>
<commit_before>621bebe6-2e4f-11e5-8822-28cfe91dbc4b<commit_msg>6222600c-2e4f-11e5-92a0-28cfe91dbc4b<commit_after>6222600c-2e4f-11e5-92a0-28cfe91dbc4b<|endoftext|>
<commit_before>76c34064-2d53-11e5-baeb-247703a38240<commit_msg>76c3be2c-2d53-11e5-baeb-247703a38240<commit_after>76c3be2c-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>1c38fbf8-2f67-11e5-8ccf-6c40088e03e4<commit_msg>1c3fec00-2f67-11e5-ba9a-6c40088e03e4<commit_after>1c3fec00-2f67-11e5-ba9a-6c40088e03e4<|endoftext|>
<commit_before>d50e9911-313a-11e5-b7b6-3c15c2e10482<commit_msg>d514c954-313a-11e5-9efd-3c15c2e10482<commit_after>d514c954-313a-11e5-9efd-3c15c2e10482<|endoftext|>
<commit_before>d675295e-327f-11e5-b67a-9cf387a8033e<commit_msg>d67b3419-327f-11e5-afbc-9cf387a8033e<commit_after>d67b3419-327f-11e5-afbc-9cf387a8033e<|endoftext|>
<commit_before>ef3fe092-585a-11e5-a364-6c40088e03e4<commit_msg>ef46b2f0-585a-11e5-a6d4-6c40088e03e4<commit_after>ef46b2f0-585a-11e5-a6d4-6c40088e03e4<|endoftext|>
<commit_before>84a4bfca-2749-11e6-834f-e0f84713e7b8<commit_msg>I hope I am done<commit_after>84b40eb0-2749-11e6-ad43-e0f84713e7b8<|endoftext|>
<commit_before>c4c51433-327f-11e5-8249-9cf387a8033e<commit_msg>c4cb720a-327f-11e5-87b5-9cf387a8033e<commit_after>c4cb720a-327f-11e5-87b5-9cf387a8033e<|endoftext|>
<commit_before>5ae7ec4b-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ec4c-2d16-11e5-af21-0401358ea401<commit_after>5ae7ec4c-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>db2482e3-313a-11e5-ad1a-3c15c2e10482<commit_msg>db2a76b5-313a-11e5-b0fe-3c15c2e10482<commit_after>db2a76b5-313a-11e5-b0fe-3c15c2e10482<|endoftext|>
<commit_before>de016c3d-313a-11e5-bc3f-3c15c2e10482<commit_msg>de07735e-313a-11e5-9100-3c15c2e10482<commit_after>de07735e-313a-11e5-9100-3c15c2e10482<|endoftext|>
<commit_before>8431fbee-2d15-11e5-af21-0401358ea401<commit_msg>8431fbef-2d15-11e5-af21-0401358ea401<commit_after>8431fbef-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>e4e97d0c-313a-11e5-bac3-3c15c2e10482<commit_msg>e4ef8b63-313a-11e5-b07c-3c15c2e10482<commit_after>e4ef8b63-313a-11e5-b07c-3c15c2e10482<|endoftext|>
<commit_before>#include "include/main.hpp" #include <boost/algorithm/string/predicate.hpp> using namespace std; using namespace pcp; using namespace boost; using namespace boost::program_options; using namespace boost::algorithm; int DEBUG_LEVEL = 2; int main(int argc, char* argv[]) { string units, printFile, inputFile; int unsuccessfulShake, shakeStart, shakeIncrement, maxTime, rSeed; options_description options("General options"); options.add_options() ("help,h", "produce help message") ("print,p", value<string>(&printFile), "set print file (*.gv)") ("debug,d", value<int>(&DEBUG_LEVEL)->default_value(0), "set debug level") ; options_description vnsOptions("Variable Neighborhood Search options"); vnsOptions.add_options() ("units,n", value<string>(&units)->default_value("nc"), "set units") ("shakeStart,s", value<int>(&shakeStart)->default_value(0), "set shake start") ("shakeIncrement,i", value<int>(&shakeIncrement)->default_value(10), "set shake increment") ("unsuccessfulShake,u", value<int>(&unsuccessfulShake)->default_value(10), "set unsuccessful shake threshold") ("maxTime,t", value<int>(&maxTime)->default_value(10), "set VNS running time (seconds)") ("checkFinal,c", value<bool>()->zero_tokens() , "disable final check after VNS has finished") ("checkIntermediate,m", value<bool>()->zero_tokens(), "enable check after each improvement/shake") ("seed,r", value<int>(&rSeed)->default_value(time(NULL)), "set seed for random number generator") #ifdef ubigraph ("delay", value<bool>()->zero_tokens(), "delay execution after loading the graph and finishing onestepCD") ("full", value<bool>()->zero_tokens(), "render the full graph after the VNS terminates") #endif ; options_description all("Allowed options"); all.add(options).add(vnsOptions); variables_map vm; try { store(parse_command_line(argc, argv, all), vm); } catch(const boost::program_options::error& ex) { cerr << ex.what() << endl; return -1; } notify(vm); if (vm.count("help")) { cout << all << endl; return 0; } srand(rSeed); if (DEBUG_LEVEL > 4) { DEBUG_LEVEL = 4; cout << "The specified debug level (-d) exceeds" << " the maximum. It was set to " << DEBUG_LEVEL << "." << endl; } else if (DEBUG_LEVEL < 0) { DEBUG_LEVEL = 0; } Solution* fullG; if (isdigit(cin.peek())) { string buffer = ""; getline(cin, buffer); cin.seekg(0); if (buffer.find(' ') == string::npos) { if (DEBUG_LEVEL > 2) cout << "Detected .col.b input." << endl; fullG = Solution::fromColBStream(cin); } else { if (DEBUG_LEVEL > 2) cout << "Detected .pcp input." << endl; fullG = Solution::fromPcpStream(cin); } } else { if (DEBUG_LEVEL > 2) cout << "Detected .col input." << endl; fullG = Solution::fromColStream(cin); } if (fullG == NULL) { cerr << "Failed to parse input!" << endl; return -1; } #ifdef ubigraph if (vm.count("delay")) usleep(3000000); #endif if (DEBUG_LEVEL > 3) { cout << "Constructing initial solution ..." << endl; } Solution *onestep = onestepCD(*fullG); if (DEBUG_LEVEL > 2) cout << "Initial solution uses " << onestep->colorsUsed << " colors." << endl; #ifdef ubigraph Solution *onecopy = new Solution(onestep); if (vm.count("delay")) usleep(3000000); #endif Solution *best = vnsRun(*onestep, *fullG, units, unsuccessfulShake, shakeStart, shakeIncrement, maxTime, vm.count("checkIntermediate"), !vm.count("checkFinal")); if (best == NULL) return -1; if (vm.count("print")) { ofstream out(vm["print"].as<string>()); if (out.fail()) { cerr << "Error when trying to access file: " << vm["print"].as<string>() << endl; return -1; } best->print(out); out.flush(); out.close(); if (DEBUG_LEVEL > 1) cout << "Printing to '" << vm["print"].as<string>() << "' done!" << endl; } #ifdef ubigraph int offset = num_vertices(*fullG->g); onecopy->redraw(offset); if (vm.count("full")) fullG->redraw(offset * 2); delete onecopy; #endif delete best; delete fullG; return 0; } <commit_msg>Added comments to clarify behaviour<commit_after>#include "include/main.hpp" #include <boost/algorithm/string/predicate.hpp> using namespace std; using namespace pcp; using namespace boost; using namespace boost::program_options; using namespace boost::algorithm; int DEBUG_LEVEL = 2; // main method, starting point of the program int main(int argc, char* argv[]) { string units, printFile, inputFile; int unsuccessfulShake, shakeStart, shakeIncrement, maxTime, rSeed; // Add program options to be parsed using boost:program_options options_description options("General options"); options.add_options() ("help,h", "produce help message") ("print,p", value<string>(&printFile), "set print file (*.gv)") ("debug,d", value<int>(&DEBUG_LEVEL)->default_value(0), "set debug level") ; options_description vnsOptions("Variable Neighborhood Search options"); vnsOptions.add_options() ("units,n", value<string>(&units)->default_value("nc"), "set units") ("shakeStart,s", value<int>(&shakeStart)->default_value(0), "set shake start") ("shakeIncrement,i", value<int>(&shakeIncrement)->default_value(10), "set shake increment") ("unsuccessfulShake,u", value<int>(&unsuccessfulShake)->default_value(10), "set unsuccessful shake threshold") ("maxTime,t", value<int>(&maxTime)->default_value(10), "set VNS running time (seconds)") ("checkFinal,c", value<bool>()->zero_tokens() , "disable final check after VNS has finished") ("checkIntermediate,m", value<bool>()->zero_tokens(), "enable check after each improvement/shake") ("seed,r", value<int>(&rSeed)->default_value(time(NULL)), "set seed for random number generator") #ifdef ubigraph ("delay", value<bool>()->zero_tokens(), "delay execution after loading the graph and finishing onestepCD") ("full", value<bool>()->zero_tokens(), "render the full graph after the VNS terminates") #endif ; // Parse the options here options_description all("Allowed options"); all.add(options).add(vnsOptions); variables_map vm; try { store(parse_command_line(argc, argv, all), vm); } catch(const boost::program_options::error& ex) { cerr << ex.what() << endl; return -1; } notify(vm); if (vm.count("help")) { cout << all << endl; return 0; } // Set random number generator's seed here, normally time related, unless // specified otherwise srand(rSeed); if (DEBUG_LEVEL > 4) { DEBUG_LEVEL = 4; cout << "The specified debug level (-d) exceeds" << " the maximum. It was set to " << DEBUG_LEVEL << "." << endl; } else if (DEBUG_LEVEL < 0) { DEBUG_LEVEL = 0; } // New solution for the full graph Solution* fullG; // Decide which format the input is in, and parse accordingly if (isdigit(cin.peek())) { string buffer = ""; getline(cin, buffer); cin.seekg(0); if (buffer.find(' ') == string::npos) { if (DEBUG_LEVEL > 2) cout << "Detected .col.b input." << endl; fullG = Solution::fromColBStream(cin); } else { if (DEBUG_LEVEL > 2) cout << "Detected .pcp input." << endl; fullG = Solution::fromPcpStream(cin); } } else { if (DEBUG_LEVEL > 2) cout << "Detected .col input." << endl; fullG = Solution::fromColStream(cin); } if (fullG == NULL) { cerr << "Failed to parse input!" << endl; return -1; } // In case of ubigraph visualization stop the program for 3 secs #ifdef ubigraph if (vm.count("delay")) usleep(3000000); #endif if (DEBUG_LEVEL > 3) { cout << "Constructing initial solution ..." << endl; } // Calcutalte initial solution using oneStepCd Solution *onestep = onestepCD(*fullG); if (DEBUG_LEVEL > 2) cout << "Initial solution uses " << onestep->colorsUsed << " colors." << endl; // In case of ubigraph visualization stop here for 3 secs #ifdef ubigraph Solution *onecopy = new Solution(onestep); if (vm.count("delay")) usleep(3000000); #endif // Start Vns Solution *best = vnsRun(*onestep, *fullG, units, unsuccessfulShake, shakeStart, shakeIncrement, maxTime, vm.count("checkIntermediate"), !vm.count("checkFinal")); if (best == NULL) return -1; // print output if option is set if (vm.count("print")) { ofstream out(vm["print"].as<string>()); if (out.fail()) { cerr << "Error when trying to access file: " << vm["print"].as<string>() << endl; return -1; } best->print(out); out.flush(); out.close(); if (DEBUG_LEVEL > 1) cout << "Printing to '" << vm["print"].as<string>() << "' done!" << endl; } // Visualize the existing onesteo solution along side the new best solution #ifdef ubigraph int offset = num_vertices(*fullG->g); onecopy->redraw(offset); if (vm.count("full")) fullG->redraw(offset * 2); delete onecopy; #endif // Clean up duty delete best; delete fullG; return 0; } <|endoftext|>
<commit_before>#include <SDL.h> #include <vector> #include "opengl.h" int Abs(int num) { return num > 0 ? num : -num; } int PingPong(int num, int length) { return length - Abs((num % (length * 2)) - length); } int main() { const int WindowWidth = 720; const int WindowHeight = 720; if (SDL_Init(SDL_INIT_EVERYTHING)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!window) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } //// OpenGL Setup // Options SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // Connect window SDL_GLContext context = SDL_GL_CreateContext(window); if (!context) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } OpenGL_Init(); { int value = 0; SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value); SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value); SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value); SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value); } int r = 0; int g = 0; int b = 0; glViewport(0, 0, WindowWidth, WindowHeight); glClearColor(0.39f, 0.58f, 0.92f, 1.0f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Shaders const GLchar* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 position;\n" "layout (location = 1) in vec3 color;\n" "layout (location = 2) in vec2 texCoord;\n" "out vec3 ourColor;\n" "out vec2 TexCoord;\n" "void main()\n" "{\n" "gl_Position = vec4(position.x, position.y, position.z, 1.0);\n" "TexCoord = texCoord;\n" "ourColor = color;\n" "}\0"; const GLchar* fragmentShaderSource = "#version 330 core\n" "in vec3 ourColor;\n" "in vec2 TexCoord;\n" "out vec4 color;\n" "uniform sampler2D ourTexture;\n" "void main()\n" "{\n" "color = texture(ourTexture, TexCoord);\n" "color.rgb *= ourColor;\n" "}\n\0"; GLint success; GLchar logBuffer[512]; // Vertex GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer); } // Fragment GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer); } // Program GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer); } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); GLfloat vertices[] = { // Positions // Colors // Texture Coords 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // Top Right 0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // Bottom Right -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // Bottom Left -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f // Top Left }; GLuint indices[] = { 0, 1, 3, 1, 2, 3, }; GLuint VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); { // Now the VBO.. glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Finally the EBO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // Vertex Attributes glVertexAttribPointer(0, // Layout 3, // Size GL_FLOAT, // Type GL_FALSE, // Normalised 8 * sizeof(GLfloat), // Stride (void*) 0); // Array Buffer Offset glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); } glBindVertexArray(0); // Texture loading SDL_Surface* image = SDL_LoadBMP("texture.bmp"); if (!image) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load texture.bmp! %s", SDL_GetError()); return 1; } GLuint texture = 0; glGenTextures(1, &texture); { glBindTexture(GL_TEXTURE_2D, texture); // All texture functions will now operate on this texture glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // X wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Y wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Far away glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Close up // Use GL_BGR because bitmaps are silly glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->w, image->h, 0, GL_BGR, GL_UNSIGNED_BYTE, image->pixels); SDL_FreeSurface(image); } glBindTexture(GL_TEXTURE_2D, 0); // Unbind for(GLenum err; (err = glGetError()) != GL_NO_ERROR;) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "OpenGL Init: 0x%x", err); } bool running = true; SDL_Event event; float current = SDL_GetTicks(); float last = current; float interval = 1000 / 60; while (running) { // Limit frame rate current = SDL_GetTicks(); float dt = current - last; if (dt < interval) { SDL_Delay(interval - dt); continue; } last = current; // Input while(SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; break; } if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) { int x = event.window.data1; int y = event.window.data2; glViewport(0, 0, x, y); } } r = (r + 2) % (255 * 2); g = (g + 4) % (255 * 2); b = (b + 8) % (255 * 2); //Rendering glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw Triangle glUseProgram(shaderProgram); // Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); SDL_GL_SwapWindow(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); return 0; }<commit_msg>Added culling<commit_after>#include <SDL.h> #include <vector> #include "opengl.h" int Abs(int num) { return num > 0 ? num : -num; } int PingPong(int num, int length) { return length - Abs((num % (length * 2)) - length); } int main() { const int WindowWidth = 720; const int WindowHeight = 720; if (SDL_Init(SDL_INIT_EVERYTHING)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!window) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } //// OpenGL Setup // Options SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // Connect window SDL_GLContext context = SDL_GL_CreateContext(window); if (!context) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } OpenGL_Init(); { int value = 0; SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value); SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value); SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value); SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value); } int r = 0; int g = 0; int b = 0; glViewport(0, 0, WindowWidth, WindowHeight); glClearColor(0.39f, 0.58f, 0.92f, 1.0f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_CULL_FACE); // Shaders const GLchar* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 position;\n" "layout (location = 1) in vec3 color;\n" "layout (location = 2) in vec2 texCoord;\n" "out vec3 ourColor;\n" "out vec2 TexCoord;\n" "void main()\n" "{\n" "gl_Position = vec4(position.x, position.y, position.z, 1.0);\n" "TexCoord = texCoord;\n" "ourColor = color;\n" "}\0"; const GLchar* fragmentShaderSource = "#version 330 core\n" "in vec3 ourColor;\n" "in vec2 TexCoord;\n" "out vec4 color;\n" "uniform sampler2D ourTexture;\n" "void main()\n" "{\n" "color = texture(ourTexture, TexCoord);\n" "color.rgb *= ourColor;\n" "}\n\0"; GLint success; GLchar logBuffer[512]; // Vertex GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer); } // Fragment GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer); } // Program GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer); } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); GLfloat vertices[] = { // Positions // Colors // Texture Coords -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Top Left -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // Bottom Left 0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // Bottom Right 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // Top Right }; GLuint indices[] = { 0, 1, 2, 2, 3, 0, }; GLuint VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); { // Now the VBO.. glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Finally the EBO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // Vertex Attributes glVertexAttribPointer(0, // Layout 3, // Size GL_FLOAT, // Type GL_FALSE, // Normalised 8 * sizeof(GLfloat), // Stride (void*) 0); // Array Buffer Offset glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); } glBindVertexArray(0); // Texture loading SDL_Surface* image = SDL_LoadBMP("texture.bmp"); if (!image) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load texture.bmp! %s", SDL_GetError()); return 1; } GLuint texture = 0; glGenTextures(1, &texture); { glBindTexture(GL_TEXTURE_2D, texture); // All texture functions will now operate on this texture glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // X wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Y wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Far away glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Close up // Use GL_BGR because bitmaps are silly glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->w, image->h, 0, GL_BGR, GL_UNSIGNED_BYTE, image->pixels); SDL_FreeSurface(image); } glBindTexture(GL_TEXTURE_2D, 0); // Unbind for(GLenum err; (err = glGetError()) != GL_NO_ERROR;) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "OpenGL Init: 0x%x", err); } bool running = true; SDL_Event event; float current = SDL_GetTicks(); float last = current; float interval = 1000 / 60; while (running) { // Limit frame rate current = SDL_GetTicks(); float dt = current - last; if (dt < interval) { SDL_Delay(interval - dt); continue; } last = current; // Input while(SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; break; } if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) { int x = event.window.data1; int y = event.window.data2; glViewport(0, 0, x, y); } } r = (r + 2) % (255 * 2); g = (g + 4) % (255 * 2); b = (b + 8) % (255 * 2); //Rendering glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw Triangle glUseProgram(shaderProgram); // Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); SDL_GL_SwapWindow(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); return 0; }<|endoftext|>
<commit_before>126d8bde-2f67-11e5-94c2-6c40088e03e4<commit_msg>12744bec-2f67-11e5-a6d8-6c40088e03e4<commit_after>12744bec-2f67-11e5-a6d8-6c40088e03e4<|endoftext|>
<commit_before>/** * * Terminology (Matroid - Graph): * Basis - Spanning tree * Independent set - Tree (i.e. subset of a basis) * Circuit - cycle * Cocircuit - minimal edge-cut * Hyperplane - maximal set not containing any basis (= complement of a min-cut) * * Spanning forest - union of spanning trees of each component of an unconnected graph * */ #include "maybe.hpp" #include "helpers.hpp" #include <iostream> #include <stdexcept> #include <ogdf/basic/Queue.h> #include <ogdf/basic/Graph.h> #include <ogdf/basic/simple_graph_alg.h> enum { BLACK, RED, BLUE }; using namespace std; using namespace ogdf; int m = 3; // Cocircuit size bound /** * @brief Takes a csv file with lines "<id>;<source>;<target>;<edge name>;..." and transforms it into graph * @param sEdgesFileName * @return Graph */ Graph csvToGraph(string sEdgesFileName) { // This copies Graph on exit, to speed up, extend Graph and let this be a new method in our extended class Graph G; ifstream fEdges(sEdgesFileName); if (!fEdges.is_open()) throw new invalid_argument("Edges file doesn't exist or could not be accessed"); vector<node> nodes; int id, u, v, nSize = 0; for (string line; getline(fEdges, line);) { sscanf(line.c_str(), "%d;%d;%d;", &id, &u, &v); if (u > nSize) { nodes.resize(u + 1); nSize = u; } if (v > nSize) { nodes.resize(v + 1); nSize = v; } if(nodes.at(u) == nullptr) nodes[u] = G.newNode(u); if(nodes[v] == nullptr) nodes[v] = G.newNode(v); G.newEdge(nodes[u], nodes[v], id); } return G; } /** * Performs BFS to find the shortest path from s to t in graph g without using any edge from the forbidden edges. * Returns empty set if no such path exists. */ List<edge> shortestPath(const Graph &G, node s, node t, List<edge> forbidden) { List<edge> path; node v, u; edge e; Queue<node> Q; NodeArray<node> predecessor(G); NodeArray<bool> visited(G, false); Q.append(s); visited[s] = true; while(!Q.empty()) { v = Q.pop(); if (v == t) { // traceback predecessors and reconstruct path for (node n = t; n != s; n = predecessor[n]) { path.pushFront(G.searchEdge(predecessor[n], n)); } break; } forall_adj_edges(e, v) { if (forbidden.search(e).valid()) continue; // TODO: Use BST or array (id -> bool) to represent forbidden? u = e->opposite(v); if (!visited[u]) { predecessor[u] = v; // TODO: Unite predecessor and visited? visited[u] = true; Q.append(u); } } } return path; } Maybe<List<edge> > GenCocircuits(const Graph &G, List<edge> X, NodeArray<int> coloring, node red, node blue) { // if(E\X contains no hyperplane of M || X.size() > m) // return return_<Nothing>; // Find set D = (a short circuit C in G, s. t. |C ∩ X| = 1) \ X List<edge> D = shortestPath(G, red, blue, X); if (D.size() > 0) { // for each c ∈ D, recursively call GenCocircuits(X ∪ {c}). for(List<edge>::iterator iterator = D.begin(); iterator != D.end(); iterator++) { edge c = *iterator; List<edge> newX = X; newX.pushBack(c); node u = c->source(), v = c->target(); // c = (u,v) coloring[u] = RED; // Color vertices of c = (u,v) // the one closer to any RED vertex, say u, will be red (and so will be all vertices on the path from the first red to u) for(List<edge>::iterator j = D.begin(); j != iterator; j++) { edge e = *j; coloring[e->source()] = RED; coloring[e->target()] = RED; } // Color the rest of the path blue for(List<edge>::iterator j = iterator; j != D.end(); j++) { edge e = *j; coloring[e->source()] = BLUE; coloring[e->target()] = BLUE; } return GenCocircuits(G, newX, coloring, u, v); } } else { // If there is no such circuit C above (line 4), then return ‘Cocircuit: X’. return return_<Maybe>(X); } } /** * Returns edges spanning forest of (possibly disconnected) graph G * @param G */ List<edge> spanningEdges(const Graph &G) { EdgeArray<bool> isBackedge(G, false); List<edge> backedges; isAcyclicUndirected(G, backedges); for(List<edge>::iterator i = backedges.begin(); i != backedges.end(); i++) { isBackedge[*i] = true; } List<edge> spanningEdges; edge e; forall_edges(e, G) { if (!isBackedge[e]) spanningEdges.pushBack(e); } return spanningEdges; } int main() { try { Graph G = csvToGraph("data/graph3.csv"); List<edge> base = spanningEdges(G); NodeArray<int> coloring(G, BLACK); edge e; for(List<edge>::iterator i = base.begin(); i != base.end(); i++) { e = *i; List<edge> X; // (Indexes might be sufficient? Check later) X.pushBack(e); coloring[e->source()] = RED; coloring[e->target()] = BLUE; Maybe<List<edge> > cocircuit = GenCocircuits(G, X, coloring, e->source(), e->target()); if(cocircuit.isJust()) { cout << "Found a cocircuit: " << cocircuit.fromJust() << endl; } } } catch (invalid_argument *e) { cerr << "Error: " << e->what() << endl; return 1; } return 0; } <commit_msg>Some implementation of hyperplane testing<commit_after>/** * * Terminology (Matroid - Graph): * Basis - Spanning tree * Independent set - Tree (i.e. subset of a basis) * Circuit - cycle * Cocircuit - minimal edge-cut * Hyperplane - maximal set not containing any basis (= complement of a min-cut) * * Spanning forest - union of spanning trees of each component of an unconnected graph * */ #include "maybe.hpp" #include "helpers.hpp" #include <iostream> #include <stdexcept> #include <ogdf/basic/Queue.h> #include <ogdf/basic/Graph.h> #include <ogdf/basic/Stack.h> #include <ogdf/basic/simple_graph_alg.h> enum { BLACK, RED, BLUE }; using namespace std; using namespace ogdf; int m = 3; // Cocircuit size bound /** * @brief Takes a csv file with lines "<id>;<source>;<target>;<edge name>;..." and transforms it into graph * @param sEdgesFileName * @return Graph */ Graph csvToGraph(string sEdgesFileName) { // This copies Graph on exit, to speed up, extend Graph and let this be a new method in our extended class Graph G; ifstream fEdges(sEdgesFileName); if (!fEdges.is_open()) throw new invalid_argument("Edges file doesn't exist or could not be accessed"); vector<node> nodes; int id, u, v, nSize = 0; for (string line; getline(fEdges, line);) { sscanf(line.c_str(), "%d;%d;%d;", &id, &u, &v); if (u > nSize) { nodes.resize(u + 1); nSize = u; } if (v > nSize) { nodes.resize(v + 1); nSize = v; } if(nodes.at(u) == nullptr) nodes[u] = G.newNode(u); if(nodes[v] == nullptr) nodes[v] = G.newNode(v); G.newEdge(nodes[u], nodes[v], id); } return G; } /** * Performs BFS to find the shortest path from s to t in graph g without using any edge from the forbidden edges. * Returns empty set if no such path exists. */ List<edge> shortestPath(const Graph &G, node s, node t, List<edge> forbidden) { List<edge> path; node v, u; edge e; Queue<node> Q; NodeArray<node> predecessor(G); NodeArray<bool> visited(G, false); Q.append(s); visited[s] = true; while(!Q.empty()) { v = Q.pop(); if (v == t) { // traceback predecessors and reconstruct path for (node n = t; n != s; n = predecessor[n]) { path.pushFront(G.searchEdge(predecessor[n], n)); } break; } forall_adj_edges(e, v) { if (forbidden.search(e).valid()) continue; // TODO: Use BST or array (id -> bool) to represent forbidden? u = e->opposite(v); if (!visited[u]) { predecessor[u] = v; // TODO: Unite predecessor and visited? visited[u] = true; Q.append(u); } } } return path; } /** * E(G)\X contains a k-way hyperplane of G\X iff G\V(R) contains a connected subgraph G_b spanning all the blue vertices of X * @param G * @param X * @param coloring * @param blue * @return */ bool hasHyperplane(Graph &G, List<edge> X, NodeArray<int> &coloring) { for(List<edge>::iterator iterator = X.begin(); iterator != X.end(); ++iterator) { G.hideEdge(*iterator); } // Make a list of all blue vertices of X List<node> blues; for(List<edge>::iterator iterator = X.begin(); iterator != X.end(); ++iterator) { edge e = *iterator; node u = e->source(), v = e->target(); if (coloring[u] == BLUE) blues.pushBack(u); if (coloring[v] == BLUE) blues.pushBack(v); } // Pick one, call it s node s = blues.front(); // Perform a DFS on G\X from s and see if all vertices are contained NodeArray<bool> discovered(G, false); Stack<node> S; S.push(s); node v, u; adjEntry adj; while(!S.empty()) { v = S.pop(); if (!discovered[v]) { discovered[v] = true; if (coloring[v] == BLUE) // TODO: If blues were exactly those blues in X, all we would need would be simple count! (Currently the rest of the path D is painted blue) blues.removeFirst(v); forall_adj(adj, v) { u = adj->twinNode(); S.push(u); } } } G.restoreAllEdges(); return blues.empty(); } Maybe<List<edge> > GenCocircuits(Graph &G, List<edge> X, NodeArray<int> coloring, node red, node blue) { if(!hasHyperplane(G, X, coloring) || X.size() > m) { // E\X contains no hyperplane of M return Maybe<List<edge> >(); } // Find set D = (a short circuit C in G, s. t. |C ∩ X| = 1) \ X List<edge> D = shortestPath(G, red, blue, X); if (D.size() > 0) { // for each c ∈ D, recursively call GenCocircuits(X ∪ {c}). for(List<edge>::iterator iterator = D.begin(); iterator != D.end(); iterator++) { edge c = *iterator; List<edge> newX = X; newX.pushBack(c); node u = c->source(), v = c->target(); // c = (u,v) coloring[u] = RED; // Color vertices of c = (u,v) // the one closer to any RED vertex, say u, will be red (and so will be all vertices on the path from the first red to u) for(List<edge>::iterator j = D.begin(); j != iterator; j++) { edge e = *j; coloring[e->source()] = RED; coloring[e->target()] = RED; } // Color the rest of the path blue for(List<edge>::iterator j = iterator; j != D.end(); j++) { edge e = *j; coloring[e->source()] = BLUE; coloring[e->target()] = BLUE; } return GenCocircuits(G, newX, coloring, u, v); } } else { // If there is no such circuit C above (line 4), then return ‘Cocircuit: X’. return return_<Maybe>(X); } } /** * Returns edges spanning forest of (possibly disconnected) graph G * @param G */ List<edge> spanningEdges(const Graph &G) { EdgeArray<bool> isBackedge(G, false); List<edge> backedges; isAcyclicUndirected(G, backedges); for(List<edge>::iterator i = backedges.begin(); i != backedges.end(); i++) { isBackedge[*i] = true; } List<edge> spanningEdges; edge e; forall_edges(e, G) { if (!isBackedge[e]) spanningEdges.pushBack(e); } return spanningEdges; } int main() { try { Graph G = csvToGraph("data/graph2.csv"); List<edge> base = spanningEdges(G); NodeArray<int> coloring(G, BLACK); edge e; for(List<edge>::iterator i = base.begin(); i != base.end(); i++) { e = *i; List<edge> X; // (Indexes might be sufficient? Check later) X.pushBack(e); coloring[e->source()] = RED; coloring[e->target()] = BLUE; Maybe<List<edge> > cocircuit = GenCocircuits(G, X, coloring, e->source(), e->target()); if(cocircuit.isJust()) { cout << "Found a cocircuit: " << cocircuit.fromJust() << endl; } } } catch (invalid_argument *e) { cerr << "Error: " << e->what() << endl; return 1; } return 0; } <|endoftext|>
<commit_before>d85f9423-327f-11e5-af52-9cf387a8033e<commit_msg>d86570b8-327f-11e5-8ae4-9cf387a8033e<commit_after>d86570b8-327f-11e5-8ae4-9cf387a8033e<|endoftext|>
<commit_before>703ff5c7-2e4f-11e5-8811-28cfe91dbc4b<commit_msg>7047f119-2e4f-11e5-8105-28cfe91dbc4b<commit_after>7047f119-2e4f-11e5-8105-28cfe91dbc4b<|endoftext|>
<commit_before>461aae4a-5216-11e5-9a95-6c40088e03e4<commit_msg>4621437e-5216-11e5-a683-6c40088e03e4<commit_after>4621437e-5216-11e5-a683-6c40088e03e4<|endoftext|>
<commit_before>c7854d45-2747-11e6-9bd6-e0f84713e7b8<commit_msg>Gapjgjchguagdmg<commit_after>c79a2463-2747-11e6-9a6f-e0f84713e7b8<|endoftext|>
<commit_before>7f6cf57b-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf57c-2d15-11e5-af21-0401358ea401<commit_after>7f6cf57c-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>181cde58-2f67-11e5-be02-6c40088e03e4<commit_msg>18238742-2f67-11e5-afb6-6c40088e03e4<commit_after>18238742-2f67-11e5-afb6-6c40088e03e4<|endoftext|>
<commit_before>d3fe0714-585a-11e5-875d-6c40088e03e4<commit_msg>d405b218-585a-11e5-8842-6c40088e03e4<commit_after>d405b218-585a-11e5-8842-6c40088e03e4<|endoftext|>
<commit_before>4cf12954-2d3f-11e5-aecb-c82a142b6f9b<commit_msg>4d7bf62e-2d3f-11e5-8005-c82a142b6f9b<commit_after>4d7bf62e-2d3f-11e5-8005-c82a142b6f9b<|endoftext|>
<commit_before>6cc9ee7a-2e3a-11e5-9547-c03896053bdd<commit_msg>6cd625b6-2e3a-11e5-8750-c03896053bdd<commit_after>6cd625b6-2e3a-11e5-8750-c03896053bdd<|endoftext|>
<commit_before>7f6cf5ad-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf5ae-2d15-11e5-af21-0401358ea401<commit_after>7f6cf5ae-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>6fa323a6-2fa5-11e5-b0b8-00012e3d3f12<commit_msg>6fa4d154-2fa5-11e5-9d5d-00012e3d3f12<commit_after>6fa4d154-2fa5-11e5-9d5d-00012e3d3f12<|endoftext|>
<commit_before>7441fdb8-4b02-11e5-89ed-28cfe9171a43<commit_msg>That didn't fix it<commit_after>7450cc42-4b02-11e5-8126-28cfe9171a43<|endoftext|>
<commit_before>5bbfcd54-5216-11e5-bc9b-6c40088e03e4<commit_msg>5bc6b2f4-5216-11e5-b960-6c40088e03e4<commit_after>5bc6b2f4-5216-11e5-b960-6c40088e03e4<|endoftext|>
<commit_before>faec48c5-2e4e-11e5-b991-28cfe91dbc4b<commit_msg>faf98fa3-2e4e-11e5-bf64-28cfe91dbc4b<commit_after>faf98fa3-2e4e-11e5-bf64-28cfe91dbc4b<|endoftext|>
<commit_before>#include "mbed.h" #include "rtos.h" #include "encoder.h" #include "protocol.h" #include "packet_parser.h" // Logical to physical pin definitions (change these when changing boards) #define LED_1_PIN PTC2 #define LED_2_PIN PTC3 #define LED_3_PIN PTA18 #define UART_TX_PIN PTD7 #define UART_RX_PIN PTD6 #define SPI_MOSI_PIN PTC6 #define SPI_MISO_PIN PTC7 #define SPI_SCK_PIN PTC5 #define SPI_CS_PIN PTC4 #define ENABLE_PIN PTA4 #define DIRECTION_PIN PTA2 #define BRAKE_PIN PTA1 #define CURRENT_PIN PTB0 #define TEMPERATURE_PIN PTE30 #define VOLTAGE_PIN PTD5 // Global object/variable instantiations (these should not change) DigitalOut led_1(LED_1_PIN); Encoder encoder(SPI_MOSI_PIN, SPI_MISO_PIN, SPI_SCK_PIN, SPI_CS_PIN); PwmOut enable(ENABLE_PIN); DigitalOut direction(DIRECTION_PIN); DigitalOut brake(BRAKE_PIN); AnalogIn current_sense(CURRENT_PIN); AnalogIn temperature_sense(TEMPERATURE_PIN); AnalogIn voltage_sense(VOLTAGE_PIN); Timer system_timer; sensor_data_t last_sensor_data; command_data_t last_command_data; // This was the best compromise speed since mbed is 41.94MHz and ImageProc is // 40MHz #define SERIAL_BAUDRATE 873813 // Converts ticks/us to rad/s in 16.16 fixed point. Divide resulting number by // 2^16 for final result #define TICK_US_TO_RAD_S_FIXP 25142741 //78640346 // ticks to radians in 8.24 fixed point: multiply by 2^24 for scaled value // 2*pi/(2^14)*2^24 = 6433.9818 // this approximation accumulates one tick of error per 21 revolutions // 2*pi/(2^14)*2^16 = 25.1327 // this approximation accumulates 0.5% error #define TICK_TO_RAD_FIXP 25 //6434 int32_t revolutions = 0; int32_t integrator = 0; int32_t velocity_filtered = 0; uint8_t control_mode = 0; int32_t position_absolute; int32_t velocity_unfiltered; uint32_t dt; #define COMMAND_LIMIT 0.5 // maximum duty cycle: [0,1] (1 is full on) #define V_TAU 20000 // velocity LP time constant in us // 16.16 fixed point: divide by 2^16 for scaled value #define LOW_STOP -2*2*314*(1<<16)/100 // motor position limit #define HIGH_STOP 17*2*314*(1<<16)/100 // motor high position limit #define INTEGRATOR_MAX 1*(1<<16) // integrator saturation in rad*s #define KP 3*(1<<16)/10 // fraction of command per rad #define KI 1*(1<<16)/100 // fraction of command per rad*s #define KD 1*(1<<16)/50 // fraction of command per rad/s // Fills a packet with the most recent acquired sensor data void get_last_sensor_data(packet_t* pkt, uint8_t flags) { pkt->header.type = PKT_TYPE_SENSOR; pkt->header.length = sizeof(header_t) + sizeof(sensor_data_t) + 1; pkt->header.flags = flags; sensor_data_t* sensor_data = (sensor_data_t*)pkt->data_crc; sensor_data->time = last_sensor_data.time; sensor_data->position = last_sensor_data.position; sensor_data->velocity = last_sensor_data.velocity; sensor_data->current = last_sensor_data.current; sensor_data->voltage = last_sensor_data.voltage; sensor_data->temperature = last_sensor_data.temperature; sensor_data->uc_temp = last_sensor_data.uc_temp; } // Sense and control function to be run at 1kHz void sense_control_thread(void const *arg) { uint32_t last_time = last_sensor_data.time; int32_t last_position = last_sensor_data.position; // 3us last_sensor_data.time = system_timer.read_us(); // 19.6us encoder.update_state(); dt = last_sensor_data.time - last_time; // timing int32_t current_position = encoder.get_cal_state(); /* last_sensor_data.position = encoder.get_cal_state(); // 393us last_sensor_data.velocity = ( TICK_US_TO_RAD_S_FIXP*(last_sensor_data.position - last_position)) / (last_sensor_data.time-last_time); // 8.1us last_sensor_data.current = current_sense.read_u16(); //85.6us last_sensor_data.temperature = temperature_sense.read_u16(); // 85.6us last_sensor_data.uc_temp = 0x1234; */ // Position: rad in 15.16 fixed point if (current_position > 3<<12 && last_position < 1<<12) { revolutions--; } else if (current_position < 1<<12 && last_position > 3<<12) { revolutions++; } int32_t last_position_absolute = position_absolute; position_absolute = TICK_TO_RAD_FIXP * (revolutions*(1<<14) + current_position); // Velocity: rad/s in 15.16 fixed point velocity_unfiltered = 1000000*(((int64_t)position_absolute - (int64_t)last_position_absolute)/dt); velocity_filtered = dt*velocity_unfiltered/(V_TAU + dt) + V_TAU*velocity_filtered/(V_TAU + dt); // Add data to struct last_sensor_data.position = position_absolute; last_sensor_data.velocity = velocity_filtered; last_sensor_data.current = current_sense.read_u16(); last_sensor_data.temperature = temperature_sense.read_u16(); last_sensor_data.uc_temp = 0x1234; // TODO: Calculate and apply control int32_t command = 0; switch (control_mode) { case 0: command = 0; integrator = 0; break; case 1: // TODO: Current control command = 0; integrator = 0; break; case 2: int32_t target_position = 0*(1<<16); // rad in 16.16 fixed point int32_t target_velocity = 0*(1<<16); // rad/s in 16.16 fixed point /* if (last_sensor_data.time % 10000000 < 5000000) { target_position = 30*(1<<16);//1.5*(1<<16); } */ /* target_position = 6*(int64_t)last_sensor_data.time*(1<<16)/1000000; target_velocity = 6*(1<<16); */ target_position = last_command_data.position_setpoint; int32_t position_error = position_absolute - target_position; // Integrator: rad*s in 15.16 fixed point integrator += (int32_t)((int64_t)position_error*(uint64_t)dt/1000000); if (integrator > INTEGRATOR_MAX) { // integrator saturation to prevent windup integrator = INTEGRATOR_MAX; } else if (integrator < -INTEGRATOR_MAX) { integrator = -INTEGRATOR_MAX; } // Command command = (-KP*(int64_t)position_error)/(1<<16) + (-KD*((int64_t)velocity_filtered-(int64_t)target_velocity))/(1<<16) + (-KI*(int64_t)integrator)/(1<<16); break; } if (position_absolute > HIGH_STOP) { // high limit stop command = command > 0.0 ? 0.0 : command; } else if (position_absolute < LOW_STOP) { // low limit stop command = command < 0.0 ? 0.0 : command; } float command_magnitude = fabs(static_cast<float>(command)/(1<<16)); command_magnitude = command_magnitude > COMMAND_LIMIT ? COMMAND_LIMIT : command_magnitude; // limit maximum duty cycle enable.write(1-command_magnitude); direction.write(command > 0); // end Calculate and apply control (JY) // This puts the packet in the outgoing queue if there is space PacketParser* parser = (PacketParser*)(arg); packet_union_t* sensor_pkt = parser->get_send_packet(); if (sensor_pkt != NULL) { get_last_sensor_data(&(sensor_pkt->packet),0); parser->send_packet(sensor_pkt); } } int main() { enable.period_us(50); enable.write(0.9f); direction.write(0); brake.write(1); control_mode = 0; // by default, disable the motor led_1 = 1; // Start the microsecond time system_timer.start(); // Instantiate packet parser PacketParser parser( SERIAL_BAUDRATE, UART_TX_PIN, UART_RX_PIN, LED_2_PIN, LED_3_PIN); // Run the sense/control thread at 1kHz RtosTimer sense_control_ticker( &sense_control_thread, osTimerPeriodic, (void*)(&parser)); sense_control_ticker.start(1); // Pointer to received packet packet_union_t* recv_pkt = NULL; while(1) { // See if there is a received packet recv_pkt = parser.get_received_packet(); if (recv_pkt != NULL) { led_1 = !(led_1.read()); switch (recv_pkt->packet.header.type) { // If got a command packet, store command value case PKT_TYPE_COMMAND: memcpy(&last_command_data,recv_pkt->packet.data_crc, sizeof(command_data_t)); // TODO: state machine for control modes control_mode = recv_pkt->packet.header.flags; // end control modes (JY) break; default: // TODO: do something if we got an unrecognized packet type? break; } parser.free_received_packet(recv_pkt); } // This will process any outgoing packets parser.send_worker(); } } <commit_msg>Fixed wrap-around.<commit_after>#include "mbed.h" #include "rtos.h" #include "encoder.h" #include "protocol.h" #include "packet_parser.h" // Logical to physical pin definitions (change these when changing boards) #define LED_1_PIN PTC2 #define LED_2_PIN PTC3 #define LED_3_PIN PTA18 #define UART_TX_PIN PTD7 #define UART_RX_PIN PTD6 #define SPI_MOSI_PIN PTC6 #define SPI_MISO_PIN PTC7 #define SPI_SCK_PIN PTC5 #define SPI_CS_PIN PTC4 #define ENABLE_PIN PTA4 #define DIRECTION_PIN PTA2 #define BRAKE_PIN PTA1 #define CURRENT_PIN PTB0 #define TEMPERATURE_PIN PTE30 #define VOLTAGE_PIN PTD5 // Global object/variable instantiations (these should not change) DigitalOut led_1(LED_1_PIN); Encoder encoder(SPI_MOSI_PIN, SPI_MISO_PIN, SPI_SCK_PIN, SPI_CS_PIN); PwmOut enable(ENABLE_PIN); DigitalOut direction(DIRECTION_PIN); DigitalOut brake(BRAKE_PIN); AnalogIn current_sense(CURRENT_PIN); AnalogIn temperature_sense(TEMPERATURE_PIN); AnalogIn voltage_sense(VOLTAGE_PIN); Timer system_timer; sensor_data_t last_sensor_data; command_data_t last_command_data; // This was the best compromise speed since mbed is 41.94MHz and ImageProc is // 40MHz #define SERIAL_BAUDRATE 873813 // Converts ticks/us to rad/s in 16.16 fixed point. Divide resulting number by // 2^16 for final result #define TICK_US_TO_RAD_S_FIXP 25142741 //78640346 // ticks to radians in 8.24 fixed point: multiply by 2^24 for scaled value // 2*pi/(2^14)*2^24 = 6433.9818 // this approximation accumulates one tick of error per 21 revolutions // 2*pi/(2^14)*2^16 = 25.1327 // this approximation accumulates 0.5% error #define TICK_TO_RAD_FIXP 25 //6434 int32_t revolutions = 0; int32_t integrator = 0; int32_t velocity_filtered = 0; int32_t current_position = 0; uint8_t control_mode = 0; int32_t position_absolute; int32_t velocity_unfiltered; uint32_t dt; #define COMMAND_LIMIT 0.5 // maximum duty cycle: [0,1] (1 is full on) #define V_TAU 20000 // velocity LP time constant in us // 16.16 fixed point: divide by 2^16 for scaled value #define LOW_STOP -2*2*314*(1<<16)/100 // motor position limit #define HIGH_STOP 17*2*314*(1<<16)/100 // motor high position limit #define INTEGRATOR_MAX 1*(1<<16) // integrator saturation in rad*s #define KP 3*(1<<16)/10 // fraction of command per rad #define KI 1*(1<<16)/100 // fraction of command per rad*s #define KD 1*(1<<16)/50 // fraction of command per rad/s // Fills a packet with the most recent acquired sensor data void get_last_sensor_data(packet_t* pkt, uint8_t flags) { pkt->header.type = PKT_TYPE_SENSOR; pkt->header.length = sizeof(header_t) + sizeof(sensor_data_t) + 1; pkt->header.flags = flags; sensor_data_t* sensor_data = (sensor_data_t*)pkt->data_crc; sensor_data->time = last_sensor_data.time; sensor_data->position = last_sensor_data.position; sensor_data->velocity = last_sensor_data.velocity; sensor_data->current = last_sensor_data.current; sensor_data->voltage = last_sensor_data.voltage; sensor_data->temperature = last_sensor_data.temperature; sensor_data->uc_temp = last_sensor_data.uc_temp; } // Sense and control function to be run at 1kHz void sense_control_thread(void const *arg) { uint32_t last_time = last_sensor_data.time; int32_t last_position = current_position; // 3us last_sensor_data.time = system_timer.read_us(); // 19.6us encoder.update_state(); dt = last_sensor_data.time - last_time; // timing current_position = encoder.get_cal_state(); /* last_sensor_data.position = encoder.get_cal_state(); // 393us last_sensor_data.velocity = ( TICK_US_TO_RAD_S_FIXP*(last_sensor_data.position - last_position)) / (last_sensor_data.time-last_time); // 8.1us last_sensor_data.current = current_sense.read_u16(); //85.6us last_sensor_data.temperature = temperature_sense.read_u16(); // 85.6us last_sensor_data.uc_temp = 0x1234; */ // Position: rad in 15.16 fixed point if (current_position > 3<<12 && last_position < 1<<12) { revolutions--; } else if (current_position < 1<<12 && last_position > 3<<12) { revolutions++; } int32_t last_position_absolute = position_absolute; position_absolute = TICK_TO_RAD_FIXP * (revolutions*(1<<14) + current_position); // Velocity: rad/s in 15.16 fixed point velocity_unfiltered = 1000000*(((int64_t)position_absolute - (int64_t)last_position_absolute)/dt); velocity_filtered = dt*velocity_unfiltered/(V_TAU + dt) + V_TAU*velocity_filtered/(V_TAU + dt); // Add data to struct last_sensor_data.position = position_absolute; last_sensor_data.velocity = velocity_filtered; last_sensor_data.current = current_sense.read_u16(); last_sensor_data.temperature = temperature_sense.read_u16(); last_sensor_data.uc_temp = 0x1234; // TODO: Calculate and apply control int32_t command = 0; switch (control_mode) { case 0: command = 0; integrator = 0; break; case 1: // TODO: Current control command = 0; integrator = 0; break; case 2: int32_t target_position = 0*(1<<16); // rad in 16.16 fixed point int32_t target_velocity = 0*(1<<16); // rad/s in 16.16 fixed point /* if (last_sensor_data.time % 10000000 < 5000000) { target_position = 30*(1<<16);//1.5*(1<<16); } */ /* target_position = 6*(int64_t)last_sensor_data.time*(1<<16)/1000000; target_velocity = 6*(1<<16); */ target_position = last_command_data.position_setpoint; int32_t position_error = position_absolute - target_position; // Integrator: rad*s in 15.16 fixed point integrator += (int32_t)((int64_t)position_error*(uint64_t)dt/1000000); if (integrator > INTEGRATOR_MAX) { // integrator saturation to prevent windup integrator = INTEGRATOR_MAX; } else if (integrator < -INTEGRATOR_MAX) { integrator = -INTEGRATOR_MAX; } // Command command = (-KP*(int64_t)position_error)/(1<<16) + (-KD*((int64_t)velocity_filtered-(int64_t)target_velocity))/(1<<16) + (-KI*(int64_t)integrator)/(1<<16); break; } if (position_absolute > HIGH_STOP) { // high limit stop command = command > 0.0 ? 0.0 : command; } else if (position_absolute < LOW_STOP) { // low limit stop command = command < 0.0 ? 0.0 : command; } float command_magnitude = fabs(static_cast<float>(command)/(1<<16)); command_magnitude = command_magnitude > COMMAND_LIMIT ? COMMAND_LIMIT : command_magnitude; // limit maximum duty cycle enable.write(1-command_magnitude); direction.write(command > 0); // end Calculate and apply control (JY) // This puts the packet in the outgoing queue if there is space PacketParser* parser = (PacketParser*)(arg); packet_union_t* sensor_pkt = parser->get_send_packet(); if (sensor_pkt != NULL) { get_last_sensor_data(&(sensor_pkt->packet),0); parser->send_packet(sensor_pkt); } } int main() { enable.period_us(50); enable.write(0.9f); direction.write(0); brake.write(1); control_mode = 0; // by default, disable the motor led_1 = 1; // Start the microsecond time system_timer.start(); // Instantiate packet parser PacketParser parser( SERIAL_BAUDRATE, UART_TX_PIN, UART_RX_PIN, LED_2_PIN, LED_3_PIN); // Run the sense/control thread at 1kHz RtosTimer sense_control_ticker( &sense_control_thread, osTimerPeriodic, (void*)(&parser)); sense_control_ticker.start(1); // Pointer to received packet packet_union_t* recv_pkt = NULL; while(1) { // See if there is a received packet recv_pkt = parser.get_received_packet(); if (recv_pkt != NULL) { led_1 = !(led_1.read()); switch (recv_pkt->packet.header.type) { // If got a command packet, store command value case PKT_TYPE_COMMAND: memcpy(&last_command_data,recv_pkt->packet.data_crc, sizeof(command_data_t)); // TODO: state machine for control modes control_mode = recv_pkt->packet.header.flags; // end control modes (JY) break; default: // TODO: do something if we got an unrecognized packet type? break; } parser.free_received_packet(recv_pkt); } // This will process any outgoing packets parser.send_worker(); } } <|endoftext|>
<commit_before>b2f814e8-327f-11e5-9571-9cf387a8033e<commit_msg>b2fdd1a8-327f-11e5-977b-9cf387a8033e<commit_after>b2fdd1a8-327f-11e5-977b-9cf387a8033e<|endoftext|>
<commit_before>c4e5c7d8-35ca-11e5-a5e3-6c40088e03e4<commit_msg>c4ec1534-35ca-11e5-b477-6c40088e03e4<commit_after>c4ec1534-35ca-11e5-b477-6c40088e03e4<|endoftext|>
<commit_before>6ebd5786-2fa5-11e5-9107-00012e3d3f12<commit_msg>6ebf0534-2fa5-11e5-994c-00012e3d3f12<commit_after>6ebf0534-2fa5-11e5-994c-00012e3d3f12<|endoftext|>
<commit_before>cfdd1ba6-4b02-11e5-b095-28cfe9171a43<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>cfebadd9-4b02-11e5-8655-28cfe9171a43<|endoftext|>
<commit_before>#include <fstream> #include <string> #include <cassert> #include <iostream> #include <stdio.h> extern "C" { #include <pg_config.h> #include <postgres.h> #include <storage/bufpage.h> #include <storage/itemid.h> #include <access/htup.h> } #define PAGE_SIZE (8*1024) namespace { char hexadecimate(unsigned value) { switch( value ) { case 0: return '0'; case 1: return '1'; case 2: return '2'; case 3: return '3'; case 4: return '4'; case 5: return '5'; case 6: return '6'; case 7: return '7'; case 8: return '8'; case 9: return '9'; case 10: return 'A'; case 11: return 'B'; case 12: return 'C'; case 13: return 'D'; case 14: return 'E'; case 15: return 'F'; } assert(false); return '?'; } inline unsigned integral_division(unsigned dividend, unsigned divisor) { unsigned result = dividend/divisor; assert( dividend - (divisor*result) == 0 ); return result; } struct Varlena : public varlena { unsigned _size() { return *reinterpret_cast<unsigned*>(vl_len_); } unsigned size() { assert(false);//WIP return _size(); } }; struct ItemHeader; struct ItemData { ItemHeader* header; char* data; unsigned data_size; std::string hexadecimate_all(unsigned pos=0,unsigned max=-1) { std::string result; unsigned end = data_size; if( end > max ) end = max; for( unsigned int i = pos; i < end; ++i ) { if( isalnum(data[i]) ) { result += data[i]; } else if( data[i] == '\n' ) { result += "\\n"; } else if( data[i] == ' ') { result += " "; } else { // result += std::to_string( data[i] ); // result += hexadecimate( ((unsigned char)(data[i]))>>4 ); // result += hexadecimate( data[i]&0xF ); result += "X"; } // result += " "; } return result; } unsigned get_serial(unsigned pos) { return *reinterpret_cast<unsigned*>( data+pos ); }; unsigned get_serial_size() { return 4; } Varlena* get_varlena(unsigned pos) { return reinterpret_cast<Varlena*>( data+pos ); } unsigned get_varlena_size(unsigned pos) { return get_varlena(pos)->size(); } }; struct ItemHeader : public HeapTupleHeaderData { unsigned number_attributes() { return unsigned(t_infomask2 & HEAP_NATTS_MASK); } bool has_bitmap() { return bool(t_infomask & HEAP_HASNULL); } bool has_attribute(unsigned pos) { return !bool(att_isnull(pos,t_bits)); } }; struct PageData : public PageHeaderData { unsigned itemid_count() { return integral_division( pd_lower-sizeof(PageHeaderData)+sizeof(ItemIdData), sizeof(ItemIdData) ); }; ItemHeader* get_item_header(const ItemIdData& itemid) { return reinterpret_cast<ItemHeader*>( reinterpret_cast<char*>(this)+itemid.lp_off ); }; ItemData get_item_data(const ItemIdData& itemid) { ItemHeader* header = get_item_header(itemid); char* data = reinterpret_cast<char*>(header) + header->t_hoff; unsigned data_size = itemid.lp_len - header->t_hoff; ItemData result = {header,data,data_size}; return result; } }; char read_page_buffer[PAGE_SIZE]; PageData* read_page(std::istream& stream, unsigned pos) { stream.seekg(pos*PAGE_SIZE,std::istream::beg); stream.read(read_page_buffer,PAGE_SIZE); return reinterpret_cast<PageData*>(&read_page_buffer); } } void user_code(ItemIdData& itemid, ItemHeader& itemheader, ItemData& itemdata); int main(int argc, char** argv) { assert( sizeof(PageData) == 24+sizeof(ItemIdData) ); assert( sizeof(ItemIdData) == 4 ); if( argc < 2 ) { std::cerr << "Usage " << argv[0] << " input_file" << std::endl; return 1; } std::ifstream input(argv[1]); assert( input.good() ); input.seekg(0, std::ifstream::end); unsigned size = input.tellg(); input.seekg(0, std::ifstream::beg); unsigned pages = size/PAGE_SIZE; if( size - (pages*PAGE_SIZE) != 0 ) { std::cerr << "Given file is not aligned to " << PAGE_SIZE << " bytes" << std::endl; return 1; } if( pages == 0 ) { std::cerr << "Given file has zero pages" << std::endl; return 1; }; for( unsigned int which_page=0;which_page<pages;++which_page) { PageData& page = *read_page(input,which_page); std::cout << "Page " << which_page << "(" << page.itemid_count() << " itens)" << std::endl; for( unsigned int i = 0; i < page.itemid_count(); ++i ) { ItemIdData& itemid = page.pd_linp[i]; if( itemid.lp_flags != LP_NORMAL ) { std::cerr << "\tIgnoring item because it is not marked as LP_NORMAL" << std::endl; } else if( itemid.lp_len == 0 ) { std::cerr << "\tIgnoring item because it has no storage" << std::endl; } else if( itemid.lp_off > PAGE_SIZE ) { std::cerr << "\tIgnoring item because it's offset is outside of page" << std::endl; } else if( itemid.lp_off + itemid.lp_len > PAGE_SIZE ) { std::cerr << "\tIgnoring item because it spans outsize of the page" << std::endl; } else { ItemHeader& itemheader = *page.get_item_header(itemid); std::cout << "\tItem (" << itemid.lp_off << "," << itemid.lp_len << ")~" << itemid.lp_flags; std::cout << ", number of attributes is " << itemheader.number_attributes(); std::cout << " " << (itemheader.has_bitmap() ? "with" : "without") << " bitmap"; if( itemheader.has_bitmap() ) { std::cout << ":\t"; for( unsigned int j=0; j < itemheader.number_attributes(); ++j) { std::cout << " " << itemheader.has_attribute(j); } } ItemData itemdata = page.get_item_data(itemid); std::cout << ", data size is " << itemdata.data_size << std::endl; user_code(itemid,itemheader,itemdata); } }; } return 0; }; void user_code(ItemIdData& itemid, ItemHeader& itemheader, ItemData& itemdata) { std::cout << itemdata.hexadecimate_all() << std::endl; return; }; <commit_msg>Fixed bug and handle page parsing correctly<commit_after>#include <fstream> #include <string> #include <cassert> #include <iostream> #include <stdio.h> extern "C" { #include <pg_config.h> #include <postgres.h> #include <storage/bufpage.h> #include <storage/itemid.h> #include <access/htup.h> } #define PAGE_SIZE (8*1024) namespace { char hexadecimate(unsigned value) { switch( value ) { case 0: return '0'; case 1: return '1'; case 2: return '2'; case 3: return '3'; case 4: return '4'; case 5: return '5'; case 6: return '6'; case 7: return '7'; case 8: return '8'; case 9: return '9'; case 10: return 'A'; case 11: return 'B'; case 12: return 'C'; case 13: return 'D'; case 14: return 'E'; case 15: return 'F'; } assert(false); return '?'; } inline unsigned integral_division(unsigned dividend, unsigned divisor) { unsigned result = dividend/divisor; assert( dividend - (divisor*result) == 0 ); return result; } struct Varlena : public varlena { unsigned _size() { return *reinterpret_cast<unsigned*>(vl_len_); } enum LenType { NORMAL,COMPRESSED,TOASTED,ONE_BYTE }; LenType len_type() { if( vl_len_[0] & 0x1 ) { if( vl_len_[0] == 1 ) { return TOASTED; } else { return ONE_BYTE; } } else { if( (vl_len_[0] & 0x2) == 0 ) { return NORMAL; } else { return COMPRESSED; } } }; unsigned size() { switch( len_type() ) { case NORMAL: return _size()>>2; case COMPRESSED: return _size()>>2; case TOASTED: return 18; case ONE_BYTE: return (_size()&0xFF)>>1; } } std::string build_string() { unsigned size_str = size(); char* data = reinterpret_cast<char*>(this); switch( len_type() ) { case COMPRESSED: return "COMPRESSED"; case TOASTED: return "TOASTED"; case NORMAL: data += 4; size_str -= 4; break; case ONE_BYTE: data += 1; size_str -= 1; break; } std::string r; for( unsigned int i=0;i<size_str;++i ) { r += data[i]; } return r; }; }; struct ItemHeader; struct ItemData { ItemHeader* header; char* data; unsigned data_size; std::string hexadecimate_all(unsigned pos=0,unsigned max=-1) { std::string result; unsigned end = data_size; if( end > max ) end = max; for( unsigned int i = pos; i < end; ++i ) { if( data[i] >= '!' && data[i] <= '~') { result += data[i]; } else if( data[i] == '\n' ) { result += "\\n"; } else if( data[i] == ' ') { result += " "; } else { // result += std::to_string( data[i] ); result += hexadecimate( ((unsigned char)(data[i]))>>4 ); result += hexadecimate( data[i]&0xF ); // result += "X"; } result += " "; } return result; } //TODO Assuming numbers are word aligned, check this unsigned word_padding(unsigned pos) { return (4-(pos%4))%4; } unsigned get_unsigned(unsigned pos) { return *reinterpret_cast<unsigned*>( data+pos+word_padding(pos) ); }; unsigned get_unsigned_size(unsigned pos) { return 4+word_padding(pos); } int get_integer(unsigned pos) { return *reinterpret_cast<int*>( data+pos+word_padding(pos) ); }; int get_integer_size(unsigned pos) { return 4+word_padding(pos); } Varlena* get_varlena(unsigned pos) { return reinterpret_cast<Varlena*>( data+pos ); } unsigned get_varlena_size(unsigned pos) { return get_varlena(pos)->size(); } }; struct ItemHeader : public HeapTupleHeaderData { unsigned number_attributes() { return unsigned(t_infomask2 & HEAP_NATTS_MASK); } bool has_bitmap() { return bool(t_infomask & HEAP_HASNULL); } bool has_attribute(unsigned pos) { return !bool(att_isnull(pos,t_bits)); } }; struct PageData : public PageHeaderData { unsigned itemid_count() { return integral_division( pd_lower-sizeof(PageHeaderData)+sizeof(ItemIdData), sizeof(ItemIdData) ); }; ItemHeader* get_item_header(const ItemIdData& itemid) { return reinterpret_cast<ItemHeader*>( reinterpret_cast<char*>(this)+itemid.lp_off ); }; ItemData get_item_data(const ItemIdData& itemid) { ItemHeader* header = get_item_header(itemid); char* data = reinterpret_cast<char*>(header) + header->t_hoff; unsigned data_size = itemid.lp_len - header->t_hoff; ItemData result = {header,data,data_size}; return result; } }; char read_page_buffer[PAGE_SIZE]; PageData* read_page(std::istream& stream, unsigned pos) { stream.seekg(pos*PAGE_SIZE,std::istream::beg); stream.read(read_page_buffer,PAGE_SIZE); return reinterpret_cast<PageData*>(&read_page_buffer); } } void user_code(ItemIdData& itemid, ItemHeader& itemheader, ItemData& itemdata); int main(int argc, char** argv) { assert( sizeof(PageData) == 24+sizeof(ItemIdData) ); assert( sizeof(ItemIdData) == 4 ); if( argc < 2 ) { std::cerr << "Usage " << argv[0] << " input_file" << std::endl; return 1; } std::ifstream input(argv[1]); assert( input.good() ); input.seekg(0, std::ifstream::end); unsigned size = input.tellg(); input.seekg(0, std::ifstream::beg); unsigned pages = size/PAGE_SIZE; if( size - (pages*PAGE_SIZE) != 0 ) { std::cerr << "Given file is not aligned to " << PAGE_SIZE << " bytes" << std::endl; return 1; } if( pages == 0 ) { std::cerr << "Given file has zero pages" << std::endl; return 1; }; for( unsigned int which_page=0;which_page<pages;++which_page) { PageData& page = *read_page(input,which_page); std::cout << "Page " << which_page << "(" << page.itemid_count() << " itens)" << std::endl; for( unsigned int i = 0; i < page.itemid_count(); ++i ) { ItemIdData& itemid = page.pd_linp[i]; if( itemid.lp_flags != LP_NORMAL ) { std::cerr << "\tIgnoring item because it is not marked as LP_NORMAL" << std::endl; } else if( itemid.lp_len == 0 ) { std::cerr << "\tIgnoring item because it has no storage" << std::endl; } else if( itemid.lp_off > PAGE_SIZE ) { std::cerr << "\tIgnoring item because it's offset is outside of page" << std::endl; } else if( itemid.lp_off + itemid.lp_len > PAGE_SIZE ) { std::cerr << "\tIgnoring item because it spans outsize of the page" << std::endl; } else { ItemHeader& itemheader = *page.get_item_header(itemid); std::cout << "\tItem (" << itemid.lp_off << "," << itemid.lp_len << ")~" << itemid.lp_flags; std::cout << ", number of attributes is " << itemheader.number_attributes(); std::cout << " " << (itemheader.has_bitmap() ? "with" : "without") << " bitmap"; if( itemheader.has_bitmap() ) { std::cout << ":\t"; for( unsigned int j=0; j < itemheader.number_attributes(); ++j) { std::cout << " " << itemheader.has_attribute(j); } } ItemData itemdata = page.get_item_data(itemid); std::cout << ", data size is " << itemdata.data_size << std::endl; user_code(itemid,itemheader,itemdata); } }; } return 0; }; void user_code(ItemIdData& itemid, ItemHeader& itemheader, ItemData& itemdata) { std::cout << itemdata.hexadecimate_all() << std::endl; return; }; <|endoftext|>
<commit_before>551513d8-2e3a-11e5-8c17-c03896053bdd<commit_msg>5521c058-2e3a-11e5-8398-c03896053bdd<commit_after>5521c058-2e3a-11e5-8398-c03896053bdd<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ins_paste.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 04:03:39 $ * * 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 * ************************************************************************/ #ifdef SD_DLLIMPLEMENTATION #undef SD_DLLIMPLEMENTATION #endif #include "ins_paste.hrc" #include "ins_paste.hxx" // -------------------- // - SdInsertPasteDlg - // -------------------- SdInsertPasteDlg::SdInsertPasteDlg( Window* pWindow ) : ModalDialog( pWindow, SdResId( DLG_INSERT_PASTE ) ), aFlPosition( this, SdResId( FL_POSITION ) ), aRbBefore( this, SdResId( RB_BEFORE ) ), aRbAfter( this, SdResId( RB_AFTER ) ), aBtnOK( this, SdResId( BTN_OK ) ), aBtnCancel( this, SdResId( BTN_CANCEL ) ), aBtnHelp( this, SdResId( BTN_HELP ) ) { FreeResource(); aRbAfter.Check( TRUE ); } // ----------------------------------------------------------------------------- SdInsertPasteDlg::~SdInsertPasteDlg() { } // ----------------------------------------------------------------------------- BOOL SdInsertPasteDlg::IsInsertBefore() const { return( aRbBefore.IsChecked() ); } <commit_msg>INTEGRATION: CWS pchfix02 (1.3.282); FILE MERGED 2006/09/01 17:36:59 kaib 1.3.282.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ins_paste.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 18:39:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #ifdef SD_DLLIMPLEMENTATION #undef SD_DLLIMPLEMENTATION #endif #include "ins_paste.hrc" #include "ins_paste.hxx" // -------------------- // - SdInsertPasteDlg - // -------------------- SdInsertPasteDlg::SdInsertPasteDlg( Window* pWindow ) : ModalDialog( pWindow, SdResId( DLG_INSERT_PASTE ) ), aFlPosition( this, SdResId( FL_POSITION ) ), aRbBefore( this, SdResId( RB_BEFORE ) ), aRbAfter( this, SdResId( RB_AFTER ) ), aBtnOK( this, SdResId( BTN_OK ) ), aBtnCancel( this, SdResId( BTN_CANCEL ) ), aBtnHelp( this, SdResId( BTN_HELP ) ) { FreeResource(); aRbAfter.Check( TRUE ); } // ----------------------------------------------------------------------------- SdInsertPasteDlg::~SdInsertPasteDlg() { } // ----------------------------------------------------------------------------- BOOL SdInsertPasteDlg::IsInsertBefore() const { return( aRbBefore.IsChecked() ); } <|endoftext|>
<commit_before>6db70b14-2fa5-11e5-8a79-00012e3d3f12<commit_msg>6db8b8c2-2fa5-11e5-8a4b-00012e3d3f12<commit_after>6db8b8c2-2fa5-11e5-8a4b-00012e3d3f12<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ins_paste.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: ka $ $Date: 2002-04-29 10:34:49 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "ins_paste.hrc" #include "ins_paste.hxx" // -------------------- // - SdInsertPasteDlg - // -------------------- SdInsertPasteDlg::SdInsertPasteDlg( Window* pWindow ) : ModalDialog( pWindow, SdResId( DLG_INSERT_PASTE ) ), aFlPosition( this, SdResId( FL_POSITION ) ), aRbBefore( this, SdResId( RB_BEFORE ) ), aRbAfter( this, SdResId( RB_AFTER ) ), aBtnOK( this, SdResId( BTN_OK ) ), aBtnCancel( this, SdResId( BTN_CANCEL ) ), aBtnHelp( this, SdResId( BTN_HELP ) ) { FreeResource(); aRbAfter.Check( TRUE ); } // ----------------------------------------------------------------------------- SdInsertPasteDlg::~SdInsertPasteDlg() { } // ----------------------------------------------------------------------------- BOOL SdInsertPasteDlg::IsInsertBefore() const { return( aRbBefore.IsChecked() ); } <commit_msg>INTEGRATION: CWS tune03 (1.1.508); FILE MERGED 2004/08/08 12:54:06 mhu 1.1.508.1: #i29979# Added SD_DLLPUBLIC/PRIVATE (see sddllapi.h) to exported symbols/classes.<commit_after>/************************************************************************* * * $RCSfile: ins_paste.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-08-23 08:16:21 $ * * 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 SD_DLLIMPLEMENTATION #undef SD_DLLIMPLEMENTATION #endif #include "ins_paste.hrc" #include "ins_paste.hxx" // -------------------- // - SdInsertPasteDlg - // -------------------- SdInsertPasteDlg::SdInsertPasteDlg( Window* pWindow ) : ModalDialog( pWindow, SdResId( DLG_INSERT_PASTE ) ), aFlPosition( this, SdResId( FL_POSITION ) ), aRbBefore( this, SdResId( RB_BEFORE ) ), aRbAfter( this, SdResId( RB_AFTER ) ), aBtnOK( this, SdResId( BTN_OK ) ), aBtnCancel( this, SdResId( BTN_CANCEL ) ), aBtnHelp( this, SdResId( BTN_HELP ) ) { FreeResource(); aRbAfter.Check( TRUE ); } // ----------------------------------------------------------------------------- SdInsertPasteDlg::~SdInsertPasteDlg() { } // ----------------------------------------------------------------------------- BOOL SdInsertPasteDlg::IsInsertBefore() const { return( aRbBefore.IsChecked() ); } <|endoftext|>
<commit_before>78104912-2d53-11e5-baeb-247703a38240<commit_msg>7810ca4a-2d53-11e5-baeb-247703a38240<commit_after>7810ca4a-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>a4557970-2d3f-11e5-8c4a-c82a142b6f9b<commit_msg>a4b0a1ba-2d3f-11e5-a4ff-c82a142b6f9b<commit_after>a4b0a1ba-2d3f-11e5-a4ff-c82a142b6f9b<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuediglu.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:17:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "fuediglu.hxx" #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #include <svx/dialogs.hrc> #ifndef _SVDGLUE_HXX //autogen #include <svx/svdglue.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #include "app.hrc" #include "strings.hrc" #include "res_bmp.hrc" #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #include "drawdoc.hxx" #ifndef SD_FRAMW_VIEW_HXX #include "FrameView.hxx" #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" #endif #ifndef SD_TOOL_BAR_MANAGER_HXX #include "ToolBarManager.hxx" #endif namespace sd { TYPEINIT1( FuEditGluePoints, FuDraw ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuEditGluePoints::FuEditGluePoints ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuDraw(pViewSh, pWin, pView, pDoc, rReq) { } FunctionReference FuEditGluePoints::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent ) { FuEditGluePoints* pFunc; FunctionReference xFunc( pFunc = new FuEditGluePoints( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute(rReq); pFunc->SetPermanent( bPermanent ); return xFunc; } void FuEditGluePoints::DoExecute( SfxRequest& rReq ) { FuDraw::DoExecute( rReq ); mpView->SetInsGluePointMode(FALSE); mpViewShell->GetViewShellBase().GetToolBarManager().AddToolBar( ToolBarManager::TBG_FUNCTION, ToolBarManager::msGluePointsToolBar); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuEditGluePoints::~FuEditGluePoints() { mpView->BrkAction(); mpView->UnmarkAllGluePoints(); mpView->SetInsGluePointMode(FALSE); } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL FuEditGluePoints::MouseButtonDown(const MouseEvent& rMEvt) { mpView->SetActualWin( mpWindow ); BOOL bReturn = FuDraw::MouseButtonDown(rMEvt); if (mpView->IsAction()) { if (rMEvt.IsRight()) mpView->BckAction(); return TRUE; } if (rMEvt.IsLeft()) { bReturn = TRUE; USHORT nHitLog = USHORT ( mpWindow->PixelToLogic(Size(HITPIX,0)).Width() ); USHORT nDrgLog = USHORT ( mpWindow->PixelToLogic(Size(DRGPIX,0)).Width() ); mpWindow->CaptureMouse(); SdrViewEvent aVEvt; SdrHitKind eHit = mpView->PickAnything(rMEvt, SDRMOUSEBUTTONDOWN, aVEvt); if (eHit == SDRHIT_HANDLE) { /****************************************************************** * Handle draggen ******************************************************************/ SdrHdl* pHdl = aVEvt.pHdl; if (mpView->IsGluePointMarked(aVEvt.pObj, aVEvt.nGlueId) && rMEvt.IsShift()) { mpView->UnmarkGluePoint(aVEvt.pObj, aVEvt.nGlueId, aVEvt.pPV); pHdl = NULL; } if (pHdl) { // Handle draggen mpView->BegDragObj(aMDPos, (OutputDevice*) NULL, aVEvt.pHdl, nDrgLog); } } else if (eHit == SDRHIT_MARKEDOBJECT && mpView->IsInsGluePointMode()) { /****************************************************************** * Klebepunkt einfuegen ******************************************************************/ mpView->BegInsGluePoint(aMDPos); } else if (eHit == SDRHIT_MARKEDOBJECT && rMEvt.IsMod1()) { /****************************************************************** * Klebepunkt selektieren ******************************************************************/ if (!rMEvt.IsShift()) mpView->UnmarkAllGluePoints(); mpView->BegMarkGluePoints(aMDPos); } else if (eHit == SDRHIT_MARKEDOBJECT && !rMEvt.IsShift() && !rMEvt.IsMod2()) { /****************************************************************** * Objekt verschieben ******************************************************************/ mpView->BegDragObj(aMDPos, (OutputDevice*) NULL, NULL, nDrgLog); } else if (eHit == SDRHIT_GLUEPOINT) { /****************************************************************** * Klebepunkt selektieren ******************************************************************/ if (!rMEvt.IsShift()) mpView->UnmarkAllGluePoints(); mpView->MarkGluePoint(aVEvt.pObj, aVEvt.nGlueId, aVEvt.pPV); SdrHdl* pHdl = mpView->GetGluePointHdl(aVEvt.pObj, aVEvt.nGlueId); if (pHdl) { mpView->BegDragObj(aMDPos, (OutputDevice*) NULL, pHdl, nDrgLog); } } else { /****************************************************************** * Objekt selektieren oder draggen ******************************************************************/ if (!rMEvt.IsShift() && !rMEvt.IsMod2() && eHit == SDRHIT_UNMARKEDOBJECT) { mpView->UnmarkAllObj(); } BOOL bMarked = FALSE; if (!rMEvt.IsMod1()) { if (rMEvt.IsMod2()) { bMarked = mpView->MarkNextObj(aMDPos, nHitLog, rMEvt.IsShift()); } else { bMarked = mpView->MarkObj(aMDPos, nHitLog, rMEvt.IsShift()); } } if (bMarked && (!rMEvt.IsShift() || eHit == SDRHIT_MARKEDOBJECT)) { // Objekt verschieben mpView->BegDragObj(aMDPos, (OutputDevice*) NULL, aVEvt.pHdl, nDrgLog); } else if (mpView->AreObjectsMarked()) { /************************************************************** * Klebepunkt selektieren **************************************************************/ if (!rMEvt.IsShift()) mpView->UnmarkAllGluePoints(); mpView->BegMarkGluePoints(aMDPos); } else { /************************************************************** * Objekt selektieren **************************************************************/ mpView->BegMarkObj(aMDPos); } } ForcePointer(&rMEvt); } return bReturn; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL FuEditGluePoints::MouseMove(const MouseEvent& rMEvt) { mpView->SetActualWin( mpWindow ); FuDraw::MouseMove(rMEvt); if (mpView->IsAction()) { Point aPix(rMEvt.GetPosPixel()); Point aPnt( mpWindow->PixelToLogic(aPix) ); ForceScroll(aPix); mpView->MovAction(aPnt); } ForcePointer(&rMEvt); return TRUE; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL FuEditGluePoints::MouseButtonUp(const MouseEvent& rMEvt) { mpView->SetActualWin( mpWindow ); BOOL bReturn = FALSE; if (mpView->IsAction()) { bReturn = TRUE; mpView->EndAction(); } FuDraw::MouseButtonUp(rMEvt); USHORT nDrgLog = USHORT ( mpWindow->PixelToLogic(Size(DRGPIX,0)).Width() ); Point aPos = mpWindow->PixelToLogic( rMEvt.GetPosPixel() ); if (Abs(aMDPos.X() - aPos.X()) < nDrgLog && Abs(aMDPos.Y() - aPos.Y()) < nDrgLog && !rMEvt.IsShift() && !rMEvt.IsMod2()) { SdrViewEvent aVEvt; SdrHitKind eHit = mpView->PickAnything(rMEvt, SDRMOUSEBUTTONDOWN, aVEvt); if (eHit == SDRHIT_NONE) { // Klick auf der Stelle: deselektieren mpView->UnmarkAllObj(); } } mpWindow->ReleaseMouse(); return bReturn; } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL FuEditGluePoints::KeyInput(const KeyEvent& rKEvt) { mpView->SetActualWin( mpWindow ); BOOL bReturn = FuDraw::KeyInput(rKEvt); return bReturn; } /************************************************************************* |* |* Command-event |* \************************************************************************/ BOOL FuEditGluePoints::Command(const CommandEvent& rCEvt) { mpView->SetActualWin( mpWindow ); return FuPoor::Command( rCEvt ); } /************************************************************************* |* |* Funktion aktivieren |* \************************************************************************/ void FuEditGluePoints::Activate() { mpView->SetGluePointEditMode(); FuDraw::Activate(); } /************************************************************************* |* |* Funktion deaktivieren |* \************************************************************************/ void FuEditGluePoints::Deactivate() { mpView->SetGluePointEditMode( FALSE ); FuDraw::Deactivate(); } /************************************************************************* |* |* Request verarbeiten |* \************************************************************************/ void FuEditGluePoints::ReceiveRequest(SfxRequest& rReq) { switch (rReq.GetSlot()) { case SID_GLUE_INSERT_POINT: { mpView->SetInsGluePointMode(!mpView->IsInsGluePointMode()); } break; case SID_GLUE_ESCDIR_LEFT: { mpView->SetMarkedGluePointsEscDir( SDRESC_LEFT, !mpView->IsMarkedGluePointsEscDir( SDRESC_LEFT ) ); } break; case SID_GLUE_ESCDIR_RIGHT: { mpView->SetMarkedGluePointsEscDir( SDRESC_RIGHT, !mpView->IsMarkedGluePointsEscDir( SDRESC_RIGHT ) ); } break; case SID_GLUE_ESCDIR_TOP: { mpView->SetMarkedGluePointsEscDir( SDRESC_TOP, !mpView->IsMarkedGluePointsEscDir( SDRESC_TOP ) ); } break; case SID_GLUE_ESCDIR_BOTTOM: { mpView->SetMarkedGluePointsEscDir( SDRESC_BOTTOM, !mpView->IsMarkedGluePointsEscDir( SDRESC_BOTTOM ) ); } break; case SID_GLUE_PERCENT: { const SfxItemSet* pSet = rReq.GetArgs(); const SfxPoolItem& rItem = pSet->Get(SID_GLUE_PERCENT); BOOL bPercent = ((const SfxBoolItem&) rItem).GetValue(); mpView->SetMarkedGluePointsPercent(bPercent); } break; case SID_GLUE_HORZALIGN_CENTER: { mpView->SetMarkedGluePointsAlign(FALSE, SDRHORZALIGN_CENTER); } break; case SID_GLUE_HORZALIGN_LEFT: { mpView->SetMarkedGluePointsAlign(FALSE, SDRHORZALIGN_LEFT); } break; case SID_GLUE_HORZALIGN_RIGHT: { mpView->SetMarkedGluePointsAlign(FALSE, SDRHORZALIGN_RIGHT); } break; case SID_GLUE_VERTALIGN_CENTER: { mpView->SetMarkedGluePointsAlign(TRUE, SDRVERTALIGN_CENTER); } break; case SID_GLUE_VERTALIGN_TOP: { mpView->SetMarkedGluePointsAlign(TRUE, SDRVERTALIGN_TOP); } break; case SID_GLUE_VERTALIGN_BOTTOM: { mpView->SetMarkedGluePointsAlign(TRUE, SDRVERTALIGN_BOTTOM); } break; } // Zum Schluss Basisklasse rufen FuPoor::ReceiveRequest(rReq); } } // end of namespace sd <commit_msg>INTEGRATION: CWS impress122 (1.11.114); FILE MERGED 2007/06/12 15:02:09 af 1.11.114.1: #141146# Made the ToolBarManager a shared_ptr member of ViewShellBase.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuediglu.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:42:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "fuediglu.hxx" #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #include <svx/dialogs.hrc> #ifndef _SVDGLUE_HXX //autogen #include <svx/svdglue.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #include "app.hrc" #include "strings.hrc" #include "res_bmp.hrc" #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #include "drawdoc.hxx" #ifndef SD_FRAMW_VIEW_HXX #include "FrameView.hxx" #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" #endif #ifndef SD_TOOL_BAR_MANAGER_HXX #include "ToolBarManager.hxx" #endif namespace sd { TYPEINIT1( FuEditGluePoints, FuDraw ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuEditGluePoints::FuEditGluePoints ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuDraw(pViewSh, pWin, pView, pDoc, rReq) { } FunctionReference FuEditGluePoints::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent ) { FuEditGluePoints* pFunc; FunctionReference xFunc( pFunc = new FuEditGluePoints( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute(rReq); pFunc->SetPermanent( bPermanent ); return xFunc; } void FuEditGluePoints::DoExecute( SfxRequest& rReq ) { FuDraw::DoExecute( rReq ); mpView->SetInsGluePointMode(FALSE); mpViewShell->GetViewShellBase().GetToolBarManager()->AddToolBar( ToolBarManager::TBG_FUNCTION, ToolBarManager::msGluePointsToolBar); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuEditGluePoints::~FuEditGluePoints() { mpView->BrkAction(); mpView->UnmarkAllGluePoints(); mpView->SetInsGluePointMode(FALSE); } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL FuEditGluePoints::MouseButtonDown(const MouseEvent& rMEvt) { mpView->SetActualWin( mpWindow ); BOOL bReturn = FuDraw::MouseButtonDown(rMEvt); if (mpView->IsAction()) { if (rMEvt.IsRight()) mpView->BckAction(); return TRUE; } if (rMEvt.IsLeft()) { bReturn = TRUE; USHORT nHitLog = USHORT ( mpWindow->PixelToLogic(Size(HITPIX,0)).Width() ); USHORT nDrgLog = USHORT ( mpWindow->PixelToLogic(Size(DRGPIX,0)).Width() ); mpWindow->CaptureMouse(); SdrViewEvent aVEvt; SdrHitKind eHit = mpView->PickAnything(rMEvt, SDRMOUSEBUTTONDOWN, aVEvt); if (eHit == SDRHIT_HANDLE) { /****************************************************************** * Handle draggen ******************************************************************/ SdrHdl* pHdl = aVEvt.pHdl; if (mpView->IsGluePointMarked(aVEvt.pObj, aVEvt.nGlueId) && rMEvt.IsShift()) { mpView->UnmarkGluePoint(aVEvt.pObj, aVEvt.nGlueId, aVEvt.pPV); pHdl = NULL; } if (pHdl) { // Handle draggen mpView->BegDragObj(aMDPos, (OutputDevice*) NULL, aVEvt.pHdl, nDrgLog); } } else if (eHit == SDRHIT_MARKEDOBJECT && mpView->IsInsGluePointMode()) { /****************************************************************** * Klebepunkt einfuegen ******************************************************************/ mpView->BegInsGluePoint(aMDPos); } else if (eHit == SDRHIT_MARKEDOBJECT && rMEvt.IsMod1()) { /****************************************************************** * Klebepunkt selektieren ******************************************************************/ if (!rMEvt.IsShift()) mpView->UnmarkAllGluePoints(); mpView->BegMarkGluePoints(aMDPos); } else if (eHit == SDRHIT_MARKEDOBJECT && !rMEvt.IsShift() && !rMEvt.IsMod2()) { /****************************************************************** * Objekt verschieben ******************************************************************/ mpView->BegDragObj(aMDPos, (OutputDevice*) NULL, NULL, nDrgLog); } else if (eHit == SDRHIT_GLUEPOINT) { /****************************************************************** * Klebepunkt selektieren ******************************************************************/ if (!rMEvt.IsShift()) mpView->UnmarkAllGluePoints(); mpView->MarkGluePoint(aVEvt.pObj, aVEvt.nGlueId, aVEvt.pPV); SdrHdl* pHdl = mpView->GetGluePointHdl(aVEvt.pObj, aVEvt.nGlueId); if (pHdl) { mpView->BegDragObj(aMDPos, (OutputDevice*) NULL, pHdl, nDrgLog); } } else { /****************************************************************** * Objekt selektieren oder draggen ******************************************************************/ if (!rMEvt.IsShift() && !rMEvt.IsMod2() && eHit == SDRHIT_UNMARKEDOBJECT) { mpView->UnmarkAllObj(); } BOOL bMarked = FALSE; if (!rMEvt.IsMod1()) { if (rMEvt.IsMod2()) { bMarked = mpView->MarkNextObj(aMDPos, nHitLog, rMEvt.IsShift()); } else { bMarked = mpView->MarkObj(aMDPos, nHitLog, rMEvt.IsShift()); } } if (bMarked && (!rMEvt.IsShift() || eHit == SDRHIT_MARKEDOBJECT)) { // Objekt verschieben mpView->BegDragObj(aMDPos, (OutputDevice*) NULL, aVEvt.pHdl, nDrgLog); } else if (mpView->AreObjectsMarked()) { /************************************************************** * Klebepunkt selektieren **************************************************************/ if (!rMEvt.IsShift()) mpView->UnmarkAllGluePoints(); mpView->BegMarkGluePoints(aMDPos); } else { /************************************************************** * Objekt selektieren **************************************************************/ mpView->BegMarkObj(aMDPos); } } ForcePointer(&rMEvt); } return bReturn; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL FuEditGluePoints::MouseMove(const MouseEvent& rMEvt) { mpView->SetActualWin( mpWindow ); FuDraw::MouseMove(rMEvt); if (mpView->IsAction()) { Point aPix(rMEvt.GetPosPixel()); Point aPnt( mpWindow->PixelToLogic(aPix) ); ForceScroll(aPix); mpView->MovAction(aPnt); } ForcePointer(&rMEvt); return TRUE; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL FuEditGluePoints::MouseButtonUp(const MouseEvent& rMEvt) { mpView->SetActualWin( mpWindow ); BOOL bReturn = FALSE; if (mpView->IsAction()) { bReturn = TRUE; mpView->EndAction(); } FuDraw::MouseButtonUp(rMEvt); USHORT nDrgLog = USHORT ( mpWindow->PixelToLogic(Size(DRGPIX,0)).Width() ); Point aPos = mpWindow->PixelToLogic( rMEvt.GetPosPixel() ); if (Abs(aMDPos.X() - aPos.X()) < nDrgLog && Abs(aMDPos.Y() - aPos.Y()) < nDrgLog && !rMEvt.IsShift() && !rMEvt.IsMod2()) { SdrViewEvent aVEvt; SdrHitKind eHit = mpView->PickAnything(rMEvt, SDRMOUSEBUTTONDOWN, aVEvt); if (eHit == SDRHIT_NONE) { // Klick auf der Stelle: deselektieren mpView->UnmarkAllObj(); } } mpWindow->ReleaseMouse(); return bReturn; } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL FuEditGluePoints::KeyInput(const KeyEvent& rKEvt) { mpView->SetActualWin( mpWindow ); BOOL bReturn = FuDraw::KeyInput(rKEvt); return bReturn; } /************************************************************************* |* |* Command-event |* \************************************************************************/ BOOL FuEditGluePoints::Command(const CommandEvent& rCEvt) { mpView->SetActualWin( mpWindow ); return FuPoor::Command( rCEvt ); } /************************************************************************* |* |* Funktion aktivieren |* \************************************************************************/ void FuEditGluePoints::Activate() { mpView->SetGluePointEditMode(); FuDraw::Activate(); } /************************************************************************* |* |* Funktion deaktivieren |* \************************************************************************/ void FuEditGluePoints::Deactivate() { mpView->SetGluePointEditMode( FALSE ); FuDraw::Deactivate(); } /************************************************************************* |* |* Request verarbeiten |* \************************************************************************/ void FuEditGluePoints::ReceiveRequest(SfxRequest& rReq) { switch (rReq.GetSlot()) { case SID_GLUE_INSERT_POINT: { mpView->SetInsGluePointMode(!mpView->IsInsGluePointMode()); } break; case SID_GLUE_ESCDIR_LEFT: { mpView->SetMarkedGluePointsEscDir( SDRESC_LEFT, !mpView->IsMarkedGluePointsEscDir( SDRESC_LEFT ) ); } break; case SID_GLUE_ESCDIR_RIGHT: { mpView->SetMarkedGluePointsEscDir( SDRESC_RIGHT, !mpView->IsMarkedGluePointsEscDir( SDRESC_RIGHT ) ); } break; case SID_GLUE_ESCDIR_TOP: { mpView->SetMarkedGluePointsEscDir( SDRESC_TOP, !mpView->IsMarkedGluePointsEscDir( SDRESC_TOP ) ); } break; case SID_GLUE_ESCDIR_BOTTOM: { mpView->SetMarkedGluePointsEscDir( SDRESC_BOTTOM, !mpView->IsMarkedGluePointsEscDir( SDRESC_BOTTOM ) ); } break; case SID_GLUE_PERCENT: { const SfxItemSet* pSet = rReq.GetArgs(); const SfxPoolItem& rItem = pSet->Get(SID_GLUE_PERCENT); BOOL bPercent = ((const SfxBoolItem&) rItem).GetValue(); mpView->SetMarkedGluePointsPercent(bPercent); } break; case SID_GLUE_HORZALIGN_CENTER: { mpView->SetMarkedGluePointsAlign(FALSE, SDRHORZALIGN_CENTER); } break; case SID_GLUE_HORZALIGN_LEFT: { mpView->SetMarkedGluePointsAlign(FALSE, SDRHORZALIGN_LEFT); } break; case SID_GLUE_HORZALIGN_RIGHT: { mpView->SetMarkedGluePointsAlign(FALSE, SDRHORZALIGN_RIGHT); } break; case SID_GLUE_VERTALIGN_CENTER: { mpView->SetMarkedGluePointsAlign(TRUE, SDRVERTALIGN_CENTER); } break; case SID_GLUE_VERTALIGN_TOP: { mpView->SetMarkedGluePointsAlign(TRUE, SDRVERTALIGN_TOP); } break; case SID_GLUE_VERTALIGN_BOTTOM: { mpView->SetMarkedGluePointsAlign(TRUE, SDRVERTALIGN_BOTTOM); } break; } // Zum Schluss Basisklasse rufen FuPoor::ReceiveRequest(rReq); } } // end of namespace sd <|endoftext|>
<commit_before>3d62899e-5216-11e5-a394-6c40088e03e4<commit_msg>3d694c90-5216-11e5-9c8b-6c40088e03e4<commit_after>3d694c90-5216-11e5-9c8b-6c40088e03e4<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fumeasur.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-12-14 17:00:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #include "fumeasur.hxx" //CHINA001 #include <svx/measure.hxx> #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #include "drawdoc.hxx" #include <svx/svxdlg.hxx> //CHINA001 #include <svx/dialogs.hrc> //CHINA001 namespace sd { TYPEINIT1( FuMeasureDlg, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuMeasureDlg::FuMeasureDlg ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq) { } FunctionReference FuMeasureDlg::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuMeasureDlg( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute(rReq); return xFunc; } void FuMeasureDlg::DoExecute( SfxRequest& rReq ) { SfxItemSet aNewAttr( pDoc->GetPool() ); pView->GetAttributes( aNewAttr ); const SfxItemSet* pArgs = rReq.GetArgs(); ::std::auto_ptr<AbstractSfxSingleTabDialog> pDlg (NULL); if( !pArgs ) { //CHINA001 SvxMeasureDialog* pDlg = new SvxMeasureDialog( NULL, aNewAttr, pView ); SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create(); DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001 pDlg.reset (pFact->CreateSfxSingleTabDialog( NULL, aNewAttr, pView, ResId(RID_SVXPAGE_MEASURE))); DBG_ASSERT(pDlg.get()!=NULL, "Dialogdiet fail!");//CHINA001 USHORT nResult = pDlg->Execute(); switch( nResult ) { case RET_OK: { pArgs = pDlg->GetOutputItemSet(); rReq.Done( *pArgs ); } break; default: return; // Abbruch } } pView->SetAttributes( *pArgs ); } } // end of namespace sd <commit_msg>INTEGRATION: CWS pchfix02 (1.6.214); FILE MERGED 2006/09/01 17:37:07 kaib 1.6.214.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fumeasur.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-16 18:51:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "fumeasur.hxx" //CHINA001 #include <svx/measure.hxx> #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #include "drawdoc.hxx" #include <svx/svxdlg.hxx> //CHINA001 #include <svx/dialogs.hrc> //CHINA001 namespace sd { TYPEINIT1( FuMeasureDlg, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuMeasureDlg::FuMeasureDlg ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq) { } FunctionReference FuMeasureDlg::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuMeasureDlg( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute(rReq); return xFunc; } void FuMeasureDlg::DoExecute( SfxRequest& rReq ) { SfxItemSet aNewAttr( pDoc->GetPool() ); pView->GetAttributes( aNewAttr ); const SfxItemSet* pArgs = rReq.GetArgs(); ::std::auto_ptr<AbstractSfxSingleTabDialog> pDlg (NULL); if( !pArgs ) { //CHINA001 SvxMeasureDialog* pDlg = new SvxMeasureDialog( NULL, aNewAttr, pView ); SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create(); DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001 pDlg.reset (pFact->CreateSfxSingleTabDialog( NULL, aNewAttr, pView, ResId(RID_SVXPAGE_MEASURE))); DBG_ASSERT(pDlg.get()!=NULL, "Dialogdiet fail!");//CHINA001 USHORT nResult = pDlg->Execute(); switch( nResult ) { case RET_OK: { pArgs = pDlg->GetOutputItemSet(); rReq.Done( *pArgs ); } break; default: return; // Abbruch } } pView->SetAttributes( *pArgs ); } } // end of namespace sd <|endoftext|>
<commit_before>92323b0d-2d14-11e5-af21-0401358ea401<commit_msg>92323b0e-2d14-11e5-af21-0401358ea401<commit_after>92323b0e-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>78d38774-2d53-11e5-baeb-247703a38240<commit_msg>78d408a2-2d53-11e5-baeb-247703a38240<commit_after>78d408a2-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unoobj.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: cl $ $Date: 2001-12-04 16:10:38 $ * * 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 _UNOOBJ_HXX #define _UNOOBJ_HXX #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_ #include <com/sun/star/beans/XPropertyState.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_ #include <com/sun/star/document/XEventsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_ #include <com/sun/star/document/XEventsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _SVDPOOL_HXX //autogen #include <svx/svdpool.hxx> #endif #ifndef _SVX_UNOMASTER_HXX #include <svx/unomaster.hxx> #endif #include <svx/unoipset.hxx> #include <cppuhelper/implbase2.hxx> class SdrObject; class SdXImpressDocument; class SdAnimationInfo; class SdXShape : public SvxShapeMaster, public ::com::sun::star::document::XEventsSupplier { friend class SdUnoEventsAccess; private: SvxShape* mpShape; SvxItemPropertySet maPropSet; const SfxItemPropertyMap* mpMap; SdXImpressDocument* mpModel; void SetStyleSheet( const ::com::sun::star::uno::Any& rAny ) throw( ::com::sun::star::lang::IllegalArgumentException ); ::com::sun::star::uno::Any GetStyleSheet() const throw( ::com::sun::star::beans::UnknownPropertyException ); // Intern SdAnimationInfo* GetAnimationInfo( sal_Bool bCreate = sal_False ) const throw(); sal_Bool IsPresObj() const throw(); void SetPresObj( sal_Bool bPresObj ) throw(); sal_Bool IsEmptyPresObj() const throw(); void SetEmptyPresObj( sal_Bool bEmpty ) throw(); sal_Bool IsMasterDepend() const throw(); void SetMasterDepend( sal_Bool bDepend ) throw(); SdrObject* GetSdrObject() const throw(); sal_Int32 GetPresentationOrderPos() const throw(); void SetPresentationOrderPos( sal_Int32 nPos ) throw(); com::sun::star::uno::Sequence< sal_Int8 >* mpImplementationId; public: SdXShape() throw(); SdXShape(SvxShape* pShape, SdXImpressDocument* pModel) throw(); virtual ~SdXShape() throw(); virtual sal_Bool queryAggregation( const com::sun::star::uno::Type & rType, com::sun::star::uno::Any& aAny ); virtual void dispose(); // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // XServiceInfo virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); //XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); //XPropertyState virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // XEventsSupplier virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > SAL_CALL getEvents( ) throw(::com::sun::star::uno::RuntimeException); }; struct SvEventDescription; const SvEventDescription* ImplGetSupportedMacroItems(); #endif <commit_msg>INTEGRATION: CWS presentationengine01 (1.7.344); FILE MERGED 2004/08/22 22:25:10 cl 1.7.344.1: first wrapper for old animation api<commit_after>/************************************************************************* * * $RCSfile: unoobj.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2004-11-26 20:28:52 $ * * 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 _UNOOBJ_HXX #define _UNOOBJ_HXX #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_ #include <com/sun/star/beans/XPropertyState.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_ #include <com/sun/star/document/XEventsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_ #include <com/sun/star/document/XEventsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _SVDPOOL_HXX //autogen #include <svx/svdpool.hxx> #endif #ifndef _SVX_UNOMASTER_HXX #include <svx/unomaster.hxx> #endif #include <svx/unoipset.hxx> #include <cppuhelper/implbase2.hxx> class SdrObject; class SdXImpressDocument; class SdAnimationInfo; class SdXShape : public SvxShapeMaster, public ::com::sun::star::document::XEventsSupplier { friend class SdUnoEventsAccess; private: SvxShape* mpShape; SvxItemPropertySet maPropSet; const SfxItemPropertyMap* mpMap; SdXImpressDocument* mpModel; void SetStyleSheet( const ::com::sun::star::uno::Any& rAny ) throw( ::com::sun::star::lang::IllegalArgumentException ); ::com::sun::star::uno::Any GetStyleSheet() const throw( ::com::sun::star::beans::UnknownPropertyException ); // Intern SdAnimationInfo* GetAnimationInfo( sal_Bool bCreate = sal_False ) const throw(); sal_Bool IsPresObj() const throw(); void SetPresObj( sal_Bool bPresObj ) throw(); sal_Bool IsEmptyPresObj() const throw(); void SetEmptyPresObj( sal_Bool bEmpty ) throw(); sal_Bool IsMasterDepend() const throw(); void SetMasterDepend( sal_Bool bDepend ) throw(); SdrObject* GetSdrObject() const throw(); sal_Int32 GetPresentationOrderPos() const throw(); void SetPresentationOrderPos( sal_Int32 nPos ) throw(); com::sun::star::uno::Sequence< sal_Int8 >* mpImplementationId; public: SdXShape() throw(); SdXShape(SvxShape* pShape, SdXImpressDocument* pModel) throw(); virtual ~SdXShape() throw(); virtual sal_Bool queryAggregation( const com::sun::star::uno::Type & rType, com::sun::star::uno::Any& aAny ); virtual void dispose(); // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // XServiceInfo virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); //XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); //XPropertyState virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // XEventsSupplier virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > SAL_CALL getEvents( ) throw(::com::sun::star::uno::RuntimeException); private: void setOldEffect( const com::sun::star::uno::Any& aValue ); void setOldTextEffect( const com::sun::star::uno::Any& aValue ); void setOldSpeed( const com::sun::star::uno::Any& aValue ); void setOldDimColor( const com::sun::star::uno::Any& aValue ); void setOldDimHide( const com::sun::star::uno::Any& aValue ); void setOldDimPrevious( const com::sun::star::uno::Any& aValue ); void setOldPresOrder( const com::sun::star::uno::Any& aValue ); }; struct SvEventDescription; const SvEventDescription* ImplGetSupportedMacroItems(); #endif <|endoftext|>
<commit_before>fed3a607-ad5b-11e7-a3b6-ac87a332f658<commit_msg>Boyaaah!<commit_after>ff3e6da6-ad5b-11e7-90f1-ac87a332f658<|endoftext|>
<commit_before>3c2e2186-5216-11e5-a7db-6c40088e03e4<commit_msg>3c37475c-5216-11e5-b5d6-6c40088e03e4<commit_after>3c37475c-5216-11e5-b5d6-6c40088e03e4<|endoftext|>
<commit_before>e425407a-2e4e-11e5-9dcf-28cfe91dbc4b<commit_msg>e42cf8cc-2e4e-11e5-99cc-28cfe91dbc4b<commit_after>e42cf8cc-2e4e-11e5-99cc-28cfe91dbc4b<|endoftext|>
<commit_before>26de8b64-2e3a-11e5-8c3d-c03896053bdd<commit_msg>26ed3410-2e3a-11e5-8c7c-c03896053bdd<commit_after>26ed3410-2e3a-11e5-8c7c-c03896053bdd<|endoftext|>
<commit_before>0fbee18c-2f67-11e5-8cbe-6c40088e03e4<commit_msg>0fc8e24a-2f67-11e5-a169-6c40088e03e4<commit_after>0fc8e24a-2f67-11e5-a169-6c40088e03e4<|endoftext|>
<commit_before>//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These tablegen backends emit Clang diagnostics tables. // //===----------------------------------------------------------------------===// #include "ClangDiagnosticsEmitter.h" #include "Record.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Streams.h" #include "llvm/ADT/VectorExtras.h" #include "llvm/ADT/DenseSet.h" #include <set> #include <map> using namespace llvm; //===----------------------------------------------------------------------===// // Generic routines for all Clang TableGen backens. //===----------------------------------------------------------------------===// typedef std::vector<Record*> RecordVector; typedef std::vector<Record*> SuperClassVector; typedef std::vector<RecordVal> RecordValVector; static const RecordVal* findRecordVal(const Record& R, const std::string &key) { const RecordValVector &Vals = R.getValues(); for (RecordValVector::const_iterator I=Vals.begin(), E=Vals.end(); I!=E; ++I) if ((*I).getName() == key) return &*I; return 0; } static const Record* getDiagKind(const Record* DiagClass, const Record &R) { const SuperClassVector &SC = R.getSuperClasses(); for (SuperClassVector::const_iterator I=SC.begin(), E=SC.end(); I!=E; ++I) if ((*I)->isSubClassOf(DiagClass)) return *I; return 0; } static void EmitEscaped(std::ostream& OS, const std::string &s) { for (std::string::const_iterator I=s.begin(), E=s.end(); I!=E; ++I) switch (*I) { default: OS << *I; break; case '\"': OS << "\\" << *I; break; case '\\': OS << "\\\\"; break; } } static void EmitAllCaps(std::ostream& OS, const std::string &s) { for (std::string::const_iterator I=s.begin(), E=s.end(); I!=E; ++I) OS << char(toupper(*I)); } //===----------------------------------------------------------------------===// // Warning Tables (.inc file) generation. //===----------------------------------------------------------------------===// static void ProcessDiag(std::ostream& OS, const Record* DiagClass, const Record& R) { const Record* DiagKind = getDiagKind(DiagClass, R); if (!DiagKind) return; OS << "DIAG(" << R.getName() << ", "; EmitAllCaps(OS, DiagKind->getName()); const RecordVal* Text = findRecordVal(R, "Text"); assert(Text && "No 'Text' entry in Diagnostic."); const StringInit* TextVal = dynamic_cast<const StringInit*>(Text->getValue()); assert(TextVal && "Value 'Text' must be a string."); OS << ", \""; EmitEscaped(OS, TextVal->getValue()); OS << "\")\n"; } void ClangDiagsDefsEmitter::run(std::ostream &OS) { const RecordVector &Diags = Records.getAllDerivedDefinitions("Diagnostic"); const Record* DiagClass = Records.getClass("Diagnostic"); assert(DiagClass && "No Diagnostic class defined."); // Write the #if guard if (!Component.empty()) { OS << "#ifdef "; EmitAllCaps(OS, Component); OS << "START\n__"; EmitAllCaps(OS, Component); OS << "START = DIAG_START_"; EmitAllCaps(OS, Component); OS << ",\n#undef "; EmitAllCaps(OS, Component); OS << "START\n#endif\n"; } for (RecordVector::const_iterator I=Diags.begin(), E=Diags.end(); I!=E; ++I) { if (!Component.empty()) { const RecordVal* V = findRecordVal(**I, "Component"); if (!V) continue; const StringInit* SV = dynamic_cast<const StringInit*>(V->getValue()); if (SV->getValue() != Component) continue; } ProcessDiag(OS, DiagClass, **I); } } //===----------------------------------------------------------------------===// // Warning Group Tables generation. //===----------------------------------------------------------------------===// typedef std::set<const Record*> DiagnosticSet; typedef std::map<const Record*, DiagnosticSet> OptionMap; typedef llvm::DenseSet<const ListInit*> VisitedLists; static void BuildGroup(DiagnosticSet& DS, VisitedLists &Visited, const Init* X); static void BuildGroup(DiagnosticSet &DS, VisitedLists &Visited, const ListInit* LV) { // Simple hack to prevent including a list multiple times. This may be useful // if one declares an Option by including a bunch of other Options that // include other Options, etc. if (Visited.count(LV)) return; Visited.insert(LV); // Iterate through the list and grab all DiagnosticControlled. for (ListInit::const_iterator I = LV->begin(), E = LV->end(); I!=E; ++I) BuildGroup(DS, Visited, *I); } static void BuildGroup(DiagnosticSet& DS, VisitedLists &Visited, const Record *Def) { // If an Option includes another Option, inline the Diagnostics of the // included Option. if (Def->isSubClassOf("Option")) { if (const RecordVal* V = findRecordVal(*Def, "Members")) if (const ListInit* LV = dynamic_cast<const ListInit*>(V->getValue())) BuildGroup(DS, Visited, LV); return; } if (Def->isSubClassOf("DiagnosticControlled")) DS.insert(Def); } static void BuildGroup(DiagnosticSet& DS, VisitedLists &Visited, const Init* X) { if (const DefInit *D = dynamic_cast<const DefInit*>(X)) BuildGroup(DS, Visited, D->getDef()); // We may have some other cases here in the future. } void ClangOptionsEmitter::run(std::ostream &OS) { // Build up a map from options to controlled diagnostics. OptionMap OM; const RecordVector &Opts = Records.getAllDerivedDefinitions("Option"); for (RecordVector::const_iterator I=Opts.begin(), E=Opts.end(); I!=E; ++I) if (const RecordVal* V = findRecordVal(**I, "Members")) if (const ListInit* LV = dynamic_cast<const ListInit*>(V->getValue())) { VisitedLists Visited; BuildGroup(OM[*I], Visited, LV); } // Iterate through the OptionMap and emit the declarations. for (OptionMap::iterator I = OM.begin(), E = OM.end(); I!=E; ++I) { // Output the option. OS << "static const diag::kind " << I->first->getName() << "[] = { "; DiagnosticSet &DS = I->second; bool first = true; for (DiagnosticSet::iterator I2 = DS.begin(), E2 = DS.end(); I2!=E2; ++I2) { if (first) first = false; else OS << ", "; OS << "diag::" << (*I2)->getName(); } OS << " };\n"; } // Now emit the OptionTable table. OS << "\nstatic const WarningOption OptionTable[] = {"; bool first = true; for (OptionMap::iterator I = OM.begin(), E = OM.end(); I!=E; ++I) { const RecordVal *V = findRecordVal(*I->first, "Name"); assert(V && "Options must have a 'Name' value."); const StringInit* SV = dynamic_cast<const StringInit*>(V->getValue()); assert(SV && "'Name' entry must be a string."); if (first) first = false; else OS << ','; OS << "\n {\"" << SV->getValue() << "\", DIAGS(" << I->first->getName() << ")}"; } OS << "\n};\n"; } <commit_msg>tblgen -gen-clang-diags-options: Output OptionTable entries in lexicographic order.<commit_after>//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These tablegen backends emit Clang diagnostics tables. // //===----------------------------------------------------------------------===// #include "ClangDiagnosticsEmitter.h" #include "Record.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Streams.h" #include "llvm/ADT/VectorExtras.h" #include "llvm/ADT/DenseSet.h" #include <set> #include <map> using namespace llvm; //===----------------------------------------------------------------------===// // Generic routines for all Clang TableGen backens. //===----------------------------------------------------------------------===// typedef std::vector<Record*> RecordVector; typedef std::vector<Record*> SuperClassVector; typedef std::vector<RecordVal> RecordValVector; static const RecordVal* findRecordVal(const Record& R, const std::string &key) { const RecordValVector &Vals = R.getValues(); for (RecordValVector::const_iterator I=Vals.begin(), E=Vals.end(); I!=E; ++I) if ((*I).getName() == key) return &*I; return 0; } static const Record* getDiagKind(const Record* DiagClass, const Record &R) { const SuperClassVector &SC = R.getSuperClasses(); for (SuperClassVector::const_iterator I=SC.begin(), E=SC.end(); I!=E; ++I) if ((*I)->isSubClassOf(DiagClass)) return *I; return 0; } static void EmitEscaped(std::ostream& OS, const std::string &s) { for (std::string::const_iterator I=s.begin(), E=s.end(); I!=E; ++I) switch (*I) { default: OS << *I; break; case '\"': OS << "\\" << *I; break; case '\\': OS << "\\\\"; break; } } static void EmitAllCaps(std::ostream& OS, const std::string &s) { for (std::string::const_iterator I=s.begin(), E=s.end(); I!=E; ++I) OS << char(toupper(*I)); } //===----------------------------------------------------------------------===// // Warning Tables (.inc file) generation. //===----------------------------------------------------------------------===// static void ProcessDiag(std::ostream& OS, const Record* DiagClass, const Record& R) { const Record* DiagKind = getDiagKind(DiagClass, R); if (!DiagKind) return; OS << "DIAG(" << R.getName() << ", "; EmitAllCaps(OS, DiagKind->getName()); const RecordVal* Text = findRecordVal(R, "Text"); assert(Text && "No 'Text' entry in Diagnostic."); const StringInit* TextVal = dynamic_cast<const StringInit*>(Text->getValue()); assert(TextVal && "Value 'Text' must be a string."); OS << ", \""; EmitEscaped(OS, TextVal->getValue()); OS << "\")\n"; } void ClangDiagsDefsEmitter::run(std::ostream &OS) { const RecordVector &Diags = Records.getAllDerivedDefinitions("Diagnostic"); const Record* DiagClass = Records.getClass("Diagnostic"); assert(DiagClass && "No Diagnostic class defined."); // Write the #if guard if (!Component.empty()) { OS << "#ifdef "; EmitAllCaps(OS, Component); OS << "START\n__"; EmitAllCaps(OS, Component); OS << "START = DIAG_START_"; EmitAllCaps(OS, Component); OS << ",\n#undef "; EmitAllCaps(OS, Component); OS << "START\n#endif\n"; } for (RecordVector::const_iterator I=Diags.begin(), E=Diags.end(); I!=E; ++I) { if (!Component.empty()) { const RecordVal* V = findRecordVal(**I, "Component"); if (!V) continue; const StringInit* SV = dynamic_cast<const StringInit*>(V->getValue()); if (SV->getValue() != Component) continue; } ProcessDiag(OS, DiagClass, **I); } } //===----------------------------------------------------------------------===// // Warning Group Tables generation. //===----------------------------------------------------------------------===// static const std::string &getOptName(const Record *R) { const RecordVal *V = findRecordVal(*R, "Name"); assert(V && "Options must have a 'Name' value."); const StringInit* SV = dynamic_cast<const StringInit*>(V->getValue()); assert(SV && "'Name' entry must be a string."); return SV->getValue(); } namespace { struct VISIBILITY_HIDDEN CompareOptName { bool operator()(const Record* A, const Record* B) { return getOptName(A) < getOptName(B); } }; } typedef std::set<const Record*> DiagnosticSet; typedef std::map<const Record*, DiagnosticSet, CompareOptName> OptionMap; typedef llvm::DenseSet<const ListInit*> VisitedLists; static void BuildGroup(DiagnosticSet& DS, VisitedLists &Visited, const Init* X); static void BuildGroup(DiagnosticSet &DS, VisitedLists &Visited, const ListInit* LV) { // Simple hack to prevent including a list multiple times. This may be useful // if one declares an Option by including a bunch of other Options that // include other Options, etc. if (Visited.count(LV)) return; Visited.insert(LV); // Iterate through the list and grab all DiagnosticControlled. for (ListInit::const_iterator I = LV->begin(), E = LV->end(); I!=E; ++I) BuildGroup(DS, Visited, *I); } static void BuildGroup(DiagnosticSet& DS, VisitedLists &Visited, const Record *Def) { // If an Option includes another Option, inline the Diagnostics of the // included Option. if (Def->isSubClassOf("Option")) { if (const RecordVal* V = findRecordVal(*Def, "Members")) if (const ListInit* LV = dynamic_cast<const ListInit*>(V->getValue())) BuildGroup(DS, Visited, LV); return; } if (Def->isSubClassOf("DiagnosticControlled")) DS.insert(Def); } static void BuildGroup(DiagnosticSet& DS, VisitedLists &Visited, const Init* X) { if (const DefInit *D = dynamic_cast<const DefInit*>(X)) BuildGroup(DS, Visited, D->getDef()); // We may have some other cases here in the future. } void ClangOptionsEmitter::run(std::ostream &OS) { // Build up a map from options to controlled diagnostics. OptionMap OM; const RecordVector &Opts = Records.getAllDerivedDefinitions("Option"); for (RecordVector::const_iterator I=Opts.begin(), E=Opts.end(); I!=E; ++I) if (const RecordVal* V = findRecordVal(**I, "Members")) if (const ListInit* LV = dynamic_cast<const ListInit*>(V->getValue())) { VisitedLists Visited; BuildGroup(OM[*I], Visited, LV); } // Iterate through the OptionMap and emit the declarations. for (OptionMap::iterator I = OM.begin(), E = OM.end(); I!=E; ++I) { // Output the option. OS << "static const diag::kind " << I->first->getName() << "[] = { "; DiagnosticSet &DS = I->second; bool first = true; for (DiagnosticSet::iterator I2 = DS.begin(), E2 = DS.end(); I2!=E2; ++I2) { if (first) first = false; else OS << ", "; OS << "diag::" << (*I2)->getName(); } OS << " };\n"; } // Now emit the OptionTable table. OS << "\nstatic const WarningOption OptionTable[] = {"; bool first = true; for (OptionMap::iterator I = OM.begin(), E = OM.end(); I!=E; ++I) { if (first) first = false; else OS << ','; OS << "\n {\"" << getOptName(I->first) << "\", DIAGS(" << I->first->getName() << ")}"; } OS << "\n};\n"; } <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> using namespace std; class basic { double** p; int x; int y; public: basic(int x1 = 0, int y1 = 0) { cout << "Creating basic" << endl; x = x1; y = y1; alloc(x, y); } ~basic() { cout << "Deleting basic" << endl; free_mem(x, y); } void alloc(int x, int y) { p = new double* [x]; for(int i = 0; i < x; i++) *(p + i) = new double[y]; } void free_mem(int x, int y) { for(int i = 0; i < x; i++) delete[] * (p + i); delete[] p; } void show_all() { cout << "Showing object" << endl; for(int i = 0; i < x; i++) for(int j = 0; j < y; j++) cout << "a[" << i << "][" << j << "]" << " = " << p[i][j] << endl; cout << endl; } void set_object() { double value; cout << "Setting object" << endl; for(int i = 0; i < x; i++) for(int j = 0; j < y; j++) { cout << "a[" << i << "][" << j << "]" << " = "; cin >> value; p[i][j] = value; } cout << endl; } const basic& operator=(const basic& obj2) { cout << "Operator =" << endl; free_mem(x, y); x = obj2.x; y = obj2.y; alloc(x, y); for(int i = 0; i < x; i++) for(int j = 0; j < y; j++) (*this).p[i][j] = obj2.p[i][j]; return *this; } void* operator new(size_t size) { cout << "Using overloaded new:" << size << endl; return malloc(size); } void* operator new [](size_t size) { cout << "Using overloaded new[]:" << size << endl; return malloc(size); } void operator delete(void* p) { cout << "Using overloaded delete:" << endl; free(p); } void operator delete [](void* p) { cout << "Using overloaded delete[]:" << endl; free(p); } /* const basic operator+(const basic& obj2) { int x_min, y_min, x_max, y_max; cout << "Operator +" << endl; if(x > obj2.x) { x_min = obj2.x; x_max = x; } else { x_min = x; x_max = obj2.x; } if(y > obj2.y) { y_min = obj2.y; y_max = y; } else { y_min = y; y_max = obj2.y; } basic temp(x_max, y_max); for(int i = 0; i < x_min; i++) for(int j = 0; j < y_min; j++) temp.p[i][j] = p[i][j] + obj2.p[i][j]; //дописать дополнение разных элементов return temp; }*/ /*void compare(const basic& obj2) { int x_min, y_min; if(x > obj2.x) x_min = obj2.x; else x_min = x; if(y > obj2.y) y_min = obj2.y; else y_min = y; for(int i = 0; i < x_min; i++) { for(int j = 0; j < y_min; j++) if(p[i][j]< obj2.p[i][j]) { cout << "obj1[" << i << "][" << j << "][" << k << "] < "; cout << "obj2[" << i << "][" << j << "][" << k << "] " << endl; } else if(p[i][j][k] > obj2.p[i][j][k]) { cout << "obj1[" << i << "][" << j << "][" << k << "] > "; cout << "obj2[" << i << "][" << j << "][" << k << "] " << endl; } else { cout << "obj1[" << i << "][" << j << "][" << k << "] = "; cout << "obj2[" << i << "][" << j << "][" << k << "] " << endl; } } cout << endl; }*/ friend const basic operator+(const basic&, double); friend const basic operator+(double, const basic& ); }; const basic operator+(const basic& obj2, double d) { basic temp(obj2.x, obj2.y); cout << "Operator + (friendly)" << endl; for(int i = 0; i < obj2.x; i++) for(int j = 0; j < obj2.y; j++) temp.p[i][j] = obj2.p[i][j] + d; return temp; } const basic operator+(double d, const basic& obj2) { basic temp(obj2.x, obj2.y); cout << "Operator + (friendly)" << endl; for(int i = 0; i < obj2.x; i++) for(int j = 0; j < obj2.y; j++) temp.p[i][j] = obj2.p[i][j] + d; return temp; } int main() { //пример для локального оператора = /*basic obj1(2, 1), obj2(2, 2); obj1.set_object(); obj1.show_all(); obj2.set_object(); obj2.show_all(); obj1 = obj2; obj1.show_all();*/ //пример для локальных new & delete /*basic* ptr; ptr = new basic; ptr->show_all(); delete ptr;*/ //пример для локальных new[] & delete[] /*basic* ptr2; ptr2 = new basic [2]; for(int i = 0; i < 2; i++) ptr2->show_all(); delete[] ptr2;*/ //пример для локального оператора = (дописать код) /*basic obj11(1, 1), obj12(2, 2); obj11.set_object(); obj11.show_all(); obj12.set_object(); obj12.show_all(); obj1 + obj2; obj1.show_all();*/ //пример для дружественного оператора = basic obj2(2, 1), obj21; double d = 8.56; obj2.set_object(); obj2.show_all(); obj21 = d+obj2 + d ; obj21.show_all(); return 0; } <commit_msg>Operator <<<commit_after>#include <iostream> #include <cstdlib> using namespace std; class basic { double** p; int x; int y; public: basic(int x1 = 0, int y1 = 0) { cout << "Creating basic" << endl; x = x1; y = y1; alloc(x, y); } ~basic() { cout << "Deleting basic" << endl; free_mem(x, y); } void alloc(int x, int y) { p = new double* [x]; for(int i = 0; i < x; i++) *(p + i) = new double[y]; } void free_mem(int x, int y) { for(int i = 0; i < x; i++) delete[] * (p + i); delete[] p; } void show_all() { cout << "Showing object" << endl << "X : " << x << endl << "Y : " << y << endl; for(int i = 0; i < x; i++) for(int j = 0; j < y; j++) cout << "a[" << i << "][" << j << "]" << " = " << p[i][j] << endl; cout << endl; } void set_object() { double value; cout << "Setting object" << endl; for(int i = 0; i < x; i++) for(int j = 0; j < y; j++) { cout << "a[" << i << "][" << j << "]" << " = "; cin >> value; p[i][j] = value; } cout << endl; } const basic& operator=(const basic& obj2) { cout << "Operator =" << endl; free_mem(x, y); x = obj2.x; y = obj2.y; alloc(x, y); for(int i = 0; i < x; i++) for(int j = 0; j < y; j++) (*this).p[i][j] = obj2.p[i][j]; return *this; } void* operator new(size_t size) { cout << "Using overloaded new:" << size << endl; return malloc(size); } void* operator new [](size_t size) { cout << "Using overloaded new[]:" << size << endl; return malloc(size); } void operator delete(void* p) { cout << "Using overloaded delete:" << endl; free(p); } void operator delete [](void* p) { cout << "Using overloaded delete[]:" << endl; free(p); } /* const basic operator+(const basic& obj2) { int x_min, y_min, x_max, y_max; cout << "Operator +" << endl; if(x > obj2.x) { x_min = obj2.x; x_max = x; } else { x_min = x; x_max = obj2.x; } if(y > obj2.y) { y_min = obj2.y; y_max = y; } else { y_min = y; y_max = obj2.y; } basic temp(x_max, y_max); for(int i = 0; i < x_min; i++) for(int j = 0; j < y_min; j++) temp.p[i][j] = p[i][j] + obj2.p[i][j]; //дописать дополнение разных элементов return temp; }*/ /*void compare(const basic& obj2) { int x_min, y_min; if(x > obj2.x) x_min = obj2.x; else x_min = x; if(y > obj2.y) y_min = obj2.y; else y_min = y; for(int i = 0; i < x_min; i++) { for(int j = 0; j < y_min; j++) if(p[i][j]< obj2.p[i][j]) { cout << "obj1[" << i << "][" << j << "][" << k << "] < "; cout << "obj2[" << i << "][" << j << "][" << k << "] " << endl; } else if(p[i][j][k] > obj2.p[i][j][k]) { cout << "obj1[" << i << "][" << j << "][" << k << "] > "; cout << "obj2[" << i << "][" << j << "][" << k << "] " << endl; } else { cout << "obj1[" << i << "][" << j << "][" << k << "] = "; cout << "obj2[" << i << "][" << j << "][" << k << "] " << endl; } } cout << endl; }*/ friend const basic operator+(const basic&, double); friend const basic operator+(double, const basic&); friend ostream& operator<<(ostream& s, basic& obj); }; ostream& operator<<(ostream& s, basic& obj) { s << "Operator <<" << endl; s << "Matrix size:" << endl; s << "X : " << obj.x << endl; s << "Y : " << obj.y << endl; s << "Matrix elements are:" << endl; for(int i = 0; i < obj.x; i++) for(int j = 0; j < obj.y; j++) s << "a[" << i << "][" << j << "]" << " = " << obj.p[i][j] << endl; return s; } const basic operator+(const basic& obj2, double d) { basic temp(obj2.x, obj2.y); cout << "Operator + (friendly)" << endl; for(int i = 0; i < obj2.x; i++) for(int j = 0; j < obj2.y; j++) temp.p[i][j] = obj2.p[i][j] + d; return temp; } const basic operator+(double d, const basic& obj2) { basic temp(obj2.x, obj2.y); cout << "Operator + (friendly)" << endl; for(int i = 0; i < obj2.x; i++) for(int j = 0; j < obj2.y; j++) temp.p[i][j] = obj2.p[i][j] + d; return temp; } int main() { //пример для локального оператора = /*basic obj1(2, 1), obj2(2, 2); obj1.set_object(); obj1.show_all(); obj2.set_object(); obj2.show_all(); obj1 = obj2; obj1.show_all();*/ //пример для локальных new & delete /*basic* ptr; ptr = new basic; ptr->show_all(); delete ptr;*/ //пример для локальных new[] & delete[] /*basic* ptr2; ptr2 = new basic [2]; for(int i = 0; i < 2; i++) ptr2->show_all(); delete[] ptr2;*/ //пример для локального оператора = (дописать код) /*basic obj11(1, 1), obj12(2, 2); obj11.set_object(); obj11.show_all(); obj12.set_object(); obj12.show_all(); obj1 + obj2; obj1.show_all();*/ //пример для дружественного оператора = basic obj2(2, 1), obj21; double d = 8.56; obj2.set_object(); obj2.show_all(); obj21 = d + obj2 + d; obj21.show_all(); cout << obj21; return 0; } <|endoftext|>
<commit_before>809e91d9-2d15-11e5-af21-0401358ea401<commit_msg>809e91da-2d15-11e5-af21-0401358ea401<commit_after>809e91da-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>e7ef5b5c-313a-11e5-9770-3c15c2e10482<commit_msg>e7f53ff5-313a-11e5-834f-3c15c2e10482<commit_after>e7f53ff5-313a-11e5-834f-3c15c2e10482<|endoftext|>
<commit_before>4e45ec51-2e4f-11e5-9c50-28cfe91dbc4b<commit_msg>4e4d9ad9-2e4f-11e5-8521-28cfe91dbc4b<commit_after>4e4d9ad9-2e4f-11e5-8521-28cfe91dbc4b<|endoftext|>
<commit_before>#include <windows.h> #include "tchar.h" #include "stdio.h" LPTSTR tchar2cw(TCHAR c, LPTSTR* cw); int _tmain(int argc, TCHAR* argv[]) { /* Error message */ if (argc <= 1) { MessageBox(NULL, _T("No arguments"), _T("error"), MB_OK); return -1; } /* string to cw code */ int i = 0; int length = (int) ::_tcslen(argv[1]); //size_t -> int LPTSTR cw = 0; for (i = 0; i < length; i++) { tchar2cw(argv[1][i], &cw); _tprintf(_T("%c: %s\n"), argv[1][i], cw); } return 0; } LPTSTR tchar2cw(TCHAR c, LPTSTR* cw) { switch(c) { /* Alphabets */ case 'a': case 'A': *cw = _T(". - "); break; case 'B': case 'B': *cw = _T("- . . . "); break; case 'C': case 'C': *cw = _T("- . - . "); break; case 'D': case 'D': *cw = _T("- . . "); break; case 'e': case 'E': *cw = _T(". "); break; case 'f': case 'F': *cw = _T(". . - . "); break; case 'g': case 'G': *cw = _T("- - . "); break; case 'h': case 'H': *cw = _T(". . . . "); break; case 'i': case 'I': *cw = _T(". . "); break; case 'j': case 'J': *cw = _T(". - - - "); break; case 'k': case 'K': *cw = _T("- . - "); break; case 'l': case 'L': *cw = _T(". - . . "); break; case 'm': case 'M': *cw = _T("- - "); break; case 'n': case 'N': *cw = _T("- . "); break; case 'o': case 'O': *cw = _T("- - - "); break; case 'p': case 'P': *cw = _T(". - - . "); break; case 'q': case 'Q': *cw = _T("- - . - "); break; case 'r': case 'R': *cw = _T(". - . "); break; case 's': case 'S': *cw = _T(". . . "); break; case 't': case 'T': *cw = _T("- "); break; case 'u': case 'U': *cw = _T(". . - "); break; case 'v': case 'V': *cw = _T(". . . - "); break; case 'w': case 'W': *cw = _T(". - - "); break; case 'x': case 'X': *cw = _T("- . . - "); break; case 'y': case 'Y': *cw = _T("- . - - "); break; case 'z': case 'Z': *cw = _T("- - . . "); break; /* Numbers */ case '1': *cw = _T(". - - - - "); break; case '2': *cw = _T(". . - - - "); break; case '3': *cw = _T(". . . - - "); break; case '4': *cw = _T(". . . . - "); break; case '5': *cw = _T(". . . . . "); break; case '6': *cw = _T("- . . . . "); break; case '7': *cw = _T("- - . . . "); break; case '8': *cw = _T("- - - . . "); break; case '9': *cw = _T("- - - - . "); break; case '0': *cw = _T("- - - - - "); break; /* Simbols */ case '.': *cw = _T(". - . - . - "); case ',': *cw = _T("- - . . - - "); case '?': *cw = _T(". . - - . . "); case '-': *cw = _T("- . . . . - "); case '/': *cw = _T("- . . - . "); case '@': *cw = _T(". - - . - . "); case ' ': *cw = _T(" "); /* Nothing */ default: *cw = _T("?????"); break; } return *cw; } <commit_msg>A a ok<commit_after>#include <windows.h> #include "tchar.h" #include "stdio.h" LPTSTR tchar2cw(TCHAR c, LPTSTR* cw); int _tmain(int argc, TCHAR* argv[]) { /* Error message */ if (argc <= 1) { MessageBox(NULL, _T("No arguments"), _T("error"), MB_OK); return -1; } /* string to cw code */ int i = 0; int length = (int) ::_tcslen(argv[1]); //size_t -> int LPTSTR cw = 0; for (i = 0; i < length; i++) { tchar2cw(argv[1][i], &cw); _tprintf(_T("%c: %s\n"), argv[1][i], cw); } return 0; } LPTSTR tchar2cw(TCHAR c, LPTSTR* cw) { switch(c) { /* Alphabets */ case 'a': case 'A': *cw = _T(". - "); break; case 'b': case 'B': *cw = _T("- . . . "); break; case 'c': case 'C': *cw = _T("- . - . "); break; case 'd': case 'D': *cw = _T("- . . "); break; case 'e': case 'E': *cw = _T(". "); break; case 'f': case 'F': *cw = _T(". . - . "); break; case 'g': case 'G': *cw = _T("- - . "); break; case 'h': case 'H': *cw = _T(". . . . "); break; case 'i': case 'I': *cw = _T(". . "); break; case 'j': case 'J': *cw = _T(". - - - "); break; case 'k': case 'K': *cw = _T("- . - "); break; case 'l': case 'L': *cw = _T(". - . . "); break; case 'm': case 'M': *cw = _T("- - "); break; case 'n': case 'N': *cw = _T("- . "); break; case 'o': case 'O': *cw = _T("- - - "); break; case 'p': case 'P': *cw = _T(". - - . "); break; case 'q': case 'Q': *cw = _T("- - . - "); break; case 'r': case 'R': *cw = _T(". - . "); break; case 's': case 'S': *cw = _T(". . . "); break; case 't': case 'T': *cw = _T("- "); break; case 'u': case 'U': *cw = _T(". . - "); break; case 'v': case 'V': *cw = _T(". . . - "); break; case 'w': case 'W': *cw = _T(". - - "); break; case 'x': case 'X': *cw = _T("- . . - "); break; case 'y': case 'Y': *cw = _T("- . - - "); break; case 'z': case 'Z': *cw = _T("- - . . "); break; /* Numbers */ case '1': *cw = _T(". - - - - "); break; case '2': *cw = _T(". . - - - "); break; case '3': *cw = _T(". . . - - "); break; case '4': *cw = _T(". . . . - "); break; case '5': *cw = _T(". . . . . "); break; case '6': *cw = _T("- . . . . "); break; case '7': *cw = _T("- - . . . "); break; case '8': *cw = _T("- - - . . "); break; case '9': *cw = _T("- - - - . "); break; case '0': *cw = _T("- - - - - "); break; /* Simbols */ case '.': *cw = _T(". - . - . - "); case ',': *cw = _T("- - . . - - "); case '?': *cw = _T(". . - - . . "); case '-': *cw = _T("- . . . . - "); case '/': *cw = _T("- . . - . "); case '@': *cw = _T(". - - . - . "); case ' ': *cw = _T(" "); /* Nothing */ default: *cw = _T("?????"); break; } return *cw; } <|endoftext|>
<commit_before>d1bdc1ae-585a-11e5-b0fc-6c40088e03e4<commit_msg>d1c5315c-585a-11e5-9521-6c40088e03e4<commit_after>d1c5315c-585a-11e5-9521-6c40088e03e4<|endoftext|>
<commit_before>73fe8705-2e4f-11e5-8810-28cfe91dbc4b<commit_msg>740b034f-2e4f-11e5-8f5f-28cfe91dbc4b<commit_after>740b034f-2e4f-11e5-8f5f-28cfe91dbc4b<|endoftext|>
<commit_before>cca96ed4-35ca-11e5-bef5-6c40088e03e4<commit_msg>ccb09d80-35ca-11e5-8391-6c40088e03e4<commit_after>ccb09d80-35ca-11e5-8391-6c40088e03e4<|endoftext|>