cppgfx  0.1.0
C++17 educational graphics library
cppgfx.hpp
1 
2 #ifndef CPP_GRAPHICS_LIB_CPPGFX_HPP
3 #define CPP_GRAPHICS_LIB_CPPGFX_HPP
4 
5 #include "SFML/Graphics.hpp"
6 #include "SFML/Window.hpp"
7 #include "SFML/System.hpp"
8 #include "spdlog/spdlog.h"
9 #include "spdlog/sinks/stdout_color_sinks.h"
10 #include "spdlog/fmt/fmt.h"
11 #include "spdlog/fmt/std.h"
12 #include "spdlog/fmt/ranges.h"
13 #include <iostream>
14 #include <random>
15 
16 #include "glm/glm.hpp"
17 
18 #include "imgui.h"
19 
20 #include "cppgfx/base64.hpp"
21 
26 
31 
36 
41 
46 
51 
56 
57 enum class TextAlign {
58  Left,
59  Center,
60  Right
61 };
62 
63 enum class LineCap {
64  Round,
65  Square
66 };
67 
68 enum class RectMode {
69  Center, // Origin is at center and x y is size
70  Corner, // Origin is at top left corner and x y is size
71  Corners // Origin is at top left corner and x y is bottom right corner
72 };
73 
74 namespace cppgfx {
75 
78  class App {
79  public:
80  App();
81  ~App();
82 
83  static App& Get() {
84  if (m_instance == nullptr) {
85  throw std::logic_error("cppgfx::App::Get(): No instance of cppgfx::App exists. "
86  "Did you forget to create an instance of your application class?");
87  }
88 
89  return *m_instance;
90  }
91 
96  sf::RenderWindow window;
97 
102  bool darkTitleBar = true;
103 
108  uint32_t width = 800;
109 
114  uint32_t height = 600;
115 
119  uint32_t displayWidth = 0;
120 
124  uint32_t displayHeight = 0;
125 
130  std::string title = "My cppgfx application";
131 
136  bool focused = true;
137 
144  uint64_t frameCount = 0;
145 
151  float frameTime = 0;
152 
158  float frameRate = 0;
159 
162  constexpr static float PI = 3.14159265358979323846f;
163 
168  int mouseX = 0;
169 
175  int mouseY = 0;
176 
182  int pmouseX = 0;
183 
189  int pmouseY = 0;
190 
195  int dmouseX = 0;
196 
201  int dmouseY = 0;
202 
206  bool mousePressed = false;
207 
208 
209 
210 
211  // =======================================
212  // ===== Virtual Functions ========
213  // =======================================
214 
218  virtual void setup() = 0;
219 
223  virtual void update() = 0;
224 
228  virtual void cleanup() {}
229 
236  virtual bool onWindowClose() { return true; }
237 
243  virtual void onTextInput(const sf::Event::TextEvent& event) {}
244 
250  virtual void onKeyPressed(const sf::Event::KeyEvent& event) {}
251 
255  virtual void onKeyReleased(const sf::Event::KeyEvent& event) {}
256 
260  virtual void onMousePressed(const sf::Event::MouseButtonEvent& event) {}
261 
265  virtual void onMouseReleased(const sf::Event::MouseButtonEvent& event) {}
266 
270  virtual void onMouseMoved(const sf::Event::MouseMoveEvent& event) {}
271 
275  virtual void onMouseWheel(const sf::Event::MouseWheelScrollEvent& event) {}
276 
280  virtual void onMouseEnter() {}
281 
285  virtual void onMouseLeave() {}
286 
290  virtual void onWindowResize() {}
291 
295  virtual void onWindowFocus() {}
296 
300  virtual void onWindowUnfocus() {}
301 
302 
303 
304 
305  // =======================================
306  // ===== Graphics API ========
307  // =======================================
308 
312  void background(const sf::Color& color);
313 
317  void background(uint8_t shade);
318 
325  void background(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255);
326 
330  void fill(const sf::Color& color);
331 
335  void fill(uint8_t shade);
336 
343  void fill(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255);
344 
347  void noFill();
348 
351  void stroke(const sf::Color& color);
352 
356  void stroke(uint8_t shade);
357 
364  void stroke(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255);
365 
368  void noStroke();
369 
373  void strokeWeight(float weight);
374 
380  void push();
381 
387  void pop();
388 
395  void line(float x1, float y1, float x2, float y2);
396 
400  void lineCap(LineCap cap);
401 
409  void rect(float x, float y, float w, float h);
410 
420  void rectMode(RectMode mode);
421 
427  void circle(float x, float y, float radius);
428 
435  void ellipse(float x, float y, float w, float h);
436 
445  void triangle(float x1, float y1, float x2, float y2, float x3, float y3);
446 
455  void vector(float vectorX, float vectorY, float originX, float originY);
456 
460  void textFont(const sf::Font& font);
461 
466  sf::Font loadFont(const std::string& filename);
467 
471  void textAlign(TextAlign alignment);
472 
477  float textWidth(const std::string& text);
478 
482  void textSize(uint32_t size);
483 
489  void text(const std::string& text, float x, float y);
490 
491 
492 
493  // =======================================
494  // ===== Window API ========
495  // =======================================
496 
502  void size(int w, int h);
503 
508  void setTitle(const std::string& text);
509 
514  void setFrameRate(float framerate);
515 
519  void fullscreen();
520 
525 
529  void close();
530 
535  void focus();
536 
537 
538 
539 
540 
541  // =======================================
542  // ===== System API ========
543  // =======================================
544 
548  template<typename... Args>
549  void print(Args&&... args) {
550  fmt::print(std::forward<Args>(args)...);
551  }
552 
556  template<typename... Args>
557  void println(Args&&... args) {
558  fmt::print(std::forward<Args>(args)...);
559  fmt::print("\n");
560  }
561 
565  std::string encodeBase64(const std::vector<uint8_t>& input) {
566  return encode_base64(input);
567  }
568 
572  std::vector<uint8_t> decodeBase64(const std::string& input) {
573  return decode_base64(input);
574  }
575 
576 
577 
578 
579  // =======================================
580  // ===== Math API ========
581  // =======================================
582 
590  float dist(float x1, float y1, float x2, float y2);
591 
596  float radians(float degrees);
597 
602  float degrees(float radians);
603 
609  template<typename T>
610  T max(T a, T b) {
611  return std::max(a, b);
612  }
613 
619  template<typename T>
620  T min(T a, T b) {
621  return std::min(a, b);
622  }
623 
630  template<typename T>
631  T clamp(T value, T min, T max) {
632  return std::clamp(value, min, max);
633  }
634 
638  void randomSeed(uint32_t seed);
639 
645  int randomInt(int min, int max);
646 
651  int randomInt(int max);
652 
658  float random(float min, float max);
659 
664  float random(float max);
665 
666 
667 
668 
669  // =======================================
670  // ===== Time and Date API ========
671  // =======================================
672 
676  uint64_t micros();
677 
681  uint64_t millis();
682 
686  int second();
687 
691  int minute();
692 
696  int hour();
697 
701  int day();
702 
706  int month();
707 
711  int year();
712 
713 
714 
715 
716  // =======================================
717  // ===== Reserved API ========
718  // =======================================
719 
723  void run();
724 
725  private:
726  App(const App&) = delete;
727  App& operator=(const App&) = delete;
728 
729  void updateDisplaySize();
730 
731  inline static App* m_instance = nullptr;
732  bool m_windowShouldClose = false;
733 
734  sf::Color m_defaultBackgroundColor = sf::Color(60, 60, 60);
735  bool m_isDarkTitleBar = false;
736  sf::Clock m_lifetimeClock;
737  sf::Clock m_frametimeClock;
738 
739  uint32_t m_widthBeforeFullscreen = 0;
740  uint32_t m_heightBeforeFullscreen = 0;
741 
742  inline static sf::Font m_defaultFont;
743 
744  struct DrawStyle {
745  sf::Color m_fillColor = sf::Color::White;
746  sf::Color m_strokeColor = sf::Color::Black;
747  float m_strokeWeight = 0.f;
748  sf::Font m_font = m_defaultFont;
749  uint32_t m_fontSize = 18;
750 
751  LineCap m_lineCap = LineCap::Round;
752  RectMode m_rectMode = RectMode::Corner;
753  TextAlign m_textAlign = TextAlign::Left;
754  };
755  std::vector<DrawStyle> m_drawStyleStack;
756 
757  };
758 
759 }
760 
761 #endif //CPP_GRAPHICS_LIB_CPPGFX_HPP
The main application class.
Definition: cppgfx.hpp:78
float radians(float degrees)
Convert degrees to radians.
int randomInt(int min, int max)
Generate a random integer value between min and max.
float degrees(float radians)
Convert radians to degrees.
float random(float min, float max)
Generate a random floating point value between min and max.
T clamp(T value, T min, T max)
Clamp the value between the given min and max.
Definition: cppgfx.hpp:631
float random(float max)
Generate a random floating point value between 0 and the maximum.
void randomSeed(uint32_t seed)
Set the seed for the random number generator.
float dist(float x1, float y1, float x2, float y2)
Get the distance between two points.
T max(T a, T b)
Get the greater of two values.
Definition: cppgfx.hpp:610
constexpr static float PI
The mathematical constant PI.
Definition: cppgfx.hpp:162
std::string encodeBase64(const std::vector< uint8_t > &input)
Encode an arbitrary resource in base-64 encoding.
Definition: cppgfx.hpp:565
void run()
Run the application.
T min(T a, T b)
Get the lesser of two values.
Definition: cppgfx.hpp:620
int randomInt(int max)
Generate a random integer value between 0 and the maximum.
std::vector< uint8_t > decodeBase64(const std::string &input)
Decode a base-64 encoded string into its original form.
Definition: cppgfx.hpp:572
virtual void onKeyReleased(const sf::Event::KeyEvent &event)
This function is called when keys on the keyboard are released.
Definition: cppgfx.hpp:255
virtual void onMousePressed(const sf::Event::MouseButtonEvent &event)
This function is called when a mouse button is pressed.
Definition: cppgfx.hpp:260
virtual void onWindowFocus()
This function is called when the window is focused.
Definition: cppgfx.hpp:295
virtual void cleanup()
This function is called once at the end of the program.
Definition: cppgfx.hpp:228
virtual void onMouseEnter()
This function is called when the mouse enters the window.
Definition: cppgfx.hpp:280
virtual void update()=0
This function is called repeatedly until the program is terminated.
virtual void onMouseWheel(const sf::Event::MouseWheelScrollEvent &event)
This function is called when the mouse wheel is scrolled.
Definition: cppgfx.hpp:275
virtual void onWindowResize()
This function is called when the window is resized.
Definition: cppgfx.hpp:290
virtual bool onWindowClose()
This function can be used to intercept the window close event.
Definition: cppgfx.hpp:236
virtual void setup()=0
This function is called once at the beginning of the program.
virtual void onMouseLeave()
This function is called when the mouse leaves the window.
Definition: cppgfx.hpp:285
virtual void onKeyPressed(const sf::Event::KeyEvent &event)
This function is called when keys on the keyboard are pressed. To be used for key bindings,...
Definition: cppgfx.hpp:250
virtual void onMouseMoved(const sf::Event::MouseMoveEvent &event)
This function is called when the mouse is moved.
Definition: cppgfx.hpp:270
virtual void onWindowUnfocus()
This function is called when the window loses focus.
Definition: cppgfx.hpp:300
virtual void onTextInput(const sf::Event::TextEvent &event)
This function is called when keys on the keyboard are pressed. To be used for text input.
Definition: cppgfx.hpp:243
virtual void onMouseReleased(const sf::Event::MouseButtonEvent &event)
This function is called when a mouse button is released.
Definition: cppgfx.hpp:265
void strokeWeight(float weight)
Set the thickness of the outline for primitives.
void stroke(uint8_t r, uint8_t g, uint8_t b, uint8_t a=255)
Set the outline color for primitives.
void textFont(const sf::Font &font)
Set the current font to be used for rendering from now on.
void line(float x1, float y1, float x2, float y2)
Draw a line from (x1, y1) to (x2, y2)
void circle(float x, float y, float radius)
Draw a circle at (x, y) with the given radius.
void fill(uint8_t shade)
Set the infill color for primitives.
void triangle(float x1, float y1, float x2, float y2, float x3, float y3)
Draw a triangle with the given points.
void noFill()
Disable the infill color for primitives.
void textSize(uint32_t size)
Set the font size of the currently active font.
void push()
Push the current draw style onto the stack.
void stroke(uint8_t shade)
Set the outline color for primitives.
float textWidth(const std::string &text)
Calculate the width of a text string in pixels.
void stroke(const sf::Color &color)
Set the outline color for primitives.
void rect(float x, float y, float w, float h)
Draw a rectangle at (x, y) with the given width and height.
void text(const std::string &text, float x, float y)
Draw text at (x, y)
sf::Font loadFont(const std::string &filename)
Load a font from a file with a specific size.
void lineCap(LineCap cap)
Set the line cap style.
void rectMode(RectMode mode)
Where the origin of the rectangle is.
void textAlign(TextAlign alignment)
Set the current alignment for drawing text.
void noStroke()
Disable the outline color for primitives.
void vector(float vectorX, float vectorY, float originX, float originY)
Draw a vector arrow from the origin to origin + vector.
void fill(uint8_t r, uint8_t g, uint8_t b, uint8_t a=255)
Set the infill color for primitives.
void background(uint8_t r, uint8_t g, uint8_t b, uint8_t a=255)
Set the background color of the window.
void background(const sf::Color &color)
Set the background color of the window for the current frame.
void pop()
Pop the current draw style from the stack.
void fill(const sf::Color &color)
Set the infill color for primitives.
void ellipse(float x, float y, float w, float h)
Draw an ellipse at (x, y) with the given width and height.
void background(uint8_t shade)
Set the background color of the window for the current frame.
int dmouseX
Delta X: The difference between the current and previous mouse position X [read only].
Definition: cppgfx.hpp:195
bool mousePressed
If any mouse button is currently pressed [read only].
Definition: cppgfx.hpp:206
int pmouseX
The previous mouse position X [read only].
Definition: cppgfx.hpp:182
int mouseX
The current mouse position X [read only].
Definition: cppgfx.hpp:168
int pmouseY
The previous mouse position Y [read only].
Definition: cppgfx.hpp:189
int dmouseY
Delta Y: The difference between the current and previous mouse position Y [read only].
Definition: cppgfx.hpp:201
int mouseY
The current mouse position Y [read only].
Definition: cppgfx.hpp:175
void print(Args &&... args)
Print a formatted string without newline to the console (FMT/Python formatting supported)
Definition: cppgfx.hpp:549
void println(Args &&... args)
Print a formatted string with newline to the console (FMT/Python formatting supported)
Definition: cppgfx.hpp:557
int month()
Get the current month of the year [1-12].
int second()
Get the current second from the system clock [0-59].
int year()
Get the current year.
uint64_t micros()
Get the number of microseconds since the program started.
int day()
Get the current day of the month [1-31].
int hour()
Get the current hour from the system clock [0-23].
uint64_t millis()
Get the number of milliseconds since the program started.
int minute()
Get the current minute from the system clock [0-59].
uint32_t width
The current width of the window [read only].
Definition: cppgfx.hpp:108
uint32_t height
The current height of the window [read only].
Definition: cppgfx.hpp:114
void size(int w, int h)
Set the size of the window.
bool focused
If the window is currently focused or not [read only].
Definition: cppgfx.hpp:136
sf::RenderWindow window
The main window of your application.
Definition: cppgfx.hpp:96
uint32_t displayHeight
The pixel height of the primary monitor [read only].
Definition: cppgfx.hpp:124
void exitFullscreen()
Exit fullscreen mode.
void focus()
Request the window to be focused.
void fullscreen()
Switch to fullscreen mode.
bool darkTitleBar
If the dark title bar should be used.
Definition: cppgfx.hpp:102
std::string title
The current title of the window [read only].
Definition: cppgfx.hpp:130
void setFrameRate(float framerate)
Set the maximum framerate limit in frames per second.
uint64_t frameCount
The frame count since the program started [read only].
Definition: cppgfx.hpp:144
uint32_t displayWidth
The pixel width of the primary monitor [read only].
Definition: cppgfx.hpp:119
float frameRate
The current frameRate [read only].
Definition: cppgfx.hpp:158
void setTitle(const std::string &text)
Set the title of the window.
void close()
Stop the application.
float frameTime
The elapsed time since the last frame in seconds [read only].
Definition: cppgfx.hpp:151