diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..5deefd6 --- /dev/null +++ b/.clang-format @@ -0,0 +1,400 @@ +# clang-format +# Made by: Ingmar Delsink +# idelsink.com +# See http://clang.llvm.org/docs/ClangFormatStyleOptions.html +# Tested with: clang-format version 3.7.1 + +# General +######### + +# The style used for all options not specifically set in the configuration. +# This option is supported only in the clang-format configuration (both within -style='{...}' and the .clang-format file). +# Possible values: +# LLVM A style complying with the LLVM coding standards +# Google A style complying with Google’s C++ style guide +# Chromium A style complying with Chromium’s style guide +# Mozilla A style complying with Mozilla’s style guide +# WebKit A style complying with WebKit’s style guide +#BasedOnStyle: + +# TabWidth (unsigned) +# The number of columns used for tab stops. +TabWidth: 4 + +# IndentWidth (unsigned) +# The number of columns to use for indentation. +IndentWidth: 4 + +# UseTab (UseTabStyle) +# The way to use tab characters in the resulting file. +# Possible values: +# UT_Never (in configuration: Never) Never use tab. +# UT_ForIndentation (in configuration: ForIndentation) Use tabs only for indentation. +# UT_Always (in configuration: Always) Use tabs whenever we need to fill whitespace that spans at least from one tab stop to the next one. +UseTab: Never + +# C++ +##### + +# Language (LanguageKind) +# Language, this format style is targeted at. +# Possible values: +# LK_None (in configuration: None) Do not use. +# LK_Cpp (in configuration: Cpp) Should be used for C, C++, ObjectiveC, ObjectiveC++. +# LK_Java (in configuration: Java) Should be used for Java. +# LK_JavaScript (in configuration: JavaScript) Should be used for JavaScript. +# LK_Proto (in configuration: Proto) Should be used for Protocol Buffers (https://developers.google.com/protocol-buffers/). +# LK_TableGen (in configuration: TableGen) Should be used for TableGen code. +Language: Cpp + +# Standard (LanguageStandard) +# Format compatible with this standard, e.g. use A > instead of A> for LS_Cpp03. +# Possible values: +# LS_Cpp03 (in configuration: Cpp03) Use C++03-compatible syntax. +# LS_Cpp11 (in configuration: Cpp11) Use features of C++11 (e.g. A> instead of A >). +# LS_Auto (in configuration: Auto) Automatic detection based on the input. +Standard: Auto + +# Pointer and reference alignment style. Possible values: Left, Right, Middle. +PointerAlignment: Left + +# AccessModifierOffset (int) +# The extra indent or outdent of access modifiers, e.g. public:. +AccessModifierOffset: 0 + +# AlignAfterOpenBracket (BracketAlignmentStyle) +# If true, horizontally aligns arguments after an open bracket. +# This applies to round brackets (parentheses), angle brackets and square brackets. +# Possible values: +# BAS_Align (in configuration: Align) Align parameters on the open bracket, e.g.: +# someLongFunction(argument1, +# argument2); +# BAS_DontAlign (in configuration: DontAlign) Don’t align, instead use ContinuationIndentWidth, e.g.: +# someLongFunction(argument1, +# argument2); +# BAS_AlwaysBreak (in configuration: AlwaysBreak) Always break after an open bracket, if the parameters don’t fit on a single line, e.g.: +# someLongFunction( +# argument1, argument2); +AlignAfterOpenBracket: BlockIndent + +# AlignConsecutiveAssignments (bool) +# If true, aligns consecutive assignments. +# This will align the assignment operators of consecutive lines. This will result in formattings like +# int aaaa = 12; +# int b = 23; +# int ccc = 23; +AlignConsecutiveAssignments: true + +# AlignEscapedNewlinesLeft (bool) +# If true, aligns escaped newlines as far left as possible. Otherwise puts them into the right-most column. +AlignEscapedNewlinesLeft: true + +# AlignOperands (bool) +# If true, horizontally align operands of binary and ternary expressions. +# Specifically, this aligns operands of a single expression that needs to be split over multiple lines, e.g.: +# int aaa = bbbbbbbbbbbbbbb + +# ccccccccccccccc; +AlignOperands: false + +# AlignTrailingComments (bool) +# If true, aligns trailing comments. +AlignTrailingComments: true + +# AllowAllParametersOfDeclarationOnNextLine (bool) +# Allow putting all parameters of a function declaration onto the next line even if BinPackParameters is false. +AllowAllParametersOfDeclarationOnNextLine: false + +# AllowShortBlocksOnASingleLine (bool) +# Allows contracting simple braced statements to a single line. +AllowShortBlocksOnASingleLine: false + +# AllowShortCaseLabelsOnASingleLine (bool) +# If true, short case labels will be contracted to a single line. +AllowShortCaseLabelsOnASingleLine: true + +# AllowShortFunctionsOnASingleLine (ShortFunctionStyle) +# Dependent on the value, int f() { return 0; } can be put on a single line. +# Possible values: +# SFS_None (in configuration: None) Never merge functions into a single line. +# SFS_Empty (in configuration: Empty) Only merge empty functions. +# SFS_Inline (in configuration: Inline) Only merge functions defined inside a class. Implies “empty”. +# SFS_All (in configuration: All) Merge all functions fitting on a single line. +AllowShortFunctionsOnASingleLine: false + +# AllowShortIfStatementsOnASingleLine (bool) +# If true, if (a) return; can be put on a single line. +AllowShortIfStatementsOnASingleLine: false + +# AllowShortLoopsOnASingleLine (bool) +# If true, while (true) continue; can be put on a single line. +AllowShortLoopsOnASingleLine: false + +# AlwaysBreakBeforeMultilineStrings (bool) +# If true, always break before multiline string literals. +# This flag is mean to make cases where there are multiple multiline strings in a file look more consistent. Thus, it will only take effect if wrapping the string at that point leads to it being indented ContinuationIndentWidth spaces from the start of the line. +AlwaysBreakBeforeMultilineStrings: false + +# AlwaysBreakTemplateDeclarations (bool) +# If true, always break after the template<...> of a template declaration. +AlwaysBreakTemplateDeclarations: false + +# BinPackArguments (bool) +# If false, a function call’s arguments will either be all on the same line or will have one line each. +#BinPackArguments: false + +# BinPackParameters (bool) +# If false, a function declaration’s or function definition’s parameters will either all be on the same line or will have one line each. +BinPackParameters: false + +# BraceWrapping (BraceWrappingFlags) +# Control of individual brace wrapping cases. +# If BreakBeforeBraces is set to BS_Custom, use this to specify how each individual brace case should be handled. Otherwise, this is ignored. +# Nested configuration flags: +# bool AfterClass Wrap class definitions. +# bool AfterControlStatement Wrap control statements (if/for/while/switch/..). +# bool AfterEnum Wrap enum definitions. +# bool AfterFunction Wrap function definitions. +# bool AfterNamespace Wrap namespace definitions. +# bool AfterObjCDeclaration Wrap ObjC definitions (@autoreleasepool, interfaces, ..). +# bool AfterStruct Wrap struct definitions. +# bool AfterUnion Wrap union definitions. +# bool BeforeCatch Wrap before catch. +# bool BeforeElse Wrap before else. +# bool IndentBraces Indent the wrapped braces themselves. +#BraceWrapping: + +# BreakAfterJavaFieldAnnotations (bool) +# Break after each annotation on a field in Java files. +#BreakAfterJavaFieldAnnotations: + +# BreakBeforeBinaryOperators (BinaryOperatorStyle) +# The way to wrap binary operators. +# Possible values: +# BOS_None (in configuration: None) Break after operators. +# BOS_NonAssignment (in configuration: NonAssignment) Break before operators that aren’t assignments. +# BOS_All (in configuration: All) Break before operators. +BreakBeforeBinaryOperators: false + +# BreakBeforeBraces (BraceBreakingStyle) +# The brace breaking style to use. +# Possible values: +# BS_Attach (in configuration: Attach) Always attach braces to surrounding context. +# BS_Linux (in configuration: Linux) Like Attach, but break before braces on function, namespace and class definitions. +# BS_Mozilla (in configuration: Mozilla) Like Attach, but break before braces on enum, function, and record definitions. +# BS_Stroustrup (in configuration: Stroustrup) Like Attach, but break before function definitions, catch, and else. +# BS_Allman (in configuration: Allman) Always break before braces. +# BS_GNU (in configuration: GNU) Always break before braces and add an extra level of indentation to braces of control statements, not to those of class, function or other definitions. +# BS_WebKit (in configuration: WebKit) Like Attach, but break before functions. +# BS_Custom (in configuration: Custom) Configure each individual brace in BraceWrapping. +BreakBeforeBraces: Attach + +# BreakBeforeTernaryOperators (bool) +# If true, ternary operators will be placed after line breaks. +BreakBeforeTernaryOperators: false + +# BreakConstructorInitializersBeforeComma (bool) +# Always break constructor initializers before commas and align the commas with the colon. +BreakConstructorInitializersBeforeComma: false + +# BreakStringLiterals (bool) +# Allow breaking string literals when formatting. +#BreakStringLiterals: + +# ColumnLimit (unsigned) +# The column limit. +# A column limit of 0 means that there is no column limit. In this case, clang-format will respect the input’s line breaking decisions within statements unless they contradict other rules. +ColumnLimit: 100 + +# CommentPragmas (std::string) +# A regular expression that describes comments with special meaning, which should not be split into lines or otherwise changed. +CommentPragmas: '' + +# ConstructorInitializerAllOnOneLineOrOnePerLine (bool) +# If the constructor initializers don’t fit on a line, put each initializer on its own line. +ConstructorInitializerAllOnOneLineOrOnePerLine: false + +# ConstructorInitializerIndentWidth (unsigned) +# The number of characters to use for indentation of constructor initializer lists. +ConstructorInitializerIndentWidth: 0 + +# ContinuationIndentWidth (unsigned) +# Indent width for line continuations. +ContinuationIndentWidth: 0 + +# Cpp11BracedListStyle (bool) +# If true, format braced lists as best suited for C++11 braced lists. +# Important differences: - No spaces inside the braced list. - No line break before the closing brace. - Indentation with the continuation indent, not with the block indent. +# Fundamentally, C++11 braced lists are formatted exactly like function calls would be formatted in their place. If the braced list follows a name (e.g. a type or variable name), clang-format formats as if the {} were the parentheses of a function call with that name. If there is no name, a zero-length name is assumed. +Cpp11BracedListStyle: false + +# DerivePointerAlignment (bool) +# If true, analyze the formatted file for the most common alignment of & and \*. PointerAlignment is then used only as fallback. +DerivePointerBinding: false + +# DisableFormat (bool) +# Disables formatting completely. +#DisableFormat: + +# ExperimentalAutoDetectBinPacking (bool) +# If true, clang-format detects whether function calls and definitions are formatted with one parameter per line. +# Each call can be bin-packed, one-per-line or inconclusive. If it is inconclusive, e.g. completely on one line, but a decision needs to be made, clang-format analyzes whether there are other bin-packed cases in the input file and act accordingly. +# NOTE: This is an experimental flag, that might go away or be renamed. Do not use this in config files, etc. Use at your own risk. +#ExperimentalAutoDetectBinPacking: + +# ForEachMacros (std::vector) +# A vector of macros that should be interpreted as foreach loops instead of as function calls. +# These are expected to be macros of the form: +# FOREACH(, ...) +# +# In the .clang-format configuration file, this can be configured like: +# ForEachMacros: ['RANGES_FOR', 'FOREACH'] +# For example: BOOST_FOREACH. +#ForEachMacros: + +# IncludeCategories (std::vector) +# Regular expressions denoting the different #include categories used for ordering #includes. +# These regular expressions are matched against the filename of an include (including the <> or “”) in order. The value belonging to the first matching regular expression is assigned and #includes are sorted first according to increasing category number and then alphabetically within each category. +# If none of the regular expressions match, INT_MAX is assigned as category. The main header for a source file automatically gets category 0. so that it is generally kept at the beginning of the #includes (http://llvm.org/docs/CodingStandards.html#include-style). However, you can also assign negative priorities if you have certain headers that always need to be first. +# To configure this in the .clang-format file, use: +# IncludeCategories: +# - Regex: '^"(llvm|llvm-c|clang|clang-c)/' +# Priority: 2 +# - Regex: '^(<|"(gtest|isl|json)/)' +# Priority: 3 +# - Regex: '.\*' +# Priority: 1 +#IncludeCategories: + +# IndentCaseLabels (bool) +# Indent case labels one level from the switch statement. +# When false, use the same indentation level as for the switch statement. Switch statement body is always indented one level more than case labels. +IndentCaseLabels: false + +# IndentFunctionDeclarationAfterType (bool) +# If true, indent when breaking function declarations which are not also definitions after the type. +IndentFunctionDeclarationAfterType: false + +# IndentWrappedFunctionNames (bool) +# Indent if a function definition or declaration is wrapped after the type. +#IndentWrappedFunctionNames: + +# KeepEmptyLinesAtTheStartOfBlocks (bool) +# If true, empty lines at the start of blocks are kept. +#KeepEmptyLinesAtTheStartOfBlocks: + +# MacroBlockBegin (std::string) +# A regular expression matching macros that start a block. +#MacroBlockBegin: + +# MacroBlockEnd (std::string) +# A regular expression matching macros that end a block. +#MacroBlockEnd: + +# MaxEmptyLinesToKeep (unsigned) +# The maximum number of consecutive empty lines to keep. +MaxEmptyLinesToKeep: 2 + +# NamespaceIndentation (NamespaceIndentationKind) +# The indentation used for namespaces. +# Possible values: +# NI_None (in configuration: None) Don’t indent in namespaces. +# NI_Inner (in configuration: Inner) Indent only in inner namespaces (nested in other namespaces). +# NI_All (in configuration: All) Indent in all namespaces. +NamespaceIndentation: None + +# ObjCBlockIndentWidth (unsigned) +# The number of characters to use for indentation of ObjC blocks. +#ObjCBlockIndentWidth: + +# ObjCSpaceAfterProperty (bool) +# Add a space after @property in Objective-C, i.e. use @property (readonly) instead of @property(readonly). +ObjCSpaceAfterProperty: true + +# ObjCSpaceBeforeProtocolList (bool) +# Add a space in front of an Objective-C protocol list, i.e. use Foo instead of Foo. +ObjCSpaceBeforeProtocolList: true + +# PenaltyBreakBeforeFirstCallParameter (unsigned) +# The penalty for breaking a function call after call(. +PenaltyBreakBeforeFirstCallParameter: 100 + +# PenaltyBreakComment (unsigned) +# The penalty for each line break introduced inside a comment. +PenaltyBreakComment: 100 + +# PenaltyBreakFirstLessLess (unsigned) +# The penalty for breaking before the first <<. +PenaltyBreakFirstLessLess: 0 + +# PenaltyBreakString (unsigned) +# The penalty for each line break introduced inside a string literal. +PenaltyBreakString: 100 + +# PenaltyExcessCharacter (unsigned) +# The penalty for each character outside of the column limit. +PenaltyExcessCharacter: 1 + +# PenaltyReturnTypeOnItsOwnLine (unsigned) +# Penalty for putting the return type of a function onto its own line. +PenaltyReturnTypeOnItsOwnLine: 20 + +# PointerAlignment (PointerAlignmentStyle) +# Pointer and reference alignment style. +# Possible values: +# PAS_Left (in configuration: Left) Align pointer to the left. +# PAS_Right (in configuration: Right) Align pointer to the right. +# PAS_Middle (in configuration: Middle) Align pointer in the middle. +#PointerAlignment: + +# ReflowComments (bool) +# If true, clang-format will attempt to re-flow comments. +#ReflowComments: true (from v3.9) + +# SortIncludes (bool) +# If true, clang-format will sort #includes. +#SortIncludes: false (from v3.9) + +# SpaceAfterCStyleCast (bool) +# If true, a space may be inserted after C style casts. +SpaceAfterCStyleCast: false + +# SpaceBeforeAssignmentOperators (bool) +# If false, spaces will be removed before assignment operators. +SpaceBeforeAssignmentOperators: true + +# SpaceBeforeParens (SpaceBeforeParensOptions) +# Defines in which cases to put a space before opening parentheses. +# Possible values: +# SBPO_Never (in configuration: Never) Never put a space before opening parentheses. +# SBPO_ControlStatements (in configuration: ControlStatements) Put a space before opening parentheses only after control statement keywords (for/if/while...). +# SBPO_Always (in configuration: Always) Always put a space before opening parentheses, except when it’s prohibited by the syntax rules (in function-like macro definitions) or when determined by other style rules (after unary operators, opening parentheses, etc.) +SpaceBeforeParens: ControlStatements + +# SpaceInEmptyParentheses (bool) +# If true, spaces may be inserted into (). +SpaceInEmptyParentheses: false + +# SpacesBeforeTrailingComments (unsigned) +# The number of spaces before trailing line comments (// - comments). +# This does not affect trailing block comments (/* - comments) as those commonly have different usage patterns and a number of special cases. +SpacesBeforeTrailingComments: 1 + +# SpacesInAngles (bool) +# If true, spaces will be inserted after < and before > in template argument lists. +SpacesInAngles: false + +# SpacesInCStyleCastParentheses (bool) +# If true, spaces may be inserted into C style casts. +SpacesInCStyleCastParentheses: false + +# SpacesInContainerLiterals (bool) +# If true, spaces are inserted inside container literals (e.g. ObjC and Javascript array and dict literals). +SpacesInContainerLiterals: false + +# SpacesInParentheses (bool) +# If true, spaces will be inserted after ( and before ). +SpacesInParentheses: false + +# SpacesInSquareBrackets (bool) +# If true, spaces will be inserted after [ and before ]. +SpacesInSquareBrackets: false diff --git a/.clangd b/.clangd new file mode 100644 index 0000000..4a908bb --- /dev/null +++ b/.clangd @@ -0,0 +1,5 @@ +CompileFlags: + Add: ["-Wall", "-Wextra", "-std=c++17"] +Diagnostics: + MissingIncludes: Strict + UnusedIncludes: Strict diff --git a/Makefile b/Makefile index e2b2407..7636db6 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,11 @@ CXX = g++ SRC_DIR = src -INCLUDES = $(shell pkg-config --cflags sdl2) -I $(SRC_DIR) +INCLUDES = $(shell pkg-config --cflags sdl2) -I $(SRC_DIR) CXXFLAGS = -w $(INCLUDES) -g -Wall -Wextra -Werror -DDEBUG -std=c++17 LFLAGS = -lSDL2 -lm -lSDL2_gfx MAIN = $(SRC_DIR)/main.cpp SRCS = $(shell find $(SRC_DIR) -name "*.cpp" -type f) +HEADERS = $(shell find $(SRC_DIR) -name "*.hpp" -type f) LIB_SRCS = $(filter-out $(MAIN), $(SRCS)) TESTS = $(wildcard tests/*.cpp) EXAMPLES = $(shell find examples -name "*.cpp" -type f) @@ -30,6 +31,12 @@ examples/%.cpp: $(LIB_OBJS) FORCE %.bin: FORCE ./$@ +format/%: + clang-format -i $* + +format: $(SRCS) + clang-format -i $(SRCS) $(HEADERS) $(EXAMPLES) + examples: $(EXAMPLES) tests: $(TESTS_OBJS) diff --git a/compile_flags.txt b/compile_flags.txt new file mode 100644 index 0000000..9bef92d --- /dev/null +++ b/compile_flags.txt @@ -0,0 +1 @@ +--include-directory=src/ diff --git a/examples/basics/square-moving.cpp b/examples/basics/square-moving.cpp index 4ba6497..483aa56 100644 --- a/examples/basics/square-moving.cpp +++ b/examples/basics/square-moving.cpp @@ -1,13 +1,16 @@ -#include +#include +#include +#include +#include #include -#include +#include #include #include -#include "math/Vector2.hpp" -#include "InputHandler.hpp" #include "Game.hpp" +#include "InputHandler.hpp" +#include "math/Vector2.hpp" #define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 600 @@ -16,13 +19,9 @@ using namespace std; // keys to InputHandler observe std::map input_config = { - {"quit", SDLK_ESCAPE}, - {"up", SDLK_UP}, - {"left", SDLK_LEFT}, - {"right", SDLK_RIGHT}, - {"down", SDLK_DOWN}, - {"velocity_up", SDLK_w}, - {"velocity_down", SDLK_s}, + { "quit", SDLK_ESCAPE }, { "up", SDLK_UP }, { "left", SDLK_LEFT }, + { "right", SDLK_RIGHT }, { "down", SDLK_DOWN }, { "velocity_up", SDLK_w }, + { "velocity_down", SDLK_s }, }; struct KeyboardState { @@ -39,15 +38,15 @@ struct KeyboardState { }; struct Player { - Vector2 position = {0, 0}; - Vector2 direction = {0, 0}; - int size = 50; - SDL_Rect rect = {0, 0, size, size}; - float velocity = 300; - - void set_direction(struct KeyboardState *k) { - direction.x = k->right? 1: k->left? -1: 0; - direction.y = k->up? 1: k->down? -1: 0; + Vector2 position = { 0, 0 }; + Vector2 direction = { 0, 0 }; + int size = 50; + SDL_Rect rect = { 0, 0, size, size }; + float velocity = 300; + + void set_direction(struct KeyboardState* k) { + direction.x = k->right ? 1 : k->left ? -1 : 0; + direction.y = k->up ? 1 : k->down ? -1 : 0; } float cos_direction() { @@ -57,7 +56,7 @@ struct Player { float sin_direction() { float cos = cos_direction(); - float sin = sqrt(1 - cos*cos); + float sin = sqrt(1 - cos * cos); return -direction.y * sin; } @@ -67,74 +66,73 @@ struct Player { } }; - -struct Player player = {}; +struct Player player = {}; struct KeyboardState keyboard = {}; -InputHandler input_handler = InputHandler(input_config); +InputHandler input_handler = InputHandler(input_config); void Game::event() { static SDL_Event e; input_handler.process(e); - keyboard.up = input_handler.read("up"); - keyboard.down = input_handler.read("down"); - keyboard.left = input_handler.read("left"); - keyboard.right = input_handler.read("right"); - keyboard.velocity_up = input_handler.read("velocity_up"); + keyboard.up = input_handler.read("up"); + keyboard.down = input_handler.read("down"); + keyboard.left = input_handler.read("left"); + keyboard.right = input_handler.read("right"); + keyboard.velocity_up = input_handler.read("velocity_up"); keyboard.velocity_down = input_handler.read("velocity_down"); - this->running = !(input_handler.read(SDL_QUIT) || input_handler.read("quit")); + this->running = !(input_handler.read(SDL_QUIT) || input_handler.read("quit")); } void Game::update(float dt) { - if (keyboard.velocity_up) { - player.velocity += 50; - input_handler.write("velocity_up", false); - } - if (keyboard.velocity_down) { - player.velocity -= 50; - if (player.velocity <= 50) player.velocity = 50; - input_handler.write("velocity_down", false); - } - - if (keyboard.valid_move()) { - player.set_direction(&keyboard); - player.move(dt); - } - - if (player.position.x < 0) { - player.position.x = 0; - } else if (player.position.x + player.size > SCREEN_WIDTH) { - player.position.x = SCREEN_WIDTH - player.size; - } - if (player.position.y < 0) { - player.position.y = 0; - } else if (player.position.y + player.size > SCREEN_HEIGHT) { - player.position.y = SCREEN_HEIGHT - player.size; - } - - player.rect.x = round(player.position.x); - player.rect.y = round(player.position.y); + if (keyboard.velocity_up) { + player.velocity += 50; + input_handler.write("velocity_up", false); + } + if (keyboard.velocity_down) { + player.velocity -= 50; + if (player.velocity <= 50) + player.velocity = 50; + input_handler.write("velocity_down", false); } + if (keyboard.valid_move()) { + player.set_direction(&keyboard); + player.move(dt); + } + + if (player.position.x < 0) { + player.position.x = 0; + } else if (player.position.x + player.size > SCREEN_WIDTH) { + player.position.x = SCREEN_WIDTH - player.size; + } + if (player.position.y < 0) { + player.position.y = 0; + } else if (player.position.y + player.size > SCREEN_HEIGHT) { + player.position.y = SCREEN_HEIGHT - player.size; + } + + player.rect.x = round(player.position.x); + player.rect.y = round(player.position.y); +} + void Game::draw() { - // background - SDL_SetRenderDrawColor(this->renderer, 255, 255, 255, 255); - SDL_RenderClear(this->renderer); + // background + SDL_SetRenderDrawColor(this->renderer, 255, 255, 255, 255); + SDL_RenderClear(this->renderer); - // player - SDL_SetRenderDrawColor(this->renderer, 0, 255, 255, 255); - SDL_RenderFillRect(this->renderer, &player.rect); + // player + SDL_SetRenderDrawColor(this->renderer, 0, 255, 255, 255); + SDL_RenderFillRect(this->renderer, &player.rect); - // render everything - SDL_RenderPresent(this->renderer); + // render everything + SDL_RenderPresent(this->renderer); } void start() { cout << ":: Game initialization!" << endl; - player.position.x = SCREEN_WIDTH / 2; - player.position.y = SCREEN_HEIGHT / 2; + player.position.x = static_cast(SCREEN_WIDTH) / 2; + player.position.y = static_cast(SCREEN_HEIGHT) / 2; } - int main(void) { start(); Game game("Square Moving", SCREEN_WIDTH, SCREEN_HEIGHT); diff --git a/examples/collision/breakout.cpp b/examples/collision/breakout.cpp index 58b0bac..c53b980 100644 --- a/examples/collision/breakout.cpp +++ b/examples/collision/breakout.cpp @@ -1,7 +1,13 @@ -#include -#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include #define TITLE "BreakOut" #define SCREEN_WIDTH 800 @@ -18,12 +24,10 @@ #include "gfx/Circle.hpp" #include "math/Vector2.hpp" +// keys to InputHandler observe std::map input_config = { - {"left", SDLK_LEFT}, - {"right", SDLK_RIGHT}, - {"quit", SDLK_ESCAPE}, - {"double_size", SDLK_SPACE}, - {"run", SDLK_LSHIFT} + { "left", SDLK_LEFT }, { "right", SDLK_RIGHT }, { "quit", SDLK_ESCAPE }, + { "double_size", SDLK_SPACE }, { "run", SDLK_LSHIFT }, }; struct Keyboard { @@ -38,37 +42,39 @@ struct Keyboard { }; struct Player { - Vector2 position = {SCREEN_WIDTH / 2, SCREEN_HEIGHT - BLOCK_SIZE}; - Vector2 velocity = {500, 0}; + Vector2 position = { + static_cast(SCREEN_WIDTH) / 2, + static_cast(SCREEN_HEIGHT) - BLOCK_SIZE, + }; + Vector2 velocity = { 500, 0 }; Vector2 direction; bool running; bool double_size; - ColliderRect collider = {(int)(position.x), (int)position.y, - BLOCK_SIZE * 3, BLOCK_SIZE}; + ColliderRect collider = { + static_cast(position.x), + static_cast(position.y), + BLOCK_SIZE * 3, + BLOCK_SIZE, + }; void update(float dt) { position.x += (this->running + 1) * velocity.x * direction.x * dt; } - void read_keyboard(Keyboard &k) { - this->direction.x = k.left? -1: k.right? 1: 0; + void read_keyboard(Keyboard& k) { + this->direction.x = k.left ? -1 : k.right ? 1 : 0; this->double_size = k.double_size; - this->running = k.run; + this->running = k.run; } void reset_position() { position.x = collider.polygon.x; } ColliderRect current_collider() { - return ColliderRect( - round(position.x), - round(position.y), - BLOCK_SIZE * 3 * (this->double_size + 1), - BLOCK_SIZE - ); + return ColliderRect(round(position.x), round(position.y), BLOCK_SIZE * 3 * (this->double_size + 1), BLOCK_SIZE); } - void render(SDL_Renderer *renderer) { + void render(SDL_Renderer* renderer) { collider = current_collider(); SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255); SDL_RenderFillRect(renderer, &collider.polygon); @@ -82,7 +88,7 @@ struct Ball { Vector2 velocity; ColliderCircle collider; - Ball(Vector2 v): collider(v, BALL_RADIUS) { + Ball(Vector2 v) : collider(v, BALL_RADIUS) { this->position = v; } @@ -100,41 +106,30 @@ struct Ball { position.y = collider.center.y; } - void render(SDL_Renderer *renderer) { + void render(SDL_Renderer* renderer) { collider = current_collider(); - filledCircleRGBA(renderer,\ - collider.center.x, \ - collider.center.y, \ - collider.circle.radius, - 255, 30, 30, 255); - circleRGBA(renderer, - collider.center.x, - collider.center.y, - collider.circle.radius, - 0, 0, 0, 255); - + filledCircleRGBA(renderer, collider.center.x, collider.center.y, collider.circle.radius, 255, 30, 30, 255); + circleRGBA(renderer, collider.center.x, collider.center.y, collider.circle.radius, 0, 0, 0, 255); }; }; - struct Block { - ColliderRect collider = ColliderRect(0, 0, 2*BLOCK_SIZE, BLOCK_SIZE); - bool alive = true; - SDL_Color color = {0, 0, 0, 255}; + ColliderRect collider = ColliderRect(0, 0, 2 * BLOCK_SIZE, BLOCK_SIZE); + bool alive = true; + SDL_Color color = { 0, 0, 0, 255 }; Block(Vector2 v) { - this->collider = ColliderRect(v.x, v.y, 2*BLOCK_SIZE, BLOCK_SIZE); + this->collider = ColliderRect(v.x, v.y, 2 * BLOCK_SIZE, BLOCK_SIZE); } - void set_color(int i) { int level = (0x0f | (1 << i)); - color.r = 0.2 * level; - color.g = 0.4 * level; - color.b = 0.9 * level; + color.r = 0.2 * level; + color.g = 0.4 * level; + color.b = 0.9 * level; } - void render(SDL_Renderer *renderer) { + void render(SDL_Renderer* renderer) { SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); SDL_RenderFillRect(renderer, &collider.polygon); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); @@ -143,35 +138,38 @@ struct Block { }; ColliderScreen screen_collider = ColliderScreen(SCREEN_WIDTH, SCREEN_HEIGHT); -InputHandler input_handler = InputHandler(input_config); -Keyboard keyboard = {.left=false, .right=false}; -Ball ball = Ball(Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)); +InputHandler input_handler = InputHandler(input_config); +Keyboard keyboard = { + .left = false, + .right = false, + .run = false, + .double_size = false, +}; +Ball ball = Ball(Vector2(static_cast(SCREEN_WIDTH) / 2.0, static_cast(SCREEN_HEIGHT) / 2.0)); Player player = Player(); std::vector blocks; - void start() { - ball.velocity = {150, 300}; + ball.velocity = { 150, 300 }; for (int i = 0; i < BLOCKS; ++i) { - for (int j = 0; j < SCREEN_WIDTH / BLOCK_SIZE / 2 ; j++) { + for (int j = 0; j < SCREEN_WIDTH / BLOCK_SIZE / 2; j++) { float x = 2 * j * BLOCK_SIZE; float y = i * BLOCK_SIZE; Block b(Vector2(x, y)); - b.set_color(i+3); + b.set_color(i + 3); blocks.push_back(b); } } } - void Game::event() { static SDL_Event e; input_handler.process(e); - keyboard.left = input_handler.read("left"); - keyboard.right = input_handler.read("right"); - keyboard.run = input_handler.read("run"); + keyboard.left = input_handler.read("left"); + keyboard.right = input_handler.read("right"); + keyboard.run = input_handler.read("run"); keyboard.double_size = input_handler.read("double_size"); - running = !(input_handler.read("quit") || input_handler.read(SDL_QUIT)); + running = !(input_handler.read("quit") || input_handler.read(SDL_QUIT)); } void Game::update(float dt) { @@ -187,7 +185,7 @@ void Game::update(float dt) { auto ball_collider = ball.current_collider(); if (screen_collider.collide(&ball_collider)) { - auto &s = screen_collider; + auto& s = screen_collider; ball.reset_position(); bool x_collide = s.left.collide(&ball_collider) || s.right.collide(&ball_collider); bool y_collide = s.top.collide(&ball_collider) || s.bottom.collide(&ball_collider); @@ -207,13 +205,12 @@ void Game::update(float dt) { } } - - for (auto &b: blocks) { + for (auto& b : blocks) { if (b.alive && ball_collider.collide(&b.collider)) { b.alive = false; ball.reset_position(); ball.velocity.y *= -1; - //ball.velocity *= 1.1; + // ball.velocity *= 1.1; break; } } @@ -226,7 +223,7 @@ void Game::draw() { player.render(renderer); ball.render(renderer); - for(auto &b: blocks) { + for (auto& b : blocks) { if (b.alive) { b.render(renderer); } diff --git a/examples/collision/square-platform.cpp b/examples/collision/square-platform.cpp index 24650f6..c17827d 100644 --- a/examples/collision/square-platform.cpp +++ b/examples/collision/square-platform.cpp @@ -1,20 +1,24 @@ -#include +#include +#include +#include +#include #include -#include #include -#include -#include +#include #include +#include +#include #include #include -#include "math/Vector2.hpp" -#include "collider/ColliderRect.hpp" +#include "Game.hpp" +#include "InputHandler.hpp" +#include "collider/Collider.hpp" #include "collider/ColliderCircle.hpp" +#include "collider/ColliderRect.hpp" #include "collider/ColliderScreen.hpp" -#include "InputHandler.hpp" -#include "Game.hpp" +#include "math/Vector2.hpp" #define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 600 @@ -22,17 +26,11 @@ using namespace std; - // keys to InputHandler observe -std::map input_config = { - {"quit", SDLK_ESCAPE}, - {"up", SDLK_UP}, - {"left", SDLK_LEFT}, - {"right", SDLK_RIGHT}, - {"down", SDLK_DOWN}, - {"velocity_up", SDLK_w}, - {"velocity_down", SDLK_s}, - {"run", SDLK_LSHIFT} +std::map input_config = { + { "quit", SDLK_ESCAPE }, { "up", SDLK_UP }, { "left", SDLK_LEFT }, + { "right", SDLK_RIGHT }, { "down", SDLK_DOWN }, { "velocity_up", SDLK_w }, + { "velocity_down", SDLK_s }, { "run", SDLK_LSHIFT }, }; struct KeyboardState { @@ -45,16 +43,15 @@ struct KeyboardState { bool run; bool valid_move() { - return (up || down || left || right) && \ - !((up && down) || (left && right)); + return (up || down || left || right) && !((up && down) || (left && right)); } }; struct Player { - Vector2 position = {0, 0}; - Vector2 direction = {0, 0}; - Vector2 velocity = {300, 0}; - int size = 50; + Vector2 position = { 0, 0 }; + Vector2 direction = { 0, 0 }; + Vector2 velocity = { 300, 0 }; + int size = 50; ColliderRect collider = ColliderRect(0, 0, size, size); @@ -68,18 +65,17 @@ struct Player { } ColliderRect current_collider() { - return ColliderRect(round(position.x), - round(position.y), - collider.polygon.w, - collider.polygon.h); + return ColliderRect( + round(position.x), round(position.y), collider.polygon.w, collider.polygon.h + ); } /* * Check if the player is on top of some block */ - bool on_ground(vector &colliders) { + bool on_ground(vector& colliders) { ColliderRect player_collider = current_collider(); - for (auto collider: colliders) { + for (auto collider : colliders) { if (player_collider.on_top(collider)) { return true; } @@ -91,9 +87,9 @@ struct Player { /* * Check if the player collides with some block */ - bool collision(vector &colliders) { + bool collision(vector& colliders) { ColliderRect player_collider = current_collider(); - for (auto collider: colliders) { + for (auto collider : colliders) { if (collider->collide(&player_collider)) { return true; } @@ -112,9 +108,9 @@ struct Player { collider = current_collider(); } - void set_direction(struct KeyboardState *k) { - direction.x = k->right? 1: k->left? -1: 0; - direction.y = k->up? 1: k->down? -1: 0; + void set_direction(struct KeyboardState* k) { + direction.x = k->right ? 1 : k->left ? -1 : 0; + direction.y = k->up ? 1 : k->down ? -1 : 0; } float cos_direction() { @@ -124,7 +120,7 @@ struct Player { float sin_direction() { float cos = cos_direction(); - float sin = sqrt(1 - cos*cos); + float sin = sqrt(1 - cos * cos); return -direction.y * sin; } @@ -138,7 +134,7 @@ struct Player { void move(float dt, Vector2 velocity) { position.x += cos_direction() * velocity.x * dt; - //position.y += sin_direction() * velocity.x * dt; + // position.y += sin_direction() * velocity.x * dt; } void move(float dt, bool run) { @@ -150,29 +146,28 @@ struct Player { } }; -struct Player player = {}; -struct KeyboardState keyboard = {}; +struct Player player = {}; +struct KeyboardState keyboard = {}; ColliderScreen collider_screen = ColliderScreen(SCREEN_WIDTH, SCREEN_HEIGHT); deque squares_shadow; vector blocks; vector circles; vector colliders; -unsigned int squares_max = 50; /* Max size of squares_shadow container */ -unsigned long frames = 0; +unsigned int squares_max = 50; /* Max size of squares_shadow container */ +unsigned long frames = 0; InputHandler input_handler = InputHandler(input_config); - void Game::event() { static SDL_Event e; input_handler.process(e); - keyboard.up = input_handler.read("up"); - keyboard.down = input_handler.read("down"); - keyboard.left = input_handler.read("left"); - keyboard.right = input_handler.read("right"); - keyboard.velocity_up = input_handler.read("velocity_up"); + keyboard.up = input_handler.read("up"); + keyboard.down = input_handler.read("down"); + keyboard.left = input_handler.read("left"); + keyboard.right = input_handler.read("right"); + keyboard.velocity_up = input_handler.read("velocity_up"); keyboard.velocity_down = input_handler.read("velocity_down"); - keyboard.run = input_handler.read("run"); - running = !(input_handler.read(SDL_QUIT) || input_handler.read("quit")); + keyboard.run = input_handler.read("run"); + running = !(input_handler.read(SDL_QUIT) || input_handler.read("quit")); } void debug(float dt) { @@ -190,7 +185,7 @@ void debug(float dt) { cout << " dt: \t" << dt << "s" << endl; cout << endl; lastFrames = frames; - debugTime = 0; + debugTime = 0; } debugTime += dt; frames++; @@ -206,9 +201,11 @@ void Game::update(float dt) { if (keyboard.velocity_down) { player.velocity.x -= 50; - if (player.velocity.x <= 50) player.velocity.x = 50; + if (player.velocity.x <= 50) + player.velocity.x = 50; player.set_size(player.size - 10); - if (player.size <= 10) player.set_size(10); + if (player.size <= 10) + player.set_size(10); input_handler.write("velocity_down", false); } // gravity velocity @@ -230,7 +227,7 @@ void Game::update(float dt) { player.set_direction(&keyboard); player.move(dt, keyboard.run); } - if (player.collision(colliders)) { + if (player.collision(colliders)) { player.position = copy_position; } @@ -238,7 +235,6 @@ void Game::update(float dt) { player.update_rect(); } - static float shadow_interval = 0; if (shadow_interval <= 0) { shadow_interval = 0.005; @@ -260,21 +256,20 @@ void Game::draw() { // player int size = squares_shadow.size(); - for(int i = 0; i < size; ++i) { - int factor = round(255 * ((float) (i + 1) / size)); + for (int i = 0; i < size; ++i) { + int factor = round(255 * ((float)(i + 1) / size)); SDL_SetRenderDrawColor(this->renderer, 0, factor, 255, 255); SDL_RenderFillRect(this->renderer, &squares_shadow[i]); } // platform blocks - for(auto b: blocks) { + for (auto b : blocks) { SDL_SetRenderDrawColor(this->renderer, 0, 0, 0, 255); SDL_RenderDrawRect(this->renderer, &b.polygon); } - for(auto c: circles) { - filledCircleRGBA(this->renderer, c.center.x, c.center.y, c.circle.radius, - 0, 0, 0, 255); + for (auto c : circles) { + filledCircleRGBA(this->renderer, c.center.x, c.center.y, c.circle.radius, 0, 0, 0, 255); } // render everything @@ -283,36 +278,48 @@ void Game::draw() { void start() { cout << ":: Game initialization!" << endl; - player.position.x = SCREEN_WIDTH / 2; - player.position.y = SCREEN_HEIGHT - player.size; + player.position.x = static_cast(SCREEN_WIDTH) / 2; + player.position.y = static_cast(SCREEN_HEIGHT) - player.size; player.update_rect(); int block_size = 50; colliders.push_back(&collider_screen); - SDL_Rect block1 = {.x=0, - .y=SCREEN_HEIGHT-block_size, - .w=2*block_size, - .h=block_size}; - SDL_Rect block2 = {.x=SCREEN_WIDTH/4, - .y=SCREEN_HEIGHT-3*block_size, - .w=2*block_size, - .h=block_size}; - SDL_Rect block3 = {.x=SCREEN_WIDTH/2, - .y=SCREEN_HEIGHT-4*block_size, - .w=2*block_size, - .h=block_size}; - SDL_Rect block4 = {.x=SCREEN_WIDTH/6, - .y=SCREEN_HEIGHT-6*block_size, - .w=2*block_size, - .h=block_size}; - SDL_Rect block5 = {.x=SCREEN_WIDTH/2, - .y=SCREEN_HEIGHT-8*block_size, - .w=2*block_size, - .h=block_size}; - SDL_Rect block6 = {.x=SCREEN_WIDTH-2*block_size, - .y=SCREEN_HEIGHT-10*block_size, - .w=2*block_size, - .h=block_size}; + SDL_Rect block1 = { + .x = 0, + .y = SCREEN_HEIGHT - block_size, + .w = 2 * block_size, + .h = block_size, + }; + SDL_Rect block2 = { + .x = SCREEN_WIDTH / 4, + .y = SCREEN_HEIGHT - 3 * block_size, + .w = 2 * block_size, + .h = block_size, + }; + SDL_Rect block3 = { + .x = SCREEN_WIDTH / 2, + .y = SCREEN_HEIGHT - 4 * block_size, + .w = 2 * block_size, + .h = block_size, + }; + SDL_Rect block4 = { + .x = SCREEN_WIDTH / 6, + .y = SCREEN_HEIGHT - 6 * block_size, + .w = 2 * block_size, + .h = block_size, + }; + SDL_Rect block5 = { + .x = SCREEN_WIDTH / 2, + .y = SCREEN_HEIGHT - 8 * block_size, + .w = 2 * block_size, + .h = block_size, + }; + SDL_Rect block6 = { + .x = SCREEN_WIDTH - 2 * block_size, + .y = SCREEN_HEIGHT - 10 * block_size, + .w = 2 * block_size, + .h = block_size, + }; blocks.push_back(ColliderRect(block1)); blocks.push_back(ColliderRect(block2)); @@ -325,18 +332,17 @@ void start() { circles.push_back(ColliderCircle(Vector2(200, 150), radius)); circles.push_back(ColliderCircle(Vector2(600, 350), radius)); - for(auto &b: blocks) { + for (auto& b : blocks) { colliders.push_back(&b); } - for(auto &c: circles) { + for (auto& c : circles) { colliders.push_back(&c); } - blocks.push_back(ColliderRect(200-radius,150-radius, radius*2, radius*2)); - blocks.push_back(ColliderRect(600-radius,350-radius, radius*2, radius*2)); + blocks.push_back(ColliderRect(200 - radius, 150 - radius, radius * 2, radius * 2)); + blocks.push_back(ColliderRect(600 - radius, 350 - radius, radius * 2, radius * 2)); } - int main(void) { start(); Game game("Square Platform", SCREEN_WIDTH, SCREEN_HEIGHT); diff --git a/examples/gfx/colors-test.cpp b/examples/gfx/colors-test.cpp index 8c01932..526a620 100644 --- a/examples/gfx/colors-test.cpp +++ b/examples/gfx/colors-test.cpp @@ -4,60 +4,61 @@ * * */ -#include #include "Game.hpp" #include "InputHandler.hpp" +#include +#include +#include +#include +#include -#define SCREEN_WIDTH 800 +#define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 600 std::map input_config = { - {"quit", SDLK_ESCAPE}, + { "quit", SDLK_ESCAPE }, }; InputHandler input_handler = InputHandler(input_config); -float screen_counter = 0; -int color_cursor = 0; -int colors[4][4] = { - {225, 0, 0,0}, - {247,227, 0, 97}, - {25 ,235, 0, 42}, - {0 ,1 ,224,255} +float screen_counter = 0; +int color_cursor = 0; +int colors[4][4] = { + { 225, 0, 0, 0 }, + { 247, 227, 0, 97 }, + { 25, 235, 0, 42 }, + { 0, 1, 224, 255 }, }; -void Game::event(){ +void Game::event() { static SDL_Event e; input_handler.process(e); - //This is obligatory, if not, window will run forever and be blocked by OS when tried to close. + // This is obligatory, if not, window will run forever and be blocked by OS + // when tried to close. this->running = !(input_handler.read("quit") || input_handler.read(SDL_QUIT)); } void Game::update(float dt) { screen_counter = screen_counter + dt; - if (screen_counter > 2.0f){ + if (screen_counter > 2.0f) { screen_counter = 0; - if (color_cursor < 3){ + if (color_cursor < 3) { color_cursor = color_cursor + 1; } else { color_cursor = 0; } } - } -void Game::draw(){ - //Sets a color in a renderer and render on screen - int *color = colors[color_cursor]; - SDL_SetRenderDrawColor( - this->renderer, - color[0] , color[1], color[2], color[3] - ); +void Game::draw() { + // Sets a color in a renderer and render on screen + int* color = colors[color_cursor]; + SDL_SetRenderDrawColor(this->renderer, color[0], color[1], color[2], color[3]); SDL_RenderClear(this->renderer); SDL_RenderPresent(this->renderer); } -int main(void){ +int main(void) { Game game("Hello World", SCREEN_WIDTH, SCREEN_HEIGHT); game.set_max_frame_rate(60); return game.run(); diff --git a/examples/gfx/psx-doom-fire.cpp b/examples/gfx/psx-doom-fire.cpp index 38487d6..1e0bfb0 100644 --- a/examples/gfx/psx-doom-fire.cpp +++ b/examples/gfx/psx-doom-fire.cpp @@ -4,74 +4,52 @@ * * */ -#include -#include #include "Game.hpp" #include "InputHandler.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#define SCREEN_WIDTH 800 +#define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 600 -#define TILESIZE 4 +#define TILESIZE 4 std::map input_config = { - {"quit", SDLK_ESCAPE}, + { "quit", SDLK_ESCAPE }, }; InputHandler input_handler = InputHandler(input_config); // Game variables -int widthQuantity = SCREEN_WIDTH / TILESIZE; +int widthQuantity = SCREEN_WIDTH / TILESIZE; int heightQuantity = 96; int offsetX = 0; int offsetY = SCREEN_HEIGHT - (heightQuantity * TILESIZE) + 5; -//int tiles[widthQuantity][heightQuantity]; +// int tiles[widthQuantity][heightQuantity]; std::vector> colors = { - {0,0,0}, - {31,7,7}, - {47,15,7}, - {71,15,7}, - {87,23,7}, - {103,31,7}, - {119,31,7}, - {143,39,7}, - {159,47,7}, - {175,63,7}, - {191,71,7}, - {199,71,7}, - {223,79,7}, - {223,87,7}, - {223,87,7}, - {215,95,7}, - {215,103,15}, - {207,111,15}, - {207,119,15}, - {207,127,15}, - {207,137,23}, - {199,135,23}, - {199,143,23}, - {199,151,31}, - {191,159,31}, - {191,159,31}, - {191,167,39}, - {191,167,39}, - {191,175,47}, - {183,175,47}, - {183,183,47}, - {183,183,55}, - {207,207,111}, - {223,223,159}, - {239,239,199}, - {255,255,255} + { 0, 0, 0 }, { 31, 7, 7 }, { 47, 15, 7 }, { 71, 15, 7 }, { 87, 23, 7 }, + { 103, 31, 7 }, { 119, 31, 7 }, { 143, 39, 7 }, { 159, 47, 7 }, { 175, 63, 7 }, + { 191, 71, 7 }, { 199, 71, 7 }, { 223, 79, 7 }, { 223, 87, 7 }, { 223, 87, 7 }, + { 215, 95, 7 }, { 215, 103, 15 }, { 207, 111, 15 }, { 207, 119, 15 }, { 207, 127, 15 }, + { 207, 137, 23 }, { 199, 135, 23 }, { 199, 143, 23 }, { 199, 151, 31 }, { 191, 159, 31 }, + { 191, 159, 31 }, { 191, 167, 39 }, { 191, 167, 39 }, { 191, 175, 47 }, { 183, 175, 47 }, + { 183, 183, 47 }, { 183, 183, 55 }, { 207, 207, 111 }, { 223, 223, 159 }, { 239, 239, 199 }, + { 255, 255, 255 }, }; std::vector tiles; -void start(){ - for (int i = 0; i < widthQuantity; i++){ - for (int j = 0; j < heightQuantity; j++){ - if (j == (heightQuantity - 1)){ +void start() { + for (int i = 0; i < widthQuantity; i++) { + for (int j = 0; j < heightQuantity; j++) { + if (j == (heightQuantity - 1)) { tiles.push_back(35); } else { tiles.push_back(0); @@ -80,49 +58,50 @@ void start(){ } } -int getTileValue(int x, int y){ - return tiles.at( (x * heightQuantity) + y ); +int getTileValue(int x, int y) { + return tiles.at((x * heightQuantity) + y); } -double sortNumber(){ +double sortNumber() { return (std::rand() / (double)RAND_MAX); } -void setTileValue(int x, int y, int value){ +void setTileValue(int x, int y, int value) { tiles.at((x * heightQuantity) + y) = value; } -void Game::event(){ +void Game::event() { static SDL_Event e; input_handler.process(e); this->running = !(input_handler.read("quit") || input_handler.read(SDL_QUIT)); } -void Game::update(float dt) { - for (int i = 1; i < (widthQuantity - 1); i++){ - for (int j = 1; j < (heightQuantity - 1); j++){ - int value = getTileValue(i, (j + 1)); + +void Game::update([[maybe_unused]] float dt) { + for (int i = 1; i < (widthQuantity - 1); i++) { + for (int j = 1; j < (heightQuantity - 1); j++) { + int value = getTileValue(i, (j + 1)); double randNumber = sortNumber(); int coeficient = value - floor(randNumber * 3); - value = (coeficient > 0) ? coeficient : 0; - if (randNumber < 0.4){ - setTileValue((i - 1), j, value); - } else if (randNumber > 0.4 && randNumber <= 0.8){ - setTileValue((i + 1), j , value); + value = (coeficient > 0) ? coeficient : 0; + if (randNumber < 0.4) { + setTileValue((i - 1), j, value); + } else if (randNumber > 0.4 && randNumber <= 0.8) { + setTileValue((i + 1), j, value); } else { - setTileValue(i, (j - 1) , value); + setTileValue(i, (j - 1), value); } } } } -void Game::draw(){ - //Sets a color in a renderer and render on screen +void Game::draw() { + // Sets a color in a renderer and render on screen SDL_RenderClear(this->renderer); - for (int i = 0; i < widthQuantity; i++){ - for (int j = 0; j < heightQuantity; j++){ + for (int i = 0; i < widthQuantity; i++) { + for (int j = 0; j < heightQuantity; j++) { int tileEl = getTileValue(i, j); - SDL_SetRenderDrawColor(this->renderer, colors[tileEl][0] , colors[tileEl][1], colors[tileEl][2], 255); + SDL_SetRenderDrawColor(this->renderer, colors[tileEl][0], colors[tileEl][1], colors[tileEl][2], 255); SDL_Rect rectangle; rectangle.x = offsetX + (TILESIZE * i); @@ -132,12 +111,11 @@ void Game::draw(){ SDL_RenderFillRect(this->renderer, &rectangle); } } - SDL_SetRenderDrawColor(this->renderer, 0,0,0,255); + SDL_SetRenderDrawColor(this->renderer, 0, 0, 0, 255); SDL_RenderPresent(this->renderer); } - -int main(void){ +int main(void) { std::srand(std::time(nullptr)); start(); Game game("Doom Fire", SCREEN_WIDTH, SCREEN_HEIGHT); diff --git a/src/Game.hpp b/src/Game.hpp index e916ed4..fcf6a22 100644 --- a/src/Game.hpp +++ b/src/Game.hpp @@ -1,15 +1,19 @@ #ifndef GAME_LOOP_HPP #define GAME_LOOP_HPP -#include #include +#include #include +#include +#include +#include +#include #include "Ticker.hpp" class Game { -public: + public: int run() { try { loop(); @@ -26,18 +30,12 @@ class Game { throw std::string("SDL could not initialize: ") + SDL_GetError(); } - window = SDL_CreateWindow(title, - SDL_WINDOWPOS_UNDEFINED, - SDL_WINDOWPOS_UNDEFINED, - width, - height, - SDL_WINDOW_SHOWN); + window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN); if (window == nullptr) { throw std::string("window could not be created: ") + SDL_GetError(); } - renderer = SDL_CreateRenderer(window, -1, renderer_flags); if (!renderer) { throw std::string("renderer could not be created: ") + SDL_GetError(); @@ -59,12 +57,13 @@ class Game { this->fps_target = fps; } -private: - SDL_Window *window = nullptr; - SDL_Renderer *renderer = nullptr; - // int renderer_flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC; + private: + SDL_Window* window = nullptr; + SDL_Renderer* renderer = nullptr; + // int renderer_flags = SDL_RENDERER_ACCELERATED | + // SDL_RENDERER_PRESENTVSYNC; int renderer_flags = SDL_RENDERER_ACCELERATED; - bool running = true; + bool running = true; Ticker timer; void event(); void update(float dt); @@ -73,9 +72,9 @@ class Game { void fps_lock(float dt) { if (fps_target > 0) { - float ideal_frame_time_ms = 1000.0f/fps_target; - float frame_time_ms = 1000 * dt; - int delay_time = ideal_frame_time_ms - frame_time_ms; + float ideal_frame_time_ms = 1000.0f / fps_target; + float frame_time_ms = 1000 * dt; + int delay_time = ideal_frame_time_ms - frame_time_ms; if (delay_time > 0) { SDL_Delay(delay_time); } @@ -89,9 +88,8 @@ class Game { update(dt = timer.dt()); draw(); fps_lock(dt); - } while(running); + } while (running); } - }; #endif // GAME_LOOP_HPP diff --git a/src/InputHandler.hpp b/src/InputHandler.hpp index a8eb43b..50675d3 100644 --- a/src/InputHandler.hpp +++ b/src/InputHandler.hpp @@ -2,14 +2,13 @@ #define INPUT_HANDLER_HPP #include -#include -#include -#include #include +#include +#include class InputHandler { -public: + public: InputHandler(std::map input_config) { this->input_config = input_config; }; @@ -17,12 +16,12 @@ class InputHandler { /* * @brief Process event SDL_Event and stores state on internal map */ - void process(SDL_Event &e) { + void process(SDL_Event& e) { while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { this->input_state[SDL_QUIT] = true; } - for (auto &input : input_state) { + for (auto& input : input_state) { auto k = input.first; switch (e.type) { case SDL_KEYDOWN: @@ -62,7 +61,7 @@ class InputHandler { write(input_config[alias], state); } -private: + private: std::map input_state; std::map input_config; }; diff --git a/src/Ticker.hpp b/src/Ticker.hpp index 484b306..1b9e736 100644 --- a/src/Ticker.hpp +++ b/src/Ticker.hpp @@ -2,14 +2,15 @@ #define TICKER_HPP #include +#include /** * @brief control the time: tick and delta-time */ class Ticker { -public: - - Ticker(): last_tick(tick()) {} + public: + Ticker() : last_tick(tick()) { + } // tick in microseconds uint64_t tick() { @@ -20,13 +21,13 @@ class Ticker { // delta time in seconds float dt() { - auto t = tick(); + auto t = tick(); float delta = (t - last_tick) / 1000000.0f; - last_tick = t; + last_tick = t; return delta; } -private: + private: uint64_t last_tick; }; diff --git a/src/collider/Collider.hpp b/src/collider/Collider.hpp index abfb7bf..3d81eef 100644 --- a/src/collider/Collider.hpp +++ b/src/collider/Collider.hpp @@ -1,11 +1,11 @@ #ifndef COLLISION_HPP #define COLLISION_HPP -#include #include "math/Vector2.hpp" +#include class Collider { -public: + public: // The center of the collider polygon, it must be calculated at the // constructor Vector2 center; @@ -13,7 +13,7 @@ class Collider { /** * @brief abstract collide method */ - virtual bool collide(Collider *c) = 0; + virtual bool collide(Collider* c) = 0; /** * @brief return the object radius @@ -32,4 +32,4 @@ inline float range(float c, float min, float max) { } } -#endif //COLLISION_HPP +#endif // COLLISION_HPP diff --git a/src/collider/ColliderCircle.cpp b/src/collider/ColliderCircle.cpp index ef47a96..0976ce5 100644 --- a/src/collider/ColliderCircle.cpp +++ b/src/collider/ColliderCircle.cpp @@ -1,11 +1,15 @@ #include "collider/ColliderCircle.hpp" +#include "collider/Collider.hpp" #include "collider/ColliderRect.hpp" +#include "gfx/Circle.hpp" +#include "math/Vector2.hpp" #include -ColliderCircle::ColliderCircle(Circle const &c): ColliderCircle(c.center, c.radius) {} +ColliderCircle::ColliderCircle(Circle const& c) : ColliderCircle(c.center, c.radius) { +} ColliderCircle::ColliderCircle(Vector2 center, int radius) { - this->center = center; + this->center = center; this->circle.center = center; this->circle.radius = radius; } @@ -14,32 +18,32 @@ Vector2 ColliderCircle::radius() { return Vector2(circle.radius, circle.radius); } -bool ColliderCircle::collide(Collider *c) { +bool ColliderCircle::collide(Collider* c) { // special colllision if Collider it's actually ColliderRect bool cond = false; if (dynamic_cast(c)) { - Vector2 ct = c->center; - Vector2 r = c->radius(); - Vector2 max = ct + r; - Vector2 min = ct - r; - float nearest_x = range(this->center.x, min.x, max.x); - float nearest_y = range(this->center.y, min.y, max.y); + Vector2 ct = c->center; + Vector2 r = c->radius(); + Vector2 max = ct + r; + Vector2 min = ct - r; + float nearest_x = range(this->center.x, min.x, max.x); + float nearest_y = range(this->center.y, min.y, max.y); std::vector boundaries = { Vector2(nearest_x, max.y), // bottom Vector2(nearest_x, min.y), // top Vector2(max.x, nearest_y), // right Vector2(min.x, nearest_y), // left }; - for (auto &boundary: boundaries) { + for (auto& boundary : boundaries) { float distance = this->center.distance(boundary); if (distance < this->radius().max()) { cond = true; } } } else { - float distance = this->center.distance(c->center); + float distance = this->center.distance(c->center); float radius_sum = this->radius().max() + c->radius().max(); - cond = distance < radius_sum; + cond = distance < radius_sum; } return cond; } diff --git a/src/collider/ColliderCircle.hpp b/src/collider/ColliderCircle.hpp index bac5dbb..be27b33 100644 --- a/src/collider/ColliderCircle.hpp +++ b/src/collider/ColliderCircle.hpp @@ -3,19 +3,19 @@ #include "collider/Collider.hpp" #include "gfx/Circle.hpp" +#include "math/Vector2.hpp" class ColliderCircle : public Collider { -public: + public: Circle circle; - ColliderCircle(Circle const &c); + ColliderCircle(Circle const& c); ColliderCircle(Vector2 center, int radius); /** * @brief checks if the current collider is intersecting another one. */ - bool collide(Collider *c); - + bool collide(Collider* c); Vector2 radius(); }; -#endif //COLLIDER_RECT_H +#endif // COLLIDER_RECT_H diff --git a/src/collider/ColliderRect.cpp b/src/collider/ColliderRect.cpp index f15c70f..bf7fc3d 100644 --- a/src/collider/ColliderRect.cpp +++ b/src/collider/ColliderRect.cpp @@ -1,9 +1,13 @@ #include "collider/ColliderRect.hpp" +#include "collider/Collider.hpp" #include "collider/ColliderCircle.hpp" #include "collider/ColliderScreen.hpp" -#include +#include "math/Vector2.hpp" +#include +#include -ColliderRect::ColliderRect(SDL_Rect const &r): ColliderRect(r.x, r.y, r.w, r.h) {} +ColliderRect::ColliderRect(SDL_Rect const& r) : ColliderRect(r.x, r.y, r.w, r.h) { +} ColliderRect::ColliderRect(int x, int y, int w, int h) { polygon.x = x; @@ -11,37 +15,35 @@ ColliderRect::ColliderRect(int x, int y, int w, int h) { polygon.w = w; polygon.h = h; - center = Vector2(x + w/2, y + h/2); + center = Vector2(x + static_cast(w) / 2, y + static_cast(h) / 2); } - -bool ColliderRect::on_top(Collider *c) { +bool ColliderRect::on_top(Collider* c) { // special logic for ColliderCircle bool cond = false; if (dynamic_cast(c)) { - Vector2 ct = this->center; - Vector2 r = this->radius(); - Vector2 min = ct - r; - Vector2 max = ct + r; - float nearest_x = range(c->center.x, min.x, max.x); + Vector2 ct = this->center; + Vector2 r = this->radius(); + Vector2 min = ct - r; + Vector2 max = ct + r; + float nearest_x = range(c->center.x, min.x, max.x); Vector2 boundary = Vector2(nearest_x, max.y); // bottom; - float distance = c->center.distance(boundary); - cond = (distance - c->radius().max()) < 1; - } if (auto screen = dynamic_cast(c)) { + float distance = c->center.distance(boundary); + cond = (distance - c->radius().max()) < 1; + } + if (auto screen = dynamic_cast(c)) { cond = this->on_top(&screen->bottom); } else { // default on_top behavior - Vector2 r1 = this->radius(); - Vector2 v1 = this->center - r1; - Vector2 r2 = c->radius(); - Vector2 v2 = c->center - r2; + Vector2 r1 = this->radius(); + Vector2 v1 = this->center - r1; + Vector2 r2 = c->radius(); + Vector2 v2 = c->center - r2; float distance = v2.y - (v1.y + 2 * r1.y); int x_min = v2.x - 2 * r1.x; - int x_max = v2.x + 2 * r2.x; + int x_max = v2.x + 2 * r2.x; - cond = (v1.x >= x_min && \ - v1.x <= x_max && \ - distance == 0); + cond = (v1.x >= x_min && v1.x <= x_max && distance == 0); } return cond; @@ -50,14 +52,13 @@ bool ColliderRect::on_top(Collider *c) { /* * Equation: abs(c1 - c2) < (r1 + r2) */ -bool ColliderRect::collide(Collider *c) { +bool ColliderRect::collide(Collider* c) { Vector2 radius = this->radius() + c->radius(); - Vector2 diff = this->center - c->center; + Vector2 diff = this->center - c->center; return abs(diff.x) < radius.x && abs(diff.y) < radius.y; } - Vector2 ColliderRect::radius() { - return Vector2(polygon.w / 2, polygon.h / 2); + return Vector2(static_cast(polygon.w) / 2, static_cast(polygon.h) / 2); } diff --git a/src/collider/ColliderRect.hpp b/src/collider/ColliderRect.hpp index eb0ab81..7047673 100644 --- a/src/collider/ColliderRect.hpp +++ b/src/collider/ColliderRect.hpp @@ -2,25 +2,27 @@ #define COLLIDER_RECT_H #include +#include #include "collider/Collider.hpp" +#include "math/Vector2.hpp" class ColliderRect : public Collider { -public: + public: SDL_Rect polygon; - ColliderRect(SDL_Rect const &r); + ColliderRect(SDL_Rect const& r); ColliderRect(int x, int y, int w, int h); /** * @brief checks if the current collider is intersecting another one. */ - bool collide(Collider *c); + bool collide(Collider* c); /** - * @brief checks if the current collide is on top of another one - */ - bool on_top(Collider *c); + * @brief checks if the current collide is on top of another one + */ + bool on_top(Collider* c); Vector2 radius(); }; -#endif //COLLIDER_RECT_H +#endif // COLLIDER_RECT_H diff --git a/src/collider/ColliderScreen.cpp b/src/collider/ColliderScreen.cpp index d5ae092..d6fb723 100644 --- a/src/collider/ColliderScreen.cpp +++ b/src/collider/ColliderScreen.cpp @@ -1,18 +1,19 @@ #include "collider/ColliderScreen.hpp" - +#include "collider/Collider.hpp" +#include "math/Vector2.hpp" ColliderScreen::ColliderScreen(int width, int height) - : top(0, -1, width, 1), // top - left(-1, 0, 1, height), // left - right(width, 0, 1, height), // right - bottom(0, height, width, 1) { // bottom - this->width = width; +: top(0, -1, width, 1), // top + left(-1, 0, 1, height), // left + right(width, 0, 1, height), // right + bottom(0, height, width, 1) { // bottom + this->width = width; this->height = height; - this->center = Vector2(width / 2, height / 2); + this->center = Vector2(static_cast(width) / 2, static_cast(height) / 2); } -bool ColliderScreen::collide(Collider *c) { +bool ColliderScreen::collide(Collider* c) { return bottom.collide(c) || left.collide(c) || right.collide(c) || top.collide(c); } Vector2 ColliderScreen::radius() { - return Vector2(width / 2, height / 2); + return Vector2(static_cast(width) / 2, static_cast(height) / 2); } diff --git a/src/collider/ColliderScreen.hpp b/src/collider/ColliderScreen.hpp index f0a6e9d..ea39402 100644 --- a/src/collider/ColliderScreen.hpp +++ b/src/collider/ColliderScreen.hpp @@ -3,15 +3,16 @@ #include "collider/Collider.hpp" #include "collider/ColliderRect.hpp" +#include "math/Vector2.hpp" /** * @brief detects the collision with the screen boundaries */ -class ColliderScreen: public Collider { -public: +class ColliderScreen : public Collider { + public: ColliderScreen(int width, int height); - bool collide(Collider *c); + bool collide(Collider* c); Vector2 radius(); int width; diff --git a/src/math/Vector2.hpp b/src/math/Vector2.hpp index 7136242..56f729b 100644 --- a/src/math/Vector2.hpp +++ b/src/math/Vector2.hpp @@ -1,21 +1,24 @@ #ifndef VECTOR2_HPP #define VECTOR2_HPP +#include #include -#include #include +#include class Vector2 { -public: + public: float x; float y; - Vector2(): x(0.0f), y(0.0f) {} - Vector2(float x, float y): x(x), y(y) {} + Vector2() : x(0.0f), y(0.0f) { + } + Vector2(float x, float y) : x(x), y(y) { + } operator std::string() const { std::stringstream s; - s << "<" << x << ", " << y <<">"; + s << "<" << x << ", " << y << ">"; return s.str(); } @@ -27,15 +30,15 @@ class Vector2 { return std::sqrt(x * x + y * y); } - float dot(const Vector2 &v) { + float dot(const Vector2& v) { return (x * v.x) + (y * v.y); } - float cos(const Vector2 &v) { + float cos(const Vector2& v) { return dot(v) / (this->norm() * v.norm()); } - float distance(const Vector2 &v) { + float distance(const Vector2& v) { float d_x = x - v.x; float d_y = y - v.y; return std::sqrt(d_x * d_x + d_y * d_y); @@ -49,27 +52,27 @@ class Vector2 { * Vector2D with Vector2D operations */ - Vector2 operator+(const Vector2 &v) { + Vector2 operator+(const Vector2& v) { return Vector2(x + v.x, y + v.y); } - Vector2& operator+=(const Vector2 &v) { + Vector2& operator+=(const Vector2& v) { x += v.x; y += v.y; return *this; } - Vector2 operator-(const Vector2 &v) { + Vector2 operator-(const Vector2& v) { return Vector2(x - v.x, y - v.y); } - Vector2& operator-=(const Vector2 &v) { + Vector2& operator-=(const Vector2& v) { x -= v.x; y -= v.y; return *this; } - bool operator==(const Vector2 &u) { + bool operator==(const Vector2& u) { return u.x == x && u.y == y; } @@ -116,7 +119,6 @@ class Vector2 { y += scalar; return *this; } - }; #endif // Vector2 diff --git a/tests/TestCollision.cpp b/tests/TestCollision.cpp index e05be93..4d589d5 100644 --- a/tests/TestCollision.cpp +++ b/tests/TestCollision.cpp @@ -1,5 +1,4 @@ #include -#include #include @@ -38,9 +37,9 @@ int main(void) { */ - SDL_Rect r1 = {0, 0, 20, 20}; - SDL_Rect r2 = {0, 20, 20, 20}; - SDL_Rect r3 = {10, 30, 20, 20}; + SDL_Rect r1 = { 0, 0, 20, 20 }; + SDL_Rect r2 = { 0, 20, 20, 20 }; + SDL_Rect r3 = { 10, 30, 20, 20 }; ColliderRect c1(r1); ColliderRect c2(r2);