所以我使用Allegro 4库在C ++中编写一个简单的三维图形程序。我通过逐像素绘制以最简单的方式制作它。通常,在屏幕上放置单个像素非常慢,因为Allegro的工作方式和绘制分辨率为640x480的图形时我必须等待一两分钟。
所以我正在为我的好友渲染一个图像,所以我拖着窗户看到一个很好的截图,我发现通过拖动窗口和渲染图片,只要我抓住窗口,它就会大大加快。从2分钟开始,它将在10秒内完成所有操作。
这种眩晕行为的原因是什么?它是否与Windows相关?窗户还是由Allegro本身造成的?对此有任何解释吗?
也是我的代码
#include <allegro.h>
#include <iostream>
#include <math.h>
using namespace std;
float MAX_Z = 1;
float MIN_Z =-1;
float SCALE =50;
inline void init(unsigned int width, unsigned int height)
{
allegro_init();
set_color_depth(24);
set_gfx_mode(GFX_AUTODETECT_WINDOWED, width, height, 0, 0);
install_timer();
install_keyboard();
install_mouse();
}
inline void deinit()
{
clear_keybuf();
allegro_exit();
}
int get_z_color (float z)
{
if (z >= 0)
{
return makecol(255, (z/MAX_Z)*255, (z/MAX_Z)*255);
}
else
{
return makecol(255 - (z/MIN_Z)*255,0, 0);
}
}
float get_z (float x, float y)
{
return sin(sqrt(pow(x,2)+pow(y,2)));
}
float int_to_float (int a)
{
return a;
}
int main()
{
unsigned int res_width, res_height;
cout << "Window size (W,H): ";
cin >> res_width >> res_height;
cout << endl << "Initiating in " << res_width << "x" << res_height << " resolution..." << endl;
init(res_width,res_height);
cout << "Success! Drawing graph..." << endl;
for (int y=0; y<res_height; y++)
{
for (int x=0; x<res_width; x++)
{
float valued_x = (int_to_float(x)-(int_to_float(res_width)/2))/SCALE;
float valued_y = (int_to_float(-y)+(int_to_float(res_height)/2))/SCALE;
_putpixel24(screen,x,y,get_z_color(get_z(valued_x,valued_y)));
//cout << "Drawing (" << valued_x << "," << valued_y << ")" << endl;
}
}
cout << "Graph drawn." << endl;
cin >> new char;
cout << "Closing...";
deinit();
return 0;
}
END_OF_MAIN()
答案 0 :(得分:3)
在屏幕表面上绘图,无论您使用哪个库,都是一项代价高昂的操作。
我从未使用过Allegro(我正在使用SDL),但我猜想每次在其上放置一个像素时窗口会重新绘制屏幕表面,并且通过拖动窗口,可以防止重绘实际发生
如果您希望程序的性能大幅提升,则应始终绘制到离屏表面,并在绘图结束后将整个表面blit到屏幕表面(这是一种基本的双缓冲技术)
就像我说的那样,我从未使用Allegro,但是从我能收集的内容中,你可以做到这样的事情:
int main()
{
unsigned int res_width, res_height;
cout << "Window size (W,H): ";
cin >> res_width >> res_height;
cout << endl << "Initiating in " << res_width << "x" << res_height << " resolution..." << endl;
init(res_width,res_height);
BITMAP *temporaryBitmap = create_bitmap(res_width, res_height);
cout << "Success! Drawing graph..." << endl;
for (int y=0; y<res_height; y++)
{
for (int x=0; x<res_width; x++)
{
float valued_x = (int_to_float(x)-(int_to_float(res_width)/2))/SCALE;
float valued_y = (int_to_float(-y)+(int_to_float(res_height)/2))/SCALE;
_putpixel24(temporaryBitmap,x,y,get_z_color(get_z(valued_x,valued_y)));
//cout << "Drawing (" << valued_x << "," << valued_y << ")" << endl;
}
}
blit(temporaryBitmap, screen, 0, 0, 0, 0, temporaryBitmap->w, temporaryBitmap->h);
cout << "Graph drawn." << endl;
cin >> new char;
cout << "Closing...";
destroy_bitmap(temporaryBitmap);
deinit();
return 0;
}