WHY_CPP  0.1
sdl_texture.cpp
1 #include "sdl_texture.h"
2 #include <SDL_render.h>
3 #include <whycpp/color.h>
4 #include <whycpp/types.h>
5 #include <algorithm>
6 #include <cmath>
7 #include "../holders/video_memory_holder.h"
8 #include "../logger.h"
9 
10 SDLTexture::SDLTexture(SDL_Renderer* ren, VideoMemoryHolder* vram) : ren(ren), vram(vram) {
11  tex = std::unique_ptr<SDL_Texture, sdl_deleter>(
12  SDL_CreateTexture(ren, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, vram->GetWidth(),
13  vram->GetHeight()),
14  sdl_deleter());
15  if (!tex) {
16  LogSDLError("SDL_CreateTexture");
17  }
18 }
19 SDLTexture::~SDLTexture() = default;
20 void SDLTexture::Render() {
21  SDL_UpdateTexture(tex.get(), nullptr, vram->GetBuffer(), vram->GetWidth() * 4);
22  auto dst = CalcSizes();
23  vram->SetScreenHeight(dst.h);
24  vram->SetScreenWidth(dst.w);
25  SDL_RenderCopy(ren, tex.get(), nullptr, &dst);
26 }
27 SDL_Rect SDLTexture::CalcSizes() {
28  SDL_Rect dst = {0, 0, 0, 0};
29  SDL_QueryTexture(tex.get(), nullptr, nullptr, &dst.w, &dst.h);
30 
31  i32 sw, sh;
32  SDL_GetRendererOutputSize(ren, &sw, &sh);
33 
34  float rw = static_cast<float>(sw) / dst.w;
35  float rh = static_cast<float>(sh) / dst.h;
36  i32 r = static_cast<int>(std::floor(std::min(rw, rh)));
37 
38  dst.w *= r;
39  dst.h *= r;
40 
41  return dst;
42 }