首页 > 解决方案 > 使用基于 SDL2 的三角形光栅化器的三角形颜色不正确?

问题描述

我最近一直在用 C 语言创建一个茶壶,使用一个预制的茶壶模型,只是缩放、平移和填充三角形的颜色以及创建边界框,并且进展顺利。但是我已经做到了这一点:

在此处输入图像描述

如您所见,它不太正确,我想知道我做错了什么?它应该看起来像下面的图像。看了几个小时,我看不出我做错了什么。有什么建议么?

在此处输入图像描述

这是我的代码

三角.C

  // Fill triangle with a color
    void FillTriangle(SDL_Surface *screen, triangle_t *triangle)
    {
        // TODO: Insert code that fills the triangle with the color specified in triangle->fillcolor.
        // Hint: Draw the triangle with color TRIANGLE_PENCOLOR (this color can not
        // occur in e.g. the teapot or the example triangles).  Thus, if your 
        // approach to filling the triangle relies on looking for the edges of
        // the triangle on the screen (via the GetPixel function), you will find those
        // edges even if the triangle overlaps with a triangle that has already
        // been drawn on the screen.
        int maxx,minx,maxy,miny;
        int max(int a, int b){
            if(a>b) return a;
            return b;
        }
        int min(int a, int b){
            if (a<b) return a;
            return b;
        }
        maxx = max(triangle->sx1,max(triangle->sx2,triangle->sx3));
        minx = min(triangle->sx1,min(triangle->sx2,triangle->sx3));
        maxy = max(triangle->sy1,max(triangle->sy2,triangle->sy3));
        miny = min(triangle->sy1,min(triangle->sy2,triangle->sy3));
        int x,y;

           for(y = miny;y < maxy; y++){
            for(x = minx; x < maxx; x++){
                if((triangle->sx1 - triangle->sx2) * (y - triangle->sy1) - (triangle->sy1 - triangle->sy2) * (x - triangle->sx1) > 0 &&
                 (triangle->sx2 - triangle->sx3) * (y - triangle->sy2) - (triangle->sy2 - triangle->sy3) * (x - triangle->sx2) > 0 &&
                 (triangle->sx3 - triangle->sx1) * (y - triangle->sy3) -  (triangle->sy3 - triangle->sy1) * (x - triangle->sx3) > 0)
                {
                    SetPixel(screen,x,y,triangle->fillcolor);
                }
            }
        }



}

三角形.h

#ifndef TRIANGLE_H_
#define TRIANGLE_H_

typedef struct triangle triangle_t;

struct triangle {
    // Model coordinates
    int x1, y1;
    int x2, y2;
    int x3, y3;

    // Fill color
    unsigned int fillcolor;

    // Scale factor
    float scale;

    // Translate to these coordinates before drawing on screen
    int tx, ty;

    // Bounding box of on-screen coordinates
    int bx, by;         // upper left corner of box
    int bw, bh;         // Width and height of box

    // On-screen coordinates
    int sx1, sy1;
    int sx2, sy2;
    int sx3, sy3;
};

// Draw triangle on screen.
void DrawTriangle(SDL_Surface *screen, triangle_t *triangle);


#endif /*TRIANGLE_H_*/

线框图片(无颜色)

在此处输入图像描述

标签: csdlsdl-2

解决方案


推荐阅读