系列文章目录
简介:Computer Graphics From Scratch-《从零开始的计算机图形学》简介
第一章: Computer Graphics From Scratch - Chapter 1 介绍性概念
第二章:Computer Graphics From Scratch - Chapter 2 基本光线追踪
第三章:Computer Graphics From Scratch - Chapter 3 光照
第四章:Computer Graphics From Scratch - Chapter 4 阴影和反射
第五章:Computer Graphics From Scratch - Chapter 5 扩展光线追踪
第六章:Computer Graphics From Scratch - Chapter 6 线条
Chapter 7
Filled Triangle - 实心三角形
In the previous chapter, we took our first steps toward drawing simple shapes—namely, straight line segments—using only PutPixel and an algorithm based on simple math. In this chapter, we’ll reuse some of the math to draw something more interesting: a filled triangle.
在上一章中,我们迈出了绘制简单形状的第一步,即仅使用PutPixel
和基于简单数学的算法绘制直线段。在本章中,我们将重用一些数学来绘制更有趣的东西:实心三角形。
一、Drawing Wireframe Triangles - 绘制线框三角形
我们可以使用DrawLine
方法绘制三角形的轮廓:
DrawWireframeTriangle (P0, P1, P2, color)
{
DrawLine(P0, P1, color);
DrawLine(P1, P2, color);
DrawLine(P2, P0, color);
}
这种轮廓被称为线框,因为它看起来像一个由线条组成的三角形,如图7-1所示:
图 7-1: A wireframe triangle with vertices (–200,–250), (200,50), and (20,250)
这是一个充满希望的开始!接下来我们将探讨如何用颜色填充三角形。
二、Drawing Filled Triangles - 绘制填充三角形
我们想画一个三角形,用我们选择的颜色填充。正如计算机图形学中的情况一样,解决这个问题的方法不止一种。我们将通过将填充三角形视为水平线段的集合来绘制填充三角形,这些线段在绘制时看起来像三角形。图7-2显示了如果我们可以看到单独的线段,这样的三角形会是什么样子。
图7-2:使用水平线段绘制填充三角形
以下是我们想要做的事情的一个非常粗略的近似值:
for each horizontal line y between the triangle's top and bottom
compute x_left and x_right for this y
DrawLine(x_left, y, x_right, y)
让我们从“三角形的顶部和底部之间”开始。三角形由其三个顶点 P 0 P_0 P0、 P 1 P_1 P1和 P 2 P_2 P2定义。如果 我们 通过增加 y y y值对这些点进行排序,使得 y 0 ≤ y 1 ≤ y 2 y_0≤y_1≤y_2 y0≤y1