Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- double zeroF(double a, double b, double(*f)(double)) {
- double fa=f(a), fb=f(b), fx=1., x, eps=1e-14;
- if (fa*fb > 0) throw exception("Not applicable");
- while(fabs(fx)>eps || fabs(a-b) > eps) {
- x = f(a+b)/2.;
- fx = f(x);
- if(fx*fb < 0) a = x;
- else {b=x; fb=fx;}
- }
- return x;
- }
- ///////
- #include <iostream>
- #include <math.h>
- using namespace std;
- typedef double (*FN)(double);
- double f(double x){return 5.*sin(x/7.)+0.001*x*x;}
- double fi(double x){return x -1.25*f(x);}
- // x3+x-1000=0
- double fi2(double x){return exp(log(1000.-x)*(1./3.));}
- // eps - to4nost
- bool iterSolution(double & x, FN fi, double eps, int &iter){
- // xn - x novo; xs - x staro
- double xn, xs=x;
- for(int i=0;i<iter;i++){
- xn = fi(xs);
- if(fabs(xn-xs)<eps){
- x=xn;iter=i;return true;
- }
- xs=xn;
- }
- return false;
- }
- int main(){
- double x, eps=1e-14;
- int iters=100;
- while(true){
- cin>>x;
- double xt=x; int it=iters;
- if(iterSolution(xt,fi2,eps,it)){
- cout<<"zero="<<xt<<", it= "<<it<<endl;
- }else cout<<"Can not apply iterations!"<<endl;
- }
- return 0;
- }
- /////////////////////////////
- #define _CRT_SECURE_NO_WARNINGS
- #include <cstdio>
- #include <string>
- #include <cmath>
- #include <exception>
- #include "msw.h"
- //Начални размери на графичния прозорец в потребителски единици
- double DEFAULT_XMIN = -20;
- double DEFAULT_YMIN = 20; //знаците по Y са обърнати умишлено
- double DEFAULT_XMAX = 20;
- double DEFAULT_YMAX = -20;
- //Заглавие в рамката на приложението
- char title[200] = "ГРАФИЧНА КОНЗОЛА";
- int snapfract = 2;
- ////////
- typedef double (*FN)(double);
- double f(double x){return 5.*sin(x/7.)+0.001*x*x;}
- double fi(double x){return x -1.25*f(x);}
- // x3+x-1000=0
- double fi2(double x){return exp(log(1000.-x)*(1./3.));}
- // eps - to4nost
- bool iterSolution(double & x, FN fi, double eps, int &iter){
- // xn - x novo; xs - x staro
- double xn, xs=x;
- for(int i=0;i<iter;i++){
- xn = fi(xs);
- if(fabs(xn-xs)<eps){
- x=xn;iter=i;return true;
- }
- xs=xn;
- }
- return false;
- }
- /////////////////
- typedef double (*FUN)(double);
- double Sin(double x){return x;} // tuk
- //Изчертаване графиката на функция на една променлива
- //[argL, argR} - интервал на аргумента, f -функция
- void drawFun(double argL, double argR,FUN f){
- if(argL>argR)std::swap(argL,argR);
- //стъпка на изменение на аргумента = 2 пиксела
- double resx = cwin.disp_to_user_x(2)-cwin.disp_to_user_x(0),
- resy = cwin.disp_to_user_y(0)-cwin.disp_to_user_y(2),
- res = resx<resy? resx : resy;
- //начална точка на графиката
- Point first(argL,f(argL)),second;
- for(double x=argL+res;x<=argR;x+=res){
- second=Point(x,f(x));//текуща точка
- cwin<<Line(first,second);
- first=second;
- }
- }
- //Симулация на конзолна функция
- int win_main(){
- string yn; cwin<<RGB(0,0,100);cwin.axes();//cwin<<SNAP;
- yn=cwin.get_string("Графики на функции на една променлива. \n"
- "[y]/n за продължение:");
- double x=50, eps=1e-14;
- int iters=100;
- double xt=x; int it=iters;
- if(iterSolution(xt,fi,eps,it));
- if(yn[0]!='n'){
- cwin.axes(); //координатни оси с деления
- cwin<<RGB(120,0,0); //смяна на цвета
- drawFun(-20.,20.,Sin);//изчертаване на графиката
- }
- cwin.get_string("<Enter> за край.");
- cwin.clear();exit(0);
- return 0;
- }
- ////////////////////////////////////////////////
- //Демонстрационен програмен текст за алгоритъма на Cohen-Sutherland
- //Курс CSCB506 към програма Информатика на НБУ
- //Автор: Ст. Иванов, 2013
- #include <windows.h>
- #include <stdio.h>
- #include <math.h>
- struct PNT2{ double x, y; };//точка с реални координати
- //координати на изрязващия прозорец
- double xmin = 100, ymin = 100, xmax = 800, ymax = 500;
- //Изработване на признак за зоната, в която се намира точката
- inline BYTE outcode(PNT2 p){
- BYTE code = 0;
- if (p.y>ymax)code += 8;
- else if (p.y<ymin)code += 4;
- if (p.x>xmax)code += 2;
- else if (p.x<xmin)code += 1;
- return code;
- }
- //Изрязващ алгоритъм на Cohen-Sutherland
- //Параметрите p1 и p2 са модифицируеми: при вход съдържат крайните
- //точки на отсечката, при изход - крайните точки на участъка,
- //намиращ се вътре в правоъгълника.
- //Връщаната стойност е 1, ако отсечката е изцяло вън от правоъгълника
- //и 0, ако поне част от отсечката е вътре. Тогава в p1 и p2 са краищата
- //на въртешната част от отсечката.
- int CSClip(PNT2 & p1, PNT2 & p2){
- BYTE code1 = outcode(p1), code2 = outcode(p2), code;
- double x, y;
- do{
- if (code1&code2)return 1; //изцяло вън
- if (code1 + code2 == 0)return 0; //изцяло вътре
- //поне едната точка е вътре, взема се
- code = code1 != 0 ? code1 : code2;
- if (code & 8){//ако е отгоре, премества се по горната граница
- x = p1.x + (p2.x - p1.x)*(ymax - p1.y) / (p2.y - p1.y);
- y = ymax;
- }
- else if (code & 4){//ако е отдолу, премества се по долната граница
- x = p1.x + (p2.x - p1.x)*(ymin - p1.y) / (p2.y - p1.y);
- y = ymin;
- }
- else if (code & 2){//ако е отдясно, премества се по дясната граница
- y = p1.y + (p2.y - p1.y)*(xmax - p1.x) / (p2.x - p1.x);
- x = xmax;
- }
- else if (code & 1){//ако е отляво, премества се по лявата граница
- y = p1.y + (p2.y - p1.y)*(xmin - p1.x) / (p2.x - p1.x);
- x = xmin;
- }
- //присвояване на преместената точка и ново пресмятане на кода
- if (code == code1){
- p1.x = x; p1.y = y; code1 = outcode(p1);
- }
- else{
- p2.x = x; p2.y = y; code2 = outcode(p2);
- }
- } while (true);
- }
- void lineBres(HDC, POINT, POINT, COLORREF);
- void showCoord(HWND, LPARAM);
- void redraw(HWND);
- LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
- int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
- PSTR szCmdLine, int iCmdShow)
- {
- static TCHAR szAppName[] = L"LinesDemo";
- HWND hwnd;
- MSG msg;
- WNDCLASS wndclass;
- wndclass.style = CS_HREDRAW | CS_VREDRAW;
- wndclass.lpfnWndProc = WndProc;
- wndclass.cbClsExtra = 0;
- wndclass.cbWndExtra = 0;
- wndclass.hInstance = hInstance;
- wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
- wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
- wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
- wndclass.lpszMenuName = NULL;
- wndclass.lpszClassName = szAppName;
- if (!RegisterClass(&wndclass))
- {
- MessageBox(NULL, TEXT("Can not register the window class!"),
- szAppName, MB_ICONERROR);
- return 0;
- }
- hwnd = CreateWindow(szAppName,
- L" CSCB506-4: Clipping rectangle. NBU 2013 Ivanov",
- WS_OVERLAPPEDWINDOW,
- CW_USEDEFAULT, CW_USEDEFAULT,
- CW_USEDEFAULT, CW_USEDEFAULT,
- NULL, NULL, hInstance, NULL);
- ShowWindow(hwnd, iCmdShow);
- UpdateWindow(hwnd);
- while (GetMessage(&msg, NULL, 0, 0))
- {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- return msg.wParam;
- }
- LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
- {
- HDC hdc;
- static bool LBD = true; //сигнал за натиснат ляв бутон на мишката
- static PNT2 p1, p2; //крайни точки на отсечката в double координати
- static POINT P1, P2; //крайни точки на отсечката в int координати
- static int ip = 0; //сигнал за първа-втора въведена точка
- switch (message)
- {
- case WM_LBUTTONDOWN:
- LBD = true;
- return 0;
- case WM_MOUSEMOVE:
- showCoord(hwnd, lParam);
- return 0;
- case WM_LBUTTONUP:
- if (LBD){
- LBD = !LBD;
- if (ip == 0){//въвеждане на първа точка
- P1.x = LOWORD(lParam);
- P1.y = HIWORD(lParam);
- ip++;
- }
- else{//въвеждане на втора точка
- P2.x = LOWORD(lParam);
- P2.y = HIWORD(lParam);
- ip--;
- //и обработка на отсечката
- p1.x = P1.x; p1.y = P1.y;//прехвърляне в double координати
- p2.x = P2.x; p2.y = P2.y;
- int code = CSClip(p1, p2);//изрязване
- hdc = GetDC(hwnd);
- if (code == 1)
- //отсечката е вън - чертае се в синьо
- lineBres(hdc, P1, P2, RGB(0, 0, 150));
- else{//поне отчасти е вътре
- POINT P11, P22; //вземат се крайните точки
- //на вътрешната част
- P11.x = (int)p1.x; P11.y = (int)p1.y;
- P22.x = (int)p2.x; P22.y = (int)p2.y;
- //вътрешната част се чертае в червено
- //външната(ите) част(и) - в синьо
- lineBres(hdc, P1, P11, RGB(0, 0, 150));
- lineBres(hdc, P11, P22, RGB(150, 0, 0));
- lineBres(hdc, P2, P22, RGB(0, 0, 150));
- // DRASKA KOORDINATI W DOBULE na P1 i P2
- TCHAR mouf[100], spac[40] = L" ";
- RECT rect; HDC hdc;
- swprintf(mouf, 100, L"P1: %20.4f , %20.4f\nP2: %20.4f , %20.4f", p1.x, p1.y, p2.x, p2.y);
- hdc = GetDC(hwnd);
- GetClientRect(hwnd, &rect);
- DrawText(hdc, spac, -1, &rect,
- WNFMT_MULTILINE | DT_BOTTOM | DT_RIGHT);
- DrawText(hdc, mouf, -1, &rect,
- WNFMT_MULTILINE | DT_BOTTOM | DT_RIGHT);
- }
- ReleaseDC(hwnd, hdc);
- }
- }
- return 0;
- case WM_RBUTTONDOWN://с десен бутон се изтрива
- InvalidateRect(hwnd, NULL, TRUE);
- return 0;
- case WM_PAINT://изчертава се само рамката - изрязващ правоъгълник
- redraw(hwnd);
- return 0;
- case WM_DESTROY:
- PostQuitMessage(0);
- return 0;
- }
- return DefWindowProc(hwnd, message, wParam, lParam);
- }
- void showCoord(HWND hwnd, LPARAM lParam){
- TCHAR mouf[20], spac[20] = L" ";
- RECT rect; HDC hdc;
- wsprintf(mouf, L"%i %i", LOWORD(lParam), HIWORD(lParam));
- hdc = GetDC(hwnd);
- GetClientRect(hwnd, &rect);
- DrawText(hdc, spac, -1, &rect,
- DT_SINGLELINE | DT_BOTTOM | DT_LEFT);
- DrawText(hdc, mouf, -1, &rect,
- DT_SINGLELINE | DT_BOTTOM | DT_LEFT);
- ReleaseDC(hwnd, hdc);
- }
- void redraw(HWND hwnd){
- HDC hdc = GetDC(hwnd);
- MoveToEx(hdc, (int)xmin, (int)ymin, NULL);
- LineTo(hdc, (int)xmin, (int)ymax);
- LineTo(hdc, (int)xmax, (int)ymax);
- LineTo(hdc, (int)xmax, (int)ymin);
- LineTo(hdc, (int)xmin, (int)ymin);
- ReleaseDC(hwnd, hdc);
- }
- inline void swap(int &p, int &q){ int t = p; p = q; q = t; }
- void lineBres(HDC hdc, POINT p1, POINT p2, COLORREF c){
- int x0 = p1.x, y0 = p1.y, x1 = p2.x, y1 = p2.y;
- bool str = abs(y1 - y0)>abs(x1 - x0);
- if (str) { swap(x0, y0); swap(x1, y1); }
- if (x0>x1){ swap(x0, x1); swap(y0, y1); }
- int dx = x1 - x0, dy = abs(y1 - y0), err = 0, y = y0;
- int yst = y0<y1 ? 1 : -1;
- for (int x = x0; x <= x1; x++){
- if (str) SetPixel(hdc, y, x, c);
- else SetPixel(hdc, x, y, c);
- err += dy;
- if (2 * err >= dx){ y += yst; err -= dx; }
- }
- }
- ////////////////////////////////
- #include <iostream>
- #include <cmath>
- #include <iomanip>
- using namespace std;
- //Изходен манипулатор за форматиране на double
- ostream & setWP(ostream & s){
- s<<fixed<<setw(10)<<setprecision(10);
- return s;
- }
- //Контролирано въвеждане с подсещане на double
- double getDbl(const char *pr){
- double t;char buf[80];bool E;
- do {
- cout<<"Enter double:"<<pr;cin>>t;E=cin.fail();
- if(E){
- cin.clear();cin.getline(buf,79);
- cout<<"Input error. Try again.\n";}
- }while(E);cin.getline(buf,79);
- return t;
- }
- //Клас "3D точка"= вектор в тримерното пространство
- class Vector3{
- double x,y,z; //координати
- public:
- //Основен конструктор, при изпускане на параметрите генерира (0,0,0)
- Vector3(double x=0,double y=0,double z=0):x(x),y(y),z(z){}
- //Предефиниране на оператори за събиране, изваждане, умножение с число
- Vector3 operator +(const Vector3 &b)const{return Vector3(x+b.x,y+b.y,z+b.z);}
- Vector3 operator -(const Vector3 &b)const{return Vector3(x-b.x,y-b.y,z-b.z);}
- Vector3 operator *(double b)const{return Vector3(x*b,y*b,z*b);}
- //Оператор за скаларно произведение на вектори
- double operator %(const Vector3 &b)const{return x*b.x+y*b.y+z*b.z;}
- //Модул (големина) на вектор
- double mod()const{return sqrt(*this%*this);}
- //Оператор за векторно произведение на вектори
- Vector3 operator *(const Vector3 &b)const{
- return Vector3(y*b.z-z*b.y,z*b.x-x*b.z,x*b.y-y*b.x);
- }
- //Получаване на единичен вектор
- Vector3 operator !()const{
- double m=mod();if(m!=0)return Vector3(x/m,y/m,z/m);else return *this;
- }
- //Смяна на знака (унарен минус)
- Vector3 operator -()const{return Vector3(-x,-y,-z);}
- //Сравняване на вектори
- bool operator ==(const Vector3 &b)const{return !(*this!=b);}
- bool operator !=(const Vector3 &b)const{
- double m=mod(); return m!=0&&
- (fabs(x-b.x)/m>1e-10||fabs(y-b.y)/m>1e-10||fabs(z-b.z)/m>1e-10);
- }
- ostream & ins(ostream & s)const{
- s<<'('<<setWP<<x<<','<<setWP<<y <<','<<setWP<<z<<')'<<endl;
- return s;
- }
- //Въвеждане на вектор от конзолата
- void InpVect(){
- cout<<"Input the components of a 3-D vector:\n";
- x=getDbl("x:");y=getDbl("y:");z=getDbl("z:");
- }
- //Промяна на компоненти
- void setX(double x){this->x=x;}
- void setY(double y){this->y=y;}
- void setZ(double z){this->z=z;}
- //Извличане на компоненти
- double getX()const{return x;}
- double getY()const{return y;}
- double getZ()const{return z;}
- };
- //Умножение на число по вектор
- Vector3 operator *(double b,const Vector3 &a){return a*b;}
- //Вмъкване на вектор в изходния поток
- ostream& operator <<(ostream &s,const Vector3 &a){return a.ins(s);}
- //3 zad
- double computeTriangleArea(const Vector3 &a,const Vector3 &b,const Vector3 &c) {
- return 0.5*((b-a)*(c-a)).mod();
- }
- //4 zad
- Vector3 mediCenter(const Vector3 &a,const Vector3 &b,const Vector3 &c) {
- return (1./3.)*(a+b+c);
- }
- //5 zad
- bool izpyknalVector(const Vector3 V [], int n) {
- double z = ((V[n]- V[n-1])*(V[1]-V[0])).getZ();
- for(int i=1; i<n; i++) {
- double t = ((V[i]- V[i-1])*(V[i+1]-V[i])).getZ();
- if( z*t<0 ) return false;
- }
- return true;
- }
- int main(){
- Vector3 A,B,C;
- cout<<"Vector A:\n"; A.InpVect();
- cout<<"Vector B:\n"; B.InpVect();
- cout<<"Vector C:\n"; C.InpVect();
- //3 zad
- cout<< computeTriangleArea(A,B,C);
- //4 zad
- cout<< mediCenter(A,B,C);
- /*
- cout<<"A="<<A;cout<<"B="<<B;
- cout<<"Additive operations:\n";
- cout<<"A+B="<<A+B; cout<<"B-A="<<B-A;
- cout<<"Products:\n";
- cout<<"A * B= "<<A*B;
- cout<<"A . B= "<<A%B<<endl;
- cout<<"A*2.5="<<A*2.5;
- cout<<"0.1*B="<<0.1*B ;
- cout<<"Unary operations:\n";
- cout<<"|A|="<<A.mod()<<endl;
- cout<<"-A="<<-A;
- cout<<"unified A="<<!A;
- cout<<"Comparision:\n";
- cout<<"A==B? "<<boolalpha<<(A==B)<<endl;
- cout<<"Getters/setters:\n";
- cout<<"Input x-component of A:";double x;cin>>x;A.setX(x);
- cout<<"A is set as:"<<A;cout<<"A.x="<<A.getX()<<endl;
- */
- /////////////////////////////////////////////
- //main.cpp
- #include <windows.h>
- #include <math.h>
- #include "vector2D.h"
- COLORREF clrs[6] = { 0xAF0000, 0x00AF00, 0x0000AF, 0x00AFAF, 0xAF00AF };
- double scale = 1;
- COLORREF defClr = clrs[5];
- int clrPt = 5;
- int maxRec = 5;
- int toDraw = 0;
- void lineBres(HDC, POINT, POINT, COLORREF);
- void redrawAll(HWND);
- void Line(HDC, Point, Point);
- void drawKoch(HDC, Point, Point);
- void drawPeano(HDC, Point, Point);
- void drawGosper(HDC, Point, Point);
- void drawHarter(HDC, Point, Point);
- void drawSerp(HDC, Point, Point);
- LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
- int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
- PSTR szCmdLine, int iCmdShow)
- {
- static TCHAR szAppName[] = TEXT("Fractal Curves Demo");
- HWND hwnd;
- MSG msg;
- WNDCLASS wndclass;
- wndclass.style = CS_HREDRAW | CS_VREDRAW;
- wndclass.lpfnWndProc = WndProc;
- wndclass.cbClsExtra = 0;
- wndclass.cbWndExtra = 0;
- wndclass.hInstance = hInstance;
- wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
- wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
- wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
- wndclass.lpszMenuName = NULL;
- wndclass.lpszClassName = szAppName;
- if (!RegisterClass(&wndclass))
- {
- MessageBox(NULL, TEXT("Can not register the window class!"),
- szAppName, MB_ICONERROR);
- return 0;
- }
- hwnd = CreateWindow(szAppName, L" CSCB506-5: Recursive Curves Demo",
- WS_OVERLAPPEDWINDOW,
- CW_USEDEFAULT, CW_USEDEFAULT,
- CW_USEDEFAULT, CW_USEDEFAULT,
- NULL, NULL, hInstance, NULL);
- ShowWindow(hwnd, iCmdShow);
- UpdateWindow(hwnd);
- while (GetMessage(&msg, NULL, 0, 0))
- {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- return msg.wParam;
- }
- LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
- {
- static int cxClient, cyClient;
- switch (message)
- {
- case WM_SIZE:
- cxClient = LOWORD(lParam);
- cyClient = HIWORD(lParam);
- scale = cxClient<cyClient ? cxClient*0.1 : cyClient*0.1;
- return 0;
- case WM_KEYDOWN:
- switch (wParam)
- {
- case VK_LEFT:
- clrPt = (clrPt + 1) % 6; defClr = clrs[clrPt];
- break;
- case VK_RIGHT:
- clrPt = (clrPt + 5) % 6; defClr = clrs[clrPt];
- break;
- case VK_UP:
- maxRec--;
- break;
- case VK_DOWN:
- maxRec++;
- break;
- case VK_HOME:
- toDraw = (toDraw + 1) % 5;
- break;
- case VK_END:
- toDraw = (toDraw + 4) % 5;
- break;
- default: return 0;
- }
- InvalidateRect(hwnd, NULL, TRUE);
- return 0;
- case WM_PAINT:
- redrawAll(hwnd);
- return 0;
- case WM_DESTROY:
- PostQuitMessage(0);
- return 0;
- }
- return DefWindowProc(hwnd, message, wParam, lParam);
- }
- void Line(HDC hdc, Point a, Point b){
- POINT A, B;
- A.x = (LONG)(a.getX()*scale);
- A.y = (LONG)(a.getY()*scale);
- B.x = (LONG)(b.getX()*scale);
- B.y = (LONG)(b.getY()*scale);
- lineBres(hdc, A, B, defClr);
- }
- void drawKoch(HDC hdc, Point a, Point b){
- static int rec = 0; rec++;
- if (rec>maxRec)Line(hdc, a, b);
- else{
- Point a1 = a*(2. / 3.) + b*(1. / 3),
- b1 = a*(1. / 3.) + b*(2. / 3),
- c = a1 + ((b - a)*(1. / 3.)).rotA(60.);
- drawKoch(hdc, a, a1); drawKoch(hdc, a1, c);
- drawKoch(hdc, c, b1); drawKoch(hdc, b1, b);
- }
- rec--;
- }
- void drawPeano(HDC hdc, Point a, Point b){
- static int rec = 0; rec++;
- if (rec>maxRec)Line(hdc, a, b);
- else{
- Point t = (b - a)*(1. / 3.), n = t.rotL(),
- p1 = a + t, p2 = p1 + n, p3 = p2 + t, p4 = p3 - n, p6 = p1 - n, p7 = p6 + t;
- drawPeano(hdc, a, p1); drawPeano(hdc, p1, p2); drawPeano(hdc, p2, p3);
- drawPeano(hdc, p3, p4); /*drawPeano(hdc, p4, p1); drawPeano(hdc, p1, p6);
- drawPeano(hdc, p6, p7); drawPeano(hdc, p7, p4);*/ drawPeano(hdc, p4, b);
- }
- rec--;
- }
- void drawGosper(HDC hdc, Point a, Point b){
- static int rec = 0; rec++;
- if (rec>maxRec)Line(hdc, a, b);
- else{
- Point t = (b - a)*0.5, p = t*(5. / 7), q = t*(sqrt(3.) / 7),
- r = p + q.rotL(), p1 = a + r, p2 = b - r, p3 = p2 - r, l = p2 - (a + r*2.),
- p4 = p3 + l, p5 = p4 + r, p6 = b + l, p7 = p6 + t;
- // Point t = (b - a)*(1. / 3.), n = t.rotL(),
- // p1 = a + t, p2 = p1 + n, p3 = p2 + t, p4 = p3 - n, p6 = p1 - n, p7 = p6 + t,
- // p = t*(5. / 7), q = t*(sqrt(3.) / 7), r = p + q.rotL(), p5 = p4 + r;
- //
- drawGosper(hdc, a, p1);
- drawGosper(hdc, p1, p2); drawGosper(hdc, p2, p3);
- drawGosper(hdc, p3, p4); drawGosper(hdc, p4, p1);
- drawGosper(hdc, p1, p6); drawGosper(hdc, p6, p7);
- drawGosper(hdc, p7, p4); drawGosper(hdc, p4, b);
- }
- rec--;
- }
- void drawSerp(HDC hdc, Point a, Point b){
- static int rec = 0; rec++;
- if (rec>maxRec)Line(hdc, a, b);
- else{
- Point t = (b - a)*0.5, p1 = a + t.rotA(60.), p2 = p1 + t;
- drawSerp(hdc, p1, a);
- drawSerp(hdc, p1, p2);
- drawSerp(hdc, b, p2);
- }
- rec--;
- }
- void drawHarter(HDC hdc, Point a, Point b){
- static int rec = 0; rec++;
- if (rec>maxRec)Line(hdc, a, b);
- else{
- Point t = (b - a)*0.5, c = a + t + t.rotR();
- drawHarter(hdc, a, c); drawHarter(hdc, c, b);
- }
- rec--;
- }
- void draw1(HDC hdc, Point a, Point b){
- static int rec = 0; rec++;
- if (rec>maxRec)Line(hdc, a, b);
- else{
- Point t = (b - a)*(1. / 3.), l = t.rotA(108.), r=t.rotA(72.), rr= r.rotA(72.);
- draw1(hdc, a, a + t);
- // draw2(hdc, a+t, b+t);
- draw1(hdc, b-t, b);
- draw1(hdc, a + t, a + t + l);
- draw1(hdc, b - t, b - t + r);
- // draw1(hdc, a, a + t);
- // draw1(hdc, a, a + t);
- // draw1(hdc, a, a + t);
- }
- rec--;
- }
- void draw2(HDC hdc, Point a, Point b){
- static int rec = 0; rec++;
- if (rec>maxRec)Line(hdc, a, b);
- else{
- double tt = tan(PI / 6.);
- Point t = (b - a)*0.5, n = (t*tt).rotL(), c = a + t + n;
- draw2(hdc, a, c);
- draw2(hdc, b, c);
- }
- rec--;
- }
- void draw3(HDC hdc, Point a, Point b){
- static int rec = 0; rec++;
- if (rec>maxRec)Line(hdc, a, b);
- else{
- Point t = (b - a)*0.25, l = t.rotA(60.), r = t.rotA(90.);
- // draw3(hdc, a, c);
- // draw3(hdc, b, c);
- }
- rec--;
- }
- void redrawAll(HWND hwnd){
- HDC hdc; RECT rect; PAINTSTRUCT ps;
- TCHAR txt[30];
- wsprintf(txt, L"Дълбочина на рекурсията: %i ", maxRec);
- hdc = BeginPaint(hwnd, &ps);
- GetClientRect(hwnd, &rect);
- DrawText(hdc, txt, -1, &rect, DT_SINGLELINE | DT_TOP | DT_LEFT);
- Point cen((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2);
- cen = cen*(1 / scale);
- switch (toDraw){
- case 0:{
- DrawText(hdc, L"Крива на Peano: Up/Down за дълбочина"
- L" , Left/Right за цвят, Home/End = смяна.", -1,
- &rect, DT_SINGLELINE | DT_BOTTOM | DT_LEFT);
- Point a(-1, 0), b(1, 0); a = a + cen; b = b + cen;
- drawPeano(hdc, a, b);
- }break;
- case 1:{
- DrawText(hdc, L"Крива на Peano: Up/Down за дълбочина"
- L" , Left/Right за цвят, Home/End = смяна.", -1,
- &rect, DT_SINGLELINE | DT_BOTTOM | DT_LEFT);
- Point a(-1, 0), b(1, 0); a = a + cen; b = b + cen;
- drawPeano(hdc, a, b);
- }break;
- case 2:{
- DrawText(hdc, L"Крива на Gosper: Up/Down за дълбочина"
- L" , Left/Right за цвят, Home/End = смяна.", -1,
- &rect, DT_SINGLELINE | DT_BOTTOM | DT_LEFT);
- Point a(-2, 1), b(2, 1); a = a + cen; b = b + cen;
- drawGosper(hdc, a, b);
- }break;
- case 3:{
- DrawText(hdc, L"Дракон на Harter: Up/Down за дълбочина"
- L" , Left/Right за цвят, Home/End = смяна.", -1,
- &rect, DT_SINGLELINE | DT_BOTTOM | DT_LEFT);
- Point a(-2, 0), b(2, 0); a = a + cen; b = b + cen;
- drawHarter(hdc, a, b);
- }break;
- case 4:{
- DrawText(hdc, L"Крива на Sierpinsky: Up/Down за дълбочина"
- L" , Left/Right за цвят, Home/End = смяна.", -1,
- &rect, DT_SINGLELINE | DT_BOTTOM | DT_LEFT);
- Point a(-2, -2), b(2, -2); a = a + cen; b = b + cen;
- drawSerp(hdc, a, b);
- }
- }
- EndPaint(hwnd, &ps);
- }
- inline void swap(int &p, int &q){ int t = p; p = q; q = t; }
- void lineBres(HDC hdc, POINT p1, POINT p2, COLORREF c){
- int x0 = p1.x, y0 = p1.y, x1 = p2.x, y1 = p2.y;
- bool str = abs(y1 - y0)>abs(x1 - x0);
- if (str) { swap(x0, y0); swap(x1, y1); }
- if (x0>x1){ swap(x0, x1); swap(y0, y1); }
- int dx = x1 - x0, dy = abs(y1 - y0), err = 0, y = y0;
- int yst = y0<y1 ? 1 : -1;
- for (int x = x0; x <= x1; x++){
- if (str) SetPixel(hdc, y, x, c);
- else SetPixel(hdc, x, y, c);
- err += dy;
- if (2 * err >= dx){ y += yst; err -= dx; }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment