Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 25.08.2015, 09:01   #1
Дж.Лондон
Новичок
Джуниор
 
Регистрация: 25.08.2015
Сообщений: 2
По умолчанию Т-фрактал в С++

Задали нам фрактал написать в С++ на visual studio 2013. В универе делали лишь один - снежинку Коха. Вот код:

Код:
#include "windows.h"
#include "conio.h"
#include "math.h"
HWND hwnd;
HDC hdc;
RECT rc;
HPEN hpen;
void st()
{TCHAR title[256];
::GetConsoleTitle(title,256);
hwnd=::FindWindow(0,title);
hdc=::GetWindowDC(hwnd);
::SetWindowPos(hwnd,0,0,0,1000,1000,0);
::GetClientRect(hwnd,&rc);
hpen=::CreatePen(2,1,COLORREF(RGB(150,150,150)));
::SelectObject(hdc,hpen);}
struct fractal
{POINT pt;
fractal*prev;};
fractal * f;
fractal * l;
int h;
void F(fractal* f_c, POINT p0,int ang)
{POINT cur=f_c->pt;
POINT sym;
if(ang==90){sym.x=p0.x+p0.x-cur.x;
sym.y=cur.y;
}
else{ang=45;
sym.x=p0.x+p0.y-cur.y;
sym.y=p0.y+p0.x-cur.x;}
fractal *ptr=new fractal;
ptr->pt=sym;
ptr->prev=l;
l=ptr;
}
void f_90()
{POINT p0;
p0.x=l->pt.x+h/2;
p0.y=l->pt.y;
fractal*ptr=l;
while(ptr) {F(ptr,p0,90);
ptr=ptr->prev;}
}
void f_45()
{POINT p0;
p0.x=l->pt.x+(int)(h/sqrt(2.0));
p0.y=l->pt.y;
fractal*ptr=l;
while(ptr) {F(ptr,p0,45);
ptr=ptr->prev;}
}
void F_down()
{fractal * ptr=l;
fractal*new_ptr;
int y0=l->pt.y+h/2;
while (ptr)
{new_ptr=new fractal;
new_ptr->pt.x=ptr->pt.x;
new_ptr->pt.x=2*y0-ptr->pt.y;
new_ptr->prev=l;
ptr=ptr->prev;
//ptr=ptr->prev;
l=new_ptr;
}
}

void F_draw()
{f=new fractal;
f->pt.x=0;
f->pt.y=(rc.top+rc.bottom)/2+25;
f->prev=0;
l=f;
int w_cur;
int w_max=(rc.right-rc.left)/3;
while(1){ f_90();
f_45();
w_cur=l->pt.x-f->pt.x;
if(w_cur>=w_max) break;
}
f_90();
int x_of_set=(rc.right-l->pt.x)/2;
F_down();
::MoveToEx(hdc, l->pt.x+x_of_set, l->pt.y,0);
fractal*ptr=l->prev;
while (ptr){LineTo(hdc,ptr->pt.x+x_of_set, ptr->pt.y);
ptr=ptr->prev;}
}

void test()
{int k=0;

while (1) {st();
//printf("inpute");
//scanf_s("%d",&h);
//getch();
if(h<2) h=1000;
F_draw();
k++;
if(k%5==0) h--;


}
::system("clr");
}
Требуется написать любой другой фрактал в с++. Нашел Т-фрактал, но он отказывается работать. Там функции, которых я не знаю( glVertex2i, glClearColor и т.д.). Понятно, что они взяты из glut.h, но как их переписать, чтобы код был по типу снежинки Коха, с подключением hwnd, hdc и прочее.

Код:
#include <glut.h>
 
void drowT(int x, int y, int l, int it)
{
    int X1 = x - l / 2; //координаты вершин
    int X2 = x + l / 2;
    int Y1 = y - l / 2;
    int Y2 = y + l / 2;
    glColor3f(0.7 / it, 0.7 / it, 0.7);
    glVertex2i(X1, Y1);
    glVertex2i(X1, Y2);
    glVertex2i(X2, Y2);
    glVertex2i(X2, Y1);
    if(it != 0){
        drowT(X1, Y1, l / 2, it - 1); //вызов рекурсии для каждой из вершин
        drowT(X1, Y2, l / 2, it - 1); //квадрата
        drowT(X2, Y2, l / 2, it - 1);
        drowT(X2, Y1, l / 2, it - 1);
    }    
}
 
