From 1eff849ad34d69815ad68f9c88d2ea94c178d5e0 Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Mon, 21 Aug 2017 20:35:36 +0100 Subject: Testing out doxygen on github --- include/YAGE/Math/matrix.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/YAGE/Math/matrix.hpp b/include/YAGE/Math/matrix.hpp index 860a250c..9f7e005f 100644 --- a/include/YAGE/Math/matrix.hpp +++ b/include/YAGE/Math/matrix.hpp @@ -31,7 +31,7 @@ namespace yage { template class Matrix; -/** \internal Namespace for internal details. +/** @internal Namespace for internal details. * * Detail Namespace * ================ @@ -40,7 +40,7 @@ class Matrix; */ namespace detail { -/** \internal Internal Row class used by the Matrix class to return the +/** @internal Internal Row class used by the Matrix class to return the * internal data structure of the Matrix. * * Row -- cgit From 6a8bc8a624e2c7777d57c3363dfe8c8dadeff84f Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Mon, 21 Aug 2017 20:38:54 +0100 Subject: Highlight didn't work --- include/YAGE/Math/matrix.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/YAGE/Math/matrix.hpp b/include/YAGE/Math/matrix.hpp index 9f7e005f..860a250c 100644 --- a/include/YAGE/Math/matrix.hpp +++ b/include/YAGE/Math/matrix.hpp @@ -31,7 +31,7 @@ namespace yage { template class Matrix; -/** @internal Namespace for internal details. +/** \internal Namespace for internal details. * * Detail Namespace * ================ @@ -40,7 +40,7 @@ class Matrix; */ namespace detail { -/** @internal Internal Row class used by the Matrix class to return the +/** \internal Internal Row class used by the Matrix class to return the * internal data structure of the Matrix. * * Row -- cgit From 4b95a1ac4265e2f51bf78969ce259f0f8b91fd91 Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Mon, 21 Aug 2017 20:55:02 +0100 Subject: Adding documentation to matrix class --- include/YAGE/Math/matrix.hpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/include/YAGE/Math/matrix.hpp b/include/YAGE/Math/matrix.hpp index 860a250c..52536c17 100644 --- a/include/YAGE/Math/matrix.hpp +++ b/include/YAGE/Math/matrix.hpp @@ -121,14 +121,15 @@ public: return colMatrix; } - // iterator support for begin + /// iterator support for begin typename std::vector::iterator begin() { return data_.begin(); } - // iterator support for end + /// iterator support for end typename std::vector::iterator end() { return data_.end(); } - // prints out the matrix, but can also be implemented by other classes to - // print data differently + /** prints out the matrix, but can also be implemented by other classes to + * print data differently + */ virtual std::string toString() const { std::stringstream ss; ss << '['; -- cgit From 34f910351863163438c419dd07045f1442321293 Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Mon, 21 Aug 2017 21:14:33 +0100 Subject: Filling out readme --- README.md | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d31829a2..17176786 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,26 @@ YAGE ==== -YAGE stands for Yet Another Game Engine. +YAGE stands for Yet Another Game Engine. It is a game engine that I am developing for a game called [Arider](https://github.com/ymherklotz/Arider). + +YAGE uses OpenGL and SDL2 for the window creation and management and graphics. + +Installation and Usage +---------------------- + +To compile YAGE, create a build directory from the base directory. Then call cmake and point it to the directory containing [CMakeLists.txt](/CMakeLists.txt). + +``` shell +mkdir build +cd build +cmake .. +``` + +You can then run google test on YAGE. + +``` shell +ctest +``` License ------- -- cgit From 56b5466f014d9f7c3662544713bd53670cd8e32f Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Wed, 23 Aug 2017 20:33:34 +0100 Subject: Applied modernize rules and fixed build. Applied clang-tidy modernize rules and fixed the CMakeLists.txt file so that it also linked against the SDL2 library. --- CMakeLists.txt | 8 ++++---- README.md | 19 +++++++++++++++---- include/YAGE/Physics/body.hpp | 2 +- src/body.cpp | 8 +++++--- src/glslprogram.cpp | 2 +- src/picopng.cpp | 16 ++++++++-------- src/sprite.cpp | 4 ++-- src/spritebatch.cpp | 2 +- src/texturecache.cpp | 2 +- src/window.cpp | 2 +- 10 files changed, 39 insertions(+), 26 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f084702c..b92ec79a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -67,16 +67,16 @@ endif() # find libraries find_package(OpenGL REQUIRED) find_package(GLEW REQUIRED) +include(FindPkgConfig) +pkg_search_module(SDL2 REQUIRED sdl2) # set include directory -include_directories(${YAGE_INCLUDE_DIR} - ${YAGE_INCLUDE_DIR}/Physics/ - ${YAGE_INCLUDE_DIR}/Math/) +include_directories(${YAGE_INCLUDE_DIR}) # make it a static library add_library(${PROJECT_NAME} ${YAGE_SOURCES}) -set(YAGE_LIB_DEP_L "yage;${OPENGL_LIBRARIES};${GLEW_LIBRARIES};${SDL2_LIBRAIRES}") +set(YAGE_LIB_DEP_L "yage;${OPENGL_LIBRARIES};${GLEW_LIBRARIES};${SDL2_LIBRARIES}") message("${YAGE_LIB_DEP_L}") diff --git a/README.md b/README.md index 17176786..96a0ad70 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,25 @@ YAGE ==== -YAGE stands for Yet Another Game Engine. It is a game engine that I am developing for a game called [Arider](https://github.com/ymherklotz/Arider). +Introduction +------------ -YAGE uses OpenGL and SDL2 for the window creation and management and graphics. +YAGE stands for Yet Another Game Engine. It is a game engine that I am +developing for a game called [Arider](https://github.com/ymherklotz/Arider). +It uses OpenGL and SDL2 for the window creation and management and graphics. -Installation and Usage +Installation and usage ---------------------- -To compile YAGE, create a build directory from the base directory. Then call cmake and point it to the directory containing [CMakeLists.txt](/CMakeLists.txt). +To use YAGE for your own game, you should link it as a static library and +include the [yage.hpp](/include/YAGE/yage.hpp) header in your project. + +Build and Testing +----------------- + +To compile YAGE, create a build directory from the base directory. Then call +cmake and point it to the directory containing. +[CMakeLists.txt](/CMakeLists.txt). ``` shell mkdir build diff --git a/include/YAGE/Physics/body.hpp b/include/YAGE/Physics/body.hpp index fab28fc1..efeedb64 100644 --- a/include/YAGE/Physics/body.hpp +++ b/include/YAGE/Physics/body.hpp @@ -46,7 +46,7 @@ public: protected: // protected constructor to initialize member variables - Body(const Vector2d& position = Vector2d(0, 0), double mass = 1, const Vector2d& velocity = Vector2d(0, 0), bool gravity = false); + Body(Vector2d position = Vector2d(0, 0), double mass = 1, Vector2d velocity = Vector2d(0, 0), bool gravity = false); }; } // namespace yage diff --git a/src/body.cpp b/src/body.cpp index a17f6ee3..9c8babf1 100644 --- a/src/body.cpp +++ b/src/body.cpp @@ -6,6 +6,8 @@ * ---------------------------------------------------------------------------- */ +#include + #include "Physics/body.hpp" namespace yage { @@ -16,11 +18,11 @@ double Body::xPosition() const { return position_[0]; } double Body::yPosition() const { return position_[1]; } -Body::Body(const Vector2d& position, double mass, const Vector2d& velocity, +Body::Body(Vector2d position, double mass, Vector2d velocity, bool gravity) - : position_(position), + : position_(std::move(position)), mass_(mass), - velocity_(velocity), + velocity_(std::move(velocity)), gravity_(gravity) {} } // yage diff --git a/src/glslprogram.cpp b/src/glslprogram.cpp index a5f95ad5..6d0a60b2 100644 --- a/src/glslprogram.cpp +++ b/src/glslprogram.cpp @@ -38,7 +38,7 @@ void GlslProgram::compileShader(const GLuint& shader, // cast source to a c string to get the address of it and input it for // compilation - const GLchar* vertex_source = (const GLchar*)content.c_str(); + const auto* vertex_source = (const GLchar*)content.c_str(); glShaderSource(shader, 1, &vertex_source, nullptr); glCompileShader(shader); diff --git a/src/picopng.cpp b/src/picopng.cpp index 6fe9c1f7..f75390de 100644 --- a/src/picopng.cpp +++ b/src/picopng.cpp @@ -466,7 +466,7 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, void decode(std::vector& out, const unsigned char* in, size_t size, bool convert_to_rgba32) { error = 0; - if (size == 0 || in == 0) { + if (size == 0 || in == nullptr) { error = 48; return; } // the given data is empty @@ -543,7 +543,7 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, return; } // error: this chunk must be 2 bytes for greyscale // image - info.key_defined = 1; + info.key_defined = true; info.key_r = info.key_g = info.key_b = 256 * in[pos] + in[pos + 1]; pos += 2; @@ -552,7 +552,7 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, error = 41; return; } // error: this chunk must be 6 bytes for RGB image - info.key_defined = 1; + info.key_defined = true; info.key_r = 256 * in[pos] + in[pos + 1]; pos += 2; info.key_g = 256 * in[pos] + in[pos + 1]; @@ -590,7 +590,7 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, outlength = (info.height * info.width * bpp + 7) / 8; out.resize(outlength); // time to fill the out buffer unsigned char* out_ = - outlength ? &out[0] : 0; // use a regular pointer to the + outlength ? &out[0] : nullptr; // use a regular pointer to the // std::vector for faster code if // compiled without optimization if (info.interlaceMethod == 0) // no interlace, just filter @@ -603,7 +603,7 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, for (unsigned long y = 0; y < info.height; y++) { unsigned long filterType = scanlines[linestart]; const unsigned char* prevline = - (y == 0) ? 0 + (y == 0) ? nullptr : &out_[(y - 1) * info.width * bytewidth]; unFilterScanline(&out_[linestart - y], &scanlines[linestart + 1], prevline, @@ -619,7 +619,7 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, for (size_t y = 0, obp = 0; y < info.height; y++) { unsigned long filterType = scanlines[linestart]; const unsigned char* prevline = - (y == 0) ? 0 + (y == 0) ? nullptr : &out_[(y - 1) * info.width * bytewidth]; unFilterScanline(&templine[0], &scanlines[linestart + 1], prevline, @@ -788,7 +788,7 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, linelength = 1 + ((bpp * passw + 7) / 8); for (unsigned long y = 0; y < passh; y++) { unsigned char filterType = in[y * linelength], - *prevline = (y == 0) ? 0 : lineo; + *prevline = (y == 0) ? nullptr : lineo; unFilterScanline(linen, &in[y * linelength + 1], prevline, bytewidth, filterType, (w * bpp + 7) / 8); if (error) return; @@ -876,7 +876,7 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, out.resize(numpixels * 4); unsigned char* out_ = out.empty() - ? 0 + ? nullptr : &out[0]; // faster if compiled without optimization if (infoIn.bitDepth == 8 && infoIn.colorType == 0) // greyscale for (size_t i = 0; i < numpixels; i++) { diff --git a/src/sprite.cpp b/src/sprite.cpp index e3d74982..4cdd2ecf 100644 --- a/src/sprite.cpp +++ b/src/sprite.cpp @@ -14,7 +14,7 @@ namespace yage { -Sprite::Sprite() {} +Sprite::Sprite() = default; Sprite::~Sprite() { if (vbo_id_ != 0) glDeleteBuffers(1, &vbo_id_); @@ -50,7 +50,7 @@ void Sprite::init(float x, float y, float width, float height, vertex_data[5].setPosition(x + width, y); vertex_data[5].setUv(1.f, 0.f); - for (int i = 0; i < 6; ++i) vertex_data[i].setColor(255, 0, 255, 255); + for (auto & i : vertex_data) i.setColor(255, 0, 255, 255); vertex_data[1].setColor(0, 255, 255, 255); vertex_data[4].setColor(255, 0, 0, 255); diff --git a/src/spritebatch.cpp b/src/spritebatch.cpp index 8e64aa5e..f4767829 100644 --- a/src/spritebatch.cpp +++ b/src/spritebatch.cpp @@ -28,7 +28,7 @@ Glyph::Glyph(GLuint texture, float depth, const Vertex& top_left, RenderBatch::RenderBatch(GLint offset, GLsizei num_vertices, GLuint texture) : num_vertices_(num_vertices), offset_(offset), texture_(texture) {} -SpriteBatch::SpriteBatch() {} +SpriteBatch::SpriteBatch() = default; SpriteBatch::~SpriteBatch() { if (vao_ != 0) glDeleteVertexArrays(1, &vao_); diff --git a/src/texturecache.cpp b/src/texturecache.cpp index 6d10b209..09ac2639 100644 --- a/src/texturecache.cpp +++ b/src/texturecache.cpp @@ -13,7 +13,7 @@ namespace yage { TextureCache::TextureCache() -{} += default; Texture TextureCache::getTexture(const std::string &texture_path) { diff --git a/src/window.cpp b/src/window.cpp index 7a00b0c9..959cacb3 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -15,7 +15,7 @@ namespace yage { -Window::Window() {} +Window::Window() = default; Window::~Window() { SDL_DestroyWindow(window_); } -- cgit From e912ca9603c5407eb2732f3620d07cf2ca60c80e Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Wed, 23 Aug 2017 20:38:36 +0100 Subject: Improving gitignore. --- .gitignore | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 9b5a28d9..36a26ca2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,9 @@ # general directories to ignore -bin/ -build/ -build_clang/ -build_gcc/ -build_debug/ -build_release/ -CMakeFiles/ -Testing/ +bin +build +build_* +CMakeFiles +Testing # extensions to ignore *.o @@ -17,7 +14,6 @@ Testing/ # general files to ignore CMakeCache.txt Makefile - -# specific directories to ignore -/debug_build/ -/G* +GPATH +GTAGS +GRTAGS -- cgit From bc982b84ec3e1085c440e4d5ea1de597aee63565 Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Wed, 23 Aug 2017 20:44:42 +0100 Subject: Applied more fixes on headers. Passed all headers through clang-tidy and modernize rules. --- include/YAGE/Math/matrix.hpp | 4 ++-- include/YAGE/Physics/particlebody.hpp | 4 ++-- include/YAGE/Physics/rectanglecollider.hpp | 4 ++-- include/YAGE/vertex.hpp | 8 ++++---- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/include/YAGE/Math/matrix.hpp b/include/YAGE/Math/matrix.hpp index 52536c17..999d4274 100644 --- a/include/YAGE/Math/matrix.hpp +++ b/include/YAGE/Math/matrix.hpp @@ -273,7 +273,7 @@ public: const Type& operator[](int col) const { return this->data_[col]; } - virtual std::string toString() const { + std::string toString() const override override override { std::stringstream ss; ss << "["; for (std::size_t i = 0; i < this->data_.size() - 1; ++i) { @@ -311,7 +311,7 @@ public: }; /// Definition of a 2D vector. -typedef Vector2 Vector2d; +using Vector2d = Vector2; /** Namespace containing functions that operate on matrices. */ namespace matrix { diff --git a/include/YAGE/Physics/particlebody.hpp b/include/YAGE/Physics/particlebody.hpp index ff8b3b85..7894e301 100644 --- a/include/YAGE/Physics/particlebody.hpp +++ b/include/YAGE/Physics/particlebody.hpp @@ -22,8 +22,8 @@ public: bool gravity = true); // apply a force to the rigid body - virtual void applyForce(const Vector2d& force); - virtual void update(); + void applyForce(const Vector2d& force) override override; + void update() override override; }; } // yage diff --git a/include/YAGE/Physics/rectanglecollider.hpp b/include/YAGE/Physics/rectanglecollider.hpp index 7f9dd7f7..b66664a0 100644 --- a/include/YAGE/Physics/rectanglecollider.hpp +++ b/include/YAGE/Physics/rectanglecollider.hpp @@ -19,8 +19,8 @@ class RectangleCollider : public Collider { public: RectangleCollider(const glm::vec2& position, const glm::vec2& size); - virtual bool collides(const Collider& collider) const; - virtual bool inside(const glm::vec2& point) const; + bool collides(const Collider& collider) const override; + bool inside(const glm::vec2& point) const override; }; } // yage diff --git a/include/YAGE/vertex.hpp b/include/YAGE/vertex.hpp index d3355b11..1026253e 100644 --- a/include/YAGE/vertex.hpp +++ b/include/YAGE/vertex.hpp @@ -17,7 +17,7 @@ struct Position { float x; float y; - Position() {} + Position() = default; Position(float x_, float y_) : x(x_), y(y_) {} }; @@ -28,7 +28,7 @@ struct Color { GLubyte b; GLubyte a; - Color() {} + Color() = default; Color(GLubyte r_, GLubyte g_, GLubyte b_, GLubyte a_) : r(r_), g(g_), b(b_), a(a_) {} @@ -38,7 +38,7 @@ struct UV { float u; float v; - UV() {} + UV() = default; UV(float u_, float v_) : u(u_), v(v_) {} }; @@ -48,7 +48,7 @@ struct Vertex { Color color; UV uv; - Vertex() {} + Vertex() = default; Vertex(const Position& position_, const Color& color_, const UV& uv_) : position(position_), color(color_), uv(uv_) {} -- cgit From b4d99eb15e6337c22c011acaca25b0ce8e946e3d Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Wed, 23 Aug 2017 23:08:52 +0100 Subject: Improving settings and chaning \ to @. --- docs/Doxyfile | 30 +++++++++++++++--------------- include/YAGE/Math/matrix.hpp | 24 +++++++++++++----------- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/docs/Doxyfile b/docs/Doxyfile index a7caa23f..da9cc78b 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -107,7 +107,7 @@ BRIEF_MEMBER_DESC = YES # brief descriptions will be completely suppressed. # The default value is: YES. -REPEAT_BRIEF = YES +REPEAT_BRIEF = NO # This tag implements a quasi-intelligent brief description abbreviator that is # used to form the text in various listings. Each string in this list, if found @@ -195,7 +195,7 @@ JAVADOC_AUTOBRIEF = YES # requiring an explicit \brief command for a brief description.) # The default value is: NO. -QT_AUTOBRIEF = NO +QT_AUTOBRIEF = YES # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a # multi-line C++ special comment block (i.e. a block of //! or /// comments) as @@ -328,7 +328,7 @@ AUTOLINK_SUPPORT = YES # diagrams that involve STL classes more complete and accurate. # The default value is: NO. -BUILTIN_STL_SUPPORT = NO +BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. @@ -435,25 +435,25 @@ LOOKUP_CACHE_SIZE = 0 # normally produced when WARNINGS is set to YES. # The default value is: NO. -EXTRACT_ALL = NO +EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will # be included in the documentation. # The default value is: NO. -EXTRACT_PRIVATE = NO +EXTRACT_PRIVATE = YES # If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal # scope will be included in the documentation. # The default value is: NO. -EXTRACT_PACKAGE = YES +EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES, all static members of a file will be # included in the documentation. # The default value is: NO. -EXTRACT_STATIC = NO +EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined # locally in source files will be included in the documentation. If set to NO, @@ -486,7 +486,7 @@ EXTRACT_ANON_NSPACES = NO # section is generated. This option has no effect if EXTRACT_ALL is enabled. # The default value is: NO. -HIDE_UNDOC_MEMBERS = YES +HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. If set @@ -494,7 +494,7 @@ HIDE_UNDOC_MEMBERS = YES # has no effect if EXTRACT_ALL is enabled. # The default value is: NO. -HIDE_UNDOC_CLASSES = YES +HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend # (class|struct|union) declarations. If set to NO, these declarations will be @@ -873,8 +873,7 @@ RECURSIVE = YES # Note that relative paths are relative to the directory from which doxygen is # run. -EXCLUDE = ./test \ - ./build \ +EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded @@ -890,7 +889,8 @@ EXCLUDE_SYMLINKS = NO # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories for example use the pattern */test/* -EXCLUDE_PATTERNS = */googletest/* +EXCLUDE_PATTERNS = */googletest/* \ + */build/* # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the @@ -1282,7 +1282,7 @@ DOCSET_BUNDLE_ID = com.yannherklotz.YAGE # The default value is: org.doxygen.Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. -DOCSET_PUBLISHER_ID = org.doxygen.Publisher +DOCSET_PUBLISHER_ID = # The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. # The default value is: Publisher. @@ -1432,7 +1432,7 @@ GENERATE_ECLIPSEHELP = NO # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. -ECLIPSE_DOC_ID = org.doxygen.Project +ECLIPSE_DOC_ID = # If you want full control over the layout of the generated HTML pages it might # be necessary to disable the index and replace it with your own. The @@ -1460,7 +1460,7 @@ DISABLE_INDEX = NO # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -GENERATE_TREEVIEW = NO +GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that # doxygen will group on one line in the generated HTML documentation. diff --git a/include/YAGE/Math/matrix.hpp b/include/YAGE/Math/matrix.hpp index 999d4274..866b46e2 100644 --- a/include/YAGE/Math/matrix.hpp +++ b/include/YAGE/Math/matrix.hpp @@ -6,15 +6,17 @@ * ---------------------------------------------------------------------------- */ -/** \file matrix.hpp Templated matrix class - * - * Matrix - * ====== - * - * This is a very general matrix class that can then be inherited by - * vectors and other similar data structures to minimize code - * density. - */ +/// @file + +/** Templated matrix class + * + * Matrix + * ====== + * + * This is a very general matrix class that can then be inherited by + * vectors and other similar data structures to minimize code + * density. + */ #ifndef YAGE_MATH_MATRIX_HPP #define YAGE_MATH_MATRIX_HPP @@ -31,7 +33,7 @@ namespace yage { template class Matrix; -/** \internal Namespace for internal details. +/** @internal Namespace for internal details. * * Detail Namespace * ================ @@ -40,7 +42,7 @@ class Matrix; */ namespace detail { -/** \internal Internal Row class used by the Matrix class to return the +/** @internal Internal Row class used by the Matrix class to return the * internal data structure of the Matrix. * * Row -- cgit From 2dbcbe3575134b3c6267b1a396b57080067ed9da Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Wed, 23 Aug 2017 23:19:43 +0100 Subject: Fixed autofix issues. --- include/YAGE/Math/matrix.hpp | 2 +- include/YAGE/Physics/particlebody.hpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/include/YAGE/Math/matrix.hpp b/include/YAGE/Math/matrix.hpp index 866b46e2..e4583290 100644 --- a/include/YAGE/Math/matrix.hpp +++ b/include/YAGE/Math/matrix.hpp @@ -275,7 +275,7 @@ public: const Type& operator[](int col) const { return this->data_[col]; } - std::string toString() const override override override { + std::string toString() const override { std::stringstream ss; ss << "["; for (std::size_t i = 0; i < this->data_.size() - 1; ++i) { diff --git a/include/YAGE/Physics/particlebody.hpp b/include/YAGE/Physics/particlebody.hpp index 7894e301..fd07512f 100644 --- a/include/YAGE/Physics/particlebody.hpp +++ b/include/YAGE/Physics/particlebody.hpp @@ -22,8 +22,8 @@ public: bool gravity = true); // apply a force to the rigid body - void applyForce(const Vector2d& force) override override; - void update() override override; + void applyForce(const Vector2d& force) override; + void update() override; }; } // yage -- cgit From 5403490b941f7c031bf1aafdb91b1098f69edbf2 Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Thu, 24 Aug 2017 00:21:07 +0100 Subject: Running clang-format over everything. Edited formatting and ran it over all the files. --- .clang-format | 94 +-- .gitignore | 4 + include/YAGE/Math/matrix.hpp | 180 +++--- include/YAGE/Physics/README.org | 44 +- include/YAGE/Physics/body.hpp | 51 +- include/YAGE/Physics/collider.hpp | 18 +- include/YAGE/Physics/collisionbody.hpp | 8 +- include/YAGE/Physics/particlebody.hpp | 21 +- include/YAGE/Physics/rectanglecollider.hpp | 14 +- include/YAGE/Physics/rigidbody.hpp | 12 +- include/YAGE/camera2d.hpp | 12 +- include/YAGE/glslprogram.hpp | 26 +- include/YAGE/imageloader.hpp | 10 +- include/YAGE/inputmanager.hpp | 1 - include/YAGE/iomanager.hpp | 6 +- include/YAGE/picopng.hpp | 10 +- include/YAGE/resourcemanager.hpp | 10 +- include/YAGE/sprite.hpp | 18 +- include/YAGE/spritebatch.hpp | 35 +- include/YAGE/texture.hpp | 5 +- include/YAGE/texturecache.hpp | 10 +- include/YAGE/vertex.hpp | 24 +- include/YAGE/window.hpp | 20 +- include/YAGE/yage.hpp | 4 +- src/body.cpp | 16 +- src/camera2d.cpp | 18 +- src/glslprogram.cpp | 79 ++- src/imageloader.cpp | 53 +- src/inputmanager.cpp | 13 +- src/iomanager.cpp | 15 +- src/particlebody.cpp | 23 +- src/picopng.cpp | 891 ++++++++++++++++------------- src/rectanglecollider.cpp | 25 +- src/resourcemanager.cpp | 8 +- src/rigidbody.cpp | 13 +- src/sprite.cpp | 32 +- src/spritebatch.cpp | 92 +-- src/texturecache.cpp | 22 +- src/window.cpp | 41 +- test/matrixtest.cpp | 25 +- test/particlebodytest.cpp | 9 +- test/windowtest.cpp | 11 +- test/yagetest.cpp | 11 +- 43 files changed, 1135 insertions(+), 899 deletions(-) diff --git a/.clang-format b/.clang-format index 47342b07..13ea9cc7 100644 --- a/.clang-format +++ b/.clang-format @@ -1,94 +1,10 @@ --- -Language: Cpp -BasedOnStyle: Google +BasedOnStyle: LLVM +IndentWidth: 4 +--- +Language: Cpp AccessModifierOffset: -4 -AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: false -AlignEscapedNewlinesLeft: true -AlignOperands: true -AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: true -AllowShortLoopsOnASingleLine: true -AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: true AlwaysBreakTemplateDeclarations: true -BinPackArguments: true -BinPackParameters: true -BraceWrapping: - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: false - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - BeforeCatch: false - BeforeElse: false - IndentBraces: false -BreakBeforeBinaryOperators: None -BreakBeforeBraces: Attach -BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false -BreakAfterJavaFieldAnnotations: false -BreakStringLiterals: true -ColumnLimit: 80 -CommentPragmas: '^ IWYU pragma:' -ConstructorInitializerAllOnOneLineOrOnePerLine: true -ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 4 -Cpp11BracedListStyle: true -DerivePointerAlignment: false -DisableFormat: false -ExperimentalAutoDetectBinPacking: false -ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] -IncludeCategories: - - Regex: '^<.*\.h>' - Priority: 1 - - Regex: '^<.*' - Priority: 2 - - Regex: '.*' - Priority: 3 -IncludeIsMainRegex: '([-_](test|unittest))?$' -IndentCaseLabels: true -IndentWidth: 4 -IndentWrappedFunctionNames: false -KeepEmptyLinesAtTheStartOfBlocks: false -MacroBlockBegin: '' -MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -ObjCBlockIndentWidth: 4 -ObjCSpaceAfterProperty: false -ObjCSpaceBeforeProtocolList: false -PenaltyBreakBeforeFirstCallParameter: 1 -PenaltyBreakComment: 300 -PenaltyBreakFirstLessLess: 120 -PenaltyBreakString: 1000 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 200 -PointerAlignment: Left -ReflowComments: true -SortIncludes: true -SpaceAfterCStyleCast: false -SpaceAfterTemplateKeyword: true -SpaceBeforeAssignmentOperators: true -SpaceBeforeParens: false -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 2 -SpacesInAngles: false -SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false -SpacesInSquareBrackets: false -Standard: Auto -TabWidth: 4 -UseTab: Never +BreakBeforeBraces: Linux ... diff --git a/.gitignore b/.gitignore index 36a26ca2..76595e59 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,10 @@ Testing *.a *.cmake +# emacs +*.# +*~ + # general files to ignore CMakeCache.txt Makefile diff --git a/include/YAGE/Math/matrix.hpp b/include/YAGE/Math/matrix.hpp index e4583290..249edcc7 100644 --- a/include/YAGE/Math/matrix.hpp +++ b/include/YAGE/Math/matrix.hpp @@ -28,10 +28,10 @@ #include #include -namespace yage { +namespace yage +{ -template -class Matrix; +template class Matrix; /** @internal Namespace for internal details. * @@ -40,7 +40,8 @@ class Matrix; * * This is the namespace used for implementation detail. */ -namespace detail { +namespace detail +{ /** @internal Internal Row class used by the Matrix class to return the * internal data structure of the Matrix. @@ -50,27 +51,31 @@ namespace detail { * * Internal Row class to return a value in the row of the matrix. */ -template -class Row { +template class Row +{ private: - Matrix* parent_; + Matrix *parent_; int index_; public: - Row(Matrix* parent, int index) - : parent_(parent), index_(index) {} + Row(Matrix *parent, int index) + : parent_(parent), index_(index) + { + } - Type& operator[](int col) { + Type &operator[](int col) + { // the index is the y-position of the element in the matrix return parent_->data_[index_ * Cols + col]; } - const Type& operator[](int col) const { + const Type &operator[](int col) const + { return parent_->data_[index_ * Cols + col]; } }; -} // detail +} // detail /** Base Matrix class used by other similar classes. * @@ -80,8 +85,8 @@ public: * This is the base matrix class that can be used by all the other matrix * like data structures. */ -template -class Matrix { +template class Matrix +{ // friended with the row class so that it can access protected member data friend class detail::Row; @@ -92,7 +97,7 @@ protected: public: /// Initializes the size of the data_ vector Matrix() : data_(Rows * Cols) {} - Matrix(const std::vector& data) : data_(data) {} + Matrix(const std::vector &data) : data_(data) {} /// Returns the row size of the Matrix int rowSize() const { return Rows; } @@ -102,11 +107,12 @@ public: /** Return the row specified row as a Matrix with only one row * - * \param[in] row Row number to be returned + * @param row Row number to be returned * * Returns the row that is specified by the row variables. */ - Matrix<1, Cols, Type> getRow(int row) const { + Matrix<1, Cols, Type> getRow(int row) const + { Matrix<1, Cols, Type> rowMatrix; for (int i = 0; i < Cols; ++i) { rowMatrix[0][i] = data_[row][i]; @@ -115,7 +121,8 @@ public: } // returns the column in a column matrix - Matrix getCol(int col) const { + Matrix getCol(int col) const + { Matrix colMatrix; for (int i = 0; i < Rows; ++i) { colMatrix[i][0] = data_[i][col]; @@ -130,9 +137,10 @@ public: typename std::vector::iterator end() { return data_.end(); } /** prints out the matrix, but can also be implemented by other classes to - * print data differently - */ - virtual std::string toString() const { + * print data differently + */ + virtual std::string toString() const + { std::stringstream ss; ss << '['; for (int i = 0; i < Rows - 1; ++i) { @@ -150,17 +158,20 @@ public: return ss.str(); } - detail::Row operator[](int row) { + detail::Row operator[](int row) + { return detail::Row(this, row); } - detail::Row operator[](int row) const { - // TODO got to fix this - return detail::Row((Matrix*)this, + detail::Row operator[](int row) const + { + // @todo got to fix this + return detail::Row((Matrix *)this, row); } - Matrix& operator+=(const Matrix& rhs) { + Matrix &operator+=(const Matrix &rhs) + { std::vector out; out.reserve(data_.size()); std::transform(data_.begin(), data_.end(), rhs.data_.begin(), @@ -170,7 +181,8 @@ public: return *this; } - Matrix& operator-=(const Matrix& rhs) { + Matrix &operator-=(const Matrix &rhs) + { std::vector out; out.reserve(data_.size()); std::transform(data_.begin(), data_.end(), rhs.begin(), @@ -182,100 +194,121 @@ public: }; template -Matrix operator+(Matrix lhs, const Matrix& rhs) { +Matrix operator+(Matrix lhs, const Matrix &rhs) +{ lhs += rhs; return lhs; } template -Matrix operator-(Matrix lhs, const Matrix& rhs) { +Matrix operator-(Matrix lhs, const Matrix &rhs) +{ lhs -= rhs; return lhs; } template -Matrix operator+(Matrix lhs, const T& rhs) { - for (auto& data : lhs) { +Matrix operator+(Matrix lhs, const T &rhs) +{ + for (auto &data : lhs) { data += rhs; } return lhs; } template -Matrix operator+(const T& lhs, Matrix rhs) { - for (auto& data : rhs) { +Matrix operator+(const T &lhs, Matrix rhs) +{ + for (auto &data : rhs) { data += lhs; } return rhs; } template -Matrix operator-(Matrix lhs, const T& rhs) { - for (auto& data : lhs) { +Matrix operator-(Matrix lhs, const T &rhs) +{ + for (auto &data : lhs) { data -= rhs; } return lhs; } template -Matrix operator-(const T& lhs, Matrix rhs) { - for (auto& data : rhs) { +Matrix operator-(const T &lhs, Matrix rhs) +{ + for (auto &data : rhs) { data = lhs - data; } return rhs; } template -Matrix operator*(Matrix lhs, const T& rhs) { - for (auto& data : lhs) { +Matrix operator*(Matrix lhs, const T &rhs) +{ + for (auto &data : lhs) { data *= rhs; } return lhs; } template -Matrix operator*(const T& lhs, Matrix rhs) { - for (auto& data : rhs) { +Matrix operator*(const T &lhs, Matrix rhs) +{ + for (auto &data : rhs) { data *= lhs; } return rhs; } template -Matrix operator/(Matrix lhs, const T& rhs) { - for (auto& data : lhs) { +Matrix operator/(Matrix lhs, const T &rhs) +{ + for (auto &data : lhs) { data /= rhs; } return lhs; } template -bool operator==(const Matrix& lhs, const Matrix& rhs) { - for (int i = 0; i < M; ++i) - for (int j = 0; j < N; ++j) - if (lhs[i][j] != rhs[i][j]) return false; +bool operator==(const Matrix &lhs, const Matrix &rhs) +{ + for (int i = 0; i < M; ++i) { + for (int j = 0; j < N; ++j) { + if (lhs[i][j] != rhs[i][j]) { + return false; + } + } + } return true; } template -std::ostream& operator<<(std::ostream& os, const Matrix& mat) { +std::ostream &operator<<(std::ostream &os, const Matrix &mat) +{ return os << mat.toString(); } template -class Vector : public Matrix { +class Vector : public Matrix +{ public: Vector() : Matrix() {} - Vector(const Matrix& other) - : Matrix(other) {} - Vector(const std::vector& data) - : Matrix(data) {} + Vector(const Matrix &other) + : Matrix(other) + { + } + Vector(const std::vector &data) + : Matrix(data) + { + } - Type& operator[](int col) { return this->data_[col]; } + Type &operator[](int col) { return this->data_[col]; } - const Type& operator[](int col) const { return this->data_[col]; } + const Type &operator[](int col) const { return this->data_[col]; } - std::string toString() const override { + std::string toString() const override + { std::stringstream ss; ss << "["; for (std::size_t i = 0; i < this->data_.size() - 1; ++i) { @@ -290,40 +323,43 @@ public: * * Two dimensional vector class. */ -template -class Vector2 : public Vector<2, Type> { +template class Vector2 : public Vector<2, Type> +{ public: Vector2() : Vector<2, Type>() {} - Vector2(const std::vector& data) : Vector<2, Type>(data) {} + Vector2(const std::vector &data) : Vector<2, Type>(data) {} - Vector2(Type x, Type y) { + Vector2(Type x, Type y) + { this->data_[0] = x; this->data_[1] = y; } - Vector2(const Matrix<2, 1, Type>& other) : Vector<2, Type>(other) {} + Vector2(const Matrix<2, 1, Type> &other) : Vector<2, Type>(other) {} - Type& x() { return this->data_[0]; } + Type &x() { return this->data_[0]; } - const Type& x() const { return this->data_[0]; } + const Type &x() const { return this->data_[0]; } - Type& y() { return this->data_[1]; } + Type &y() { return this->data_[1]; } - const Type& y() const { return this->data_[1]; } + const Type &y() const { return this->data_[1]; } }; /// Definition of a 2D vector. using Vector2d = Vector2; /** Namespace containing functions that operate on matrices. */ -namespace matrix { +namespace matrix +{ /** Transposes a matrix and returns the result * * \param[in] m input matrix. */ template -Matrix transpose(const Matrix& m) { +Matrix transpose(const Matrix &m) +{ Matrix trans; for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { @@ -338,7 +374,8 @@ Matrix transpose(const Matrix& m) { * \param[in] m1,m2 Input matrices. */ template -T dot(const Matrix& m1, const Matrix& m2) { +T dot(const Matrix &m1, const Matrix &m2) +{ T sum = 0; for (int i = 0; i < R; ++i) { sum += m1[i][0] * m2[i][0]; @@ -353,7 +390,8 @@ T dot(const Matrix& m1, const Matrix& m2) { * Requires the two matrices to be compatible with multiplication. */ template -Matrix multiply(const Matrix& m1, const Matrix& m2) { +Matrix multiply(const Matrix &m1, const Matrix &m2) +{ if (N != P) { throw std::runtime_error( "Matrices don't have the right dimensions for multiplication"); @@ -370,8 +408,8 @@ Matrix multiply(const Matrix& m1, const Matrix& m2) { return res; } -} // matrix +} // matrix -} // yage +} // yage #endif diff --git a/include/YAGE/Physics/README.org b/include/YAGE/Physics/README.org index 0a2a5066..0620cc93 100644 --- a/include/YAGE/Physics/README.org +++ b/include/YAGE/Physics/README.org @@ -1,23 +1,27 @@ -#+TITLE: README -#+DATE: <2017-04-17 Mon> -#+AUTHOR: -#+EMAIL: yannherklotz@yann-arch -#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:t arch:headline -#+OPTIONS: author:t c:nil creator:comment d:(not "LOGBOOK") date:t -#+OPTIONS: e:t email:nil f:t inline:t num:t p:nil pri:nil stat:t -#+OPTIONS: tags:t tasks:t tex:t timestamp:t toc:t todo:t |:t -#+CREATOR: Emacs 25.1.1 (Org mode 8.2.10) -#+DESCRIPTION: -#+EXCLUDE_TAGS: noexport -#+KEYWORDS: -#+LANGUAGE: en -#+SELECT_TAGS: export +#+ TITLE : README +#+ DATE : <2017 - 04 - 17 Mon> +#+ AUTHOR: +#+ EMAIL : yannherklotz @yann - arch +#+ OPTIONS : ':nil *:t -:t ::t <:t H:3 \n:nil ^:t arch:headline +#+ OPTIONS : author : t c : nil creator : comment d : (not"LOGBOOK") date : t +#+ OPTIONS : e : t email : nil f : t inline : t num : t p : nil pri : nil stat : t +#+ OPTIONS : tags : t tasks : t tex : t timestamp : t toc : t todo : t | : t +#+ CREATOR : Emacs 25.1.1(Org mode 8.2.10) +#+ DESCRIPTION: +#+ EXCLUDE_TAGS : noexport +#+ KEYWORDS: +#+ LANGUAGE : en +#+ SELECT_TAGS : export -* Physics Engine +*Physics Engine -** Acceleration, speed and position + **Acceleration, + speed and position - I have a = dv/dt; v=dp/dt; - - I am going to use the second order runga kutta method with a=0, b=1, alpha=1/2 and beta=1/2 - + I have a = dv / dt; +v = dp / dt; + +I am going to use the second order runga kutta method with a = 0, b = 1, + alpha = + 1 / 2 and beta = + 1 / 2 diff --git a/include/YAGE/Physics/body.hpp b/include/YAGE/Physics/body.hpp index efeedb64..c67d2b12 100644 --- a/include/YAGE/Physics/body.hpp +++ b/include/YAGE/Physics/body.hpp @@ -11,43 +11,46 @@ #include "Math/matrix.hpp" -namespace yage { -class Body { +namespace yage +{ +class Body +{ public: - // gravity constant - static const double GRAVITY; + // gravity constant + static const double GRAVITY; protected: - // center of mass of the object - Vector2d position_ = Vector2d(0, 0); + // center of mass of the object + Vector2d position_ = Vector2d(0, 0); - // mass of the object - double mass_ = 1; + // mass of the object + double mass_ = 1; - // current velocity of the object - Vector2d velocity_ = Vector2d(0, 0); + // current velocity of the object + Vector2d velocity_ = Vector2d(0, 0); - // boolean that defines if gravity can act on the object - bool gravity_ = true; + // boolean that defines if gravity can act on the object + bool gravity_ = true; - // current acceleration - Vector2d acceleration_ = Vector2d(0, 0); + // current acceleration + Vector2d acceleration_ = Vector2d(0, 0); - // force acting on the body - Vector2d force_ = Vector2d(0, 0); + // force acting on the body + Vector2d force_ = Vector2d(0, 0); public: - // apply force to the object and update the velocity - virtual void applyForce(const Vector2d& force) = 0; - virtual void update() = 0; + // apply force to the object and update the velocity + virtual void applyForce(const Vector2d &force) = 0; + virtual void update() = 0; - double xPosition() const; - double yPosition() const; + double xPosition() const; + double yPosition() const; protected: - // protected constructor to initialize member variables - Body(Vector2d position = Vector2d(0, 0), double mass = 1, Vector2d velocity = Vector2d(0, 0), bool gravity = false); + // protected constructor to initialize member variables + Body(Vector2d position = Vector2d(0, 0), double mass = 1, + Vector2d velocity = Vector2d(0, 0), bool gravity = false); }; -} // namespace yage +} // namespace yage #endif diff --git a/include/YAGE/Physics/collider.hpp b/include/YAGE/Physics/collider.hpp index 92b90de2..7b4ff060 100644 --- a/include/YAGE/Physics/collider.hpp +++ b/include/YAGE/Physics/collider.hpp @@ -11,11 +11,13 @@ #include -namespace yage { +namespace yage +{ // The Collider class helps collision detection by providing a general shape // for different shapes to have their own collision algorithms. -class Collider { +class Collider +{ protected: // position of the object glm::vec2 position_; @@ -24,16 +26,18 @@ protected: glm::vec2 size_; public: - Collider(const glm::vec2& position, const glm::vec2& size) - : position_(position), size_(size) {} + Collider(const glm::vec2 &position, const glm::vec2 &size) + : position_(position), size_(size) + { + } // function that checks if two colliders are colliding - virtual bool collides(const Collider& collider) const = 0; + virtual bool collides(const Collider &collider) const = 0; // function that returns if a point is inside the shape - virtual bool inside(const glm::vec2& point) const = 0; + virtual bool inside(const glm::vec2 &point) const = 0; }; -} // namespace yage +} // namespace yage #endif diff --git a/include/YAGE/Physics/collisionbody.hpp b/include/YAGE/Physics/collisionbody.hpp index 5ddacacd..b7403e81 100644 --- a/include/YAGE/Physics/collisionbody.hpp +++ b/include/YAGE/Physics/collisionbody.hpp @@ -11,16 +11,18 @@ #include "Physics/body.hpp" -namespace yage { +namespace yage +{ // a collision body will be a body that is static and not affected by gravity, // with infinite mass -class CollisionBody : public Body { +class CollisionBody : public Body +{ public: CollisionBody(); virtual ~CollisionBody(); }; -} // yage +} // yage #endif diff --git a/include/YAGE/Physics/particlebody.hpp b/include/YAGE/Physics/particlebody.hpp index fd07512f..a3091773 100644 --- a/include/YAGE/Physics/particlebody.hpp +++ b/include/YAGE/Physics/particlebody.hpp @@ -6,26 +6,27 @@ * ---------------------------------------------------------------------------- */ -#ifndef YAGE_PARTICLE_BODY_HPP -#define YAGE_PARTICLE_BODY_HPP +#ifndef YAGE_PHYSICS_PARTICLE_BODY_HPP +#define YAGE_PHYSICS_PARTICLE_BODY_HPP #include "Math/matrix.hpp" +#include "Physics/body.hpp" -#include "body.hpp" +namespace yage +{ -namespace yage { - -class ParticleBody : public Body { +class ParticleBody : public Body +{ public: - ParticleBody(const Vector2d& position = Vector2d(0, 0), double mass = 1, - const Vector2d& velocity = Vector2d(0, 0), + ParticleBody(const Vector2d &position = Vector2d(0, 0), double mass = 1, + const Vector2d &velocity = Vector2d(0, 0), bool gravity = true); // apply a force to the rigid body - void applyForce(const Vector2d& force) override; + void applyForce(const Vector2d &force) override; void update() override; }; -} // yage +} // yage #endif diff --git a/include/YAGE/Physics/rectanglecollider.hpp b/include/YAGE/Physics/rectanglecollider.hpp index b66664a0..ba1d8384 100644 --- a/include/YAGE/Physics/rectanglecollider.hpp +++ b/include/YAGE/Physics/rectanglecollider.hpp @@ -13,16 +13,18 @@ #include -namespace yage { +namespace yage +{ -class RectangleCollider : public Collider { +class RectangleCollider : public Collider +{ public: - RectangleCollider(const glm::vec2& position, const glm::vec2& size); + RectangleCollider(const glm::vec2 &position, const glm::vec2 &size); - bool collides(const Collider& collider) const override; - bool inside(const glm::vec2& point) const override; + bool collides(const Collider &collider) const override; + bool inside(const glm::vec2 &point) const override; }; -} // yage +} // yage #endif diff --git a/include/YAGE/Physics/rigidbody.hpp b/include/YAGE/Physics/rigidbody.hpp index fd19dc7c..6fc969f5 100644 --- a/include/YAGE/Physics/rigidbody.hpp +++ b/include/YAGE/Physics/rigidbody.hpp @@ -13,14 +13,16 @@ #include "particlebody.hpp" -namespace yage { +namespace yage +{ -class RigidBody : public ParticleBody { +class RigidBody : public ParticleBody +{ public: - RigidBody(const Vector2d& position = Vector2d(0, 0), double mass = 1, - const Vector2d& velocity = Vector2d(0, 0), bool gravity = true); + RigidBody(const Vector2d &position = Vector2d(0, 0), double mass = 1, + const Vector2d &velocity = Vector2d(0, 0), bool gravity = true); }; -} // yage +} // yage #endif diff --git a/include/YAGE/camera2d.hpp b/include/YAGE/camera2d.hpp index e5e4e651..89f2f35c 100644 --- a/include/YAGE/camera2d.hpp +++ b/include/YAGE/camera2d.hpp @@ -14,9 +14,11 @@ #include #include -namespace yage { +namespace yage +{ -class Camera2D { +class Camera2D +{ private: bool matrix_needs_update_ = true; float scale_ = 1; @@ -28,11 +30,11 @@ public: Camera2D(int screen_width = 1280, int screen_height = 720); // update camera location - void update(GlslProgram& program); + void update(GlslProgram &program); // camera movement - void move(const glm::vec2& direction); + void move(const glm::vec2 &direction); }; -} // yage +} // yage #endif diff --git a/include/YAGE/glslprogram.hpp b/include/YAGE/glslprogram.hpp index fd97c3a0..eaa19c52 100644 --- a/include/YAGE/glslprogram.hpp +++ b/include/YAGE/glslprogram.hpp @@ -13,9 +13,11 @@ #include -namespace yage { +namespace yage +{ -class GlslProgram { +class GlslProgram +{ private: /// compiled shader program id GLuint program_id_ = 0; @@ -24,27 +26,27 @@ private: int attribute_index_ = 0; /// compiles one shader - void compileShader(const GLuint& shader, const std::string& file_path); + void compileShader(const GLuint &shader, const std::string &file_path); public: GlslProgram() = default; - GlslProgram(const GlslProgram&) = delete; - GlslProgram(GlslProgram&&) = delete; + GlslProgram(const GlslProgram &) = delete; + GlslProgram(GlslProgram &&) = delete; ~GlslProgram(); - GlslProgram& operator=(const GlslProgram&) = delete; - GlslProgram& operator=(GlslProgram&&) = delete; + GlslProgram &operator=(const GlslProgram &) = delete; + GlslProgram &operator=(GlslProgram &&) = delete; /// compiles vertex and fragment shader - void compileShaders(const std::string& vertex_shader_path, - const std::string& fragment_shader_path); + void compileShaders(const std::string &vertex_shader_path, + const std::string &fragment_shader_path); void linkShaders(); - void addAttribute(const std::string& attribute_name); - GLint getUniformLocation(const std::string& uniform_name); + void addAttribute(const std::string &attribute_name); + GLint getUniformLocation(const std::string &uniform_name); void use(); void unuse(); }; -} // yage +} // yage #endif diff --git a/include/YAGE/imageloader.hpp b/include/YAGE/imageloader.hpp index 90425cab..a9c00c4b 100644 --- a/include/YAGE/imageloader.hpp +++ b/include/YAGE/imageloader.hpp @@ -13,13 +13,15 @@ #include -namespace yage { +namespace yage +{ -class ImageLoader { +class ImageLoader +{ public: - static Texture loadPng(const std::string& file_path); + static Texture loadPng(const std::string &file_path); }; -} // yage +} // yage #endif diff --git a/include/YAGE/inputmanager.hpp b/include/YAGE/inputmanager.hpp index f8a0c710..0d5c65e7 100644 --- a/include/YAGE/inputmanager.hpp +++ b/include/YAGE/inputmanager.hpp @@ -24,6 +24,5 @@ public: void keyReleased(unsigned key); bool isKeyPressed(unsigned key) const; }; - } #endif diff --git a/include/YAGE/iomanager.hpp b/include/YAGE/iomanager.hpp index 3b1f5278..35f77e43 100644 --- a/include/YAGE/iomanager.hpp +++ b/include/YAGE/iomanager.hpp @@ -12,9 +12,11 @@ #include #include -namespace yage { +namespace yage +{ -class IoManager { +class IoManager +{ public: static bool readFileToBuffer(const std::string &file_path, std::vector &buffer); diff --git a/include/YAGE/picopng.hpp b/include/YAGE/picopng.hpp index b1318da0..ded8ffa1 100644 --- a/include/YAGE/picopng.hpp +++ b/include/YAGE/picopng.hpp @@ -6,17 +6,15 @@ * ---------------------------------------------------------------------------- */ -#include #include +#include namespace yage { extern int decodePNG(std::vector &out_image, - unsigned long &image_width, - unsigned long &image_height, - const unsigned char *in_png, - size_t in_size, - bool convert_to_rgba32 = true); + unsigned long &image_width, unsigned long &image_height, + const unsigned char *in_png, size_t in_size, + bool convert_to_rgba32 = true); } // yage diff --git a/include/YAGE/resourcemanager.hpp b/include/YAGE/resourcemanager.hpp index 3d824d61..38587dfc 100644 --- a/include/YAGE/resourcemanager.hpp +++ b/include/YAGE/resourcemanager.hpp @@ -14,16 +14,18 @@ #include -namespace yage { +namespace yage +{ -class ResourceManager { +class ResourceManager +{ private: static TextureCache texture_cache_; public: - static Texture getTexture(const std::string& texture_path); + static Texture getTexture(const std::string &texture_path); }; -} // yage +} // yage #endif diff --git a/include/YAGE/sprite.hpp b/include/YAGE/sprite.hpp index 969d0a67..4b5f2489 100644 --- a/include/YAGE/sprite.hpp +++ b/include/YAGE/sprite.hpp @@ -15,9 +15,11 @@ #include -namespace yage { +namespace yage +{ -class Sprite { +class Sprite +{ private: float x_; float y_; @@ -28,18 +30,18 @@ private: public: Sprite(); - Sprite(const Sprite&) = delete; - Sprite(Sprite&&) = delete; + Sprite(const Sprite &) = delete; + Sprite(Sprite &&) = delete; ~Sprite(); - Sprite& operator=(const Sprite&) = delete; - Sprite& operator=(Sprite&&) = delete; + Sprite &operator=(const Sprite &) = delete; + Sprite &operator=(Sprite &&) = delete; void init(float x, float y, float width, float height, - const std::string& texture_path); + const std::string &texture_path); void draw(); }; -} // yage +} // yage #endif diff --git a/include/YAGE/spritebatch.hpp b/include/YAGE/spritebatch.hpp index d47672ef..add58b43 100644 --- a/include/YAGE/spritebatch.hpp +++ b/include/YAGE/spritebatch.hpp @@ -16,13 +16,15 @@ #include -namespace yage { +namespace yage +{ class SpriteBatch; /** Glyph with information of the texture. */ -class Glyph { +class Glyph +{ private: GLuint texture_; float depth_; @@ -32,9 +34,9 @@ private: Vertex bottom_left_; public: - Glyph(GLuint texture, float depth, const Vertex& top_left, - const Vertex& top_right, const Vertex& bottom_right, - const Vertex& bottom_left); + Glyph(GLuint texture, float depth, const Vertex &top_left, + const Vertex &top_right, const Vertex &bottom_right, + const Vertex &bottom_left); GLuint texture() const { return texture_; } float depth() const { return depth_; } @@ -44,8 +46,10 @@ public: Vertex bottom_left() const { return bottom_left_; } }; -class RenderBatch { +class RenderBatch +{ friend SpriteBatch; + private: GLsizei num_vertices_; GLint offset_; @@ -59,7 +63,8 @@ public: GLuint texture() const { return texture_; } }; -class SpriteBatch { +class SpriteBatch +{ public: static const int NUM_VERTICES = 6; @@ -67,25 +72,25 @@ private: GLuint vbo_ = 0; GLuint vao_ = 0; std::vector glyphs_; - std::vector glyph_ptrs_; + std::vector glyph_ptrs_; std::vector render_batches_; public: SpriteBatch(); - SpriteBatch(const SpriteBatch&) = delete; - SpriteBatch(SpriteBatch&&) = delete; + SpriteBatch(const SpriteBatch &) = delete; + SpriteBatch(SpriteBatch &&) = delete; ~SpriteBatch(); - SpriteBatch& operator=(const SpriteBatch&) = delete; - SpriteBatch& operator=(SpriteBatch&&) = delete; + SpriteBatch &operator=(const SpriteBatch &) = delete; + SpriteBatch &operator=(SpriteBatch &&) = delete; // initialize vaos and vbos void init(); void begin(); void end(); // adds a sprite to the sprite batch to be rendered later - void draw(const glm::vec4& destination_rect, const glm::vec4& uv_rect, - GLuint texture, const Color& color, float depth); + void draw(const glm::vec4 &destination_rect, const glm::vec4 &uv_rect, + GLuint texture, const Color &color, float depth); // render the batch void render(); @@ -95,6 +100,6 @@ private: void sortGlyphs(); }; -} // namespace yage +} // namespace yage #endif diff --git a/include/YAGE/texture.hpp b/include/YAGE/texture.hpp index 65f3f651..b5fe7acd 100644 --- a/include/YAGE/texture.hpp +++ b/include/YAGE/texture.hpp @@ -11,7 +11,8 @@ #include -namespace yage { +namespace yage +{ struct Texture { GLuint id; @@ -19,6 +20,6 @@ struct Texture { int height; }; -} // yage +} // yage #endif diff --git a/include/YAGE/texturecache.hpp b/include/YAGE/texturecache.hpp index 0de5c12a..9765b919 100644 --- a/include/YAGE/texturecache.hpp +++ b/include/YAGE/texturecache.hpp @@ -13,18 +13,20 @@ #include -namespace yage { +namespace yage +{ -class TextureCache { +class TextureCache +{ private: std::unordered_map texture_map_; public: TextureCache(); - Texture getTexture(const std::string& texture_path); + Texture getTexture(const std::string &texture_path); }; -} // yage +} // yage #endif diff --git a/include/YAGE/vertex.hpp b/include/YAGE/vertex.hpp index 1026253e..9201393b 100644 --- a/include/YAGE/vertex.hpp +++ b/include/YAGE/vertex.hpp @@ -11,7 +11,8 @@ #include -namespace yage { +namespace yage +{ struct Position { float x; @@ -31,7 +32,9 @@ struct Color { Color() = default; Color(GLubyte r_, GLubyte g_, GLubyte b_, GLubyte a_) - : r(r_), g(g_), b(b_), a(a_) {} + : r(r_), g(g_), b(b_), a(a_) + { + } }; struct UV { @@ -50,27 +53,32 @@ struct Vertex { Vertex() = default; - Vertex(const Position& position_, const Color& color_, const UV& uv_) - : position(position_), color(color_), uv(uv_) {} + Vertex(const Position &position_, const Color &color_, const UV &uv_) + : position(position_), color(color_), uv(uv_) + { + } - void setPosition(float x, float y) { + void setPosition(float x, float y) + { position.x = x; position.y = y; } - void setColor(GLubyte r, GLubyte g, GLubyte b, GLubyte a) { + void setColor(GLubyte r, GLubyte g, GLubyte b, GLubyte a) + { color.r = r; color.g = g; color.b = b; color.a = a; } - void setUv(float u, float v) { + void setUv(float u, float v) + { uv.u = u; uv.v = v; } }; -} // yage +} // yage #endif diff --git a/include/YAGE/window.hpp b/include/YAGE/window.hpp index c2003a94..51b217f8 100644 --- a/include/YAGE/window.hpp +++ b/include/YAGE/window.hpp @@ -13,7 +13,8 @@ #include -namespace yage { +namespace yage +{ // window flags that can change it's appearance enum WindowFlags : unsigned { @@ -24,23 +25,24 @@ enum WindowFlags : unsigned { }; // window wrapper around SDL_Window pointer -class Window { +class Window +{ private: /// window handle - SDL_Window* window_ = nullptr; + SDL_Window *window_ = nullptr; public: Window(); - Window(const Window&) = delete; - Window(Window&&) = delete; + Window(const Window &) = delete; + Window(Window &&) = delete; /// destroys the window handle ~Window(); - Window& operator=(const Window&) = delete; - Window& operator=(Window&&) = delete; + Window &operator=(const Window &) = delete; + Window &operator=(Window &&) = delete; /// create the window, initialize the handle and update the width and height - void create(const std::string& window_name, int width, int height, + void create(const std::string &window_name, int width, int height, unsigned flags = WindowFlags::SHOWN); /// swap the buffer void swapBuffer(); @@ -48,6 +50,6 @@ public: void clearBuffer(); }; -} // namespace yage +} // namespace yage #endif diff --git a/include/YAGE/yage.hpp b/include/YAGE/yage.hpp index 31289d64..b426eed9 100644 --- a/include/YAGE/yage.hpp +++ b/include/YAGE/yage.hpp @@ -25,11 +25,11 @@ #include -namespace yage { +namespace yage +{ bool init() { return SDL_Init(SDL_INIT_VIDEO); } void quit() { SDL_Quit(); } - }; #endif diff --git a/src/body.cpp b/src/body.cpp index 9c8babf1..96d01c22 100644 --- a/src/body.cpp +++ b/src/body.cpp @@ -10,7 +10,8 @@ #include "Physics/body.hpp" -namespace yage { +namespace yage +{ const double Body::GRAVITY = -9.81; @@ -18,11 +19,10 @@ double Body::xPosition() const { return position_[0]; } double Body::yPosition() const { return position_[1]; } -Body::Body(Vector2d position, double mass, Vector2d velocity, - bool gravity) - : position_(std::move(position)), - mass_(mass), - velocity_(std::move(velocity)), - gravity_(gravity) {} +Body::Body(Vector2d position, double mass, Vector2d velocity, bool gravity) + : position_(std::move(position)), mass_(mass), + velocity_(std::move(velocity)), gravity_(gravity) +{ +} -} // yage +} // yage diff --git a/src/camera2d.cpp b/src/camera2d.cpp index 690ac98d..9f210ddc 100644 --- a/src/camera2d.cpp +++ b/src/camera2d.cpp @@ -10,15 +10,18 @@ #include -namespace yage { +namespace yage +{ Camera2D::Camera2D(int screen_width, int screen_height) - : position_(0.f, 0.f), - camera_matrix_(1.f), + : position_(0.f, 0.f), camera_matrix_(1.f), ortho_matrix_( - glm::ortho(0.f, (float)screen_width, 0.f, (float)screen_height)) {} + glm::ortho(0.f, (float)screen_width, 0.f, (float)screen_height)) +{ +} -void Camera2D::update(GlslProgram& program) { +void Camera2D::update(GlslProgram &program) +{ if (matrix_needs_update_) { glm::vec3 translate(-position_.x, -position_.y, 0.f); glm::vec3 scale(scale_, scale_, 0.f); @@ -33,9 +36,10 @@ void Camera2D::update(GlslProgram& program) { glUniformMatrix4fv(matrix_location, 1, GL_FALSE, &(camera_matrix_[0][0])); } -void Camera2D::move(const glm::vec2& direction) { +void Camera2D::move(const glm::vec2 &direction) +{ position_ += direction; matrix_needs_update_ = true; } -} // yage +} // yage diff --git a/src/glslprogram.cpp b/src/glslprogram.cpp index 6d0a60b2..d77f373d 100644 --- a/src/glslprogram.cpp +++ b/src/glslprogram.cpp @@ -12,39 +12,51 @@ #include #include -namespace yage { +namespace yage +{ -GlslProgram::~GlslProgram() { +GlslProgram::~GlslProgram() +{ // cleanup all the shaders and the program - if (fragment_shader_id_ != 0) glDeleteShader(fragment_shader_id_); + if (fragment_shader_id_ != 0) { + glDeleteShader(fragment_shader_id_); + } - if (vertex_shader_id_ != 0) glDeleteShader(vertex_shader_id_); + if (vertex_shader_id_ != 0) { + glDeleteShader(vertex_shader_id_); + } - if (program_id_ != 0) glDeleteProgram(program_id_); + if (program_id_ != 0) { + glDeleteProgram(program_id_); + } } -void GlslProgram::compileShader(const GLuint& shader, - const std::string& file_path) { +void GlslProgram::compileShader(const GLuint &shader, + const std::string &file_path) +{ // get a string with the input from the shader file std::ifstream file(file_path); - if (!file.is_open()) + if (!file.is_open()) { throw std::runtime_error("Failed to open '" + file_path + "'"); + } std::string content = ""; std::string line; - while (std::getline(file, line)) content += line + "\n"; + while (std::getline(file, line)) { + content += line + "\n"; + } file.close(); // cast source to a c string to get the address of it and input it for // compilation - const auto* vertex_source = (const GLchar*)content.c_str(); + const auto *vertex_source = (const GLchar *)content.c_str(); glShaderSource(shader, 1, &vertex_source, nullptr); glCompileShader(shader); // check if compilation was successful GLint is_compiled = 0; - glGetShaderiv(shader, GL_COMPILE_STATUS, (int*)&is_compiled); + glGetShaderiv(shader, GL_COMPILE_STATUS, (int *)&is_compiled); // if it isn't compiled throw exception to clean up if (is_compiled == GL_FALSE) { @@ -53,34 +65,38 @@ void GlslProgram::compileShader(const GLuint& shader, std::vector error_log(max_length); glGetShaderInfoLog(shader, max_length, &max_length, &error_log[0]); - std::string error_log_str((const char*)&error_log[0]); + std::string error_log_str((const char *)&error_log[0]); throw std::runtime_error("Couldn't compile " + file_path + " : " + error_log_str); } } -void GlslProgram::compileShaders(const std::string& vertex_shader_path, - const std::string& fragment_shader_path) { +void GlslProgram::compileShaders(const std::string &vertex_shader_path, + const std::string &fragment_shader_path) +{ // create the program that will be run on GPU program_id_ = glCreateProgram(); // create vertex shader vertex_shader_id_ = glCreateShader(GL_VERTEX_SHADER); - if (vertex_shader_id_ == 0) + if (vertex_shader_id_ == 0) { throw std::runtime_error("Vertex shader failed to be created"); + } // create fragment shader fragment_shader_id_ = glCreateShader(GL_FRAGMENT_SHADER); - if (fragment_shader_id_ == 0) + if (fragment_shader_id_ == 0) { throw std::runtime_error("Fragment shader failed to be created"); + } // compile the two shaders compileShader(vertex_shader_id_, vertex_shader_path); compileShader(fragment_shader_id_, fragment_shader_path); } -void GlslProgram::linkShaders() { +void GlslProgram::linkShaders() +{ // attach the shaders that we want glAttachShader(program_id_, vertex_shader_id_); glAttachShader(program_id_, fragment_shader_id_); @@ -89,7 +105,7 @@ void GlslProgram::linkShaders() { glLinkProgram(program_id_); GLint is_linked = 0; - glGetProgramiv(program_id_, GL_LINK_STATUS, (int*)&is_linked); + glGetProgramiv(program_id_, GL_LINK_STATUS, (int *)&is_linked); if (is_linked == GL_FALSE) { GLint max_length = 0; glGetProgramiv(program_id_, GL_INFO_LOG_LENGTH, &max_length); @@ -98,7 +114,7 @@ void GlslProgram::linkShaders() { glGetProgramInfoLog(program_id_, max_length, &max_length, &error_log[0]); - std::string error_log_str((const char*)&error_log[0]); + std::string error_log_str((const char *)&error_log[0]); throw std::runtime_error("Could not link program : " + error_log_str); } @@ -112,26 +128,35 @@ void GlslProgram::linkShaders() { glDeleteShader(vertex_shader_id_); } -void GlslProgram::addAttribute(const std::string& attribute_name) { +void GlslProgram::addAttribute(const std::string &attribute_name) +{ glBindAttribLocation(program_id_, attribute_index_++, attribute_name.c_str()); } -GLint GlslProgram::getUniformLocation(const std::string& uniform_name) { +GLint GlslProgram::getUniformLocation(const std::string &uniform_name) +{ GLint location = glGetUniformLocation(program_id_, uniform_name.c_str()); - if ((GLuint)location == GL_INVALID_INDEX) + if ((GLuint)location == GL_INVALID_INDEX) { throw std::runtime_error("'" + uniform_name + "' not found"); + } return location; } -void GlslProgram::use() { +void GlslProgram::use() +{ glUseProgram(program_id_); - for (int i = 0; i < attribute_index_; ++i) glEnableVertexAttribArray(i); + for (int i = 0; i < attribute_index_; ++i) { + glEnableVertexAttribArray(i); + } } -void GlslProgram::unuse() { - for (int i = 0; i < attribute_index_; ++i) glDisableVertexAttribArray(i); +void GlslProgram::unuse() +{ + for (int i = 0; i < attribute_index_; ++i) { + glDisableVertexAttribArray(i); + } glUseProgram(0); } -} // yage +} // yage diff --git a/src/imageloader.cpp b/src/imageloader.cpp index 241cf588..95c73021 100644 --- a/src/imageloader.cpp +++ b/src/imageloader.cpp @@ -17,37 +17,44 @@ namespace yage Texture ImageLoader::loadPng(const std::string &file_path) { - Texture texture = {}; + Texture texture = {}; - std::vector in; - std::vector out; - unsigned long width, height; + std::vector in; + std::vector out; + unsigned long width, height; - if(!IoManager::readFileToBuffer(file_path, in)) - throw std::runtime_error("Failed to load '"+file_path+"' to buffer"); + if (!IoManager::readFileToBuffer(file_path, in)) { + throw std::runtime_error("Failed to load '" + file_path + + "' to buffer"); + } - int error_code = decodePNG(out, width, height, &in[0], in.size()); - if(error_code != 0) - throw std::runtime_error("Failed to load '"+file_path+"' to png with error code"+std::to_string(error_code)); + int error_code = decodePNG(out, width, height, &in[0], in.size()); + if (error_code != 0) { + throw std::runtime_error("Failed to load '" + file_path + + "' to png with error code" + + std::to_string(error_code)); + } - glGenTextures(1, &texture.id); - - glBindTexture(GL_TEXTURE_2D, texture.id); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &out[0]); + glGenTextures(1, &texture.id); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glBindTexture(GL_TEXTURE_2D, texture.id); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, &out[0]); - glGenerateMipmap(GL_TEXTURE_2D); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + GL_LINEAR_MIPMAP_LINEAR); - glBindTexture(GL_TEXTURE_2D, 0); + glGenerateMipmap(GL_TEXTURE_2D); - texture.width = (int)width; - texture.height = (int)height; + glBindTexture(GL_TEXTURE_2D, 0); - return texture; + texture.width = (int)width; + texture.height = (int)height; + + return texture; } - + } // yage diff --git a/src/inputmanager.cpp b/src/inputmanager.cpp index 2583201a..cbb9d2df 100644 --- a/src/inputmanager.cpp +++ b/src/inputmanager.cpp @@ -8,15 +8,20 @@ #include "inputmanager.hpp" -namespace yage { +namespace yage +{ void InputManager::keyPressed(unsigned key) { key_map_[key] = true; } void InputManager::keyReleased(unsigned key) { key_map_[key] = false; } -bool InputManager::isKeyPressed(unsigned key) const { +bool InputManager::isKeyPressed(unsigned key) const +{ auto key_index = key_map_.find(key); - if (key_index != key_map_.end()) return key_index->second; + if (key_index != key_map_.end()) { + return key_index->second; + } return false; } -} + +} // yage diff --git a/src/iomanager.cpp b/src/iomanager.cpp index 6059bfbc..60cd7201 100644 --- a/src/iomanager.cpp +++ b/src/iomanager.cpp @@ -11,13 +11,16 @@ #include #include -namespace yage { +namespace yage +{ -bool IoManager::readFileToBuffer(const std::string& file_path, - std::vector& buffer) { +bool IoManager::readFileToBuffer(const std::string &file_path, + std::vector &buffer) +{ std::ifstream file(file_path, std::ios::binary); - if (!file.is_open()) + if (!file.is_open()) { throw std::runtime_error("Could not open '" + file_path + "'"); + } // seek to the end file.seekg(0, std::ios::end); @@ -30,10 +33,10 @@ bool IoManager::readFileToBuffer(const std::string& file_path, file_size -= file.tellg(); buffer.resize(file_size); - file.read((char*)&buffer[0], file_size); + file.read((char *)&buffer[0], file_size); file.close(); return true; } -} // yage +} // yage diff --git a/src/particlebody.cpp b/src/particlebody.cpp index e120d3c5..20682368 100644 --- a/src/particlebody.cpp +++ b/src/particlebody.cpp @@ -11,15 +11,19 @@ #include #include -namespace yage { +namespace yage +{ -ParticleBody::ParticleBody(const Vector2d& position, double mass, - const Vector2d& velocity, bool gravity) - : Body(position, mass, velocity, gravity) {} +ParticleBody::ParticleBody(const Vector2d &position, double mass, + const Vector2d &velocity, bool gravity) + : Body(position, mass, velocity, gravity) +{ +} -void ParticleBody::applyForce(const Vector2d& force) { force_ += force; } +void ParticleBody::applyForce(const Vector2d &force) { force_ += force; } -void ParticleBody::update() { +void ParticleBody::update() +{ // set the time_step for 60fps double time_step = 1.0 / 60.0; @@ -31,11 +35,12 @@ void ParticleBody::update() { (0.5 * last_acceleration * std::pow(time_step, 2)); // update the acceleration - if (gravity_) + if (gravity_) { acceleration_ = Vector2d(force_.x() / mass_, (GRAVITY + force_.y()) / mass_); - else + } else { acceleration_ = Vector2d(force_.x() / mass_, force_.y() / mass_); + } Vector2d avg_acceleration = (acceleration_ + last_acceleration) / 2.0; @@ -43,4 +48,4 @@ void ParticleBody::update() { velocity_ += avg_acceleration * time_step; } -} // yage +} // yage diff --git a/src/picopng.cpp b/src/picopng.cpp index f75390de..337038ba 100644 --- a/src/picopng.cpp +++ b/src/picopng.cpp @@ -1,7 +1,8 @@ #include #include -namespace yage { +namespace yage +{ /* decodePNG: The picoPNG function, decodes a PNG file buffer in memory, into a @@ -30,9 +31,10 @@ namespace yage { information. return: 0 if success, not 0 if some error occured. */ -int decodePNG(std::vector& out_image, unsigned long& image_width, - unsigned long& image_height, const unsigned char* in_png, - size_t in_size, bool convert_to_rgba32) { +int decodePNG(std::vector &out_image, unsigned long &image_width, + unsigned long &image_height, const unsigned char *in_png, + size_t in_size, bool convert_to_rgba32) +{ // picoPNG version 20101224 // Copyright (c) 2005-2010 Lode Vandevenne // @@ -82,409 +84,465 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static const unsigned long CLCL[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, - 11, 4, 12, 3, 13, 2, 14, 1, 15}; // code length code lengths - struct Zlib // nested functions for zlib decompression + 11, 4, 12, 3, 13, 2, 14, 1, 15}; // code length code lengths + struct Zlib // nested functions for zlib decompression { - static unsigned long readBitFromStream(size_t& bitp, - const unsigned char* bits) { + static unsigned long readBitFromStream(size_t &bitp, + const unsigned char *bits) + { unsigned long result = (bits[bitp >> 3] >> (bitp & 0x7)) & 1; bitp++; return result; } - static unsigned long readBitsFromStream(size_t& bitp, - const unsigned char* bits, - size_t nbits) { + static unsigned long readBitsFromStream(size_t &bitp, + const unsigned char *bits, + size_t nbits) + { unsigned long result = 0; - for (size_t i = 0; i < nbits; i++) + for (size_t i = 0; i < nbits; i++) { result += (readBitFromStream(bitp, bits)) << i; + } return result; } struct HuffmanTree { - int makeFromLengths( - const std::vector& bitlen, - unsigned long maxbitlen) { // make tree given the lengths + int makeFromLengths(const std::vector &bitlen, + unsigned long maxbitlen) + { // make tree given the lengths unsigned long numcodes = (unsigned long)(bitlen.size()), treepos = 0, nodefilled = 0; std::vector tree1d(numcodes), blcount(maxbitlen + 1, 0), nextcode(maxbitlen + 1, 0); - for (unsigned long bits = 0; bits < numcodes; bits++) - blcount[bitlen[bits]]++; // count number of instances of - // each code length - for (unsigned long bits = 1; bits <= maxbitlen; bits++) + for (unsigned long bits = 0; bits < numcodes; bits++) { + blcount[bitlen[bits]]++; // count number of instances of + } + // each code length + for (unsigned long bits = 1; bits <= maxbitlen; bits++) { nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1; - for (unsigned long n = 0; n < numcodes; n++) - if (bitlen[n] != 0) + } + for (unsigned long n = 0; n < numcodes; n++) { + if (bitlen[n] != 0) { tree1d[n] = - nextcode[bitlen[n]]++; // generate all the codes + nextcode[bitlen[n]]++; // generate all the codes + } + } tree2d.clear(); - tree2d.resize(numcodes * 2, 32767); // 32767 here means the - // tree2d isn't filled - // there yet - for (unsigned long n = 0; n < numcodes; n++) // the codes + tree2d.resize(numcodes * 2, 32767); // 32767 here means the + // tree2d isn't filled + // there yet + for (unsigned long n = 0; n < numcodes; n++) { // the codes for (unsigned long i = 0; i < bitlen[n]; - i++) // the bits for this code + i++) // the bits for this code { unsigned long bit = (tree1d[n] >> (bitlen[n] - i - 1)) & 1; - if (treepos > numcodes - 2) return 55; + if (treepos > numcodes - 2) { + return 55; + } if (tree2d[2 * treepos + bit] == - 32767) // not yet filled in + 32767) // not yet filled in { if (i + 1 == bitlen[n]) { tree2d[2 * treepos + bit] = n; treepos = 0; - } // last bit + } // last bit else { tree2d[2 * treepos + bit] = ++nodefilled + numcodes; treepos = nodefilled; - } // addresses are encoded as values > numcodes - } else + } // addresses are encoded as values > numcodes + } else { treepos = tree2d[2 * treepos + bit] - - numcodes; // subtract numcodes from - // address to get address value + numcodes; // subtract numcodes from + } + // address to get address value } + } return 0; } - int decode( - bool& decoded, unsigned long& result, size_t& treepos, - unsigned long bit) const { // Decodes a symbol from the tree + int decode(bool &decoded, unsigned long &result, size_t &treepos, + unsigned long bit) const + { // Decodes a symbol from the tree unsigned long numcodes = (unsigned long)tree2d.size() / 2; - if (treepos >= numcodes) - return 11; // error: you appeared outside the codetree + if (treepos >= numcodes) { + return 11; // error: you appeared outside the codetree + } result = tree2d[2 * treepos + bit]; decoded = (result < numcodes); treepos = decoded ? 0 : result - numcodes; return 0; } - std::vector tree2d; // 2D representation of a - // huffman tree: The one - // dimension is "0" or "1", the - // other contains all nodes and - // leaves of the tree. + std::vector tree2d; // 2D representation of a + // huffman tree: The one + // dimension is "0" or "1", the + // other contains all nodes and + // leaves of the tree. }; struct Inflator { int error; - void inflate(std::vector& out, - const std::vector& in, - size_t inpos = 0) { - size_t bp = 0, pos = 0; // bit pointer and byte pointer + void inflate(std::vector &out, + const std::vector &in, size_t inpos = 0) + { + size_t bp = 0, pos = 0; // bit pointer and byte pointer error = 0; unsigned long BFINAL = 0; while (!BFINAL && !error) { if (bp >> 3 >= in.size()) { error = 52; return; - } // error, bit pointer will jump past memory + } // error, bit pointer will jump past memory BFINAL = readBitFromStream(bp, &in[inpos]); unsigned long BTYPE = readBitFromStream(bp, &in[inpos]); BTYPE += 2 * readBitFromStream(bp, &in[inpos]); if (BTYPE == 3) { error = 20; return; - } // error: invalid BTYPE - else if (BTYPE == 0) + } // error: invalid BTYPE + else if (BTYPE == 0) { inflateNoCompression(out, &in[inpos], bp, pos, in.size()); - else + } else { inflateHuffmanBlock(out, &in[inpos], bp, pos, in.size(), BTYPE); + } } - if (!error) - out.resize(pos); // Only now we know the true size of out, - // resize it to that + if (!error) { + out.resize(pos); // Only now we know the true size of out, + } + // resize it to that } - void generateFixedTrees(HuffmanTree& tree, - HuffmanTree& treeD) // get the tree of a - // deflated block with - // fixed tree + void generateFixedTrees(HuffmanTree &tree, + HuffmanTree &treeD) // get the tree of a + // deflated block with + // fixed tree { std::vector bitlen(288, 8), bitlenD(32, 5); ; - for (size_t i = 144; i <= 255; i++) bitlen[i] = 9; - for (size_t i = 256; i <= 279; i++) bitlen[i] = 7; + for (size_t i = 144; i <= 255; i++) { + bitlen[i] = 9; + } + for (size_t i = 256; i <= 279; i++) { + bitlen[i] = 7; + } tree.makeFromLengths(bitlen, 15); treeD.makeFromLengths(bitlenD, 15); } HuffmanTree codetree, codetreeD, - codelengthcodetree; // the code tree for Huffman codes, dist - // codes, and code length codes - unsigned long huffmanDecodeSymbol( - const unsigned char* in, size_t& bp, - const HuffmanTree& codetree, - size_t inlength) { // decode a single symbol from given list of - // bits with given code tree. return value - // is the symbol + codelengthcodetree; // the code tree for Huffman codes, dist + // codes, and code length codes + unsigned long huffmanDecodeSymbol(const unsigned char *in, + size_t &bp, + const HuffmanTree &codetree, + size_t inlength) + { // decode a single symbol from given list of + // bits with given code tree. return value + // is the symbol bool decoded; unsigned long ct; for (size_t treepos = 0;;) { if ((bp & 0x07) == 0 && (bp >> 3) > inlength) { error = 10; return 0; - } // error: end reached without endcode + } // error: end reached without endcode error = codetree.decode(decoded, ct, treepos, readBitFromStream(bp, in)); - if (error) return 0; // stop, an error happened - if (decoded) return ct; + if (error) { + return 0; // stop, an error happened + } + if (decoded) { + return ct; + } } } - void getTreeInflateDynamic( - HuffmanTree& tree, HuffmanTree& treeD, const unsigned char* in, - size_t& bp, - size_t inlength) { // get the tree of a deflated block with - // dynamic tree, the tree itself is also - // Huffman compressed with a known tree + void getTreeInflateDynamic(HuffmanTree &tree, HuffmanTree &treeD, + const unsigned char *in, size_t &bp, + size_t inlength) + { // get the tree of a deflated block with + // dynamic tree, the tree itself is also + // Huffman compressed with a known tree std::vector bitlen(288, 0), bitlenD(32, 0); if (bp >> 3 >= inlength - 2) { error = 49; return; - } // the bit pointer is or will go past the memory + } // the bit pointer is or will go past the memory size_t HLIT = readBitsFromStream(bp, in, 5) + - 257; // number of literal/length codes + 257 + 257; // number of literal/length codes + 257 size_t HDIST = readBitsFromStream(bp, in, 5) + - 1; // number of dist codes + 1 + 1; // number of dist codes + 1 size_t HCLEN = readBitsFromStream(bp, in, 4) + - 4; // number of code length codes + 4 + 4; // number of code length codes + 4 std::vector codelengthcode( - 19); // lengths of tree to decode the lengths of the - // dynamic tree - for (size_t i = 0; i < 19; i++) + 19); // lengths of tree to decode the lengths of the + // dynamic tree + for (size_t i = 0; i < 19; i++) { codelengthcode[CLCL[i]] = (i < HCLEN) ? readBitsFromStream(bp, in, 3) : 0; + } error = codelengthcodetree.makeFromLengths(codelengthcode, 7); - if (error) return; + if (error) { + return; + } size_t i = 0, replength; while (i < HLIT + HDIST) { unsigned long code = huffmanDecodeSymbol( in, bp, codelengthcodetree, inlength); - if (error) return; + if (error) { + return; + } if (code <= 15) { - if (i < HLIT) + if (i < HLIT) { bitlen[i++] = code; - else + } else { bitlenD[i++ - HLIT] = code; - } // a length code - else if (code == 16) // repeat previous + } + } // a length code + else if (code == 16) // repeat previous { if (bp >> 3 >= inlength) { error = 50; return; - } // error, bit pointer jumps past memory + } // error, bit pointer jumps past memory replength = 3 + readBitsFromStream(bp, in, 2); - unsigned long value; // set value to the previous code - if ((i - 1) < HLIT) + unsigned long value; // set value to the previous code + if ((i - 1) < HLIT) { value = bitlen[i - 1]; - else + } else { value = bitlenD[i - HLIT - 1]; + } for (size_t n = 0; n < replength; - n++) // repeat this value in the next lengths + n++) // repeat this value in the next lengths { if (i >= HLIT + HDIST) { error = 13; return; - } // error: i is larger than the amount of codes - if (i < HLIT) + } // error: i is larger than the amount of codes + if (i < HLIT) { bitlen[i++] = value; - else + } else { bitlenD[i++ - HLIT] = value; + } } - } else if (code == 17) // repeat "0" 3-10 times + } else if (code == 17) // repeat "0" 3-10 times { if (bp >> 3 >= inlength) { error = 50; return; - } // error, bit pointer jumps past memory + } // error, bit pointer jumps past memory replength = 3 + readBitsFromStream(bp, in, 3); for (size_t n = 0; n < replength; - n++) // repeat this value in the next lengths + n++) // repeat this value in the next lengths { if (i >= HLIT + HDIST) { error = 14; return; - } // error: i is larger than the amount of codes - if (i < HLIT) + } // error: i is larger than the amount of codes + if (i < HLIT) { bitlen[i++] = 0; - else + } else { bitlenD[i++ - HLIT] = 0; + } } - } else if (code == 18) // repeat "0" 11-138 times + } else if (code == 18) // repeat "0" 11-138 times { if (bp >> 3 >= inlength) { error = 50; return; - } // error, bit pointer jumps past memory + } // error, bit pointer jumps past memory replength = 11 + readBitsFromStream(bp, in, 7); for (size_t n = 0; n < replength; - n++) // repeat this value in the next lengths + n++) // repeat this value in the next lengths { if (i >= HLIT + HDIST) { error = 15; return; - } // error: i is larger than the amount of codes - if (i < HLIT) + } // error: i is larger than the amount of codes + if (i < HLIT) { bitlen[i++] = 0; - else + } else { bitlenD[i++ - HLIT] = 0; + } } } else { error = 16; return; - } // error: somehow an unexisting code appeared. This can - // never happen. + } // error: somehow an unexisting code appeared. This can + // never happen. } if (bitlen[256] == 0) { error = 64; return; - } // the length of the end code 256 must be larger than 0 + } // the length of the end code 256 must be larger than 0 error = tree.makeFromLengths(bitlen, 15); - if (error) - return; // now we've finally got HLIT and HDIST, so - // generate the code trees, and the function is - // done + if (error) { + return; // now we've finally got HLIT and HDIST, so + } + // generate the code trees, and the function is + // done error = treeD.makeFromLengths(bitlenD, 15); - if (error) return; + if (error) { + return; + } } - void inflateHuffmanBlock(std::vector& out, - const unsigned char* in, size_t& bp, - size_t& pos, size_t inlength, - unsigned long btype) { + void inflateHuffmanBlock(std::vector &out, + const unsigned char *in, size_t &bp, + size_t &pos, size_t inlength, + unsigned long btype) + { if (btype == 1) { generateFixedTrees(codetree, codetreeD); } else if (btype == 2) { getTreeInflateDynamic(codetree, codetreeD, in, bp, inlength); - if (error) return; + if (error) { + return; + } } for (;;) { unsigned long code = huffmanDecodeSymbol(in, bp, codetree, inlength); - if (error) return; - if (code == 256) - return; // end code - else if (code <= 255) // literal symbol + if (error) { + return; + } + if (code == 256) { + return; // end code + } else if (code <= 255) // literal symbol { - if (pos >= out.size()) - out.resize((pos + 1) * 2); // reserve more room + if (pos >= out.size()) { + out.resize((pos + 1) * 2); // reserve more room + } out[pos++] = (unsigned char)(code); - } else if (code >= 257 && code <= 285) // length code + } else if (code >= 257 && code <= 285) // length code { size_t length = LENBASE[code - 257], numextrabits = LENEXTRA[code - 257]; if ((bp >> 3) >= inlength) { error = 51; return; - } // error, bit pointer will jump past memory + } // error, bit pointer will jump past memory length += readBitsFromStream(bp, in, numextrabits); unsigned long codeD = huffmanDecodeSymbol(in, bp, codetreeD, inlength); - if (error) return; + if (error) { + return; + } if (codeD > 29) { error = 18; return; - } // error: invalid dist code (30-31 are never used) + } // error: invalid dist code (30-31 are never used) unsigned long dist = DISTBASE[codeD], numextrabitsD = DISTEXTRA[codeD]; if ((bp >> 3) >= inlength) { error = 51; return; - } // error, bit pointer will jump past memory + } // error, bit pointer will jump past memory dist += readBitsFromStream(bp, in, numextrabitsD); - size_t start = pos, back = start - dist; // backwards - if (pos + length >= out.size()) - out.resize((pos + length) * 2); // reserve more - // room + size_t start = pos, back = start - dist; // backwards + if (pos + length >= out.size()) { + out.resize((pos + length) * 2); // reserve more + } + // room for (size_t i = 0; i < length; i++) { out[pos++] = out[back++]; - if (back >= start) back = start - dist; + if (back >= start) { + back = start - dist; + } } } } } - void inflateNoCompression(std::vector& out, - const unsigned char* in, size_t& bp, - size_t& pos, size_t inlength) { - while ((bp & 0x7) != 0) bp++; // go to first boundary of byte + void inflateNoCompression(std::vector &out, + const unsigned char *in, size_t &bp, + size_t &pos, size_t inlength) + { + while ((bp & 0x7) != 0) { + bp++; // go to first boundary of byte + } size_t p = bp / 8; if (p >= inlength - 4) { error = 52; return; - } // error, bit pointer will jump past memory + } // error, bit pointer will jump past memory unsigned long LEN = in[p] + 256 * in[p + 1], NLEN = in[p + 2] + 256 * in[p + 3]; p += 4; if (LEN + NLEN != 65535) { error = 21; return; - } // error: NLEN is not one's complement of LEN - if (pos + LEN >= out.size()) out.resize(pos + LEN); + } // error: NLEN is not one's complement of LEN + if (pos + LEN >= out.size()) { + out.resize(pos + LEN); + } if (p + LEN > inlength) { error = 23; return; - } // error: reading outside of in buffer - for (unsigned long n = 0; n < LEN; n++) - out[pos++] = in[p++]; // read LEN bytes of literal data + } // error: reading outside of in buffer + for (unsigned long n = 0; n < LEN; n++) { + out[pos++] = in[p++]; // read LEN bytes of literal data + } bp = p * 8; } }; - int decompress( - std::vector& out, - const std::vector& in) // returns error value + int + decompress(std::vector &out, + const std::vector &in) // returns error value { Inflator inflator; if (in.size() < 2) { return 53; - } // error, size of zlib data too small + } // error, size of zlib data too small if ((in[0] * 256 + in[1]) % 31 != 0) { return 24; - } // error: 256 * in[0] + in[1] must be a multiple of 31, the - // FCHECK value is supposed to be made that way + } // error: 256 * in[0] + in[1] must be a multiple of 31, the + // FCHECK value is supposed to be made that way unsigned long CM = in[0] & 15, CINFO = (in[0] >> 4) & 15, FDICT = (in[1] >> 5) & 1; if (CM != 8 || CINFO > 7) { return 25; - } // error: only compression method 8: inflate with sliding window - // of 32k is supported by the PNG spec + } // error: only compression method 8: inflate with sliding window + // of 32k is supported by the PNG spec if (FDICT != 0) { return 26; - } // error: the specification of PNG says about the zlib stream: - // "The additional flags shall not specify a preset dictionary." + } // error: the specification of PNG says about the zlib stream: + // "The additional flags shall not specify a preset dictionary." inflator.inflate(out, in, 2); return inflator - .error; // note: adler32 checksum was skipped and ignored + .error; // note: adler32 checksum was skipped and ignored } }; - struct PNG // nested functions for PNG decoding + struct PNG // nested functions for PNG decoding { struct Info { unsigned long width, height, colorType, bitDepth, compressionMethod, filterMethod, interlaceMethod, key_r, key_g, key_b; - bool key_defined; // is a transparent color key given? + bool key_defined; // is a transparent color key given? std::vector palette; } info; int error; - void decode(std::vector& out, const unsigned char* in, - size_t size, bool convert_to_rgba32) { + void decode(std::vector &out, const unsigned char *in, + size_t size, bool convert_to_rgba32) + { error = 0; if (size == 0 || in == nullptr) { error = 48; return; - } // the given data is empty + } // the given data is empty readPngHeader(&in[0], size); - if (error) return; - size_t pos = 33; // first byte of the first chunk after the header - std::vector idat; // the data from idat chunks + if (error) { + return; + } + size_t pos = 33; // first byte of the first chunk after the header + std::vector idat; // the data from idat chunks bool IEND = false, known_type = true; info.key_defined = false; - while (!IEND) // loop through the chunks, ignoring unknown chunks - // and stopping at IEND chunk. IDAT data is put at - // the start of the in buffer + while (!IEND) // loop through the chunks, ignoring unknown chunks + // and stopping at IEND chunk. IDAT data is put at + // the start of the in buffer { if (pos + 8 >= size) { error = 30; return; - } // error: size of the in buffer too small to contain next - // chunk + } // error: size of the in buffer too small to contain next + // chunk size_t chunkLength = read32bitInt(&in[pos]); pos += 4; if (chunkLength > 2147483647) { @@ -494,12 +552,12 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, if (pos + chunkLength >= size) { error = 35; return; - } // error: size of the in buffer too small to contain next - // chunk + } // error: size of the in buffer too small to contain next + // chunk if (in[pos + 0] == 'I' && in[pos + 1] == 'D' && in[pos + 2] == 'A' && in[pos + 3] == - 'T') // IDAT chunk, containing compressed image data + 'T') // IDAT chunk, containing compressed image data { idat.insert(idat.end(), &in[pos + 4], &in[pos + 4 + chunkLength]); @@ -510,39 +568,41 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, IEND = true; } else if (in[pos + 0] == 'P' && in[pos + 1] == 'L' && in[pos + 2] == 'T' && - in[pos + 3] == 'E') // palette chunk (PLTE) + in[pos + 3] == 'E') // palette chunk (PLTE) { - pos += 4; // go after the 4 letters + pos += 4; // go after the 4 letters info.palette.resize(4 * (chunkLength / 3)); if (info.palette.size() > (4 * 256)) { error = 38; return; - } // error: palette too big + } // error: palette too big for (size_t i = 0; i < info.palette.size(); i += 4) { - for (size_t j = 0; j < 3; j++) - info.palette[i + j] = in[pos++]; // RGB - info.palette[i + 3] = 255; // alpha + for (size_t j = 0; j < 3; j++) { + info.palette[i + j] = in[pos++]; // RGB + } + info.palette[i + 3] = 255; // alpha } } else if (in[pos + 0] == 't' && in[pos + 1] == 'R' && in[pos + 2] == 'N' && in[pos + 3] == - 'S') // palette transparency chunk (tRNS) + 'S') // palette transparency chunk (tRNS) { - pos += 4; // go after the 4 letters + pos += 4; // go after the 4 letters if (info.colorType == 3) { if (4 * chunkLength > info.palette.size()) { error = 39; return; - } // error: more alpha values given than there are - // palette entries - for (size_t i = 0; i < chunkLength; i++) + } // error: more alpha values given than there are + // palette entries + for (size_t i = 0; i < chunkLength; i++) { info.palette[4 * i + 3] = in[pos++]; + } } else if (info.colorType == 0) { if (chunkLength != 2) { error = 40; return; - } // error: this chunk must be 2 bytes for greyscale - // image + } // error: this chunk must be 2 bytes for greyscale + // image info.key_defined = true; info.key_r = info.key_g = info.key_b = 256 * in[pos] + in[pos + 1]; @@ -551,7 +611,7 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, if (chunkLength != 6) { error = 41; return; - } // error: this chunk must be 6 bytes for RGB image + } // error: this chunk must be 6 bytes for RGB image info.key_defined = true; info.key_r = 256 * in[pos] + in[pos + 1]; pos += 2; @@ -562,78 +622,84 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, } else { error = 42; return; - } // error: tRNS chunk not allowed for other color models - } else // it's not an implemented chunk type, so ignore it: - // skip over the data + } // error: tRNS chunk not allowed for other color models + } else // it's not an implemented chunk type, so ignore it: + // skip over the data { if (!(in[pos + 0] & 32)) { error = 69; return; - } // error: unknown critical chunk (5th bit of first byte - // of chunk type is 0) - pos += (chunkLength + 4); // skip 4 letters and - // uninterpreted data of - // unimplemented chunk + } // error: unknown critical chunk (5th bit of first byte + // of chunk type is 0) + pos += (chunkLength + 4); // skip 4 letters and + // uninterpreted data of + // unimplemented chunk known_type = false; } - pos += 4; // step over CRC (which is ignored) + pos += 4; // step over CRC (which is ignored) } unsigned long bpp = getBpp(info); std::vector scanlines( ((info.width * (info.height * bpp + 7)) / 8) + - info.height); // now the out buffer will be filled - Zlib zlib; // decompress with the Zlib decompressor + info.height); // now the out buffer will be filled + Zlib zlib; // decompress with the Zlib decompressor error = zlib.decompress(scanlines, idat); - if (error) - return; // stop if the zlib decompressor returned an error + if (error) { + return; // stop if the zlib decompressor returned an error + } size_t bytewidth = (bpp + 7) / 8, outlength = (info.height * info.width * bpp + 7) / 8; - out.resize(outlength); // time to fill the out buffer - unsigned char* out_ = - outlength ? &out[0] : nullptr; // use a regular pointer to the - // std::vector for faster code if - // compiled without optimization - if (info.interlaceMethod == 0) // no interlace, just filter + out.resize(outlength); // time to fill the out buffer + unsigned char *out_ = + outlength ? &out[0] : nullptr; // use a regular pointer to the + // std::vector for faster code if + // compiled without optimization + if (info.interlaceMethod == 0) // no interlace, just filter { size_t linestart = 0, linelength = (info.width * bpp + 7) / - 8; // length in bytes of a scanline, - // excluding the filtertype byte - if (bpp >= 8) // byte per byte + 8; // length in bytes of a scanline, + // excluding the filtertype byte + if (bpp >= 8) { // byte per byte for (unsigned long y = 0; y < info.height; y++) { unsigned long filterType = scanlines[linestart]; - const unsigned char* prevline = + const unsigned char *prevline = (y == 0) ? nullptr : &out_[(y - 1) * info.width * bytewidth]; unFilterScanline(&out_[linestart - y], &scanlines[linestart + 1], prevline, bytewidth, filterType, linelength); - if (error) return; + if (error) { + return; + } linestart += - (1 + linelength); // go to start of next scanline + (1 + linelength); // go to start of next scanline } - else // less than 8 bits per pixel, so fill it up bit per bit + } else // less than 8 bits per pixel, so fill it up bit per bit { std::vector templine( - (info.width * bpp + 7) >> 3); // only used if bpp < 8 + (info.width * bpp + 7) >> 3); // only used if bpp < 8 for (size_t y = 0, obp = 0; y < info.height; y++) { unsigned long filterType = scanlines[linestart]; - const unsigned char* prevline = + const unsigned char *prevline = (y == 0) ? nullptr : &out_[(y - 1) * info.width * bytewidth]; unFilterScanline(&templine[0], &scanlines[linestart + 1], prevline, bytewidth, filterType, linelength); - if (error) return; - for (size_t bp = 0; bp < info.width * bpp;) + if (error) { + return; + } + for (size_t bp = 0; bp < info.width * bpp;) { setBitOfReversedStream( obp, out_, readBitFromReversedStream(bp, &templine[0])); + } linestart += - (1 + linelength); // go to start of next scanline + (1 + linelength); // go to start of next scanline } } - } else // interlaceMethod is 1 (Adam7) + } else // interlaceMethod is 1 (Adam7) { size_t passw[7] = {(info.width + 7) / 8, (info.width + 3) / 8, (info.width + 3) / 4, (info.width + 1) / 4, @@ -644,50 +710,52 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, (info.height + 1) / 4, (info.height + 1) / 2, (info.height + 0) / 2}; size_t passstart[7] = {0}; - size_t pattern[28] = { - 0, 4, 0, 2, 0, 1, 0, 0, 0, 4, 0, 2, 0, 1, 8, - 8, 4, 4, 2, 2, 1, 8, 8, 8, 4, 4, 2, 2}; // values for the - // adam7 passes - for (int i = 0; i < 6; i++) + size_t pattern[28] = {0, 4, 0, 2, 0, 1, 0, 0, 0, 4, + 0, 2, 0, 1, 8, 8, 4, 4, 2, 2, + 1, 8, 8, 8, 4, 4, 2, 2}; // values for the + // adam7 passes + for (int i = 0; i < 6; i++) { passstart[i + 1] = passstart[i] + passh[i] * ((passw[i] ? 1 : 0) + (passw[i] * bpp + 7) / 8); + } std::vector scanlineo((info.width * bpp + 7) / 8), scanlinen((info.width * bpp + 7) / - 8); //"old" and "new" scanline - for (int i = 0; i < 7; i++) + 8); //"old" and "new" scanline + for (int i = 0; i < 7; i++) { adam7Pass(&out_[0], &scanlinen[0], &scanlineo[0], &scanlines[passstart[i]], info.width, pattern[i], pattern[i + 7], pattern[i + 14], pattern[i + 21], passw[i], passh[i], bpp); + } } if (convert_to_rgba32 && (info.colorType != 6 || - info.bitDepth != 8)) // conversion needed + info.bitDepth != 8)) // conversion needed { std::vector data = out; error = convert(out, &data[0], info, info.width, info.height); } } - void readPngHeader(const unsigned char* in, - size_t inlength) // read the information from the - // header and store it in the Info + void readPngHeader(const unsigned char *in, + size_t inlength) // read the information from the + // header and store it in the Info { if (inlength < 29) { error = 27; return; - } // error: the data length is smaller than the length of the - // header + } // error: the data length is smaller than the length of the + // header if (in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { error = 28; return; - } // no PNG signature + } // no PNG signature if (in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R') { error = 29; return; - } // error: it doesn't start with a IHDR chunk! + } // error: it doesn't start with a IHDR chunk! info.width = read32bitInt(&in[16]); info.height = read32bitInt(&in[20]); info.bitDepth = in[24]; @@ -696,94 +764,112 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, if (in[26] != 0) { error = 32; return; - } // error: only compression method 0 is allowed in the - // specification + } // error: only compression method 0 is allowed in the + // specification info.filterMethod = in[27]; if (in[27] != 0) { error = 33; return; - } // error: only filter method 0 is allowed in the specification + } // error: only filter method 0 is allowed in the specification info.interlaceMethod = in[28]; if (in[28] > 1) { error = 34; return; - } // error: only interlace methods 0 and 1 exist in the - // specification + } // error: only interlace methods 0 and 1 exist in the + // specification error = checkColorValidity(info.colorType, info.bitDepth); } - void unFilterScanline(unsigned char* recon, - const unsigned char* scanline, - const unsigned char* precon, size_t bytewidth, - unsigned long filterType, size_t length) { + void unFilterScanline(unsigned char *recon, + const unsigned char *scanline, + const unsigned char *precon, size_t bytewidth, + unsigned long filterType, size_t length) + { switch (filterType) { - case 0: - for (size_t i = 0; i < length; i++) recon[i] = scanline[i]; - break; - case 1: - for (size_t i = 0; i < bytewidth; i++) + case 0: + for (size_t i = 0; i < length; i++) { + recon[i] = scanline[i]; + } + break; + case 1: + for (size_t i = 0; i < bytewidth; i++) { + recon[i] = scanline[i]; + } + for (size_t i = bytewidth; i < length; i++) { + recon[i] = scanline[i] + recon[i - bytewidth]; + } + break; + case 2: + if (precon) { + for (size_t i = 0; i < length; i++) { + recon[i] = scanline[i] + precon[i]; + } + } else { + for (size_t i = 0; i < length; i++) { recon[i] = scanline[i]; - for (size_t i = bytewidth; i < length; i++) - recon[i] = scanline[i] + recon[i - bytewidth]; - break; - case 2: - if (precon) - for (size_t i = 0; i < length; i++) - recon[i] = scanline[i] + precon[i]; - else - for (size_t i = 0; i < length; i++) - recon[i] = scanline[i]; - break; - case 3: - if (precon) { - for (size_t i = 0; i < bytewidth; i++) - recon[i] = scanline[i] + precon[i] / 2; - for (size_t i = bytewidth; i < length; i++) - recon[i] = scanline[i] + - ((recon[i - bytewidth] + precon[i]) / 2); - } else { - for (size_t i = 0; i < bytewidth; i++) - recon[i] = scanline[i]; - for (size_t i = bytewidth; i < length; i++) - recon[i] = scanline[i] + recon[i - bytewidth] / 2; - } - break; - case 4: - if (precon) { - for (size_t i = 0; i < bytewidth; i++) - recon[i] = - scanline[i] + paethPredictor(0, precon[i], 0); - for (size_t i = bytewidth; i < length; i++) - recon[i] = - scanline[i] + - paethPredictor(recon[i - bytewidth], precon[i], - precon[i - bytewidth]); - } else { - for (size_t i = 0; i < bytewidth; i++) - recon[i] = scanline[i]; - for (size_t i = bytewidth; i < length; i++) - recon[i] = - scanline[i] + - paethPredictor(recon[i - bytewidth], 0, 0); - } - break; - default: - error = 36; - return; // error: unexisting filter type given + } + } + break; + case 3: + if (precon) { + for (size_t i = 0; i < bytewidth; i++) { + recon[i] = scanline[i] + precon[i] / 2; + } + for (size_t i = bytewidth; i < length; i++) { + recon[i] = scanline[i] + + ((recon[i - bytewidth] + precon[i]) / 2); + } + } else { + for (size_t i = 0; i < bytewidth; i++) { + recon[i] = scanline[i]; + } + for (size_t i = bytewidth; i < length; i++) { + recon[i] = scanline[i] + recon[i - bytewidth] / 2; + } + } + break; + case 4: + if (precon) { + for (size_t i = 0; i < bytewidth; i++) { + recon[i] = + scanline[i] + paethPredictor(0, precon[i], 0); + } + for (size_t i = bytewidth; i < length; i++) { + recon[i] = + scanline[i] + paethPredictor(recon[i - bytewidth], + precon[i], + precon[i - bytewidth]); + } + } else { + for (size_t i = 0; i < bytewidth; i++) { + recon[i] = scanline[i]; + } + for (size_t i = bytewidth; i < length; i++) { + recon[i] = scanline[i] + + paethPredictor(recon[i - bytewidth], 0, 0); + } + } + break; + default: + error = 36; + return; // error: unexisting filter type given } } - void adam7Pass(unsigned char* out, unsigned char* linen, - unsigned char* lineo, const unsigned char* in, + void adam7Pass(unsigned char *out, unsigned char *linen, + unsigned char *lineo, const unsigned char *in, unsigned long w, size_t passleft, size_t passtop, size_t spacex, size_t spacey, size_t passw, size_t passh, - unsigned long bpp) { // filter and reposition the pixels - // into the output when the image - // is Adam7 interlaced. This - // function can only do it after - // the full image is already - // decoded. The out buffer must - // have the correct allocated - // memory size already. - if (passw == 0) return; + unsigned long bpp) + { // filter and reposition the pixels + // into the output when the image + // is Adam7 interlaced. This + // function can only do it after + // the full image is already + // decoded. The out buffer must + // have the correct allocated + // memory size already. + if (passw == 0) { + return; + } size_t bytewidth = (bpp + 7) / 8, linelength = 1 + ((bpp * passw + 7) / 8); for (unsigned long y = 0; y < passh; y++) { @@ -791,104 +877,123 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, *prevline = (y == 0) ? nullptr : lineo; unFilterScanline(linen, &in[y * linelength + 1], prevline, bytewidth, filterType, (w * bpp + 7) / 8); - if (error) return; - if (bpp >= 8) - for (size_t i = 0; i < passw; i++) + if (error) { + return; + } + if (bpp >= 8) { + for (size_t i = 0; i < passw; i++) { for (size_t b = 0; b < bytewidth; - b++) // b = current byte of this pixel + b++) { // b = current byte of this pixel out[bytewidth * w * (passtop + spacey * y) + bytewidth * (passleft + spacex * i) + b] = linen[bytewidth * i + b]; - else + } + } + } else { for (size_t i = 0; i < passw; i++) { size_t obp = bpp * w * (passtop + spacey * y) + bpp * (passleft + spacex * i), bp = i * bpp; - for (size_t b = 0; b < bpp; b++) + for (size_t b = 0; b < bpp; b++) { setBitOfReversedStream( obp, out, readBitFromReversedStream(bp, &linen[0])); + } } - unsigned char* temp = linen; + } + unsigned char *temp = linen; linen = lineo; - lineo = temp; // swap the two buffer pointers "line old" and - // "line new" + lineo = temp; // swap the two buffer pointers "line old" and + // "line new" } } - static unsigned long readBitFromReversedStream( - size_t& bitp, const unsigned char* bits) { + static unsigned long + readBitFromReversedStream(size_t &bitp, const unsigned char *bits) + { unsigned long result = (bits[bitp >> 3] >> (7 - (bitp & 0x7))) & 1; bitp++; return result; } - static unsigned long readBitsFromReversedStream( - size_t& bitp, const unsigned char* bits, unsigned long nbits) { + static unsigned long + readBitsFromReversedStream(size_t &bitp, const unsigned char *bits, + unsigned long nbits) + { unsigned long result = 0; - for (size_t i = nbits - 1; i < nbits; i--) + for (size_t i = nbits - 1; i < nbits; i--) { result += ((readBitFromReversedStream(bitp, bits)) << i); + } return result; } - void setBitOfReversedStream(size_t& bitp, unsigned char* bits, - unsigned long bit) { + void setBitOfReversedStream(size_t &bitp, unsigned char *bits, + unsigned long bit) + { bits[bitp >> 3] |= (bit << (7 - (bitp & 0x7))); bitp++; } - unsigned long read32bitInt(const unsigned char* buffer) { + unsigned long read32bitInt(const unsigned char *buffer) + { return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; } int checkColorValidity( unsigned long colorType, - unsigned long bd) // return type is a LodePNG error code + unsigned long bd) // return type is a LodePNG error code { if ((colorType == 2 || colorType == 4 || colorType == 6)) { - if (!(bd == 8 || bd == 16)) + if (!(bd == 8 || bd == 16)) { return 37; - else + } else { return 0; + } } else if (colorType == 0) { - if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) + if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) { return 37; - else + } else { return 0; + } } else if (colorType == 3) { - if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8)) + if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8)) { return 37; - else + } else { return 0; - } else - return 31; // unexisting color type + } + } else { + return 31; // unexisting color type + } } - unsigned long getBpp(const Info& info) { - if (info.colorType == 2) + unsigned long getBpp(const Info &info) + { + if (info.colorType == 2) { return (3 * info.bitDepth); - else if (info.colorType >= 4) + } else if (info.colorType >= 4) { return (info.colorType - 2) * info.bitDepth; - else + } else { return info.bitDepth; + } } - int convert(std::vector& out, const unsigned char* in, - Info& infoIn, unsigned long w, - unsigned long h) { // converts from any color type to - // 32-bit. return value = LodePNG error - // code + int convert(std::vector &out, const unsigned char *in, + Info &infoIn, unsigned long w, unsigned long h) + { // converts from any color type to + // 32-bit. return value = LodePNG error + // code size_t numpixels = w * h, bp = 0; out.resize(numpixels * 4); - unsigned char* out_ = + unsigned char *out_ = out.empty() ? nullptr - : &out[0]; // faster if compiled without optimization - if (infoIn.bitDepth == 8 && infoIn.colorType == 0) // greyscale + : &out[0]; // faster if compiled without optimization + if (infoIn.bitDepth == 8 && infoIn.colorType == 0) { // greyscale for (size_t i = 0; i < numpixels; i++) { out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[i]; out_[4 * i + 3] = (infoIn.key_defined && in[i] == infoIn.key_r) ? 0 : 255; } - else if (infoIn.bitDepth == 8 && infoIn.colorType == 2) // RGB - // color + } else if (infoIn.bitDepth == 8 && infoIn.colorType == 2) { // RGB + // color for (size_t i = 0; i < numpixels; i++) { - for (size_t c = 0; c < 3; c++) + for (size_t c = 0; c < 3; c++) { out_[4 * i + c] = in[3 * i + c]; + } out_[4 * i + 3] = (infoIn.key_defined == 1 && in[3 * i + 0] == infoIn.key_r && in[3 * i + 1] == infoIn.key_g && @@ -896,28 +1001,33 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, ? 0 : 255; } - else if (infoIn.bitDepth == 8 && - infoIn.colorType == 3) // indexed color (palette) + } else if (infoIn.bitDepth == 8 && + infoIn.colorType == 3) { // indexed color (palette) for (size_t i = 0; i < numpixels; i++) { - if (4U * in[i] >= infoIn.palette.size()) return 46; - for (size_t c = 0; c < 4; c++) + if (4U * in[i] >= infoIn.palette.size()) { + return 46; + } + for (size_t c = 0; c < 4; c++) { out_[4 * i + c] = - infoIn.palette[4 * in[i] + c]; // get rgb colors - // from the palette + infoIn.palette[4 * in[i] + c]; // get rgb colors + } + // from the palette } - else if (infoIn.bitDepth == 8 && - infoIn.colorType == 4) // greyscale with alpha + } else if (infoIn.bitDepth == 8 && + infoIn.colorType == 4) { // greyscale with alpha for (size_t i = 0; i < numpixels; i++) { out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[2 * i + 0]; out_[4 * i + 3] = in[2 * i + 1]; } - else if (infoIn.bitDepth == 8 && infoIn.colorType == 6) - for (size_t i = 0; i < numpixels; i++) - for (size_t c = 0; c < 4; c++) - out_[4 * i + c] = in[4 * i + c]; // RGB with alpha - else if (infoIn.bitDepth == 16 && - infoIn.colorType == 0) // greyscale + } else if (infoIn.bitDepth == 8 && infoIn.colorType == 6) { + for (size_t i = 0; i < numpixels; i++) { + for (size_t c = 0; c < 4; c++) { + out_[4 * i + c] = in[4 * i + c]; // RGB with alpha + } + } + } else if (infoIn.bitDepth == 16 && + infoIn.colorType == 0) { // greyscale for (size_t i = 0; i < numpixels; i++) { out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[2 * i]; @@ -926,11 +1036,12 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, ? 0 : 255; } - else if (infoIn.bitDepth == 16 && - infoIn.colorType == 2) // RGB color + } else if (infoIn.bitDepth == 16 && + infoIn.colorType == 2) { // RGB color for (size_t i = 0; i < numpixels; i++) { - for (size_t c = 0; c < 3; c++) + for (size_t c = 0; c < 3; c++) { out_[4 * i + c] = in[6 * i + 2 * c]; + } out_[4 * i + 3] = (infoIn.key_defined && 256U * in[6 * i + 0] + in[6 * i + 1] == infoIn.key_r && @@ -939,24 +1050,27 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, ? 0 : 255; } - else if (infoIn.bitDepth == 16 && - infoIn.colorType == 4) // greyscale with alpha + } else if (infoIn.bitDepth == 16 && + infoIn.colorType == 4) { // greyscale with alpha for (size_t i = 0; i < numpixels; i++) { out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = - in[4 * i]; // most significant byte + in[4 * i]; // most significant byte out_[4 * i + 3] = in[4 * i + 2]; } - else if (infoIn.bitDepth == 16 && infoIn.colorType == 6) - for (size_t i = 0; i < numpixels; i++) - for (size_t c = 0; c < 4; c++) - out_[4 * i + c] = in[8 * i + 2 * c]; // RGB with alpha - else if (infoIn.bitDepth < 8 && infoIn.colorType == 0) // greyscale + } else if (infoIn.bitDepth == 16 && infoIn.colorType == 6) { + for (size_t i = 0; i < numpixels; i++) { + for (size_t c = 0; c < 4; c++) { + out_[4 * i + c] = in[8 * i + 2 * c]; // RGB with alpha + } + } + } else if (infoIn.bitDepth < 8 && + infoIn.colorType == 0) { // greyscale for (size_t i = 0; i < numpixels; i++) { unsigned long value = (readBitsFromReversedStream(bp, in, infoIn.bitDepth) * 255) / ((1 << infoIn.bitDepth) - - 1); // scale value from 0 to 255 + 1); // scale value from 0 to 255 out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = (unsigned char)(value); out_[4 * i + 3] = @@ -966,21 +1080,26 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, ? 0 : 255; } - else if (infoIn.bitDepth < 8 && infoIn.colorType == 3) // palette + } else if (infoIn.bitDepth < 8 && + infoIn.colorType == 3) { // palette for (size_t i = 0; i < numpixels; i++) { unsigned long value = readBitsFromReversedStream(bp, in, infoIn.bitDepth); - if (4 * value >= infoIn.palette.size()) return 47; - for (size_t c = 0; c < 4; c++) + if (4 * value >= infoIn.palette.size()) { + return 47; + } + for (size_t c = 0; c < 4; c++) { out_[4 * i + c] = - infoIn.palette[4 * value + c]; // get rgb colors - // from the palette + infoIn.palette[4 * value + c]; // get rgb colors + } + // from the palette } + } return 0; } - unsigned char paethPredictor( - short a, short b, - short c) // Paeth predicter, used by PNG filter type 4 + unsigned char + paethPredictor(short a, short b, + short c) // Paeth predicter, used by PNG filter type 4 { short p = a + b - c, pa = p > a ? (p - a) : (a - p), pb = p > b ? (p - b) : (b - p), @@ -996,4 +1115,4 @@ int decodePNG(std::vector& out_image, unsigned long& image_width, return decoder.error; } -} // yage +} // yage diff --git a/src/rectanglecollider.cpp b/src/rectanglecollider.cpp index e9f695d7..936ac06a 100644 --- a/src/rectanglecollider.cpp +++ b/src/rectanglecollider.cpp @@ -8,22 +8,29 @@ #include "Physics/rectanglecollider.hpp" -namespace yage { +namespace yage +{ -RectangleCollider::RectangleCollider(const glm::vec2& position, - const glm::vec2& size) - : Collider(position, size) {} +RectangleCollider::RectangleCollider(const glm::vec2 &position, + const glm::vec2 &size) + : Collider(position, size) +{ +} -bool RectangleCollider::collides(const Collider& collider) const { - for (int i = position_.x; i < position_.x + size_.x; ++i) - for (int j = position_.y; j < position_.y + size_.y; ++j) +bool RectangleCollider::collides(const Collider &collider) const +{ + for (int i = position_.x; i < position_.x + size_.x; ++i) { + for (int j = position_.y; j < position_.y + size_.y; ++j) { return collider.inside(glm::vec2(i, j)); + } + } return false; } -inline bool RectangleCollider::inside(const glm::vec2& point) const { +inline bool RectangleCollider::inside(const glm::vec2 &point) const +{ return position_.x < point.x && position_.x + size_.x > point.x && position_.y < point.y && position_.y + size_.y > point.y; } -} // yage +} // yage diff --git a/src/resourcemanager.cpp b/src/resourcemanager.cpp index 15fb606f..8444161f 100644 --- a/src/resourcemanager.cpp +++ b/src/resourcemanager.cpp @@ -8,12 +8,14 @@ #include "resourcemanager.hpp" -namespace yage { +namespace yage +{ TextureCache ResourceManager::texture_cache_; -Texture ResourceManager::getTexture(const std::string& texture_path) { +Texture ResourceManager::getTexture(const std::string &texture_path) +{ return texture_cache_.getTexture(texture_path); } -} // yage +} // yage diff --git a/src/rigidbody.cpp b/src/rigidbody.cpp index f19d63ac..deb8aee9 100644 --- a/src/rigidbody.cpp +++ b/src/rigidbody.cpp @@ -8,10 +8,13 @@ #include "Physics/rigidbody.hpp" -namespace yage { +namespace yage +{ -RigidBody::RigidBody(const Vector2d& position, double mass, - const Vector2d& velocity, bool gravity) - : ParticleBody(position, mass, velocity, gravity) {} +RigidBody::RigidBody(const Vector2d &position, double mass, + const Vector2d &velocity, bool gravity) + : ParticleBody(position, mass, velocity, gravity) +{ +} -} // yage +} // yage diff --git a/src/sprite.cpp b/src/sprite.cpp index 4cdd2ecf..92dd584c 100644 --- a/src/sprite.cpp +++ b/src/sprite.cpp @@ -12,23 +12,30 @@ #include -namespace yage { +namespace yage +{ Sprite::Sprite() = default; -Sprite::~Sprite() { - if (vbo_id_ != 0) glDeleteBuffers(1, &vbo_id_); +Sprite::~Sprite() +{ + if (vbo_id_ != 0) { + glDeleteBuffers(1, &vbo_id_); + } } void Sprite::init(float x, float y, float width, float height, - const std::string& texture_path) { + const std::string &texture_path) +{ x_ = x; y_ = y; width_ = width; height_ = height; texture_ = ResourceManager::getTexture(texture_path); - if (vbo_id_ == 0) glGenBuffers(1, &vbo_id_); + if (vbo_id_ == 0) { + glGenBuffers(1, &vbo_id_); + } Vertex vertex_data[6]; @@ -50,7 +57,9 @@ void Sprite::init(float x, float y, float width, float height, vertex_data[5].setPosition(x + width, y); vertex_data[5].setUv(1.f, 0.f); - for (auto & i : vertex_data) i.setColor(255, 0, 255, 255); + for (auto &i : vertex_data) { + i.setColor(255, 0, 255, 255); + } vertex_data[1].setColor(0, 255, 255, 255); vertex_data[4].setColor(255, 0, 0, 255); @@ -61,7 +70,8 @@ void Sprite::init(float x, float y, float width, float height, glBindBuffer(GL_ARRAY_BUFFER, 0); } -void Sprite::draw() { +void Sprite::draw() +{ glBindTexture(GL_TEXTURE_2D, texture_.id); glBindBuffer(GL_ARRAY_BUFFER, vbo_id_); @@ -70,11 +80,11 @@ void Sprite::draw() { glEnableVertexAttribArray(2); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), - (void*)offsetof(Vertex, position)); + (void *)offsetof(Vertex, position)); glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), - (void*)offsetof(Vertex, color)); + (void *)offsetof(Vertex, color)); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), - (void*)offsetof(Vertex, uv)); + (void *)offsetof(Vertex, uv)); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(2); @@ -84,4 +94,4 @@ void Sprite::draw() { glBindBuffer(GL_ARRAY_BUFFER, 0); } -} // yage +} // yage diff --git a/src/spritebatch.cpp b/src/spritebatch.cpp index f4767829..efca0b8d 100644 --- a/src/spritebatch.cpp +++ b/src/spritebatch.cpp @@ -11,47 +11,57 @@ #include #include -namespace yage { +namespace yage +{ const int SpriteBatch::NUM_VERTICES; -Glyph::Glyph(GLuint texture, float depth, const Vertex& top_left, - const Vertex& top_right, const Vertex& bottom_right, - const Vertex& bottom_left) - : texture_(texture), - depth_(depth), - top_left_(top_left), - top_right_(top_right), - bottom_right_(bottom_right), - bottom_left_(bottom_left) {} +Glyph::Glyph(GLuint texture, float depth, const Vertex &top_left, + const Vertex &top_right, const Vertex &bottom_right, + const Vertex &bottom_left) + : texture_(texture), depth_(depth), top_left_(top_left), + top_right_(top_right), bottom_right_(bottom_right), + bottom_left_(bottom_left) +{ +} RenderBatch::RenderBatch(GLint offset, GLsizei num_vertices, GLuint texture) - : num_vertices_(num_vertices), offset_(offset), texture_(texture) {} + : num_vertices_(num_vertices), offset_(offset), texture_(texture) +{ +} SpriteBatch::SpriteBatch() = default; -SpriteBatch::~SpriteBatch() { - if (vao_ != 0) glDeleteVertexArrays(1, &vao_); +SpriteBatch::~SpriteBatch() +{ + if (vao_ != 0) { + glDeleteVertexArrays(1, &vao_); + } - if (vbo_ != 0) glDeleteVertexArrays(1, &vbo_); + if (vbo_ != 0) { + glDeleteVertexArrays(1, &vbo_); + } } void SpriteBatch::init() { createVertexArray(); } -void SpriteBatch::begin() { +void SpriteBatch::begin() +{ glyphs_.clear(); glyph_ptrs_.clear(); render_batches_.clear(); } -void SpriteBatch::end() { +void SpriteBatch::end() +{ sortGlyphs(); createRenderBatches(); } -void SpriteBatch::draw(const glm::vec4& destination_rect, - const glm::vec4& uv_rect, GLuint texture, - const Color& color, float depth) { +void SpriteBatch::draw(const glm::vec4 &destination_rect, + const glm::vec4 &uv_rect, GLuint texture, + const Color &color, float depth) +{ Vertex top_left, top_right, bottom_right, bottom_left; top_left.color = color; @@ -79,26 +89,32 @@ void SpriteBatch::draw(const glm::vec4& destination_rect, glyph_ptrs_.push_back(&glyphs_.back()); } -void SpriteBatch::render() { +void SpriteBatch::render() +{ glBindVertexArray(vao_); - for (auto&& batch : render_batches_) { + for (auto &&batch : render_batches_) { glBindTexture(GL_TEXTURE_2D, batch.texture()); glDrawArrays(GL_TRIANGLES, batch.offset(), batch.num_vertices()); } glBindVertexArray(0); } -void SpriteBatch::createVertexArray() { +void SpriteBatch::createVertexArray() +{ if (vao_ == 0) { glGenVertexArrays(1, &vao_); - if (vao_ == 0) throw std::runtime_error("glGenVertexArrays failed"); + if (vao_ == 0) { + throw std::runtime_error("glGenVertexArrays failed"); + } } // bind vertex array object glBindVertexArray(vao_); if (vbo_ == 0) { glGenBuffers(1, &vbo_); - if (vbo_ == 0) throw std::runtime_error("glGenBuffers failed"); + if (vbo_ == 0) { + throw std::runtime_error("glGenBuffers failed"); + } } // bind vertex buffer object glBindBuffer(GL_ARRAY_BUFFER, vbo_); @@ -110,30 +126,34 @@ void SpriteBatch::createVertexArray() { // set the vertex attribute pointers glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), - (void*)offsetof(Vertex, position)); + (void *)offsetof(Vertex, position)); glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), - (void*)offsetof(Vertex, color)); + (void *)offsetof(Vertex, color)); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), - (void*)offsetof(Vertex, uv)); + (void *)offsetof(Vertex, uv)); glDrawArrays(GL_TRIANGLES, 0, 6); // unbind vertex array object glBindVertexArray(0); } -void SpriteBatch::createRenderBatches() { +void SpriteBatch::createRenderBatches() +{ std::vector vertices; - if (glyph_ptrs_.empty()) return; + if (glyph_ptrs_.empty()) { + return; + } render_batches_.reserve(glyph_ptrs_.size() * NUM_VERTICES); for (int i = 0; i < (int)glyph_ptrs_.size(); ++i) { if (i == 0 || (i > 0 && (glyph_ptrs_[i]->texture() != - glyph_ptrs_[i - 1]->texture()))) + glyph_ptrs_[i - 1]->texture()))) { render_batches_.emplace_back(i * NUM_VERTICES, NUM_VERTICES, glyph_ptrs_[i]->texture()); - else + } else { render_batches_.back().num_vertices_ += NUM_VERTICES; + } vertices.push_back(glyph_ptrs_[i]->bottom_left()); vertices.push_back(glyph_ptrs_[i]->top_left()); @@ -155,14 +175,16 @@ void SpriteBatch::createRenderBatches() { } } -void SpriteBatch::sortGlyphs() { +void SpriteBatch::sortGlyphs() +{ // sort using introsort or quicksort std::sort(glyph_ptrs_.begin(), glyph_ptrs_.end(), - [](Glyph* a, Glyph* b) -> bool { - if (a->depth() == b->depth()) + [](Glyph *a, Glyph *b) -> bool { + if (a->depth() == b->depth()) { return a->texture() < b->texture(); + } return a->depth() < b->depth(); }); } -} // yage +} // yage diff --git a/src/texturecache.cpp b/src/texturecache.cpp index 09ac2639..5ce89dc1 100644 --- a/src/texturecache.cpp +++ b/src/texturecache.cpp @@ -6,27 +6,25 @@ * ---------------------------------------------------------------------------- */ -#include "imageloader.hpp" #include "texturecache.hpp" +#include "imageloader.hpp" namespace yage { -TextureCache::TextureCache() -= default; +TextureCache::TextureCache() = default; Texture TextureCache::getTexture(const std::string &texture_path) { - auto itr = texture_map_.find(texture_path); + auto itr = texture_map_.find(texture_path); - if(itr == texture_map_.end()) - { - Texture new_texture = ImageLoader::loadPng(texture_path); - texture_map_.insert(make_pair(texture_path, new_texture)); - return new_texture; - } + if (itr == texture_map_.end()) { + Texture new_texture = ImageLoader::loadPng(texture_path); + texture_map_.insert(make_pair(texture_path, new_texture)); + return new_texture; + } - return itr->second; + return itr->second; } - + } // yage diff --git a/src/window.cpp b/src/window.cpp index 959cacb3..14671bf9 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -13,23 +13,31 @@ #include #include -namespace yage { +namespace yage +{ Window::Window() = default; Window::~Window() { SDL_DestroyWindow(window_); } -void Window::create(const std::string& window_name, int width, int height, - unsigned flags) { +void Window::create(const std::string &window_name, int width, int height, + unsigned flags) +{ Uint32 gl_window_states = 0; // set the correct input flags - if (flags & WindowFlags::SHOWN) gl_window_states |= SDL_WINDOW_OPENGL; - if (flags & WindowFlags::HIDDEN) gl_window_states |= SDL_WINDOW_HIDDEN; - if (flags & WindowFlags::FULLSCREEN) + if (flags & WindowFlags::SHOWN) { + gl_window_states |= SDL_WINDOW_OPENGL; + } + if (flags & WindowFlags::HIDDEN) { + gl_window_states |= SDL_WINDOW_HIDDEN; + } + if (flags & WindowFlags::FULLSCREEN) { gl_window_states |= SDL_WINDOW_FULLSCREEN; - if (flags & WindowFlags::BORDERLESS) + } + if (flags & WindowFlags::BORDERLESS) { gl_window_states |= SDL_WINDOW_BORDERLESS; + } // SDL_GL options @@ -41,16 +49,21 @@ void Window::create(const std::string& window_name, int width, int height, window_ = SDL_CreateWindow(window_name.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, gl_window_states); - if (window_ == nullptr) throw std::runtime_error("SDL_CreateWindow failed"); + if (window_ == nullptr) { + throw std::runtime_error("SDL_CreateWindow failed"); + } // initialize the GL context in the window SDL_GLContext gl_context = SDL_GL_CreateContext(window_); - if (gl_context == nullptr) + if (gl_context == nullptr) { throw std::runtime_error("SDL_GL_CreateContext failed"); + } // initialize glew GLenum error = glewInit(); - if (error != GLEW_OK) throw std::runtime_error("glewInit failed"); + if (error != GLEW_OK) { + throw std::runtime_error("glewInit failed"); + } // print out the current OpenGL version to debug std::cout << "*** OpenGL version: " << glGetString(GL_VERSION) @@ -65,16 +78,18 @@ void Window::create(const std::string& window_name, int width, int height, glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } -void Window::swapBuffer() { +void Window::swapBuffer() +{ // swap the window buffer SDL_GL_SwapWindow(window_); } -void Window::clearBuffer() { +void Window::clearBuffer() +{ // set the clear depth glClearDepth(1.f); // clears buffer with clear color glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } -} // yage +} // yage diff --git a/test/matrixtest.cpp b/test/matrixtest.cpp index 1b27b544..d388948b 100644 --- a/test/matrixtest.cpp +++ b/test/matrixtest.cpp @@ -16,7 +16,8 @@ #include "gtest/gtest.h" template -int matrixAssign(int number, int i, int j) { +int matrixAssign(int number, int i, int j) +{ yage::Matrix m; m[j][i] = number; @@ -24,7 +25,8 @@ int matrixAssign(int number, int i, int j) { } template -int matrixAddition(int num1, int num2) { +int matrixAddition(int num1, int num2) +{ yage::Matrix m1, m2; m1[1][1] = num1; m2[1][1] = num2; @@ -34,8 +36,9 @@ int matrixAddition(int num1, int num2) { return m3[1][1]; } -int vectorDotProduct(const std::vector& vec_contents_f, - const std::vector& vec_contents_s) { +int vectorDotProduct(const std::vector &vec_contents_f, + const std::vector &vec_contents_s) +{ yage::Vector<3, int> v1(vec_contents_f); yage::Vector<3, int> v2(vec_contents_s); @@ -48,28 +51,32 @@ bool matrixMultiplication() { return false; } // TESTS -TEST(Matrix, Assign) { +TEST(Matrix, Assign) +{ int rand_num = rand(); ASSERT_EQ(rand_num, matrixAssign<10>(rand_num, 4, 2)); } -TEST(Matrix, Addition) { +TEST(Matrix, Addition) +{ int rand_x = rand(); int rand_y = rand(); ASSERT_EQ(rand_x + rand_y, matrixAddition<10>(rand_x, rand_y)); } -TEST(Vector, DotProduct) { +TEST(Vector, DotProduct) +{ std::vector contents_i = {rand() % 100, rand() % 100, rand() % 100}; std::vector contents_j = {rand() % 100, rand() % 100, rand() % 100}; int sum = 0; - for(std::size_t i = 0; i < contents_i.size(); ++i) { + for (std::size_t i = 0; i < contents_i.size(); ++i) { sum += contents_i[i] * contents_j[i]; } ASSERT_EQ(sum, vectorDotProduct(contents_i, contents_j)); } -int main(int argc, char** argv) { +int main(int argc, char **argv) +{ srand(static_cast(time(nullptr))); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test/particlebodytest.cpp b/test/particlebodytest.cpp index 5c915a9a..65c3885c 100644 --- a/test/particlebodytest.cpp +++ b/test/particlebodytest.cpp @@ -12,7 +12,8 @@ #include "Physics/particlebody.hpp" #include "gtest/gtest.h" -double gravityAcceleration(int iterations) { +double gravityAcceleration(int iterations) +{ yage::ParticleBody body; for (int i = 0; i < 60 * iterations; ++i) { body.update(); @@ -23,7 +24,8 @@ double gravityAcceleration(int iterations) { // Tests -TEST(ParticleBody, Gravity) { +TEST(ParticleBody, Gravity) +{ int randomItr = rand() % 10; double idealPosition = 0.5 * -9.81 * std::pow(randomItr, 2); @@ -31,7 +33,8 @@ TEST(ParticleBody, Gravity) { ASSERT_LE(idealPosition * 1.05, gravityAcceleration(randomItr)); } -int main(int argc, char** argv) { +int main(int argc, char **argv) +{ testing::InitGoogleTest(&argc, argv); srand(static_cast(time(nullptr))); return RUN_ALL_TESTS(); diff --git a/test/windowtest.cpp b/test/windowtest.cpp index 6fb4e462..73e2f82c 100644 --- a/test/windowtest.cpp +++ b/test/windowtest.cpp @@ -10,11 +10,10 @@ #include "yage.hpp" -TEST(Window, Open) { - ASSERT_TRUE(true); -} +TEST(Window, Open) { ASSERT_TRUE(true); } -int main(int argc, char** argv) { - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); +int main(int argc, char **argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); } diff --git a/test/yagetest.cpp b/test/yagetest.cpp index 8ca6c83e..90d915a8 100644 --- a/test/yagetest.cpp +++ b/test/yagetest.cpp @@ -10,11 +10,10 @@ #include "yage.hpp" -TEST(YAGE, InitQuit) { - ASSERT_TRUE(true); -} +TEST(YAGE, InitQuit) { ASSERT_TRUE(true); } -int main(int argc, char** argv) { - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); +int main(int argc, char **argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); } -- cgit