summaryrefslogtreecommitdiff
path: root/test/test.c
blob: be3be931c36f0e2a9ea984cacc79107d26e2abb9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "test.h"

#include <swgfx.h>

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>

typedef struct RGB { uint8_t r, g, b; } RGB;

static bool WritePPM(int width, int height, const RGB* image, const char* path) {
  const size_t num_pixels = width * height;
  
  FILE* file = fopen(path, "wb");
  if (!file) {
    return false;
  }
  
  fprintf(file, "P6\n%d %d\n255\n", width, height);
  if (fwrite(image, sizeof(RGB), num_pixels, file) != num_pixels) {
    fclose(file);
    return false;
  }
  
  fclose(file);
  return true;
}

static void ToRGB(int width, int height, const sgPixel* rgba, RGB* rgb) {
  assert(rgba);
  assert(rgb);
  for (int y = 0; y < height; ++y) {
    for (int x = 0; x < width; ++x) {
      const sgPixel p = *rgba++;
      *rgb++ = (RGB){p.r, p.g, p.b};
    }
  }
}

static void Checkerboard(swgfx* gfx, int width, int height) {
  assert(gfx);
  const sgPixel colour = (sgPixel){255, 0, 255, 255};
  for (int y = 0; y < height; ++y) {
    for (int x = 0; x < width; ++x) {
      if (((x ^ y) & 1) == 1) {
        const sgVec2i position = (sgVec2i){x, y};
        sgPixels(gfx, 1, &position, colour);
      }
    }
  }
}

static void TestTriangle(swgfx* gfx) {
  assert(gfx);
  
  const int     BufferWidth  = 160;
  const int     BufferHeight = 120;
  const int     N            = BufferWidth * BufferHeight;
  const sgVec2i BufferDims   = (sgVec2i){.x = BufferWidth, .y = BufferHeight};
  
  sgPixel colour[N];
  RGB     rgb[N];
  
  sgColourBuffer(gfx, BufferDims, colour);
  sgClear(gfx);
  Checkerboard(gfx, BufferWidth, BufferHeight);
  
  const sgVec2 p0  = (sgVec2){20, 20};
  const sgVec2 p1  = (sgVec2){80, 20};
  const sgVec2 p2  = (sgVec2){50, 50};
  const sgTri2 tri = (sgTri2){p0, p1, p2};
  sgTriangles2(gfx, 1, &tri);
  
  ToRGB(BufferWidth, BufferHeight, colour, rgb);
  WritePPM(BufferWidth, BufferHeight, rgb, "triangle.ppm");
  // TODO: Assert the contents. Turn this file into a unit test executable.
  //  Write a helper function that first writes the image to a file and then
  //  asserts its contents.
}

#define GFX_TEST(NAME, FUNC) \
  TEST_CASE(NAME) {\
    swgfx* gfx = nullptr;\
    if (!(gfx = sgNew())) {\
      SET_FAILURE("Failed to create swgfx\n", false);\
    }\
    FUNC(gfx);\
    sgDel(&gfx);\
  }

GFX_TEST(triangle, TestTriangle)

int main() { return 0; }