void reshape(int w, int h)
{   
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glViewport(0, 0, w, h);
 
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, w, 0, h);
 
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}
 
void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
 
    glBegin(GL_QUADS);
        drowT(400, 400, 400, 10); //вызов функции вырисовки
    glEnd();   
 
	glutSwapBuffers();
}
 
int main(int argc, char *argv[])
{
      glutInit(&argc, argv);
      glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
      glutInitWindowSize(800, 800);
 
      glutCreateWindow("Levy");
 
      glutDisplayFunc(display);
      glutReshapeFunc(reshape);
 
      glutMainLoop();
}
Помогите программу переписать так, чтобы работала в visual studio 2013. Необходимо модули hwnd,hdc подключать.

Последний раз редактировалось Аватар; 25.08.2015 в 09:05.
Дж.Лондон вне форума Ответить с цитированием
Старый 25.08.2015, 12:28   #2
GreenWizard
мальчик-помогай =)
Форумчанин
 
Регистрация: 16.09.2010
Сообщений: 522
По умолчанию

glVertex2i нужно заменить на SetPixel (или DrawLine, не знаю точно), НО основная беда в том, что тут glut сам окно создаёт и обрабатывает, а тебе придёт это делать вручную и в WM_PAINT уже вызывать DrawT и рисовать на форме через hdc
GreenWizard вне форума Ответить с цитированием
Старый 26.08.2015, 04:13   #3
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,601
По умолчанию

Код вроде бы работает.
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Старый 27.08.2015, 11:44   #4
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,601
По умолчанию

Попытался переписать вторую программу. Не знаю, получилось ли то, что надо или нет

Код:
#include <math.h>
#include <conio.h>
#include <windows.h>

#pragma comment(lib, "user32.lib")
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "gdi32.lib")


HWND hwnd;
HDC hdc;
RECT rc;
HPEN hpen;//это графика для консоли, если я правильно понимаю

void drowT(int x, int y, int l, int it)
{
    int X1 = x - l / 2; //координаты вершин
    int X2 = x + l / 2;
    int Y1 = y - l / 2;
    int Y2 = y + l / 2;
SetPixel(hdc, X1, Y1, RGB(0,0,255) ); // glVertex2i(X1, Y1);    
SetPixel(hdc, X1, Y2, RGB(0,0,255) ); // glVertex2i(X1, Y2);    
SetPixel(hdc, X2, Y2, RGB(0,0,255) ); // glVertex2i(X2, Y2);    
SetPixel(hdc, X2, Y1, RGB(0,0,255) ); // glVertex2i(X2, Y1);
    if(it != 0){
        drowT(X1, Y1, l / 2, it - 1); //вызов рекурсии для каждой из вершин
        drowT(X1, Y2, l / 2, it - 1); //квадрата
        drowT(X2, Y2, l / 2, it - 1);
        drowT(X2, Y1, l / 2, it - 1);
    }    
}
 



void st()
{TCHAR title[256];
::GetConsoleTitle(title,256);
hwnd=::FindWindow(0,title);
hdc=::GetWindowDC(hwnd);
::SetWindowPos(hwnd,0,0,0,1000,1000,0);
::GetClientRect(hwnd,&rc);
hpen=::CreatePen(2,1,COLORREF(RGB(150,150,150)));
::SelectObject(hdc,hpen);

drowT(400, 400, 400, 10);


}

int main()
{
  st();
  getch(); 
  return 0;
}
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Старый 27.08.2015, 12:06   #5
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,601
По умолчанию

описание фрактала https://en.wikipedia.org/wiki/T-square_(fractal)



переписал код в таком виде:
Код:
#include <math.h>
#include <conio.h>
#include <windows.h>

#pragma comment(lib, "user32.lib")
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "gdi32.lib")


HWND hwnd;
HDC hdc;
RECT rc;
HPEN hpen;//это графика для консоли, если я правильно понимаю

