Skip to content

Instantly share code, notes, and snippets.

@abenezeradane
Last active August 16, 2022 02:52
Show Gist options
  • Select an option

  • Save abenezeradane/922971ad48fdb8a3187497ff914c07df to your computer and use it in GitHub Desktop.

Select an option

Save abenezeradane/922971ad48fdb8a3187497ff914c07df to your computer and use it in GitHub Desktop.
Simple SDL2 window creation implementation in C
#ifndef APPLICATION_H
#define APPLICATION_H
#include <stdio.h>
#include <SDL2/SDL.h>
typedef struct Application {
SDL_Window* window;
char* title;
int quit, flags;
int x, y, width, height, fps;
void (*step)(void);
void (*load)(void);
} Application;
static float now;
static float last;
static float delta;
double time(void);
void init(Application* app) {
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) != 0) {
fprintf(stderr, strcat("SDL2 Failed to Initialize!\n> SDL2 Error: ", SDL_GetError()));
exit(-1);
}
app -> window = SDL_CreateWindow(
app -> title ? app -> title : "Application",
app -> x ? app -> x : SDL_WINDOWPOS_CENTERED,
app -> y ? app -> y : SDL_WINDOWPOS_CENTERED,
app -> width ? app -> width : 720,
app -> height ? app -> height : 480,
app -> flags ? app -> flags : SDL_WINDOW_SHOWN
);
if ((app -> window) == NULL) {
fprintf(stderr, strcat("SDL2 Failed to Create Window!\n> SDL2 Error: ", SDL_GetError()));
exit(-1);
}
if (app -> load)
app -> load();
last = time();
while (!(app -> quit)) {
now = time();
delta = now - last;
if (delta > (1000 / (app -> fps ? app -> fps : 60))) {
last = now;
SDL_Event event;
if (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT)
app -> quit = 1;
}
if (app -> step)
app -> step();
SDL_GL_SwapWindow(app -> window);
}
}
}
double time(void) {
return (double) SDL_GetTicks();
}
#endif // APPLICATION_H
#include "Application.h"
static void load(void);
static void frame(void);
int WinMain(int argc, char const *argv[]) {
Application app = {
.title = "[PROJECT NAME]",
.width = 1280, .height = 720, .fps = 60,
.load = load, .step = frame
}; init(&app);
return 0;
}
static void load(void) {
}
static void frame(void) {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment