消隐采用的是深度排序算法(油画家算法)
运行结果:
源程序:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <queue>
#include "graphics.h"
using namespace std;
struct MyRectangle {
double x0;
double y0;
double x1;
double y1;
MyRectangle():x0(0), y0(0), x1(0), y1(0){}
};
// 每一个元素由一个矩形和它的深度及颜色组成
struct Element {
MyRectangle rec;
double buffer;
COLORREF color;
Element():buffer(0), color(0){}
bool operator<(const Element &other) const {
return this->buffer > other.buffer; // 让深度较小的排在前面,先出队
}
};
void Draw(priority_queue Q)
{
initgraph(500, 500);
while (!Q.empty())
{
Element tmp = Q.top();
Q.pop();
int x0 = (int)tmp.rec.x0;
int y0 = (int)tmp.rec.y0;
int x1 = (int)tmp.rec.x1;
int y1 = (int)tmp.rec.y1;
COLORREF color = tmp.color;
setfillstyle(color);
bar(x0, y0, x1, y1);
Sleep(2000);
}
closegraph();
}
int main(int argc, char **argv)
{
freopen("cin.txt", "r", stdin);
priority_queue<Element> Q; // 按深度来排的优先队列
Element tmp;
while (cin >> tmp.rec.x0 >> tmp.rec.y0 >> tmp.rec.x1 >> tmp.rec.y1 >> tmp.buffer) // Element最好重载>>
{
// 颜色用十六进制输入,如:0xA80000或A80000
scanf("%x", &tmp.color);
Q.push(tmp);
}
Draw(Q);
return 0;
}
/**cin.txt
0 0 200 200 0.7 0xA80000
27 27 300 300 2 0x00A800
35 440 90 10 1 0xA8A800
470 40 10 160 3 0x0000A8
*/