void drowT(int x, int y, int l, int it)
{
    int X1 = x - l / 2; //координаты вершин
    int X2 = x + l / 2;
    int Y1 = y - l / 2;
    int Y2 = y + l / 2;
SetPixel(hdc, X1, Y1, RGB(0,0,255) ); // glVertex2i(X1, Y1); 
SetPixel(hdc, X1, Y2, RGB(0,0,255) ); // glVertex2i(X1, Y2);    
SetPixel(hdc, X2, Y2, RGB(0,0,255) ); // glVertex2i(X2, Y2);    
SetPixel(hdc, X2, Y1, RGB(0,0,255) ); // glVertex2i(X2, Y1);

MoveToEx(hdc, X1 , Y1, NULL); LineTo(hdc, X1,Y2);
MoveToEx(hdc, X1 , Y1, NULL); LineTo(hdc, X2, Y1); 

MoveToEx(hdc, X1,Y2, NULL); LineTo(hdc, X2, Y2);
MoveToEx(hdc, X2, Y1, NULL); LineTo(hdc, X2, Y2); 

for(i1 = X1;i1 < X2; i1++)
{
MoveToEx(hdc, i1 , Y1, NULL); LineTo(hdc, i1,Y2); // закраска как бы внутренности квадрата
}


    if(it != 0){
        drowT(X1, Y1, l / 2, it - 1); //вызов рекурсии для каждой из вершин
        drowT(X1, Y2, l / 2, it - 1); //квадрата
        drowT(X2, Y2, l / 2, it - 1);
        drowT(X2, Y1, l / 2, it - 1);
    }    
}
 



void st()
{TCHAR title[256];
::GetConsoleTitle(title,256);
hwnd=::FindWindow(0,title);
hdc=GetDC(0); //::GetWindowDC(hwnd);
::SetWindowPos(hwnd,0,0,0,1000,1000,0);
::GetClientRect(hwnd,&rc);
hpen=::CreatePen(2,1,COLORREF(RGB(150,150,150)));
::SelectObject(hdc,hpen);

drowT(400, 400, 400, 10);


}

int main()
{
  st();
  getch(); 
  return 0;
}
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Старый 27.08.2015, 12:09   #6
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,601
По умолчанию

Код с GLUT требует подключения библиотеки windows.h и статических библиотек.
Код:
#include <windows.h>
#include <glut.h>

#pragma comment(lib, "user32.lib")
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
#pragma comment(lib, "glut.lib")
#pragma comment(lib, "glut32.lib")
В итоге у меня появилась ошибка с dll, сперва, что opengl.dll не найден, а когда заменил opengl32.dll на opengl.dll, что точка входа в процедуру GetPixelFormat в opengl.dll не найдена. Не найдена, потому что это функция из gdi32.dll. Более современную версию компилятора и библиотек нужно - у меня компилятор и либы из DDK.
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Старый 27.08.2015, 16:28   #7
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,601
По умолчанию

Кривая Коха

Код:
#include <math.h>
#include <conio.h>
#include <windows.h>

#pragma comment(lib, "user32.lib")
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "gdi32.lib")


HWND hwnd;
HDC hdc;
RECT rc;
HPEN hpen;//это графика для консоли, если я правильно понимаю

void drawT(int x1, int y1, int x2, int y2, int it)
{

if (it == 0)
return;

int X1 = (float)x1 + (float)(x2-x1) * (1.0/3.0);
int Y1 = (float)y1 + (float)(y2-y1) * (1.0/3.0);

int X3 = (float)x1 + (float)(x2-x1) * (2.0/3.0);
int Y3 = (float)y1 + (float)(y2-y1) * (2.0/3.0);

float cos60 = 0.5;
float sin60 = -0.866;

int X2 = (float)X1 + (float)(X3-X1) * cos60 - sin60 * (float)(Y3-Y1);
int Y2 = (float)Y1 + (float)(X3-X1) * sin60 + cos60 * (float)(Y3-Y1);

MoveToEx(hdc, x1 , y1, NULL); LineTo(hdc, X1, Y1);
MoveToEx(hdc, X1, Y1, NULL); LineTo(hdc, X2, Y2);
MoveToEx(hdc, X2, Y2, NULL); LineTo(hdc, X3, Y3);
MoveToEx(hdc, X3, Y3, NULL); LineTo(hdc, x2,y2);


    if(it != 0){
        drawT(x1, y1, X1, Y1, it-1);
        drawT(X1, Y1, X2, Y2, it-1);
        drawT(X2, Y2, X3, Y3, it-1);
        drawT(X3, Y3, x2, y2, it-1);
    } 

}





void st()
{
TCHAR title[256];
::GetConsoleTitle(title,256);
hwnd=::FindWindow(0,title);
hdc=GetDC(0); //::GetWindowDC(hwnd);
::SetWindowPos(hwnd,0,0,0,1000,1000,0);
::GetClientRect(hwnd,&rc);
hpen=::CreatePen(2,1,COLORREF(RGB(150,150,150)));
::SelectObject(hdc,hpen);
drawT(0, 500, 500, 500, 4);
}

