source: opengl-game/gui/ui-value.hpp

feature/imgui-sdl
Last change on this file was f809ae6, checked in by Dmitry Portnoy <dmitry.portnoy@…>, 4 years ago

Show the score and frame rate on the game screen

  • Property mode set to 100644
File size: 2.5 KB
Line 
1#ifndef _UI_VALUE_HPP
2#define _UI_VALUE_HPP
3
4#include <sstream>
5#include <stdint.h>
6#include <string>
7
8#include <SDL2/SDL.h>
9#include <SDL2/SDL_ttf.h>
10
11#include "ui-element.hpp"
12
13template<class T>
14class UIValue : public UIElement {
15public:
16 UIValue(int x, int y, string label, T& value, TTF_Font* font, uint32_t textColor,
17 SDL_Renderer& renderer);
18 ~UIValue() override;
19
20 void render(int x, int y) override;
21
22private:
23 string label;
24 T* value;
25 T oldValue;
26
27 TTF_Font* font;
28 SDL_Color textColor;
29
30 SDL_Texture* texture;
31
32 void createTexture();
33};
34
35template<class T>
36UIValue<T>::UIValue(int x, int y, string label, T& value, TTF_Font* font, uint32_t textColor,
37 SDL_Renderer& renderer) :
38 UIElement(x, y, 0, 0, renderer, nullptr, nullptr, nullptr),
39 label(label), value(&value), oldValue(value), font(font), texture(nullptr) {
40 this->textColor = {
41 static_cast<Uint8>((textColor >> 24) & 0xFF),
42 static_cast<Uint8>((textColor >> 16) & 0xFF),
43 static_cast<Uint8>((textColor >> 8) & 0xFF),
44 static_cast<Uint8>(textColor & 0xFF)
45 };
46
47 this->createTexture();
48}
49
50template<class T>
51UIValue<T>::~UIValue() {
52 if (this->texture != nullptr) {
53 SDL_DestroyTexture(this->texture);
54 this->texture = nullptr;
55 }
56}
57
58template<class T>
59void UIValue<T>::createTexture() {
60 // destroy the old texture before re-creating it
61 if (this->texture != nullptr) {
62 SDL_DestroyTexture(this->texture);
63 this->texture = nullptr;
64 }
65
66 ostringstream oss;
67 oss << label << *this->value;
68
69 string text = oss.str();
70
71 SDL_Surface* surface = TTF_RenderText_Blended(this->font, text.c_str(),
72 this->textColor);
73 if (surface == nullptr) {
74 cout << "Unable to render text surface! SDL_ttf Error: " << TTF_GetError() << endl;
75 }
76
77 this->texture = SDL_CreateTextureFromSurface(&this->renderer, surface);
78 if (this->texture == nullptr) {
79 cout << "Unable to create texture from rendered text! SDL Error: " << SDL_GetError() << endl;
80 // SDL_FreeSurface(surface);
81 }
82
83 SDL_FreeSurface(surface);
84
85 TTF_SizeText(this->font, text.c_str(), &this->width, &this->height);
86}
87
88template<class T>
89void UIValue<T>::render(int x, int y) {
90 if (this->oldValue != *this->value) {
91 this->createTexture();
92 this->oldValue = *this->value;
93 }
94
95 SDL_Rect rect = {
96 this->x + x,
97 this->y + y,
98 this->width,
99 this->height
100 };
101
102 SDL_RenderCopy(&this->renderer, this->texture, nullptr, &rect);
103}
104
105#endif // _UI_VALUE_HPP
Note: See TracBrowser for help on using the repository browser.