aboutsummaryrefslogtreecommitdiff
path: root/src/scale.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/scale.c')
-rw-r--r--src/scale.c109
1 files changed, 109 insertions, 0 deletions
diff --git a/src/scale.c b/src/scale.c
new file mode 100644
index 0000000..da35e63
--- /dev/null
+++ b/src/scale.c
@@ -0,0 +1,109 @@
+#include "scale.h"
+#include "SDL3/SDL_error.h"
+#include "SDL3/SDL_render.h"
+#include "SDL3/SDL_stdinc.h"
+
+static SDL_ScaleMode scale_pixel_perfect(float twf, float thf, int rw, int rh,
+ SDL_FRect *target) {
+ int tw = (int)twf;
+ int th = (int)thf;
+ int scale = SDL_min(rw / tw, rh / th);
+ if (!scale) {
+ return SDL_SCALEMODE_INVALID;
+ }
+
+ int w = scale * tw;
+ int h = scale * th;
+ int x = (rw - w) / 2;
+ int y = (rh - h) / 2;
+
+ target->w = (float)w;
+ target->h = (float)h;
+ target->x = (float)x;
+ target->y = (float)y;
+
+ return SDL_SCALEMODE_NEAREST;
+}
+
+static SDL_ScaleMode scale_fill(float twf, float thf, int rw, int rh,
+ SDL_FRect *target) {
+ float rwf = (float)rw;
+ float rhf = (float)rh;
+ float scale = SDL_min(rwf / twf, rhf / thf);
+
+ float w = scale * twf;
+ float h = scale * thf;
+ float x = (rw - w) / 2.;
+ float y = (rh - h) / 2.;
+
+ target->w = w;
+ target->h = h;
+ target->x = x;
+ target->y = y;
+
+ return SDL_SCALEMODE_PIXELART;
+}
+
+static SDL_ScaleMode scale_stretch(float twf, float thf, int rw, int rh,
+ SDL_FRect *target) {
+ (void)twf;
+ (void)thf;
+
+ target->w = rw;
+ target->h = rh;
+ target->x = 0.;
+ target->y = 0.;
+
+ return SDL_SCALEMODE_PIXELART;
+}
+
+bool pw_scale(enum pw_scale_mode mode, SDL_Texture *texture,
+ SDL_FRect *target) {
+ SDL_ScaleMode (*scalefn)(float, float, int, int, SDL_FRect *);
+ switch (mode) {
+ case PW_SCALE_MODE_PIXEL_PERFECT:
+ scalefn = scale_pixel_perfect;
+ break;
+ case PW_SCALE_MODE_FILL:
+ scalefn = scale_fill;
+ break;
+ case PW_SCALE_MODE_STRETCH:
+ scalefn = scale_stretch;
+ break;
+ default:
+ SDL_InvalidParamError("mode");
+ return false;
+ }
+ if (!texture) {
+ SDL_InvalidParamError("texture");
+ return false;
+ }
+ if (!target) {
+ SDL_InvalidParamError("target");
+ return false;
+ }
+
+ float twf, thf;
+ if (!SDL_GetTextureSize(texture, &twf, &thf)) {
+ return false;
+ }
+
+ SDL_Renderer *renderer = SDL_GetRendererFromTexture(texture);
+ if (!renderer) {
+ return false;
+ }
+
+ int rw, rh;
+ if (!SDL_GetRenderOutputSize(renderer, &rw, &rh)) {
+ return false;
+ }
+
+ SDL_FRect t;
+ SDL_ScaleMode m = scalefn(twf, thf, rw, rh, &t);
+ if (m == SDL_SCALEMODE_INVALID || !SDL_SetTextureScaleMode(texture, m)) {
+ return false;
+ }
+
+ SDL_memcpy(target, &t, sizeof(*target));
+ return true;
+}