summaryrefslogtreecommitdiff
path: root/main.c
blob: a3b9539218a619e43e8123669121d4f4bd9a7d63 (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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>

#include "chip8.h"

/* references
 * https://austinmorlan.com/posts/chip8_emulator/
 * http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter/
 * http://mattmik.com/files/chip8/mastering/chip8.html (lots of info)
 * http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#0.1
 */

#define VIDEO_SCALE 10

SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *texture;

void init_video();
void update_video();
void toggle_pixel(int x, int y);
void quit();
void usage(char *);

extern uint32_t video[WIDTH*HEIGHT];

void
usage(char *program)
{
	printf("usage: %s [romfile]\n", program);
}

void
quit()
{
	SDL_DestroyTexture(texture);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	SDL_Quit();

}

void
init_video()
{
	SDL_Init(SDL_INIT_VIDEO);
	window = SDL_CreateWindow("chip8 interpreter", 0, 0, WIDTH*VIDEO_SCALE, HEIGHT*VIDEO_SCALE, SDL_WINDOW_SHOWN);
	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
	texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STREAMING, WIDTH, HEIGHT);
}

void
update_video()
{
	static int count = 0;
	printf("frame %d\n", count++);
	/*
	for (uint32_t i = 0 ;i < WIDTH*HEIGHT; i++)
	{

		video[i] = (255<<16)|(255<<8)|255;
	}
	video[0] = (255);
	video[1] = (255<<8);
	video[2] = (255<<16);
	*/

	toggle_pixel(0, 0);
	SDL_UpdateTexture(texture, NULL, video, sizeof(video[0])*WIDTH);
	SDL_RenderClear(renderer);
	SDL_RenderCopy(renderer, texture, NULL, NULL);
	SDL_RenderPresent(renderer);
}

void
toggle_pixel(int x, int y)
{
	// TODO: clean
	uint32_t dos = video[WIDTH*y+x];
	if (dos <= 0)
		video[WIDTH*y+x] = (255<<16)|(255<<8)|255;
	else
		video[WIDTH*y+x] = 0;
}

int main(int argc, char *argv[])
{
	if (argc < 2)
	{
		usage(argv[0]);
		exit(EXIT_FAILURE);
	}

	if (!load_rom(argv[1]))
	{
		fprintf(stderr, "cannot start interpreter\n");
		exit(EXIT_FAILURE);
	}

	chip8_init();

	init_video();

	const int fps = 60;
	const int frame_delay = 1000/fps;
	uint32_t  frame_start;
	uint32_t frame_time;
	int do_quit = 0;
	while(!do_quit)
	{
		frame_start = SDL_GetTicks();

		// logic
		update_video();

		frame_time = SDL_GetTicks() - frame_start;
		if (frame_delay > frame_time)
		{
			SDL_Delay(frame_delay - frame_time);
		}
	}

	quit();
	return EXIT_SUCCESS;
}