oexited
February 12, 2025, 1:26am
1
in sdl2 in c, if i wanted to change a pixel in the window. i would take sdl surface ( a struct) and acess pixels field ( a void* and array) , which i turn into uint8_t and change the value i want.
can someone please just show how to do this in zig? please
geemili
February 12, 2025, 5:09am
2
I assume you mean this SDL_surface ? It should look something like the following:
fn render(surface: c.SDL_surface) void {
const pixels: [*]u8 = @ptrCast(surface.pixels orelse return);
pixels[0] = 0xFF;
pixels[1] = 0xFF;
pixels[2] = 0xFF;
pixels[3] = 0xFF;
// etc.
}
If you know the pixel format you might want to use a struct for it:
const Pixel = extern struct { b: u8, g: u8, r: u8, a: u8 };
fn render(surface: c.SDL_surface) void {
// Note that we now need an `@alignCast` because `@alignOf(Pixel) != @alignOf(anyopaque)`
const pixels: [*]Pixel = @alignCast(@ptrCast(surface.pixels orelse return));
pixels[0] = .{ .r = 0xFF, .g = 0xFF, .b = 0xFF, .a = 0xFF };
// etc.
}
To get bounds checking when writing to the pixel buffer:
const Pixel = extern struct { b: u8, g: u8, r: u8, a: u8 };
fn render(surface: c.SDL_surface) void {
// Note that we now need an `@alignCast` because `@alignOf(Pixel) != @alignOf(anyopaque)`
const pixels_ptr: [*]Pixel = @alignCast(@ptrCast(surface.pixels orelse return));
const pitch_u: usize = @intCast(surface.pitch);
const pixels_len = pitch_u * surface.h;
const pixels: []Pixel = pixels_ptr[0..pixels_len];
pixels[0] = .{ .r = 0xFF, .g = 0xFF, .b = 0xFF, .a = 0xFF };
// set pixel 3 rows down and 2 columns over
pixels[3 * pitch_u + 2] = .{ .r = 0xFF, .g = 0xFF, .b = 0xFF, .a = 0xFF };
// etc.
}