summaryrefslogtreecommitdiff
path: root/test.c
blob: 32f0474fd3c29abab167ab6b94a9cadda6c830d1 (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
94
95
96
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include "lodepng.h"
#include "gb.h"

#define NUM_FRAMES 600

static uint32_t
file_size(
  const char * const path
) {
  struct stat st;

  if (stat(path, &st)) {
    perror("stat():");
    exit(EXIT_FAILURE);
  }

  return st.st_size;
}

static const uint8_t *
load(
  const char * const path,
  uint32_t * const r_file_size
) {
  const uint32_t rom_size = file_size(path);
  uint8_t *rom_data = malloc(rom_size);
  if (!rom_data) {
    perror("malloc():");
    exit(EXIT_FAILURE);
  }

  FILE *fh = fopen(path, "rb");
  if (!fh) {
    perror("fopen():");
    exit(EXIT_FAILURE);
  }

  if (!fread(rom_data, rom_size, 1, fh)) {
    perror("fread():");
    exit(EXIT_FAILURE);
  }

  fclose(fh);

  if (r_file_size) {
    *r_file_size = (uint32_t) rom_size;
  }
  
  return rom_data;
}

// buffer for rendered frames
static uint8_t frames[NUM_FRAMES * GB_FRAME_SIZE];

int main(int argc, char *argv[]) {
  for (int i = 1; i < argc; i++) {
    uint32_t rom_size = 0;
    const uint8_t *rom_data = load(argv[i], &rom_size);
    fprintf(stderr, "loaded \"%s\" (%u bytes)\n", argv[i], rom_size);

    gb_t ctx;
    gb_init(&ctx, rom_data, rom_size);
    fprintf(stderr, "gb context initialized\n");

    // render several frames
    for (size_t j = 0; j < NUM_FRAMES; j++) {
      // render frame
      gb_frame(&ctx);

      // copy frame to buffer
      memcpy(frames + GB_FRAME_SIZE * j, gb_get_rgb_frame(&ctx), GB_FRAME_SIZE);
    }

    // save png
    if (lodepng_encode24_file("out.png", frames, 160, 144 * NUM_FRAMES)) {
      fprintf(stderr, "lode_png_encode24_file() failed\n");
      return EXIT_FAILURE;
    }

    fprintf(stderr, "%d frames rendered\n", NUM_FRAMES);

    // free rom data
    free((void*) rom_data);
  }

  // return success
  return 0;
}