Skip to content

Instantly share code, notes, and snippets.

@p1xelHer0
Created May 14, 2025 22:32
Show Gist options
  • Save p1xelHer0/7549eb0484147e68c7cf7af1d6c412de to your computer and use it in GitHub Desktop.
Save p1xelHer0/7549eb0484147e68c7cf7af1d6c412de to your computer and use it in GitHub Desktop.
Pixel perfect viewport with resolution scaling
GAME_WIDTH :: f32(320)
GAME_HEIGHT :: f32(180)
gfx_get_resolution_scaling :: proc(window_pixel_width, window_pixel_height: i32) -> int
{
dpi_scale := sdl.GetWindowPixelDensity(G.WINDOW)
width := f32(window_pixel_width) * dpi_scale
height := f32(window_pixel_height) * dpi_scale
window_aspect_ratio := width / height
game_aspect_ratio := GAME_WIDTH / GAME_HEIGHT
res := int(height / GAME_HEIGHT if game_aspect_ratio < window_aspect_ratio else width / GAME_WIDTH)
return res if res > 1 else 1
}
gfx_get_pixel_perfect_viewport :: proc(window_pixel_width, window_pixel_height: i32, resolution_scale: int) -> sdl.GPUViewport
{
dpi_scale := sdl.GetWindowPixelDensity(G.WINDOW)
width := f32(window_pixel_width) * dpi_scale
height := f32(window_pixel_height) * dpi_scale
scale := f32(resolution_scale)
platform_width := GAME_WIDTH * scale
platform_height := GAME_HEIGHT * scale
vp_x := (width - platform_width) / 2
vp_y := (height - platform_height) / 2
vp_w := platform_width
vp_h := platform_height
vp := sdl.GPUViewport {
x = sdl.roundf(vp_x),
y = sdl.roundf(vp_y),
w = sdl.roundf(vp_w),
h = sdl.roundf(vp_h),
}
return vp
}
resolution_scale := gfx_get_resolution_scaling(window_width, window_height)
viewport := gfx_get_pixel_perfect_viewport(window_width, window_height, resolution_scale)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment