use tabs over spaces

This commit is contained in:
2025-06-18 15:48:56 +02:00
parent 3b306288e9
commit b446a43738
19 changed files with 599 additions and 605 deletions

View File

@@ -6,7 +6,7 @@ BasedOnStyle: '' # (LLVM,Google,Chromium,Mozilla,Web
Standard: Auto # automatically detect the language version Standard: Auto # automatically detect the language version
ColumnLimit: 0 # 0: disable column limit ColumnLimit: 0 # 0: disable column limit
LineEnding: LF # use LF line endings LineEnding: LF # use LF line endings
UseTab: Never # (Never,ForIndentation,ForContinuationAndIndentation,Always) UseTab: ForContinuationAndIndentation # (Never,ForIndentation,ForContinuationAndIndentation,Always)
TabWidth: 4 # recommended to set this equal to IndentWidth TabWidth: 4 # recommended to set this equal to IndentWidth
IndentWidth: 4 # how wide each indent is IndentWidth: 4 # how wide each indent is
ContinuationIndentWidth: 4 # width for a line continuation ContinuationIndentWidth: 4 # width for a line continuation

View File

@@ -1,22 +1,16 @@
root = true
[*] [*]
charset = utf-8 charset = utf-8
end_of_line = lf end_of_line = lf
insert_final_newline = true insert_final_newline = true
trim_trailing_whitespace = true trim_trailing_whitespace = true
[*.{rs}]
indent_style = space
indent_size = 4
[*.{c,h,cpp,hpp}] [*.{c,h,cpp,hpp}]
indent_style = space indent_style = tab
indent_size = 4 indent_size = tab
[makefile] [makefile]
indent_style = tab indent_style = tab
indent_size = 2 indent_size = tab
[*.{yaml,json}] [*.{yaml,json}]
indent_style = space indent_style = space

View File

@@ -6,27 +6,27 @@
/* defines statuses in the 0..127, any higher/negative values are POSIX-reserved. /* defines statuses in the 0..127, any higher/negative values are POSIX-reserved.
* The max value (or -1) shall mean the application is running, anything else shall mean an exit code of some kind */ * The max value (or -1) shall mean the application is running, anything else shall mean an exit code of some kind */
enum gamestatus { enum gamestatus {
// clang-format off // clang-format off
STATUS_SUCCESS = 0, // 0; successful exit STATUS_SUCCESS = 0, // 0; successful exit
STATUS_ERROR = 1, // miscellaneous error STATUS_ERROR = 1, // miscellaneous error
ERROR_INIT = STATUS_ERROR | 2, // initialisation error ERROR_INIT = STATUS_ERROR | 2, // initialisation error
ERROR_STD = STATUS_ERROR | 64, // standard library error ERROR_STD = STATUS_ERROR | 64, // standard library error
ERROR_STD_INIT = ERROR_INIT | 64, // standard library initialisation error ERROR_STD_INIT = ERROR_INIT | 64, // standard library initialisation error
ERROR_STD_MEMORY = ERROR_STD | 32, // memory error ERROR_STD_MEMORY = ERROR_STD | 32, // memory error
ERROR_STD_MEMORY_INIT = ERROR_STD_INIT | 32, // memory initialization error ERROR_STD_MEMORY_INIT = ERROR_STD_INIT | 32, // memory initialization error
ERROR_SDL = STATUS_ERROR | 32, // SDL error ERROR_SDL = STATUS_ERROR | 32, // SDL error
ERROR_SDL_INIT = ERROR_INIT | 32, // SDL initialization error ERROR_SDL_INIT = ERROR_INIT | 32, // SDL initialization error
ERROR_SDL_RENDERING = ERROR_SDL | 16, // rendering error ERROR_SDL_RENDERING = ERROR_SDL | 16, // rendering error
ERROR_SDL_RENDERING_INIT = ERROR_SDL_INIT | 16, // rendering initialization error ERROR_SDL_RENDERING_INIT = ERROR_SDL_INIT | 16, // rendering initialization error
ERROR_SDL_AUDIO = ERROR_SDL | 8, // audio error ERROR_SDL_AUDIO = ERROR_SDL | 8, // audio error
ERROR_SDL_AUDIO_INIT = ERROR_SDL_INIT | 8, // audio initialization error ERROR_SDL_AUDIO_INIT = ERROR_SDL_INIT | 8, // audio initialization error
ERROR_SDL_FONT = ERROR_SDL | 4, // font error ERROR_SDL_FONT = ERROR_SDL | 4, // font error
ERROR_SDL_FONT_INIT = ERROR_SDL_INIT | 4, // font initialization error ERROR_SDL_FONT_INIT = ERROR_SDL_INIT | 4, // font initialization error
STATUS_RUNNING = -1, STATUS_RUNNING = -1,
// clang-format on // clang-format on
}; };
#if __INCLUDE_LEVEL__ > 0 #if __INCLUDE_LEVEL__ > 0
@@ -43,8 +43,8 @@ enum gamestatus {
#define error(s, ...) fprintf(stderr, "\033[91m" __FILE__ ":" MACRO_STR2(__LINE__) ": [ERR]: " s "\033[0m\n" __VA_OPT__(, __VA_ARGS__)) #define error(s, ...) fprintf(stderr, "\033[91m" __FILE__ ":" MACRO_STR2(__LINE__) ": [ERR]: " s "\033[0m\n" __VA_OPT__(, __VA_ARGS__))
#define fatal(c, s, ...) \ #define fatal(c, s, ...) \
do { \ do { \
printf("\033[101m" __FILE__ ":" MACRO_STR2(__LINE__) ": [FAT]: " s "\033[0m\n" __VA_OPT__(, __VA_ARGS__)); \ printf("\033[101m" __FILE__ ":" MACRO_STR2(__LINE__) ": [FAT]: " s "\033[0m\n" __VA_OPT__(, __VA_ARGS__)); \
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "something went wrong! :O", "view stderr for full details: \n" s, NULL); \ SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "something went wrong! :O", "view stderr for full details: \n" s, NULL); \
exit(c); \ exit(c); \
} while (0) } while (0)

View File

@@ -15,138 +15,138 @@
/* shuffle the array using a FisherYates shuffle */ /* shuffle the array using a FisherYates shuffle */
static inline void shuffle(uint8_t const size, shape_id* const elmnts) { static inline void shuffle(uint8_t const size, shape_id* const elmnts) {
for (uint8_t i = 0; i < (size - 1); i++) { for (uint8_t i = 0; i < (size - 1); i++) {
uint8_t const j = i + rand() % (size - i); uint8_t const j = i + rand() % (size - i);
shape_id const cache = elmnts[i]; shape_id const cache = elmnts[i];
elmnts[i] = elmnts[j]; elmnts[i] = elmnts[j];
elmnts[j] = cache; elmnts[j] = cache;
} }
} }
void next_shape(gamedata* const dat) { void next_shape(gamedata* const dat) {
dat->curr_idx++; // increase the current shape index dat->curr_idx++; // increase the current shape index
dat->sel_x = COLUMNS / 2 - SHAPE_WIDTH / 2; // move the shape position to the centre dat->sel_x = COLUMNS / 2 - SHAPE_WIDTH / 2; // move the shape position to the centre
dat->sel_y = 0; dat->sel_y = 0;
// return if know which shape is next // return if know which shape is next
if (dat->curr_idx < (TETROMINO_COUNT - 1)) if (dat->curr_idx < (TETROMINO_COUNT - 1))
return; return;
dat->curr_idx = 0; dat->curr_idx = 0;
shuffle(TETROMINO_COUNT - 1, dat->nxt); shuffle(TETROMINO_COUNT - 1, dat->nxt);
shape_id cache = dat->nxt[0]; shape_id cache = dat->nxt[0];
dat->nxt[0] = dat->nxt[TETROMINO_COUNT - 1]; dat->nxt[0] = dat->nxt[TETROMINO_COUNT - 1];
dat->nxt[TETROMINO_COUNT - 1] = cache; dat->nxt[TETROMINO_COUNT - 1] = cache;
} }
void game_init(gamedata* const dat) { void game_init(gamedata* const dat) {
// set a random seed using the system clock // set a random seed using the system clock
srand(time(NULL)); srand(time(NULL));
struct gametime gt = {{0}, 0}; struct gametime gt = {{0}, 0};
gametime_get(&gt.ts); gametime_get(&gt.ts);
// initialize audio device // initialize audio device
audiodevice* ad = audio_device_init(32000, AUDIO_S16, 1, 4096); audiodevice* ad = audio_device_init(32000, AUDIO_S16, 1, 4096);
*dat = (gamedata){ *dat = (gamedata){
{0}, // rowdat {0}, // rowdat
{0}, // row {0}, // row
gt, // time gt, // time
ad, // audio_device ad, // audio_device
audio_wav_load(ad, "korobeiniki.wav"), // music audio_wav_load(ad, "korobeiniki.wav"), // music
audio_wav_load(ad, "place.wav"), // place_sfx audio_wav_load(ad, "place.wav"), // place_sfx
0, // score 0, // score
{0}, // nxt {0}, // nxt
0, // curr_idx 0, // curr_idx
0, // sel_x 0, // sel_x
0, // sel_y 0, // sel_y
true, // run true, // run
}; };
// initialize the rows within the game data // initialize the rows within the game data
for (int8_t i = 0; i < ROWS; i++) { for (int8_t i = 0; i < ROWS; i++) {
dat->rows[i] = dat->rowdat + (i * COLUMNS); dat->rows[i] = dat->rowdat + (i * COLUMNS);
} }
// set the shape data in each slot to it's corrsponding ID // set the shape data in each slot to it's corrsponding ID
for (shape_id i = 0; i < TETROMINO_COUNT; i++) for (shape_id i = 0; i < TETROMINO_COUNT; i++)
dat->nxt[i] = i; dat->nxt[i] = i;
dat->curr_idx = -1; // set the current index to the max so it becomes zero after increasement dat->curr_idx = -1; // set the current index to the max so it becomes zero after increasement
next_shape(dat); // select the next shape (shuffle should not be triggered) next_shape(dat); // select the next shape (shuffle should not be triggered)
shuffle(TETROMINO_COUNT, dat->nxt); // manually trigger a shuffle shuffle(TETROMINO_COUNT, dat->nxt); // manually trigger a shuffle
} }
// updates the gametime // updates the gametime
static inline void update_gametime(gamedata* dat) { static inline void update_gametime(gamedata* dat) {
struct timespec ts; struct timespec ts;
gametime_get(&ts); gametime_get(&ts);
dat->time.ms = ts.tv_sec * 1000 + ts.tv_nsec / 1000000; dat->time.ms = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
dat->time.ts = ts; dat->time.ts = ts;
} }
// called every time the game's state is updated // called every time the game's state is updated
void game_update(gamedata* const dat) { void game_update(gamedata* const dat) {
static time_t timer_update = 0; static time_t timer_update = 0;
static time_t timer_music = 0; static time_t timer_music = 0;
static time_t timer_move = 0; static time_t timer_move = 0;
static time_t timer_rot = 0; static time_t timer_rot = 0;
update_gametime(dat); update_gametime(dat);
uint8_t const* keys = SDL_GetKeyboardState(NULL); uint8_t const* keys = SDL_GetKeyboardState(NULL);
if (keys[SDL_SCANCODE_ESCAPE]) if (keys[SDL_SCANCODE_ESCAPE])
dat->run = false; dat->run = false;
input_data move = MOVE_NONE; // contains the move data input_data move = MOVE_NONE; // contains the move data
time_t ctime = dat->time.ms; time_t ctime = dat->time.ms;
if (ctime > timer_update) { if (ctime > timer_update) {
timer_update = ctime + 500; timer_update = ctime + 500;
move |= MOVE_DOWN; move |= MOVE_DOWN;
} }
if (ctime > timer_music) { if (ctime > timer_music) {
timer_music = ctime + (dat->music.ms); timer_music = ctime + (dat->music.ms);
audio_play(dat->audio_device, &dat->music); audio_play(dat->audio_device, &dat->music);
} }
// for rotation updating // for rotation updating
if (ctime > timer_rot) { if (ctime > timer_rot) {
input_data urot = MOVE_NONE; input_data urot = MOVE_NONE;
if (keys[SDL_SCANCODE_Q]) urot |= MOVE_ROTLEFT; if (keys[SDL_SCANCODE_Q]) urot |= MOVE_ROTLEFT;
if (keys[SDL_SCANCODE_E]) urot |= MOVE_ROTRIGHT; if (keys[SDL_SCANCODE_E]) urot |= MOVE_ROTRIGHT;
if (urot != MOVE_NONE) { if (urot != MOVE_NONE) {
timer_rot = ctime + 100; timer_rot = ctime + 100;
move |= urot; move |= urot;
} }
} }
// for movement updating // for movement updating
if (ctime > timer_move) { if (ctime > timer_move) {
input_data umove = MOVE_NONE; input_data umove = MOVE_NONE;
if (keys[SDL_SCANCODE_LEFT] || keys[SDL_SCANCODE_A]) umove |= MOVE_LEFT; if (keys[SDL_SCANCODE_LEFT] || keys[SDL_SCANCODE_A]) umove |= MOVE_LEFT;
if (keys[SDL_SCANCODE_RIGHT] || keys[SDL_SCANCODE_D]) umove |= MOVE_RIGHT; if (keys[SDL_SCANCODE_RIGHT] || keys[SDL_SCANCODE_D]) umove |= MOVE_RIGHT;
if (keys[SDL_SCANCODE_DOWN] || keys[SDL_SCANCODE_S] || keys[SDL_SCANCODE_SPACE]) umove |= MOVE_DOWN; if (keys[SDL_SCANCODE_DOWN] || keys[SDL_SCANCODE_S] || keys[SDL_SCANCODE_SPACE]) umove |= MOVE_DOWN;
if (umove != MOVE_NONE) { if (umove != MOVE_NONE) {
timer_move = ctime + 20; timer_move = ctime + 20;
move |= umove; move |= umove;
} }
} }
// update the block position // update the block position
if (move != MOVE_NONE) if (move != MOVE_NONE)
place_update(dat, move); place_update(dat, move);
} }
void game_free(gamedata* const dat) { void game_free(gamedata* const dat) {
audio_wav_unload(&dat->music); audio_wav_unload(&dat->music);
audio_wav_unload(&dat->place_sfx); audio_wav_unload(&dat->place_sfx);
audio_device_free(dat->audio_device); audio_device_free(dat->audio_device);
// zero-out the rest of the data // zero-out the rest of the data
*dat = (gamedata){0}; *dat = (gamedata){0};
} }

View File

@@ -22,18 +22,18 @@ typedef colour8 const* const row_const;
typedef colour8* row; typedef colour8* row;
typedef struct { typedef struct {
colour8 rowdat[ROWS * COLUMNS]; colour8 rowdat[ROWS * COLUMNS];
colour8* rows[ROWS]; colour8* rows[ROWS];
struct gametime time; struct gametime time;
audiodevice* audio_device; audiodevice* audio_device;
audiodata music; audiodata music;
audiodata place_sfx; audiodata place_sfx;
uint16_t score; uint16_t score;
shape_id nxt[7]; // the order of the shape ids that they should appear in shape_id nxt[7]; // the order of the shape ids that they should appear in
uint8_t curr_idx; // current shape index uint8_t curr_idx; // current shape index
int8_t sel_x; // selected shape x position int8_t sel_x; // selected shape x position
int8_t sel_y; // selected shape y position int8_t sel_y; // selected shape y position
bool run; bool run;
} gamedata; } gamedata;
void next_shape(gamedata*); // initializes everything needed to start the game; outputs to gamedata void next_shape(gamedata*); // initializes everything needed to start the game; outputs to gamedata

View File

@@ -2,8 +2,8 @@
#include <time.h> #include <time.h>
struct gametime { struct gametime {
struct timespec ts; struct timespec ts;
time_t ms; time_t ms;
}; };
#if __has_include(<features.h>) #if __has_include(<features.h>)
@@ -12,17 +12,17 @@ struct gametime {
#if __has_include(<features.h>) && _POSIX_C_SOURCE >= 199309L #if __has_include(<features.h>) && _POSIX_C_SOURCE >= 199309L
#include <bits/time.h> #include <bits/time.h>
static inline void gametime_get(struct timespec* ts) { static inline void gametime_get(struct timespec* ts) {
clock_gettime(CLOCK_MONOTONIC, ts); clock_gettime(CLOCK_MONOTONIC, ts);
} }
#elif defined(_WIN32) #elif defined(_WIN32)
#include <profileapi.h> #include <profileapi.h>
#include <windows.h> #include <windows.h>
#include <winnt.h> #include <winnt.h>
static inline void gametime_get(struct timespec* ts) { static inline void gametime_get(struct timespec* ts) {
LARGE_INTEGER cnt, frq; LARGE_INTEGER cnt, frq;
QueryPerformanceCounter(&cnt); QueryPerformanceCounter(&cnt);
QueryPerformanceFrequency(&frq); QueryPerformanceFrequency(&frq);
ts->tv_sec = (time_t)(cnt.QuadPart / frq.QuadPart); ts->tv_sec = (time_t)(cnt.QuadPart / frq.QuadPart);
ts->tv_nsec = (time_t)((cnt.QuadPart % frq.QuadPart) * 1000000000 / frq.QuadPart); ts->tv_nsec = (time_t)((cnt.QuadPart % frq.QuadPart) * 1000000000 / frq.QuadPart);
} }
#endif #endif

View File

@@ -13,56 +13,56 @@ char const* restrict path_place_sfx = NULL;
// gets the game's data path, returns 0 on failure, otherwise the datapath's string length // gets the game's data path, returns 0 on failure, otherwise the datapath's string length
static unsigned getdatpath(void) { static unsigned getdatpath(void) {
char const* home = getenv(unixonly("HOME") winonly("APPDATA")); // get the user data directory path (appropriated for each platform) char const* home = getenv(unixonly("HOME") winonly("APPDATA")); // get the user data directory path (appropriated for each platform)
if (!home) home = "."; // if this failed, set the path to `.`, which represents cwd if (!home) home = "."; // if this failed, set the path to `.`, which represents cwd
unsigned len = strlen(home); unsigned len = strlen(home);
len += 1 + 20 unixonly(+13); // add 21 bytes to the home length, to account for adding .local/share later len += 1 + 20 unixonly(+13); // add 21 bytes to the home length, to account for adding .local/share later
char* datpath = malloc(len); char* datpath = malloc(len);
if (!datpath) return 0; if (!datpath) return 0;
// copy the data from home into the datapath // copy the data from home into the datapath
strcpy(datpath, home); strcpy(datpath, home);
#ifdef __unix__ #ifdef __unix__
// include the .local/share directory, if the HOME environment variable was valid // include the .local/share directory, if the HOME environment variable was valid
if (home[0] != '.') strcat(datpath, "/.local/share"); if (home[0] != '.') strcat(datpath, "/.local/share");
else { else {
// if the HOME directory wasn't defined, shrink the string // if the HOME directory wasn't defined, shrink the string
len -= 13; len -= 13;
void* ptr = realloc(datpath, len); void* ptr = realloc(datpath, len);
if (ptr) datpath = ptr; // likely doesn't actually change the pointer, but just to be sure if (ptr) datpath = ptr; // likely doesn't actually change the pointer, but just to be sure
} }
#endif #endif
strcat(datpath, PATH_SEP_STR "quinns_tetris_clone"); strcat(datpath, PATH_SEP_STR "quinns_tetris_clone");
path_dat = datpath; path_dat = datpath;
return len; return len;
} }
static inline char const* init_path(char const* restrict const str, unsigned len) { static inline char const* init_path(char const* restrict const str, unsigned len) {
void* ptr = malloc(len); void* ptr = malloc(len);
if (!ptr) return NULL; if (!ptr) return NULL;
strcpy(ptr, path_dat); strcpy(ptr, path_dat);
strcat(ptr, str); strcat(ptr, str);
return ptr; return ptr;
} }
int paths_init(void) { int paths_init(void) {
unsigned len = getdatpath(); unsigned len = getdatpath();
if (!len) return 1; if (!len) return 1;
// these are explicitly static, as string literals just work like that // these are explicitly static, as string literals just work like that
path_opts = init_path("/opts.cfg", len + 9); // TODO: shouldn't opts be stored at .config/? path_opts = init_path("/opts.cfg", len + 9); // TODO: shouldn't opts be stored at .config/?
path_font = init_path("/pixeldroid_botic-regular.ttf", len + 29); // TODO: these three paths should not be stored like opts path_font = init_path("/pixeldroid_botic-regular.ttf", len + 29); // TODO: these three paths should not be stored like opts
path_music = init_path("/korobeiniki.wav", len + 16); path_music = init_path("/korobeiniki.wav", len + 16);
path_place_sfx = init_path("place.wav", len + 10); path_place_sfx = init_path("place.wav", len + 10);
return -(!path_opts || !path_font || !path_music || !path_place_sfx); return -(!path_opts || !path_font || !path_music || !path_place_sfx);
} }
void paths_free(void) { void paths_free(void) {
free((void*)path_dat), path_dat = NULL; free((void*)path_dat), path_dat = NULL;
free((void*)path_opts), path_opts = NULL; free((void*)path_opts), path_opts = NULL;
free((void*)path_music), path_music = NULL; free((void*)path_music), path_music = NULL;
free((void*)path_place_sfx), path_place_sfx = NULL; free((void*)path_place_sfx), path_place_sfx = NULL;
} }

View File

@@ -9,136 +9,136 @@
static int is_filled(row_const const row) { static int is_filled(row_const const row) {
for (int8_t x = 0; x < COLUMNS; x++) { for (int8_t x = 0; x < COLUMNS; x++) {
if (row[x] == 0) { if (row[x] == 0) {
return 0; return 0;
} }
} }
return 1; return 1;
} }
static void clear_rows(row* const rows, uint16_t* const score) { static void clear_rows(row* const rows, uint16_t* const score) {
row cache[4] = {0}; // you can only clear four rows at a time row cache[4] = {0}; // you can only clear four rows at a time
unsigned filled = 0; unsigned filled = 0;
unsigned checked = 0; unsigned checked = 0;
// loop through each row (excluding the empty rows at the top when clearing a line) // loop through each row (excluding the empty rows at the top when clearing a line)
for (unsigned y = 0; y < (ROWS - filled); y++) { for (unsigned y = 0; y < (ROWS - filled); y++) {
int const i = (ROWS - 1) - y; // get the index starting from the bottom int const i = (ROWS - 1) - y; // get the index starting from the bottom
rows[i] = rows[i - filled]; // set the row to the new or same address rows[i] = rows[i - filled]; // set the row to the new or same address
// continue if the line isn't filled or the max amount has been reached // continue if the line isn't filled or the max amount has been reached
if (checked >= 4 || !is_filled(rows[i])) { if (checked >= 4 || !is_filled(rows[i])) {
if (filled > 0 && checked < 4) checked++; if (filled > 0 && checked < 4) checked++;
continue; // continue to the next line continue; // continue to the next line
} }
cache[filled] = rows[i]; // cache the current row address cache[filled] = rows[i]; // cache the current row address
filled++; // increase filled, and keep the row in the cache filled++; // increase filled, and keep the row in the cache
checked++; // increase the checked count checked++; // increase the checked count
y--; // decrease y to check this line again y--; // decrease y to check this line again
} }
if (filled == 0) return; if (filled == 0) return;
*score += 8 << filled; *score += 8 << filled;
// do while, as we already know that entering the loop that filled is non-zero // do while, as we already know that entering the loop that filled is non-zero
do { do {
filled--; filled--;
rows[filled] = cache[filled]; rows[filled] = cache[filled];
// zero out the filled row // zero out the filled row
for (unsigned x = 0; x < COLUMNS; x++) for (unsigned x = 0; x < COLUMNS; x++)
cache[filled][x] = 0; cache[filled][x] = 0;
} while (filled > 0); } while (filled > 0);
} }
// sets a shape to the screen // sets a shape to the screen
static void set_shape_i(row const* const row, shape_id const id, int8_t const pos_x) { static void set_shape_i(row const* const row, shape_id const id, int8_t const pos_x) {
shape const shape = shape_from_id(id); shape const shape = shape_from_id(id);
colour8 const colour = colour_from_id(id); colour8 const colour = colour_from_id(id);
for (int8_t y = 0; y < SHAPE_HEIGHT; y++) { for (int8_t y = 0; y < SHAPE_HEIGHT; y++) {
shape_row const shape_row = shape_get_row(shape, y); shape_row const shape_row = shape_get_row(shape, y);
if (shape_row == 0) if (shape_row == 0)
continue; continue;
for (int8_t x = 0; x < SHAPE_WIDTH; x++) for (int8_t x = 0; x < SHAPE_WIDTH; x++)
if (shape_is_set(shape_row, x)) if (shape_is_set(shape_row, x))
row[y][x + pos_x] = colour; row[y][x + pos_x] = colour;
} }
} }
static inline void set_shape(row const* const row, shape_id const id, int8_t const pos_x, int8_t const pos_y) { static inline void set_shape(row const* const row, shape_id const id, int8_t const pos_x, int8_t const pos_y) {
set_shape_i(&row[pos_y], id, pos_x); // calls itself, but omitting the pos_y argument, instead opting for specifying the row set_shape_i(&row[pos_y], id, pos_x); // calls itself, but omitting the pos_y argument, instead opting for specifying the row
} }
static int shape_intersects(row const* const rows, shape_id const id, int8_t const x, int8_t const y) { static int shape_intersects(row const* const rows, shape_id const id, int8_t const x, int8_t const y) {
shape const shape = shape_from_id(id); shape const shape = shape_from_id(id);
for (int y0 = 0; y0 < SHAPE_HEIGHT; y0++) { for (int y0 = 0; y0 < SHAPE_HEIGHT; y0++) {
shape_row const shape_row = shape_get_row(shape, y0); // get the shape row shape_row const shape_row = shape_get_row(shape, y0); // get the shape row
if (shape_row == 0) continue; // if the row doesn't contain data; continue if (shape_row == 0) continue; // if the row doesn't contain data; continue
for (int x0 = 0; x0 < SHAPE_WIDTH; x0++) { for (int x0 = 0; x0 < SHAPE_WIDTH; x0++) {
if (shape_is_set(shape_row, x0) == false) continue; // if the bit isn't set at this index; continue if (shape_is_set(shape_row, x0) == false) continue; // if the bit isn't set at this index; continue
int const x1 = x + x0; int const x1 = x + x0;
int const y1 = y + y0; int const y1 = y + y0;
if (x1 < 0 || x1 >= COLUMNS) return 1; // if X is out of bounds if (x1 < 0 || x1 >= COLUMNS) return 1; // if X is out of bounds
if (y1 < 0 || y1 >= ROWS) return 1; // if Y is out of bounds if (y1 < 0 || y1 >= ROWS) return 1; // if Y is out of bounds
if (rows[y1][x1] != 0) return 1; // if there is a block here if (rows[y1][x1] != 0) return 1; // if there is a block here
} }
} }
return 0; return 0;
} }
static inline shape_id rotate_id(shape_id const id, int const dir) { static inline shape_id rotate_id(shape_id const id, int const dir) {
return (id + dir) & 31; return (id + dir) & 31;
} }
void place_update(gamedata* const game_data, input_data const move) { void place_update(gamedata* const game_data, input_data const move) {
// store the current index and ID, only changes when placed (which yields no movement) and rotation (which occurs last) // store the current index and ID, only changes when placed (which yields no movement) and rotation (which occurs last)
uint8_t const curr_idx = game_data->curr_idx; uint8_t const curr_idx = game_data->curr_idx;
shape_id const curr_id = game_data->nxt[curr_idx]; shape_id const curr_id = game_data->nxt[curr_idx];
// set the shape if we moved vertically and intersected // set the shape if we moved vertically and intersected
if (move & 4) { if (move & 4) {
int8_t const y = game_data->sel_y + 1; int8_t const y = game_data->sel_y + 1;
if (shape_intersects(game_data->rows, curr_id, game_data->sel_x, y)) { if (shape_intersects(game_data->rows, curr_id, game_data->sel_x, y)) {
set_shape(game_data->rows, curr_id, game_data->sel_x, game_data->sel_y); // if the shape intersects vertically, write the shape at the current position and return set_shape(game_data->rows, curr_id, game_data->sel_x, game_data->sel_y); // if the shape intersects vertically, write the shape at the current position and return
clear_rows(game_data->rows, &game_data->score); // clear the rows that have been completed clear_rows(game_data->rows, &game_data->score); // clear the rows that have been completed
audio_play(game_data->audio_device, &game_data->place_sfx); audio_play(game_data->audio_device, &game_data->place_sfx);
next_shape(game_data); next_shape(game_data);
if (shape_intersects(game_data->rows, game_data->curr_idx, game_data->sel_x, game_data->sel_y)) if (shape_intersects(game_data->rows, game_data->curr_idx, game_data->sel_x, game_data->sel_y))
game_data->run = false; game_data->run = false;
return; return;
} }
// otherwise, just set Y // otherwise, just set Y
game_data->sel_y = y; game_data->sel_y = y;
} }
// update shape's X coordinate movement // update shape's X coordinate movement
if ((move & 3) != 3 && (move & 3)) { if ((move & 3) != 3 && (move & 3)) {
int8_t const x = game_data->sel_x + ((move & 3) == 1 ? -1 : 1); // either move along -x or +x int8_t const x = game_data->sel_x + ((move & 3) == 1 ? -1 : 1); // either move along -x or +x
if (shape_intersects(game_data->rows, curr_id, x, game_data->sel_y) == false) { if (shape_intersects(game_data->rows, curr_id, x, game_data->sel_y) == false) {
game_data->sel_x = x; // set X if the shape does not intersect game_data->sel_x = x; // set X if the shape does not intersect
} }
} }
// update the shape's rotation // update the shape's rotation
if (move & 8 || move & 16) { if (move & 8 || move & 16) {
shape_id const id = move & 8 // check which direction we should move shape_id const id = move & 8 // check which direction we should move
? rotate_id(curr_id, -8) ? rotate_id(curr_id, -8)
: rotate_id(curr_id, 8); : rotate_id(curr_id, 8);
if (shape_intersects(game_data->rows, id, game_data->sel_x, game_data->sel_y) == false) { if (shape_intersects(game_data->rows, id, game_data->sel_x, game_data->sel_y) == false) {
game_data->nxt[curr_idx] = id; game_data->nxt[curr_idx] = id;
} }
} }
} }

View File

@@ -7,12 +7,12 @@
typedef uint8_t input_data; typedef uint8_t input_data;
enum { enum {
MOVE_NONE = 0, MOVE_NONE = 0,
MOVE_LEFT = 1, MOVE_LEFT = 1,
MOVE_RIGHT = 2, MOVE_RIGHT = 2,
MOVE_DOWN = 4, MOVE_DOWN = 4,
MOVE_ROTLEFT = 8, MOVE_ROTLEFT = 8,
MOVE_ROTRIGHT = 16, MOVE_ROTRIGHT = 16,
}; };
void place_update(gamedata* game_data, input_data move); void place_update(gamedata* game_data, input_data move);

View File

@@ -36,30 +36,30 @@
#define SHAPE_J_270 ((shape)0x0E20) // 0000 1110 0010 0000 the J tetromino with a 270° rotation #define SHAPE_J_270 ((shape)0x0E20) // 0000 1110 0010 0000 the J tetromino with a 270° rotation
shape shape_from_id(shape_id const id) { shape shape_from_id(shape_id const id) {
static shape const shapes[TETROMINO_COUNT][4] = { static shape const shapes[TETROMINO_COUNT][4] = {
// 0° 90° 180° 170° // 0° 90° 180° 170°
{SHAPE_O, SHAPE_O, SHAPE_O, SHAPE_O }, {SHAPE_O, SHAPE_O, SHAPE_O, SHAPE_O },
{SHAPE_I, SHAPE_I_90, SHAPE_I_180, SHAPE_I_270}, {SHAPE_I, SHAPE_I_90, SHAPE_I_180, SHAPE_I_270},
{SHAPE_S, SHAPE_S_90, SHAPE_S_180, SHAPE_S_270}, {SHAPE_S, SHAPE_S_90, SHAPE_S_180, SHAPE_S_270},
{SHAPE_Z, SHAPE_Z_90, SHAPE_Z_180, SHAPE_Z_270}, {SHAPE_Z, SHAPE_Z_90, SHAPE_Z_180, SHAPE_Z_270},
{SHAPE_T, SHAPE_T_90, SHAPE_T_180, SHAPE_T_270}, {SHAPE_T, SHAPE_T_90, SHAPE_T_180, SHAPE_T_270},
{SHAPE_L, SHAPE_L_90, SHAPE_L_180, SHAPE_L_270}, {SHAPE_L, SHAPE_L_90, SHAPE_L_180, SHAPE_L_270},
{SHAPE_J, SHAPE_J_90, SHAPE_J_180, SHAPE_J_270}, {SHAPE_J, SHAPE_J_90, SHAPE_J_180, SHAPE_J_270},
}; };
// first 3 bits is the shape type, the rest is rotation data // first 3 bits is the shape type, the rest is rotation data
return shapes[id & 7][id >> 3]; return shapes[id & 7][id >> 3];
} }
colour8 colour_from_id(shape_id const id) { colour8 colour_from_id(shape_id const id) {
switch (id & 7) { switch (id & 7) {
case TETROMINO_O: return COLOUR8_YELLOW; case TETROMINO_O: return COLOUR8_YELLOW;
case TETROMINO_I: return COLOUR8_CYAN; case TETROMINO_I: return COLOUR8_CYAN;
case TETROMINO_S: return COLOUR8_GREEN; case TETROMINO_S: return COLOUR8_GREEN;
case TETROMINO_Z: return COLOUR8_RED; case TETROMINO_Z: return COLOUR8_RED;
case TETROMINO_T: return COLOUR8_MAGENTA; case TETROMINO_T: return COLOUR8_MAGENTA;
case TETROMINO_L: return COLOUR8_ORANGE; case TETROMINO_L: return COLOUR8_ORANGE;
case TETROMINO_J: return COLOUR8_BLUE; case TETROMINO_J: return COLOUR8_BLUE;
default: return COLOUR8_BLACK; default: return COLOUR8_BLACK;
} }
} }

View File

@@ -9,16 +9,16 @@ typedef uint8_t shape_row;
typedef uint8_t shape_id; typedef uint8_t shape_id;
enum { enum {
TETROMINO_O = 0, TETROMINO_O = 0,
TETROMINO_I = 1, TETROMINO_I = 1,
TETROMINO_S = 2, TETROMINO_S = 2,
TETROMINO_Z = 3, TETROMINO_Z = 3,
TETROMINO_T = 4, TETROMINO_T = 4,
TETROMINO_L = 5, TETROMINO_L = 5,
TETROMINO_J = 6, TETROMINO_J = 6,
TETROMINO_ROTATED_90 = 8, TETROMINO_ROTATED_90 = 8,
TETROMINO_ROTATED_180 = 16, TETROMINO_ROTATED_180 = 16,
TETROMINO_ROTATED_270 = 24, TETROMINO_ROTATED_270 = 24,
}; };
#define SHAPE_WIDTH 4 #define SHAPE_WIDTH 4
@@ -28,11 +28,11 @@ enum {
static inline shape_row shape_get_row(shape const shape, uint8_t const index) { static inline shape_row shape_get_row(shape const shape, uint8_t const index) {
return shape >> (((SHAPE_HEIGHT - 1) - index) * SHAPE_WIDTH) & 0xF; return shape >> (((SHAPE_HEIGHT - 1) - index) * SHAPE_WIDTH) & 0xF;
} }
static inline bool shape_is_set(shape_row const row, uint8_t const index) { static inline bool shape_is_set(shape_row const row, uint8_t const index) {
return (row >> ((SHAPE_WIDTH - 1) - index) & 1) != 0; return (row >> ((SHAPE_WIDTH - 1) - index) & 1) != 0;
} }
shape shape_from_id(shape_id id); shape shape_from_id(shape_id id);

View File

@@ -11,179 +11,179 @@
#include "../util/compat.h" #include "../util/compat.h"
static void audiomixer(void* const userdata, uint8_t* const stream, int const len) { static void audiomixer(void* const userdata, uint8_t* const stream, int const len) {
memset(stream, 0, len); // clear the playing audio memset(stream, 0, len); // clear the playing audio
audiodevice* const dev = userdata; // retreive the callback data audiodevice* const dev = userdata; // retreive the callback data
// return if dev is null, since it can fail to initialize // return if dev is null, since it can fail to initialize
if (dev == NULL) return; if (dev == NULL) return;
struct audioplayer* prev = NULL; struct audioplayer* prev = NULL;
struct audioplayer* curr = dev->audio_players; struct audioplayer* curr = dev->audio_players;
while (curr != NULL) { while (curr != NULL) {
// if the current audio fragment has reached the end of their data // if the current audio fragment has reached the end of their data
if (curr->len == 0) { if (curr->len == 0) {
struct audioplayer* ncurr = curr->nxt; struct audioplayer* ncurr = curr->nxt;
// free the memory allocated to it and assign the next to to the currently playing // free the memory allocated to it and assign the next to to the currently playing
free(curr); free(curr);
curr = ncurr; curr = ncurr;
// write to the audio device if prev hasn't been set yet // write to the audio device if prev hasn't been set yet
if (prev == NULL) if (prev == NULL)
dev->audio_players = curr; dev->audio_players = curr;
else else
prev->nxt = curr; prev->nxt = curr;
// continue so if curr is now NULL, the loop stops // continue so if curr is now NULL, the loop stops
continue; continue;
} }
// calculate how much of the current audio player we should mix into the stream // calculate how much of the current audio player we should mix into the stream
int const mixlen = SDL_min(curr->len, (unsigned)len); int const mixlen = SDL_min(curr->len, (unsigned)len);
// mix the current buffer into the stream, and update the audio player values accordingly // mix the current buffer into the stream, and update the audio player values accordingly
SDL_MixAudioFormat(stream, curr->buf, dev->fmt, mixlen, SDL_MIX_MAXVOLUME); SDL_MixAudioFormat(stream, curr->buf, dev->fmt, mixlen, SDL_MIX_MAXVOLUME);
curr->buf += mixlen; curr->buf += mixlen;
curr->len -= mixlen; curr->len -= mixlen;
// increment the current node // increment the current node
prev = curr; prev = curr;
curr = curr->nxt; curr = curr->nxt;
} }
} }
// converts the inputted audio to the format of dev // converts the inputted audio to the format of dev
// returns 1 upon failure, 0 upon success. When 1 is returned *bufptr will be freed. Otherwise *bufptr is reallocated // returns 1 upon failure, 0 upon success. When 1 is returned *bufptr will be freed. Otherwise *bufptr is reallocated
static int8_t audio_cvt(audiodevice const* dev, SDL_AudioSpec const* spec, uint8_t** bufptr, unsigned* len) { static int8_t audio_cvt(audiodevice const* dev, SDL_AudioSpec const* spec, uint8_t** bufptr, unsigned* len) {
// init the converter // init the converter
SDL_AudioCVT cvt; SDL_AudioCVT cvt;
if (SDL_BuildAudioCVT(&cvt, spec->format, spec->channels, spec->freq, dev->fmt, dev->channels, dev->freq) < 0) { if (SDL_BuildAudioCVT(&cvt, spec->format, spec->channels, spec->freq, dev->fmt, dev->channels, dev->freq) < 0) {
error("%s:%u could not build the audio converter! SDL Error: %s", __FILE_NAME__, __LINE__, SDL_GetError()); error("%s:%u could not build the audio converter! SDL Error: %s", __FILE_NAME__, __LINE__, SDL_GetError());
free(*bufptr); // free the buffer upon an error, as we won't be using this free(*bufptr); // free the buffer upon an error, as we won't be using this
return 1; return 1;
} else if (!cvt.needed) { // ensure the conversion is necessary } else if (!cvt.needed) { // ensure the conversion is necessary
return 0; return 0;
} }
cvt.len = (*len); // specify the length of the source data buffer in bytes (warn: uint32_t -> int32_t) cvt.len = (*len); // specify the length of the source data buffer in bytes (warn: uint32_t -> int32_t)
cvt.buf = realloc(*bufptr, cvt.len * cvt.len_mult); // grow the inputted buffer for the conversion cvt.buf = realloc(*bufptr, cvt.len * cvt.len_mult); // grow the inputted buffer for the conversion
// ensure the conversion buffer reallocation goes correctly // ensure the conversion buffer reallocation goes correctly
if (cvt.buf == NULL) { if (cvt.buf == NULL) {
error("%s:%u failed to reallocate the audio buffer to the new size of %u bytes!", __FILE_NAME__, __LINE__, cvt.len); error("%s:%u failed to reallocate the audio buffer to the new size of %u bytes!", __FILE_NAME__, __LINE__, cvt.len);
free(*bufptr); // free the inputted pointer, as realloc doesn't clear this address if it fails free(*bufptr); // free the inputted pointer, as realloc doesn't clear this address if it fails
return 1; return 1;
} }
// converts the audio to the new format // converts the audio to the new format
if (SDL_ConvertAudio(&cvt)) { if (SDL_ConvertAudio(&cvt)) {
error("%s:%u something went wrong when loading/converting an audio buffer! SDL Error: %s", __FILE_NAME__, __LINE__, SDL_GetError()); error("%s:%u something went wrong when loading/converting an audio buffer! SDL Error: %s", __FILE_NAME__, __LINE__, SDL_GetError());
free(cvt.buf); // free the conversion buffer if it fails, as realloc moved the data to this adress; old adress is no longer valid free(cvt.buf); // free the conversion buffer if it fails, as realloc moved the data to this adress; old adress is no longer valid
return 1; return 1;
} }
// update output // update output
*len = cvt.len_cvt; // set the length to the new length after the conversion *len = cvt.len_cvt; // set the length to the new length after the conversion
*bufptr = realloc(cvt.buf, cvt.len_cvt); // reallocate the buffer to the new size *bufptr = realloc(cvt.buf, cvt.len_cvt); // reallocate the buffer to the new size
if (*bufptr == NULL) { if (*bufptr == NULL) {
warn("%s:%u something went wrong whilst shrinking the audio buffer whilst converting!", __FILE_NAME__, __LINE__); warn("%s:%u something went wrong whilst shrinking the audio buffer whilst converting!", __FILE_NAME__, __LINE__);
*bufptr = cvt.buf; // use the conversion buffer, as this one will be valid if realloc fails *bufptr = cvt.buf; // use the conversion buffer, as this one will be valid if realloc fails
} }
return 0; return 0;
} }
audiodevice* audio_device_init(int freq, SDL_AudioFormat fmt, uint8_t channels, uint16_t samples) { audiodevice* audio_device_init(int freq, SDL_AudioFormat fmt, uint8_t channels, uint16_t samples) {
audiodevice* dev = malloc(sizeof(audiodevice)); audiodevice* dev = malloc(sizeof(audiodevice));
if (dev == NULL) { if (dev == NULL) {
error("%s:%u null pointer when allocating memory for the audio device!", __FILE_NAME__, __LINE__); error("%s:%u null pointer when allocating memory for the audio device!", __FILE_NAME__, __LINE__);
return NULL; return NULL;
} }
// define the audio specification // define the audio specification
SDL_AudioSpec spec = {freq, fmt, channels, 0, samples, 0, 0, NULL, NULL}; SDL_AudioSpec spec = {freq, fmt, channels, 0, samples, 0, 0, NULL, NULL};
spec.callback = audiomixer; spec.callback = audiomixer;
spec.userdata = dev; spec.userdata = dev;
// create the audio device // create the audio device
*dev = (audiodevice){ *dev = (audiodevice){
NULL, NULL,
SDL_OpenAudioDevice(NULL, 0, &spec, NULL, 0), SDL_OpenAudioDevice(NULL, 0, &spec, NULL, 0),
freq, freq,
fmt, fmt,
channels, channels,
}; };
if (dev->id < 1) { if (dev->id < 1) {
error("%s:%u audio device failed to open! SDL Error: %s", __FILE_NAME__, __LINE__, SDL_GetError()); error("%s:%u audio device failed to open! SDL Error: %s", __FILE_NAME__, __LINE__, SDL_GetError());
free(dev); free(dev);
return NULL; return NULL;
} }
// default state of the device is paused, so we unpause it here // default state of the device is paused, so we unpause it here
SDL_PauseAudioDevice(dev->id, 0); SDL_PauseAudioDevice(dev->id, 0);
return dev; return dev;
} }
void audio_play(audiodevice* dev, audiodata const* audio) { void audio_play(audiodevice* dev, audiodata const* audio) {
if (dev == NULL) return; // dev might fail to initialize if (dev == NULL) return; // dev might fail to initialize
if (audio->len == 0) return; // audio might fail to initialize if (audio->len == 0) return; // audio might fail to initialize
// create an audio player // create an audio player
struct audioplayer* player = malloc(sizeof(struct audioplayer)); struct audioplayer* player = malloc(sizeof(struct audioplayer));
*player = (struct audioplayer){ *player = (struct audioplayer){
dev->audio_players, // set nxt to the first item in dev (can be NULL, this is fine) dev->audio_players, // set nxt to the first item in dev (can be NULL, this is fine)
audio->buf, audio->buf,
audio->len, audio->len,
}; };
// assign ourselves to the first item // assign ourselves to the first item
dev->audio_players = player; dev->audio_players = player;
} }
void audio_device_free(audiodevice* dev) { void audio_device_free(audiodevice* dev) {
if (dev == NULL) return; if (dev == NULL) return;
SDL_CloseAudioDevice(dev->id); SDL_CloseAudioDevice(dev->id);
struct audioplayer* curr = dev->audio_players; struct audioplayer* curr = dev->audio_players;
// free all audio players // free all audio players
while (curr != NULL) { while (curr != NULL) {
dev->audio_players = curr->nxt; // use audio_players in dev as a cache dev->audio_players = curr->nxt; // use audio_players in dev as a cache
free(curr); free(curr);
curr = dev->audio_players; curr = dev->audio_players;
} }
// free the audio device itself // free the audio device itself
free(dev); free(dev);
} }
audiodata audio_wav_load(audiodevice const* dev, char const* fpath) { audiodata audio_wav_load(audiodevice const* dev, char const* fpath) {
if (dev == NULL) return (audiodata){0}; if (dev == NULL) return (audiodata){0};
SDL_AudioSpec spec; SDL_AudioSpec spec;
audiodata audio; audiodata audio;
debug("loading audio file '%s'...", fpath); debug("loading audio file '%s'...", fpath);
if (faccess(fpath, FA_R)) { if (faccess(fpath, FA_R)) {
error("%s:%u audio file either isn't readable or doesn't exist. path: '%s'!", __FILE_NAME__, __LINE__, fpath); error("%s:%u audio file either isn't readable or doesn't exist. path: '%s'!", __FILE_NAME__, __LINE__, fpath);
return (audiodata){0}; return (audiodata){0};
} }
// load and parse the audio to the correct format // load and parse the audio to the correct format
SDL_LoadWAV(fpath, &spec, &audio.buf, &audio.len); SDL_LoadWAV(fpath, &spec, &audio.buf, &audio.len);
if (audio_cvt(dev, &spec, &audio.buf, &audio.len)) { if (audio_cvt(dev, &spec, &audio.buf, &audio.len)) {
return (audiodata){0}; return (audiodata){0};
} }
// calculate the time in milliseconds of the audio fragment // calculate the time in milliseconds of the audio fragment
// by dividing the audio bytelength by the format's bitsize, by the audio device's channels and the audio device's frequency // by dividing the audio bytelength by the format's bitsize, by the audio device's channels and the audio device's frequency
audio.ms = (((1000 * audio.len) / (SDL_AUDIO_BITSIZE(dev->fmt) / 8)) / dev->channels / dev->freq); audio.ms = (((1000 * audio.len) / (SDL_AUDIO_BITSIZE(dev->fmt) / 8)) / dev->channels / dev->freq);
return audio; return audio;
} }
void audio_wav_unload(audiodata* audio) { void audio_wav_unload(audiodata* audio) {
free(audio->buf); free(audio->buf);
*audio = (audiodata){0}; // zero out all audio data *audio = (audiodata){0}; // zero out all audio data
} }

View File

@@ -4,24 +4,24 @@
#include <stdint.h> #include <stdint.h>
struct audiodata { struct audiodata {
uint8_t* buf; // pointer to the audio buffer uint8_t* buf; // pointer to the audio buffer
uint32_t len; // length in bytes of the audio buffer uint32_t len; // length in bytes of the audio buffer
uint32_t ms; // length in miliseconds of the audio buffer uint32_t ms; // length in miliseconds of the audio buffer
}; };
// contains the data of the audio fragments to be played // contains the data of the audio fragments to be played
struct audioplayer { struct audioplayer {
struct audioplayer* nxt; // pointer to the next audioplayer (may be null) struct audioplayer* nxt; // pointer to the next audioplayer (may be null)
uint8_t* buf; // pointer to the current item in the buffer to be played uint8_t* buf; // pointer to the current item in the buffer to be played
uint32_t len; // the length in bytes that the buffer has remaining uint32_t len; // the length in bytes that the buffer has remaining
}; };
struct audiodevice { struct audiodevice {
struct audioplayer* audio_players; struct audioplayer* audio_players;
SDL_AudioDeviceID id; SDL_AudioDeviceID id;
int freq; int freq;
SDL_AudioFormat fmt; SDL_AudioFormat fmt;
uint8_t channels; uint8_t channels;
}; };
typedef struct audiodata audiodata; typedef struct audiodata audiodata;

View File

@@ -5,13 +5,13 @@
// stores colour in a rgba format, each channel being a 8 bits wide. // stores colour in a rgba format, each channel being a 8 bits wide.
typedef union { typedef union {
uint32_t packed; uint32_t packed;
struct { struct {
uint8_t a; uint8_t a;
uint8_t b; uint8_t b;
uint8_t g; uint8_t g;
uint8_t r; uint8_t r;
}; };
} colour32; } colour32;
#define COLOUR32_BLACK ((colour32){0x000000FF}) #define COLOUR32_BLACK ((colour32){0x000000FF})
@@ -26,7 +26,7 @@ typedef union {
// sets the render colour to a colour32 value // sets the render colour to a colour32 value
static inline void set_colour32(SDL_Renderer* const renderer, colour32 const c) { static inline void set_colour32(SDL_Renderer* const renderer, colour32 const c) {
(void)SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, c.a); (void)SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, c.a);
} }
// american macros: // american macros:

View File

@@ -19,22 +19,22 @@ typedef uint8_t colour8;
// gets the red channel in 32 bit colour space // gets the red channel in 32 bit colour space
static inline uint8_t colour8_red32(colour8 const colour) { static inline uint8_t colour8_red32(colour8 const colour) {
return (colour >> 5) * (255 / 7); return (colour >> 5) * (255 / 7);
} }
// gets the green channel in 32 bit colour space // gets the green channel in 32 bit colour space
static inline uint8_t colour8_green32(colour8 const colour) { static inline uint8_t colour8_green32(colour8 const colour) {
return ((colour >> 2) & 7) * (255 / 7); return ((colour >> 2) & 7) * (255 / 7);
} }
// gets the blue channel in 32 bit colour space // gets the blue channel in 32 bit colour space
static inline uint8_t colour8_blue32(colour8 const colour) { static inline uint8_t colour8_blue32(colour8 const colour) {
return (colour & 3) * (255 / 3); return (colour & 3) * (255 / 3);
} }
// sets the render colour to a colour8 value // sets the render colour to a colour8 value
static inline void set_colour8(SDL_Renderer* const renderer, colour8 const c) { static inline void set_colour8(SDL_Renderer* const renderer, colour8 const c) {
(void)SDL_SetRenderDrawColor(renderer, colour8_red32(c), colour8_green32(c), colour8_blue32(c), 0xFF); (void)SDL_SetRenderDrawColor(renderer, colour8_red32(c), colour8_green32(c), colour8_blue32(c), 0xFF);
} }
// american macros: // american macros:

View File

@@ -21,141 +21,141 @@
#define COLOUR_SCORE COLOUR32_YELLOW #define COLOUR_SCORE COLOUR32_YELLOW
void render_init(renderdata* const render_dat, gamedata const* const game_dat) { void render_init(renderdata* const render_dat, gamedata const* const game_dat) {
SDL_Window* const window = SDL_CreateWindow("tetris clone", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); SDL_Window* const window = SDL_CreateWindow("tetris clone", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) fatal(ERROR_SDL_RENDERING_INIT, "Window failed to be created! SDL Error: %s", SDL_GetError()); if (window == NULL) fatal(ERROR_SDL_RENDERING_INIT, "Window failed to be created! SDL Error: %s", SDL_GetError());
SDL_Renderer* const renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); SDL_Renderer* const renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);
if (renderer == NULL) fatal(ERROR_SDL_RENDERING_INIT, "Renderer failed to be created! SDL Error: %s", SDL_GetError()); if (renderer == NULL) fatal(ERROR_SDL_RENDERING_INIT, "Renderer failed to be created! SDL Error: %s", SDL_GetError());
TTF_Font* const font = TTF_OpenFont("pixeldroid_botic-regular.ttf", PX_DENS); TTF_Font* const font = TTF_OpenFont("pixeldroid_botic-regular.ttf", PX_DENS);
if (font == NULL) error("Failed to open font! TTF Error: %s", TTF_GetError()); if (font == NULL) error("Failed to open font! TTF Error: %s", TTF_GetError());
// initialize the render data // initialize the render data
*render_dat = (renderdata){ *render_dat = (renderdata){
game_dat, game_dat,
window, window,
renderer, renderer,
font, font,
calloc(1, sizeof(struct render_cache)), // zero-initialize the memory as we read from it calloc(1, sizeof(struct render_cache)), // zero-initialize the memory as we read from it
}; };
} }
static inline int32_t get_column_pos(uint8_t column) { static inline int32_t get_column_pos(uint8_t column) {
return column * BLOCK_WIDTH + 1 + TET_PADDING; return column * BLOCK_WIDTH + 1 + TET_PADDING;
} }
static inline int32_t get_row_pos(uint8_t row) { static inline int32_t get_row_pos(uint8_t row) {
return row * BLOCK_HEIGHT + 1 + TET_PADDING; return row * BLOCK_HEIGHT + 1 + TET_PADDING;
} }
static void draw_score_text(renderdata const* dat) { static void draw_score_text(renderdata const* dat) {
struct render_cache* const cache = dat->cache; struct render_cache* const cache = dat->cache;
uint16_t const score = dat->game_dat->score; uint16_t const score = dat->game_dat->score;
SDL_Renderer* const renderer = dat->renderer; SDL_Renderer* const renderer = dat->renderer;
TTF_Font* const font = dat->font; TTF_Font* const font = dat->font;
if (cache->prevscore != score || cache->score_texture == NULL) { if (cache->prevscore != score || cache->score_texture == NULL) {
char score_text[6]; // max digits of a uint16 + \0 terminator char score_text[6]; // max digits of a uint16 + \0 terminator
if (!score) sprintf(score_text, "0"); if (!score) sprintf(score_text, "0");
else sprintf(score_text, "%hu0", score); else sprintf(score_text, "%hu0", score);
SDL_Surface* const txt_surface = TTF_RenderText_Solid(font, score_text, (SDL_Colour){COLOUR_SCORE.r, COLOUR_SCORE.g, COLOUR_SCORE.b, COLOUR_SCORE.a}); SDL_Surface* const txt_surface = TTF_RenderText_Solid(font, score_text, (SDL_Colour){COLOUR_SCORE.r, COLOUR_SCORE.g, COLOUR_SCORE.b, COLOUR_SCORE.a});
SDL_Texture* const txt_texture = SDL_CreateTextureFromSurface(renderer, txt_surface); SDL_Texture* const txt_texture = SDL_CreateTextureFromSurface(renderer, txt_surface);
if (cache->score_texture != NULL || cache->score_surface != NULL) { if (cache->score_texture != NULL || cache->score_surface != NULL) {
// free old data // free old data
SDL_FreeSurface(cache->score_surface); SDL_FreeSurface(cache->score_surface);
SDL_DestroyTexture(cache->score_texture); SDL_DestroyTexture(cache->score_texture);
} }
// write data to cache // write data to cache
cache->score_surface = txt_surface; cache->score_surface = txt_surface;
cache->score_texture = txt_texture; cache->score_texture = txt_texture;
} }
if (cache->score_surface == NULL || cache->score_texture == NULL) { if (cache->score_surface == NULL || cache->score_texture == NULL) {
error("the score texture was unavailable!",); error("the score texture was unavailable!", );
return; return;
} }
SDL_Rect text_rect = {get_column_pos(COLUMNS + 1), get_row_pos(0), cache->score_surface->w, cache->score_surface->h}; SDL_Rect text_rect = {get_column_pos(COLUMNS + 1), get_row_pos(0), cache->score_surface->w, cache->score_surface->h};
SDL_RenderCopy(renderer, cache->score_texture, NULL, &text_rect); SDL_RenderCopy(renderer, cache->score_texture, NULL, &text_rect);
} }
// draws a block at the specified position // draws a block at the specified position
static inline int draw_block(SDL_Renderer* const renderer, int8_t const x, int8_t const y) { static inline int draw_block(SDL_Renderer* const renderer, int8_t const x, int8_t const y) {
SDL_Rect const block = {get_column_pos(x), get_row_pos(y), BLOCK_WIDTH - 1, BLOCK_HEIGHT - 1}; SDL_Rect const block = {get_column_pos(x), get_row_pos(y), BLOCK_WIDTH - 1, BLOCK_HEIGHT - 1};
return SDL_RenderFillRect(renderer, &block); return SDL_RenderFillRect(renderer, &block);
} }
// draws a shape at the specified position // draws a shape at the specified position
static void draw_shape(SDL_Renderer* const renderer, shape_id const id, int8_t const pos_x, int8_t const pos_y) { static void draw_shape(SDL_Renderer* const renderer, shape_id const id, int8_t const pos_x, int8_t const pos_y) {
shape const shape = shape_from_id(id); shape const shape = shape_from_id(id);
set_colour8(renderer, colour_from_id(id)); set_colour8(renderer, colour_from_id(id));
for (int8_t y = 0; y < SHAPE_HEIGHT; y++) { for (int8_t y = 0; y < SHAPE_HEIGHT; y++) {
shape_row const shape_row = shape_get_row(shape, y); shape_row const shape_row = shape_get_row(shape, y);
if (shape_row == 0) if (shape_row == 0)
continue; continue;
for (int8_t x = 0; x < SHAPE_WIDTH; x++) for (int8_t x = 0; x < SHAPE_WIDTH; x++)
if (shape_is_set(shape_row, x)) if (shape_is_set(shape_row, x))
draw_block(renderer, pos_x + x, pos_y + y); draw_block(renderer, pos_x + x, pos_y + y);
} }
} }
// draw the block data in the level // draw the block data in the level
static void render_level(SDL_Renderer* const renderer, gamedata const* const data) { static void render_level(SDL_Renderer* const renderer, gamedata const* const data) {
for (int8_t y = 0; y < ROWS; y++) { for (int8_t y = 0; y < ROWS; y++) {
row_const const row = data->rows[y]; row_const const row = data->rows[y];
for (int8_t x = 0; x < COLUMNS; x++) { for (int8_t x = 0; x < COLUMNS; x++) {
if (row[x] != 0) { if (row[x] != 0) {
set_colour8(renderer, row[x]); set_colour8(renderer, row[x]);
draw_block(renderer, x, y); draw_block(renderer, x, y);
} }
} }
} }
} }
void render_update(renderdata const* const dat) { void render_update(renderdata const* const dat) {
SDL_Renderer* const renderer = dat->renderer; SDL_Renderer* const renderer = dat->renderer;
gamedata const* const game_data = dat->game_dat; gamedata const* const game_data = dat->game_dat;
int success = 0; // if an error occurs, this value is <0 int success = 0; // if an error occurs, this value is <0
// clear render // clear render
set_colour32(renderer, COLOUR32_BLACK); // using colour32 is more efficient, as it sets the colours directly set_colour32(renderer, COLOUR32_BLACK); // using colour32 is more efficient, as it sets the colours directly
success |= SDL_RenderClear(renderer); success |= SDL_RenderClear(renderer);
set_colour32(renderer, COLOUR32_WHITE); set_colour32(renderer, COLOUR32_WHITE);
static SDL_Rect const field_size = {TET_PADDING, TET_PADDING, TET_WIDTH + 1, TET_HEIGHT + 1}; static SDL_Rect const field_size = {TET_PADDING, TET_PADDING, TET_WIDTH + 1, TET_HEIGHT + 1};
SDL_RenderDrawRect(renderer, &field_size); SDL_RenderDrawRect(renderer, &field_size);
draw_shape(renderer, game_data->nxt[game_data->curr_idx + 1], COLUMNS + 1, 3); // draw the next shape draw_shape(renderer, game_data->nxt[game_data->curr_idx + 1], COLUMNS + 1, 3); // draw the next shape
if (dat->font) if (dat->font)
draw_score_text(dat); draw_score_text(dat);
render_level(renderer, dat->game_dat); render_level(renderer, dat->game_dat);
draw_shape(renderer, game_data->nxt[game_data->curr_idx], game_data->sel_x, game_data->sel_y); // draw the current shape draw_shape(renderer, game_data->nxt[game_data->curr_idx], game_data->sel_x, game_data->sel_y); // draw the current shape
if (success < 0) { if (success < 0) {
warn("something went wrong whilst renderering! SDL Error: %s\n", SDL_GetError()); warn("something went wrong whilst renderering! SDL Error: %s\n", SDL_GetError());
return; return;
} }
SDL_RenderPresent(renderer); SDL_RenderPresent(renderer);
} }
void render_free(renderdata* const render_data) { void render_free(renderdata* const render_data) {
SDL_DestroyRenderer(render_data->renderer); SDL_DestroyRenderer(render_data->renderer);
SDL_DestroyWindow(render_data->window); SDL_DestroyWindow(render_data->window);
TTF_CloseFont(render_data->font); TTF_CloseFont(render_data->font);
SDL_FreeSurface(render_data->cache->score_surface); SDL_FreeSurface(render_data->cache->score_surface);
SDL_DestroyTexture(render_data->cache->score_texture); SDL_DestroyTexture(render_data->cache->score_texture);
free(render_data->cache); free(render_data->cache);
*render_data = (renderdata){0}; *render_data = (renderdata){0};
} }

View File

@@ -19,18 +19,18 @@
// contains the data that's cached between renders // contains the data that's cached between renders
struct render_cache { struct render_cache {
SDL_Texture* score_texture; SDL_Texture* score_texture;
SDL_Surface* score_surface; SDL_Surface* score_surface;
uint16_t prevscore; uint16_t prevscore;
}; };
// contains the data necessary for rendering // contains the data necessary for rendering
typedef struct { typedef struct {
gamedata const* game_dat; gamedata const* game_dat;
SDL_Window* window; SDL_Window* window;
SDL_Renderer* renderer; SDL_Renderer* renderer;
TTF_Font* font; TTF_Font* font;
struct render_cache* cache; struct render_cache* cache;
} renderdata; } renderdata;
void render_init(renderdata*, gamedata const*); // initializes the renderer, outputs to render_data void render_init(renderdata*, gamedata const*); // initializes the renderer, outputs to render_data

View File

@@ -14,49 +14,49 @@ static renderdata rdat;
// initialize the game // initialize the game
static void init(void) { static void init(void) {
// initialize SDL // initialize SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) fatal(ERROR_SDL_INIT, "SDL could not initialize! SDL Error: %s", SDL_GetError()); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) fatal(ERROR_SDL_INIT, "SDL could not initialize! SDL Error: %s", SDL_GetError());
if (TTF_Init() != 0) fatal(ERROR_SDL_FONT_INIT, "the TTF module of SDL could not initialize! TTF Error: %s", TTF_GetError()); if (TTF_Init() != 0) fatal(ERROR_SDL_FONT_INIT, "the TTF module of SDL could not initialize! TTF Error: %s", TTF_GetError());
// initialize other game components // initialize other game components
paths_init(); paths_init();
game_init(&gdat); game_init(&gdat);
render_init(&rdat, &gdat); render_init(&rdat, &gdat);
} }
// perform the updates to the game // perform the updates to the game
static void update(void) { static void update(void) {
// update the input // update the input
{ {
SDL_Event e; SDL_Event e;
while (SDL_PollEvent(&e)) { while (SDL_PollEvent(&e)) {
switch (e.type) { switch (e.type) {
case SDL_QUIT: case SDL_QUIT:
gdat.run = false; gdat.run = false;
break; break;
} }
} }
} }
// perform updates // perform updates
game_update(&gdat); game_update(&gdat);
render_update(&rdat); render_update(&rdat);
} }
// entry-point of the application // entry-point of the application
int main(int argc, char** argv) { int main(int argc, char** argv) {
(void)argc, (void)argv; (void)argc, (void)argv;
init(); init();
debug("successfully initialized!", ); debug("successfully initialized!", );
while (gdat.run == true) while (gdat.run == true)
update(); update();
debug("done! starting to free resources...", ); debug("done! starting to free resources...", );
game_free(&gdat); game_free(&gdat);
render_free(&rdat); render_free(&rdat);
paths_free(); paths_free();
SDL_Quit(); SDL_Quit();
return 0; return 0;
} }

View File

@@ -38,19 +38,19 @@
#endif #endif
enum faccess_perms { enum faccess_perms {
FA_F = F_OK, // test for file's existence FA_F = F_OK, // test for file's existence
FA_X = X_OK, // test for executing permission FA_X = X_OK, // test for executing permission
FA_W = W_OK, // test for write permissions FA_W = W_OK, // test for write permissions
FA_R = R_OK, // test for read permissions FA_R = R_OK, // test for read permissions
}; };
/* tests a files access with F_OK, X_OK, R_OK, W_OK OR'd together /* tests a files access with F_OK, X_OK, R_OK, W_OK OR'd together
returns 0 upon success. -1 when errno is set and anything else when one or more of the permissions isn't set */ returns 0 upon success. -1 when errno is set and anything else when one or more of the permissions isn't set */
static inline int faccess(char const* restrict fname, int perms) { static inline int faccess(char const* restrict fname, int perms) {
#if defined __unix__ && _POSIX_C_SOURCE >= 200809L #if defined __unix__ && _POSIX_C_SOURCE >= 200809L
return access(fname, perms); return access(fname, perms);
#elif defined _WIN32 #elif defined _WIN32
return _access(fname, perms); return _access(fname, perms);
#else #else
#error platform unsupported! #error platform unsupported!
#endif #endif