int main()
{
  st();
  getch(); 
  return 0;
}
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Старый 27.08.2015, 17:26   #8
ResourceSpace
Форумчанин
 
Аватар для ResourceSpace
 
Регистрация: 30.06.2015
Сообщений: 353
По умолчанию

Цитата:
В итоге у меня появилась ошибка с dll, сперва, что opengl.dll не найден, а когда заменил opengl32.dll на opengl.dll, что точка входа в процедуру...
А разве задача не в том, чтоб было без OGL?
Цитата:
HPEN hpen;//это графика для консоли, если я правильно понимаю
Нет, это "кисть линий", или как там её правильнее обозвать. Задаёт толщину, тип и цвет линий.
ResourceSpace вне форума Ответить с цитированием
Старый 17.03.2016, 20:29   #9
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,601
По умолчанию

glutdlls36.zip нужно скачать по ссылке http://compgraphics.info/OpenGL/template_glut.php

Изменение переменных среды: Панель управления - Система и безопасность - Система - Изменить параметры - Дополнительно - Переменные среды

После каждого изменения переменных требуется перезагрузка операционной системы.
Пути зависят, от того, куда у вас установлен SDK/DDK/VS.

Прописываем переменные среды для компиляции:
Имя переменной: PATH
Значение:
C:\DDK\bin\x86;C:\DDK\bin\x86\x86;C :\DDK\vs\VC\redist\x86\Microsoft.VC 140.CRT

Имя переменной: INCLUDE
Значение:
C:\DDK\inc\crt;C:\DDK\inc\api;C:\DD K\DXSDK\Include;C:\DDK\inc\api\crt\ stl60;C:\Perl\dx8\include

Имя переменной: LIB
Значение: C:\DDK\lib\Crt\i386;C:\DDK\lib\win7 \i386;C:\DDK\DXSDK\Lib\x86;C:\Perl\ dx8\lib

Разбираемся с архивом glutdlls36.zip:
glut32.dll помещается в PATH
glut32.lib помещается в LIB
glut.h помещается в INCLUDE

Строка компиляции: cl имя_файла.

Нельзя одновременно:
Код:
#pragma comment(lib, "glut.lib")
#pragma comment(lib, "glut32.lib")
Нужно только:
Код:
#pragma comment(lib, "glut32.lib")
Код:
#include <windows.h>
#include <gl/glut.h>

#pragma comment(lib, "user32.lib")
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
#pragma comment(lib, "glut32.lib")
 
void drowT(int x, int y, int l, int it)
{
    int X1 = x - l / 2; //координаты вершин
    int X2 = x + l / 2;
    int Y1 = y - l / 2;
    int Y2 = y + l / 2;
    glColor3f(0.7 / it, 0.7 / it, 0.7);
    glVertex2i(X1, Y1);
    glVertex2i(X1, Y2);
    glVertex2i(X2, Y2);
    glVertex2i(X2, Y1);
    if(it != 0){
        drowT(X1, Y1, l / 2, it - 1); //вызов рекурсии для каждой из вершин
        drowT(X1, Y2, l / 2, it - 1); //квадрата
        drowT(X2, Y2, l / 2, it - 1);
        drowT(X2, Y1, l / 2, it - 1);
    }    
}
 
void reshape(int w, int h)
{   
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glViewport(0, 0, w, h);
 
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, w, 0, h);
 
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}
 
void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
 
    glBegin(GL_QUADS);
        drowT(400, 400, 400, 10); //вызов функции вырисовки
    glEnd();   
 
	glutSwapBuffers();
}
 
int main(int argc, char *argv[])
{
      glutInit(&argc, argv);
      glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
      glutInitWindowSize(800, 800);
 
      glutCreateWindow("Levy");
 
      glutDisplayFunc(display);
      glutReshapeFunc(reshape);
 
      glutMainLoop();
}
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Фрактал Цесаро Pein95 Общие вопросы C/C++ 0 01.11.2014 11:17
Фрактал marat-link Помощь студентам 4 01.10.2012 14:14
Фрактал. Pascal. stas45rus Помощь студентам 3 05.06.2012 11:12
Произвольный фрактал ilushkabond Общие вопросы .NET 0 28.02.2012 23:03