From 3ef15b94aafa385171a0d83bafcb92693ee57041 Mon Sep 17 00:00:00 2001 From: condret Date: Tue, 1 Oct 2024 00:08:11 +0200 Subject: [PATCH] Add pixbuf api --- include/ragb_sdl.h | 21 +++++++++++++++ sdl/pixbuf.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 include/ragb_sdl.h create mode 100644 sdl/pixbuf.c diff --git a/include/ragb_sdl.h b/include/ragb_sdl.h new file mode 100644 index 0000000..f196f8e --- /dev/null +++ b/include/ragb_sdl.h @@ -0,0 +1,21 @@ +#ifndef RAGB_SDL_H +#define RAGB_SDL_H +#include +#include + +typedef struct gb_pixel_buffer_t { + SDL_Renderer *renderer; + SDL_Texture *texture; + ut8 *buf; //buffer containing pixeldata + ut32 color[4]; //rgb colors + ut16 w; //x size in pixel + ut16 h; //y size in pixel +// ut16 xsf; //x scale factor for projecting onto the texture +// ut16 ysf; //y scale factor for projecting onto the texture +} GBPixBuf; + +GBPixBuf *gb_pix_buf_new(SDL_Renderer *renderer, ut16 w, ut16 h); +void gb_pix_buf_free(GBPixBuf *pb); +void gb_pix_buf_set_pixel(GBPixBuf *pb, ut16 x, ut16 y, ut8 pixval); +void gb_pix_buf_set_color(GBPixBuf *pb, ut8 color_idx, ut32 rgb); +#endif diff --git a/sdl/pixbuf.c b/sdl/pixbuf.c new file mode 100644 index 0000000..c1d9bf2 --- /dev/null +++ b/sdl/pixbuf.c @@ -0,0 +1,64 @@ +#include +#include +#include + +GBPixBuf *gb_pix_buf_new (SDL_Renderer *renderer, ut16 w, ut16 h) { + if (!renderer || !w || !h) { + return NULL; + } + GBPixBuf *pb = R_NEW (GBPixBuf); + if (!pb) { + return NULL; + } + const ut32 bitsize = w * h * 2; + const ut32 bytesize = (!!(bitsize & 0x7)) + (bitsize >> 3); + pb->buf = R_NEWS0 (ut8, bytesize); + if (!pb->buf) { + free (pb); + return NULL; + } + pb->texture = SDL_CreateTexture (renderer, SDL_PIXELFORMAT_ARGB32, + SDL_TEXTUREACCESS_TARGET, w, h); + if (!texture) { + free (pb->buf); + free (pb); + return NULL; + } + pb->w = w; + pb->h = h; + return pb; +} + +void gb_pix_buf_free (GBPixBuf *pb) { + if (!pb) { + return; + } + SDL_DestroyTexture (pb->texture); + free (pb->buf); + free (pb); +} + +void gb_pix_buf_set_pixel (GBPixBuf *pb, ut16 x, ut16 y, ut8 pixval) { + if (!pb) { + return; + } + const ut32 bitpos = (pb->w * y + x) * 2; + const ut32 bytepos = bitpos >> 3; + const ut32 shl = bitpos & 0x6; + pixval = pixval & 0x3; + const ut8 mask = ~(0x3 << shl) + pb->buf[bytepos] = (pb->buf[bytepos] & mask) | (pixval << shl); + SDL_Texture *target = SDL_GetRenderTarget (pb->renderer); + SDL_SetRenderTarget (pb->renderer, pb->texture); + SDL_SetRenderDrawColor (pb->renderer, (pb->color[pixval] >> 16) & 0xff, + (pb->color[pixval] >> 8) & 0xff, pb->color[pixval] & 0xff, 0xff); + SDL_RenderDrawPoint (pb->renderer, x, y); + SDL_SetRenderTarget (pb->renderer, target); +} + +void gb_pix_buf_set_color (GBPixBuf *pb, ut8 color_idx, ut32 rgb) { + if (!pb) { + return; + } + pb->color[color_idx & 0x3] = rgb; +}