Created
November 12, 2019 20:57
-
-
Save tuket/52a3edf755b67884c7923bd759220ccc to your computer and use it in GitHub Desktop.
basic SDL game loop in Zig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const warn = std.debug.warn; | |
const fmt = std.fmt; | |
const c = @cImport({ | |
@cInclude("SDL2/SDL.h"); | |
}); | |
const assert = @import("std").debug.assert; | |
const SDL_WINDOWPOS_UNDEFINED = @bitCast(c_int, c.SDL_WINDOWPOS_UNDEFINED_MASK); | |
const SDL_INIT_EVERYTHING = | |
c.SDL_INIT_TIMER | | |
c.SDL_INIT_AUDIO | | |
c.SDL_INIT_VIDEO | | |
c.SDL_INIT_EVENTS | | |
c.SDL_INIT_JOYSTICK | | |
c.SDL_INIT_HAPTIC | | |
c.SDL_INIT_GAMECONTROLLER; | |
const INIT_WIDTH = 800; | |
const INIT_HEIGHT = 600; | |
const maxFps = 60; | |
const targetDt = 1000 / maxFps; | |
var keepRunning = true; | |
pub fn main() !void { | |
if (c.SDL_Init(c.SDL_INIT_VIDEO) != 0) { | |
c.SDL_Log(c"Unable to initialize SDL: %s", c.SDL_GetError()); | |
return error.SDLInitializationFailed; | |
} | |
defer c.SDL_Quit(); | |
const window = c.SDL_CreateWindow(c"Paint", | |
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, | |
@intCast(c_int, INIT_WIDTH), @intCast(c_int, INIT_HEIGHT), | |
c.SDL_WINDOW_OPENGL | c.SDL_WINDOW_RESIZABLE) | |
orelse { | |
c.SDL_Log(c"Unable to create window: %s", c.SDL_GetError()); | |
return error.SDLInitializationFailed; | |
}; | |
defer c.SDL_DestroyWindow(window); | |
const renderer = c.SDL_CreateRenderer(window, -1, 0) | |
orelse { | |
c.SDL_Log(c"Unable to create renderer: %s", c.SDL_GetError()); | |
return error.SDLInitializationFailed; | |
}; | |
defer c.SDL_DestroyRenderer(renderer); | |
var t0 = @intCast(u32, c.SDL_GetTicks()); | |
var t1 = t0; | |
var dt : f32 = 0.001 * @intToFloat(f32, targetDt); | |
while(keepRunning) | |
{ | |
var event : c.SDL_Event = undefined; | |
while(c.SDL_PollEvent(&event) != 0) { | |
switch(event.@"type") { | |
c.SDL_QUIT => { | |
keepRunning = false; | |
}, | |
else => {} | |
} | |
} | |
t1 = @intCast(u32, c.SDL_GetTicks()); | |
const dtInt = t1 - t0; | |
if(dtInt < targetDt) { | |
c.SDL_Delay(targetDt - dtInt); | |
dt = 0.001 * @intToFloat(f32, targetDt); | |
} | |
else { | |
dt = 0.001 * @intToFloat(f32, t1 - t0); | |
} | |
t0 = t1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment