Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //AUTHOR: Loukas Xanthos (thetrojan01)
- //T-square fractal drawer;
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- using namespace std;
- #define WHITE false
- #define BLACK true
- #define FG BLACK
- #define BG WHITE
- // "draws" a square in bmp with center (x,y) and sides of length = len.
- void mksq(vector< vector<bool> > &bmp, unsigned int centerx, unsigned int centery, unsigned int len)
- {
- if(len == 1) {
- bmp[centerx][centery] = FG;
- return;
- }
- // move from the center to the corner at down-left and draw the square in the bitset;
- centerx -= len/2;
- centery -= len/2;
- for(unsigned int x = centerx; x < centerx + len; x++)
- for(unsigned int y = centery; y < centery + len; y++)
- bmp[x][y] = FG;
- }
- // recursively starts drawing a fractal havig as center (centerx, centery);
- void fractal(vector< vector<bool> > &bmp, unsigned int centerx, unsigned int centery, unsigned int len)
- {
- if(len < 1) return;
- mksq(bmp, centerx, centery, len);
- fractal(bmp, centerx - len/2, centery - len/2, len/2); //the same at down-left;
- fractal(bmp, centerx + len/2, centery - len/2, len/2); //the same at down-right;
- fractal(bmp, centerx - len/2, centery + len/2, len/2); //the same at up-left;
- fractal(bmp, centerx + len/2, centery + len/2, len/2); //the same at up-right;
- }
- // saves a 2D bit map in a BW pbm file;
- int createBmp(vector< vector<bool> > &bmp, string strFName)
- {
- int szDim = bmp.size();
- ofstream fout(strFName.c_str());
- if(!fout.is_open()) {
- cerr << "Cannot open the output file." << endl;
- return 1;
- }
- // header
- fout << "P1\n";
- fout << szDim << ' ' << szDim << '\n';
- // the actual bitmap
- for(int i=0; i < szDim; i++) {
- for(int j=0; j < szDim - 1; j++) {
- fout << bmp[i][j] << ' ';
- }
- fout << bmp[i][szDim-1];
- fout << "\n";
- }
- return 0;
- }
- int main()
- {
- unsigned int szDim;
- string fname;
- vector< vector<bool> > bmp;
- //gets from standard input:
- // dimension of the surrounding square;
- // filename of the output image;
- cin >> szDim;
- cin >> fname;
- if(szDim < 4) {
- return 0;
- }
- bmp.resize(szDim);
- for(unsigned int i=0; i < szDim; i++)
- bmp[i].resize(szDim, BG);
- fractal(bmp, szDim/2, szDim/2, szDim/2);
- return createBmp(bmp, fname);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement