Compare commits

...

21 Commits

Author SHA1 Message Date
49f45423d1 Port to entt 2025-06-09 10:49:59 +02:00
a69fc7d2b0 Sound effects 2025-06-01 18:44:19 +02:00
f9336dcbd8 Stop game at 0 2025-06-01 12:52:06 +02:00
d019c761bf Add render module 2025-06-01 12:44:38 +02:00
e2a2d6efdf Refactor audio system 2025-06-01 12:34:45 +02:00
81f4d6157e Use C++ random device 2025-06-01 12:34:45 +02:00
ae5733ae62 Spawning system refactor 2025-06-01 11:54:46 +02:00
6eb5046523 Add spiders 2025-06-01 11:19:42 +02:00
b18543e04e Fall faster fruits 2025-06-01 11:19:24 +02:00
0c99e625ba Add score text 2025-06-01 11:19:24 +02:00
c7fd00a1b8 Fix propagate system 2025-05-31 17:16:42 +02:00
a456a87728 Propagate world position system 2025-05-31 16:58:58 +02:00
dbddea69f5 Add asset module 2025-05-31 16:58:58 +02:00
af6fd5fc45 Add physics and level module 2025-05-31 16:58:58 +02:00
b828bf6bd2 Format project 2025-05-31 12:36:20 +02:00
3a1ebd4dfa Restructure project 2025-05-31 12:36:20 +02:00
d8c0876aa4 Force compile commands 2025-05-31 12:36:20 +02:00
7ef431a9f0 Collision detection 2025-05-26 22:57:02 +02:00
ea539bdf99 Add collision box with parent child relationship 2025-05-26 22:39:05 +02:00
5134bf74b2 32kHz Audio 2025-05-26 22:08:56 +02:00
c15732e865 New basket 2025-05-26 22:03:57 +02:00
32 changed files with 838 additions and 364 deletions

View File

@@ -2,14 +2,46 @@ cmake_minimum_required(VERSION 3.24)
project(HansTheGatherer)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Option to switch real platform vs. SDL implementation...
include(FetchContent)
FetchContent_Declare(
SDL3
URL https://github.com/libsdl-org/SDL/releases/download/release-3.2.14/SDL3-3.2.14.tar.gz
OVERRIDE_FIND_PACKAGE
)
FetchContent_MakeAvailable(SDL3)
FetchContent_Declare(
SDL3_ttf
URL https://github.com/libsdl-org/SDL_ttf/releases/download/release-3.2.2/SDL3_ttf-3.2.2.tar.gz
OVERRIDE_FIND_PACKAGE
)
FetchContent_MakeAvailable(SDL3_ttf)
FetchContent_Declare(
entt
URL https://github.com/skypjack/entt/archive/refs/tags/v3.15.0.tar.gz
OVERRIDE_FIND_PACKAGE
)
FetchContent_MakeAvailable(entt)
find_package(entt CONFIG REQUIRED)
find_package(SDL3 CONFIG REQUIRED)
find_package(flecs CONFIG REQUIRED)
find_package(SDL3_ttf CONFIG REQUIRED)
find_package(spdlog CONFIG REQUIRED)
add_executable(HansTheGatherer main.cpp assets.cpp)
add_executable(HansTheGatherer
src/main.cpp
src/audio.cpp
src/assets.cpp
src/level.cpp
src/physics.cpp
src/render.cpp
)
target_link_libraries(HansTheGatherer SDL3::SDL3 flecs::flecs spdlog::spdlog)
target_link_libraries(HansTheGatherer SDL3::SDL3 SDL3_ttf::SDL3_ttf EnTT spdlog::spdlog)
set_property(TARGET HansTheGatherer PROPERTY CXX_STANDARD 20)

2
NOTICE
View File

@@ -6,3 +6,5 @@ Assets used by this project:
URL: https://trashboat93.itch.io/jungle-background-parallax
- "Jamaican Sunrise - Reggae" by DavidKBD
URL: https://davidkbd.itch.io/tropical-dreams-spring-and-summer-music-pack
- "SPIDER ENEMY PIXEL ART" by camacebra
URL: https://camacebra.itch.io/spider-pixel-art-pack-16x16

View File

@@ -1,70 +0,0 @@
#include "assets.hpp"
#include "audio.hpp"
#include "sdl_types.hpp"
#include <cstdint>
#include <spdlog/spdlog.h>
static constexpr uint8_t BACKGROUND_DATA[] = {
#embed "assets/images/jungle.bmp"
};
static constexpr uint8_t FRUITS_DATA[] = {
#embed "assets/images/fruits.bmp"
};
static constexpr uint8_t BACKGROUND_MUSIC_DATA[] = {
#embed "assets/sounds/JamaicanSunrise.wav"
};
SDL_Texture *load_texture(uint8_t const *data, size_t size,
SDL_Renderer *renderer) {
auto *iostream = SDL_IOFromConstMem(data, size);
SDL_Surface *surface = SDL_LoadBMP_IO(iostream, false);
if (surface == nullptr) {
spdlog::error("Failed to load SDL surface!\nCause: {}", SDL_GetError());
}
SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface);
if (texture == nullptr) {
spdlog::error("Failed to create texture from surface!\nCause: {}",
SDL_GetError());
}
return texture;
}
AudioAsset load_audio(uint8_t const *data, size_t size) {
AudioAsset audio_asset;
auto *iostream = SDL_IOFromConstMem(data, size);
bool res = SDL_LoadWAV_IO(iostream, false, &audio_asset.spec,
&audio_asset.buffer, &audio_asset.buffer_length);
if (!res) {
spdlog::error("Failed to load audio file!\nCause: {}", SDL_GetError());
}
return audio_asset;
}
void init_assets(flecs::world &world) {
auto *renderer = world.get<SdlHandles>()->renderer;
auto *background =
load_texture(BACKGROUND_DATA, sizeof(BACKGROUND_DATA), renderer);
TextureAtlasLayout background_layout = {
.width = 866, .height = 510, .rows = 1, .columns = 1};
auto *fruits = load_texture(FRUITS_DATA, sizeof(FRUITS_DATA), renderer);
TextureAtlasLayout fruits_layout = {
.width = 16, .height = 16, .rows = 6, .columns = 38};
world.set<TextureAssets>(TextureAssets{
.background = Texture{.sdl_texture = background,
.texture_atlas_layout = background_layout},
.fruits = Texture{.sdl_texture = fruits,
.texture_atlas_layout = fruits_layout}});
auto background_music =
load_audio(BACKGROUND_MUSIC_DATA, sizeof(BACKGROUND_MUSIC_DATA));
world.set<AudioAssets>(AudioAssets{.background_music = background_music});
}

View File

@@ -1,29 +0,0 @@
#pragma once
#include "audio.hpp"
#include <SDL3/SDL.h>
#include <flecs.h>
struct TextureAtlasLayout {
uint16_t width;
uint16_t height;
uint8_t rows;
uint8_t columns;
};
struct Texture {
SDL_Texture *sdl_texture;
TextureAtlasLayout texture_atlas_layout;
};
struct TextureAssets {
Texture background;
Texture fruits;
};
struct AudioAssets {
AudioAsset background_music;
};
void init_assets(flecs::world &world);

Binary file not shown.

BIN
assets/images/basket.bmp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
assets/images/spiders.bmp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

Binary file not shown.

BIN
assets/sounds/hit.wav Normal file

Binary file not shown.

BIN
assets/sounds/pickup.wav Normal file

Binary file not shown.

View File

@@ -1,10 +0,0 @@
#pragma once
#include <SDL3/SDL.h>
#include <cstdint>
struct AudioAsset {
SDL_AudioSpec spec;
uint8_t *buffer;
uint32_t buffer_length;
};

View File

@@ -1,11 +0,0 @@
#pragma once
#include <set>
#include <SDL3/SDL.h>
struct ButtonInput {
std::set<SDL_Keycode> pressed;
std::set<SDL_Keycode> just_pressed;
std::set<SDL_Keycode> just_released;
};

215
main.cpp
View File

@@ -1,215 +0,0 @@
#include "assets.hpp"
#include "input.hpp"
#include "sdl_types.hpp"
#include "sprite.hpp"
#include <SDL3/SDL.h>
#include <SDL3/SDL_error.h>
#include <SDL3/SDL_events.h>
#include <SDL3/SDL_iostream.h>
#include <SDL3/SDL_render.h>
#include <SDL3/SDL_video.h>
#include <flecs.h>
#include <spdlog/spdlog.h>
static constexpr int WINDOW_WIDTH = 400;
static constexpr int WINDOW_HEIGHT = 240;
struct Position {
int x;
int y;
};
struct Velocity {
int x;
int y;
};
struct Size {
int w;
int h;
};
struct Game {
uint32_t ticks;
};
int main() {
spdlog::info("Initialize SDL...");
SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1");
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) {
spdlog::critical("Failed to initialize SDL!\nCause: {}", SDL_GetError());
std::terminate();
}
auto *window =
SDL_CreateWindow("HansTheGatherer", WINDOW_WIDTH, WINDOW_HEIGHT, 0);
if (window == nullptr) {
spdlog::critical("Failed to create SDL window!\nCause: {}", SDL_GetError());
}
auto *renderer = SDL_CreateRenderer(window, nullptr);
if (renderer == nullptr) {
spdlog::critical("Failed to create SDL renderer!\nCause: {}",
SDL_GetError());
}
flecs::world world;
world.set<Game>(Game{.ticks = 0});
world.set<ButtonInput>(ButtonInput{});
world.set<SdlHandles>(SdlHandles{.window = window, .renderer = renderer});
init_assets(world);
auto *texture_assets = world.get<TextureAssets>();
world.entity("Background")
.set<Position>(Position{.x = 0, .y = 0})
.set<Sprite>(Sprite{.texture = &texture_assets->background,
.texture_atlas_index = 0})
.set<Size>(Size{.w = WINDOW_WIDTH, .h = WINDOW_HEIGHT});
struct Fruit {};
struct Basket {};
world.system<Game>("IncrementTicks")
.term_at(0)
.singleton()
.each([](Game &game_ticks) { game_ticks.ticks += 1; });
world.entity("Basket")
.set<Position>(
Position{.x = WINDOW_WIDTH / 2 - 32, .y = WINDOW_HEIGHT - 32})
.set<Sprite>(Sprite{.texture = &texture_assets->fruits,
.texture_atlas_index = 212})
.set<Size>(Size{.w = 72, .h = 32})
.add<Basket>();
world.system<Game const, TextureAssets const>("SpawnFruits")
.term_at(0)
.singleton()
.term_at(1)
.singleton()
.each([](flecs::iter &it, size_t index, Game const &game,
TextureAssets const &texture_assets) {
if ((game.ticks % 100) == 0) {
it.world()
.entity()
.set<Position>(Position{
.x = static_cast<int>(game.ticks % WINDOW_WIDTH), .y = -16})
.set<Velocity>(Velocity{.x = 0, .y = 1})
.set<Sprite>(Sprite{.texture = &texture_assets.fruits,
.texture_atlas_index =
static_cast<uint16_t>(game.ticks % 228)})
.set<Size>(Size{.w = 32, .h = 32});
}
});
world
.system<SdlHandles const, Position const, Size const, Sprite const>(
"RenderSprites")
.term_at(0)
.singleton()
.each([](SdlHandles const &sdl_handles, Position const &pos,
Size const &size, Sprite const &sprite) {
TextureAtlasLayout layout = sprite.texture->texture_atlas_layout;
uint8_t row = sprite.texture_atlas_index / layout.columns;
uint8_t column = sprite.texture_atlas_index % layout.columns;
SDL_FRect srcrect{static_cast<float>(column * layout.width),
static_cast<float>(row * layout.height),
static_cast<float>(layout.width),
static_cast<float>(layout.height)};
SDL_FRect dstrect{static_cast<float>(pos.x), static_cast<float>(pos.y),
static_cast<float>(size.w),
static_cast<float>(size.h)};
SDL_RenderTexture(sdl_handles.renderer, sprite.texture->sdl_texture,
&srcrect, &dstrect);
});
world
.system<ButtonInput const, Position, Size const, Sprite const, Basket>(
"MoveBasket")
.term_at(0)
.singleton()
.each([](ButtonInput const &input, Position &pos, Size const &size,
Sprite const &sprite, Basket) {
if (input.pressed.contains(SDLK_LEFT)) {
pos.x -= 5;
}
if (input.pressed.contains(SDLK_RIGHT)) {
pos.x += 5;
}
pos.x = pos.x < 0 ? 0 : pos.x;
pos.x = pos.x > WINDOW_WIDTH - size.w ? WINDOW_WIDTH - size.w : pos.x;
});
world.system<Position, Velocity const>("MoveSprites")
.each([](Position &pos, Velocity const &vel) {
pos.x += vel.x;
pos.y += vel.y;
});
auto *audio_assets = world.get<AudioAssets>();
auto *stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK,
&audio_assets->background_music.spec,
NULL, NULL);
if (!stream) {
SDL_Log("Couldn't create audio stream: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
SDL_ResumeAudioStreamDevice(stream);
bool exit_gameloop = false;
while (!exit_gameloop) {
auto *input = world.get_mut<ButtonInput>();
// Clear just pressed/released
input->just_pressed.clear();
input->just_released.clear();
// Input
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_EVENT_QUIT:
exit_gameloop = true;
break;
case SDL_EVENT_KEY_DOWN:
if (event.key.key == SDLK_ESCAPE) {
exit_gameloop = true;
}
if (input->pressed.insert(event.key.key).second) {
input->just_pressed.insert(event.key.key);
}
break;
case SDL_EVENT_KEY_UP:
if (input->pressed.erase(event.key.key) != 0) {
input->just_released.insert(event.key.key);
}
break;
}
}
// Game Logic
if (SDL_GetAudioStreamQueued(stream) <
(int)audio_assets->background_music.buffer_length) {
SDL_PutAudioStreamData(stream, audio_assets->background_music.buffer,
audio_assets->background_music.buffer_length);
}
// Render
SDL_RenderClear(renderer);
world.progress();
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}

View File

@@ -1,9 +0,0 @@
#pragma once
#include <SDL3/SDL.h>
struct SdlHandles {
SDL_Window *window;
SDL_Renderer *renderer;
};

115
src/assets.cpp Normal file
View File

@@ -0,0 +1,115 @@
#include "assets.hpp"
#include "audio.hpp"
#include "definitions.hpp"
#include <cstdint>
#include <spdlog/spdlog.h>
static constexpr uint8_t BACKGROUND_DATA[] = {
#embed "../assets/images/jungle.bmp"
};
static constexpr uint8_t FRUITS_DATA[] = {
#embed "../assets/images/fruits.bmp"
};
static constexpr uint8_t SPIDERS_DATA[] = {
#embed "../assets/images/spiders.bmp"
};
static constexpr uint8_t BASKET_DATA[] = {
#embed "../assets/images/basket.bmp"
};
static constexpr uint8_t BACKGROUND_MUSIC_DATA[] = {
#embed "../assets/sounds/JamaicanSunrise.wav"
};
static constexpr uint8_t PICKUP_SOUND_DATA[] = {
#embed "../assets/sounds/pickup.wav"
};
static constexpr uint8_t HIT_SOUND_DATA[] = {
#embed "../assets/sounds/hit.wav"
};
static constexpr uint8_t DEFAULT_FONT_DATA[] = {
#embed "../assets/fonts/OpenTTD-Sans.ttf"
};
SDL_Texture* load_texture(uint8_t const* data, size_t size, SDL_Renderer* renderer)
{
auto* iostream = SDL_IOFromConstMem(data, size);
SDL_Surface* surface = SDL_LoadBMP_IO(iostream, false);
if (surface == nullptr)
{
spdlog::error("Failed to load SDL surface!\nCause: {}", SDL_GetError());
}
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
if (texture == nullptr)
{
spdlog::error("Failed to create texture from surface!\nCause: {}", SDL_GetError());
}
return texture;
}
AudioAsset load_audio(uint8_t const* data, size_t size)
{
AudioAsset audio_asset;
auto* iostream = SDL_IOFromConstMem(data, size);
bool res = SDL_LoadWAV_IO(
iostream, false, &audio_asset.spec, &audio_asset.buffer, &audio_asset.buffer_length);
if (!res)
{
spdlog::error("Failed to load audio file!\nCause: {}", SDL_GetError());
}
return audio_asset;
}
FontAsset load_font(uint8_t const* data, size_t size)
{
FontAsset font_asset;
auto* iostream = SDL_IOFromConstMem(data, size);
auto* ttf = TTF_OpenFontIO(iostream, false, 20);
font_asset.font = ttf;
return font_asset;
}
AssetModule::AssetModule(entt::registry& registry)
{
auto renderer = registry.ctx().get<SdlHandles>().renderer;
auto* background = load_texture(BACKGROUND_DATA, sizeof(BACKGROUND_DATA), renderer);
TextureAtlasLayout background_layout = {.width = 866, .height = 510, .rows = 1, .columns = 1};
auto* fruits = load_texture(FRUITS_DATA, sizeof(FRUITS_DATA), renderer);
TextureAtlasLayout fruits_layout = {.width = 16, .height = 16, .rows = 6, .columns = 38};
auto* spiders = load_texture(SPIDERS_DATA, sizeof(SPIDERS_DATA), renderer);
TextureAtlasLayout spiders_layout = {.width = 16, .height = 16, .rows = 2, .columns = 4};
auto* basket = load_texture(BASKET_DATA, sizeof(BASKET_DATA), renderer);
TextureAtlasLayout basket_layout = {.width = 16, .height = 16, .rows = 1, .columns = 1};
registry.ctx().emplace<TextureAssets>(TextureAssets{
.background = Texture{.sdl_texture = background, .texture_atlas_layout = background_layout},
.fruits = Texture{.sdl_texture = fruits, .texture_atlas_layout = fruits_layout},
.spiders = Texture{.sdl_texture = spiders, .texture_atlas_layout = spiders_layout},
.basket = Texture{.sdl_texture = basket, .texture_atlas_layout = basket_layout}});
auto background_music = load_audio(BACKGROUND_MUSIC_DATA, sizeof(BACKGROUND_MUSIC_DATA));
auto pickup_sound = load_audio(PICKUP_SOUND_DATA, sizeof(PICKUP_SOUND_DATA));
auto hit_sound = load_audio(HIT_SOUND_DATA, sizeof(HIT_SOUND_DATA));
registry.ctx().emplace<AudioAssets>(AudioAssets{.background_music = background_music,
.pickup_sound = pickup_sound,
.hit_sound = hit_sound});
auto font = load_font(DEFAULT_FONT_DATA, sizeof(DEFAULT_FONT_DATA));
registry.ctx().emplace<FontAssets>(FontAssets{.default_font = font});
}

51
src/assets.hpp Normal file
View File

@@ -0,0 +1,51 @@
#pragma once
#include "audio.hpp"
#include <SDL3/SDL.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <entt/entt.hpp>
struct TextureAtlasLayout
{
uint16_t width;
uint16_t height;
uint8_t rows;
uint8_t columns;
};
struct Texture
{
SDL_Texture* sdl_texture;
TextureAtlasLayout texture_atlas_layout;
};
struct TextureAssets
{
Texture background;
Texture fruits;
Texture spiders;
Texture basket;
};
struct AudioAssets
{
AudioAsset background_music;
AudioAsset pickup_sound;
AudioAsset hit_sound;
};
struct FontAsset
{
TTF_Font* font;
};
struct FontAssets
{
FontAsset default_font;
};
struct AssetModule
{
AssetModule(entt::registry& registry);
};

31
src/audio.cpp Normal file
View File

@@ -0,0 +1,31 @@
#include "audio.hpp"
#include "assets.hpp"
AudioModule::AudioModule(entt::registry& registry)
{
auto const& audio_assets = registry.ctx().get<AudioAssets>();
auto* music_stream = SDL_OpenAudioDeviceStream(
SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audio_assets.background_music.spec, NULL, NULL);
auto* sound_stream = SDL_OpenAudioDeviceStream(
SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audio_assets.pickup_sound.spec, NULL, NULL);
SDL_ResumeAudioStreamDevice(music_stream);
SDL_ResumeAudioStreamDevice(sound_stream);
registry.ctx().emplace<AudioStreams>(
AudioStreams{.music_stream = music_stream, .sound_stream = sound_stream});
}
void AudioModule::FeedAudioStreams(entt::registry& registry)
{
auto audio_streams = registry.ctx().get<AudioStreams>();
auto audio_assets = registry.ctx().get<AudioAssets>();
if (SDL_GetAudioStreamQueued(audio_streams.music_stream) <
static_cast<int>(audio_assets.background_music.buffer_length))
{
SDL_PutAudioStreamData(audio_streams.music_stream,
audio_assets.background_music.buffer,
audio_assets.background_music.buffer_length);
}
}

24
src/audio.hpp Normal file
View File

@@ -0,0 +1,24 @@
#pragma once
#include <SDL3/SDL.h>
#include <cstdint>
#include <entt/entt.hpp>
struct AudioAsset
{
SDL_AudioSpec spec;
uint8_t* buffer;
uint32_t buffer_length;
};
struct AudioStreams
{
SDL_AudioStream* music_stream;
SDL_AudioStream* sound_stream;
};
struct AudioModule
{
AudioModule(entt::registry& registry);
static void FeedAudioStreams(entt::registry& registry);
};

23
src/definitions.hpp Normal file
View File

@@ -0,0 +1,23 @@
#pragma once
#include <SDL3/SDL.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <random>
static constexpr int WINDOW_WIDTH = 400;
static constexpr int WINDOW_HEIGHT = 240;
struct SdlHandles
{
SDL_Window* window;
SDL_Renderer* renderer;
TTF_TextEngine* text_engine;
};
struct Game
{
uint32_t ticks;
int32_t time;
int32_t score;
std::default_random_engine random_engine;
};

11
src/input.hpp Normal file
View File

@@ -0,0 +1,11 @@
#pragma once
#include <SDL3/SDL.h>
#include <set>
struct ButtonInput
{
std::set<SDL_Keycode> pressed;
std::set<SDL_Keycode> just_pressed;
std::set<SDL_Keycode> just_released;
};

125
src/level.cpp Normal file
View File

@@ -0,0 +1,125 @@
#include "level.hpp"
#include "input.hpp"
#include <spdlog/spdlog.h>
void LevelModule::MoveBasket(entt::registry& registry)
{
auto const& input = registry.ctx().get<ButtonInput>();
auto basket_view = registry.view<Position, Size const, Sprite const, Basket>();
for (auto [entity, pos, size, sprite] : basket_view.each())
{
if (input.pressed.contains(SDLK_LEFT))
{
pos.x -= 5;
}
if (input.pressed.contains(SDLK_RIGHT))
{
pos.x += 5;
}
pos.x = pos.x < 0 ? 0 : pos.x;
pos.x = pos.x > WINDOW_WIDTH - size.w ? WINDOW_WIDTH - size.w : pos.x;
}
}
void LevelModule::SpawnFruits(entt::registry& registry)
{
auto& game = registry.ctx().get<Game>();
auto const& texture_assets = registry.ctx().get<TextureAssets>();
std::bernoulli_distribution spider_dist(0.25);
bool spider = spider_dist(game.random_engine);
std::binomial_distribution<> velocity_dist(3, 0.5);
int vel = velocity_dist(game.random_engine) + 1;
if ((game.ticks % 50) == 0)
{
auto item = registry.create();
std::uniform_int_distribution<> xpos_dist(32, WINDOW_WIDTH - 32);
int xpos = xpos_dist(game.random_engine);
if (!spider)
{
std::uniform_int_distribution<> index_dist(0, 228 - 1);
uint16_t index = index_dist(game.random_engine);
registry.emplace<Fruit>(item);
registry.emplace<WorldPosition>(item);
registry.emplace<Position>(item, Position{.x = xpos, .y = -16});
registry.emplace<Velocity>(item, Velocity{.x = 0, .y = vel});
registry.emplace<Sprite>(
item, Sprite{.texture = &texture_assets.fruits, .texture_atlas_index = index});
registry.emplace<Size>(item, Size{.w = 32, .h = 32});
}
else
{
std::uniform_int_distribution<> index_dist(0, 8 - 1);
uint16_t index = index_dist(game.random_engine);
registry.emplace<Spider>(item);
registry.emplace<WorldPosition>(item);
registry.emplace<Position>(item, Position{.x = xpos, .y = -16});
registry.emplace<Velocity>(item, Velocity{.x = 0, .y = vel});
registry.emplace<Sprite>(
item, Sprite{.texture = &texture_assets.spiders, .texture_atlas_index = index});
registry.emplace<Size>(item, Size{.w = 32, .h = 32});
}
auto collision_box = registry.create();
registry.emplace<Parent>(collision_box, item);
registry.emplace<WorldPosition>(collision_box);
registry.emplace<Position>(collision_box, Position{.x = 0, .y = 0});
registry.emplace<Size>(collision_box, Size{.w = 32, .h = 32});
registry.emplace<CollisionBox>(collision_box, item);
}
}
void LevelModule::CollectFruit(entt::registry& registry)
{
auto& game = registry.ctx().get<Game>();
auto const& audio_streams = registry.ctx().get<AudioStreams>();
auto const& audio_assets = registry.ctx().get<AudioAssets>();
auto view = registry.view<Position, Fruit, Collided>();
for (auto [entity, pos] : view.each())
{
game.score += 10;
pos.x += 1000;
// registry.destroy(entity);
SDL_PutAudioStreamData(audio_streams.sound_stream,
audio_assets.pickup_sound.buffer,
audio_assets.pickup_sound.buffer_length);
}
}
void LevelModule::CollectSpider(entt::registry& registry)
{
auto& game = registry.ctx().get<Game>();
auto const& audio_streams = registry.ctx().get<AudioStreams>();
auto const& audio_assets = registry.ctx().get<AudioAssets>();
auto view = registry.view<Position, Spider, Collided>();
for (auto [entity, pos] : view.each())
{
game.score -= 50;
pos.x += 1000;
// registry.destroy(entity);
SDL_PutAudioStreamData(audio_streams.sound_stream,
audio_assets.hit_sound.buffer,
audio_assets.hit_sound.buffer_length);
};
}
void LevelModule::DespawnItems(entt::registry& registry)
{
auto view = registry.view<WorldPosition const, Item>();
for (auto [entity, pos] : view.each())
{
if (pos.y >= WINDOW_HEIGHT)
registry.destroy(entity);
}
}

70
src/level.hpp Normal file
View File

@@ -0,0 +1,70 @@
#pragma once
#include "definitions.hpp"
#include "physics.hpp"
#include "sprite.hpp"
#include <entt/entt.hpp>
#include <spdlog/spdlog.h>
struct Background
{
};
struct Fruit
{
};
struct Spider
{
};
struct Item
{
};
struct Basket
{
};
struct BasketCollisionBox
{
};
struct LevelModule
{
LevelModule(entt::registry& registry)
{
auto const* texture_assets = &registry.ctx().get<TextureAssets>();
auto background = registry.create();
registry.emplace<Position>(background, Position{.x = 0, .y = 0});
registry.emplace<Sprite>(
background, Sprite{.texture = &texture_assets->background, .texture_atlas_index = 0});
registry.emplace<Size>(background, Size{.w = WINDOW_WIDTH, .h = WINDOW_HEIGHT});
registry.emplace<Background>(background);
auto basket = registry.create();
registry.emplace<WorldPosition>(basket);
registry.emplace<Position>(basket,
Position{.x = WINDOW_WIDTH / 2 - 32, .y = WINDOW_HEIGHT - 32});
registry.emplace<Sprite>(
basket, Sprite{.texture = &texture_assets->basket, .texture_atlas_index = 0});
registry.emplace<Size>(basket, Size{.w = 64, .h = 32});
registry.emplace<Basket>(basket);
auto basket_cb = registry.create();
registry.emplace<WorldPosition>(basket_cb);
registry.emplace<Position>(basket_cb, Position{.x = 0, .y = 16});
registry.emplace<Size>(basket_cb, Size{.w = 64, .h = 16});
registry.emplace<CollisionBox>(basket_cb);
registry.emplace<Parent>(basket_cb, basket);
registry.emplace<BasketCollisionBox>(basket_cb);
}
static void MoveBasket(entt::registry& registry);
static void SpawnFruits(entt::registry& registry);
static void CollectFruit(entt::registry &registry);
static void CollectSpider(entt::registry &registry);
static void DespawnItems(entt::registry &registry);
};

132
src/main.cpp Normal file
View File

@@ -0,0 +1,132 @@
#include "assets.hpp"
#include "definitions.hpp"
#include "input.hpp"
#include "level.hpp"
#include "physics.hpp"
#include "render.hpp"
#include <SDL3/SDL.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <entt/entt.hpp>
#include <spdlog/spdlog.h>
void increment_ticks(entt::registry& registry)
{
auto& game = registry.ctx().get<Game>();
// auto& translate_system = registry.ctx().get<TranslateSystem>();
game.ticks += 1;
if (game.ticks % 60 == 0)
{
game.time = std::max(0, game.time - 1);
}
// if (game.time == 0)
// translate_system.translate_system.disable();
}
int main()
{
spdlog::info("Initialize SDL...");
SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1");
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO))
{
spdlog::critical("Failed to initialize SDL!\nCause: {}", SDL_GetError());
std::terminate();
}
TTF_Init();
auto* window = SDL_CreateWindow("HansTheGatherer", WINDOW_WIDTH, WINDOW_HEIGHT, 0);
if (window == nullptr)
{
spdlog::critical("Failed to create SDL window!\nCause: {}", SDL_GetError());
}
auto* renderer = SDL_CreateRenderer(window, nullptr);
if (renderer == nullptr)
{
spdlog::critical("Failed to create SDL renderer!\nCause: {}", SDL_GetError());
}
auto* text_engine = TTF_CreateRendererTextEngine(renderer);
entt::registry registry;
registry.ctx().emplace<Game>(Game{.ticks = 0, .time = 60, .score = 0, .random_engine = {}});
registry.ctx().emplace<ButtonInput>(ButtonInput{});
auto sdl_handles = registry.ctx().emplace<SdlHandles>(
SdlHandles{.window = window, .renderer = renderer, .text_engine = text_engine});
AssetModule asset_module(registry);
AudioModule audio_module(registry);
RenderModule render_module(registry);
PhysicsModule physics_module(registry);
LevelModule level_module(registry);
bool exit_gameloop = false;
while (!exit_gameloop)
{
auto* input = &registry.ctx().get<ButtonInput>();
// Clear just pressed/released
input->just_pressed.clear();
input->just_released.clear();
// Input
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_EVENT_QUIT:
exit_gameloop = true;
break;
case SDL_EVENT_KEY_DOWN:
if (event.key.key == SDLK_ESCAPE)
{
exit_gameloop = true;
}
if (input->pressed.insert(event.key.key).second)
{
input->just_pressed.insert(event.key.key);
}
break;
case SDL_EVENT_KEY_UP:
if (input->pressed.erase(event.key.key) != 0)
{
input->just_released.insert(event.key.key);
}
break;
}
}
AudioModule::FeedAudioStreams(registry);
increment_ticks(registry);
LevelModule::MoveBasket(registry);
LevelModule::SpawnFruits(registry);
LevelModule::CollectFruit(registry);
LevelModule::CollectSpider(registry);
// LevelModule::DespawnItems(registry);
PhysicsModule::TranslatePhysicsObject(registry);
PhysicsModule::PropagatePosition(registry);
PhysicsModule::RemoveCollisionMarker(registry);
PhysicsModule::CollisionCheck(registry);
SDL_RenderClear(sdl_handles.renderer);
RenderModule::RenderSprites(registry);
RenderModule::RenderScore(registry);
SDL_RenderPresent(sdl_handles.renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}

70
src/physics.cpp Normal file
View File

@@ -0,0 +1,70 @@
#include "physics.hpp"
#include "level.hpp"
#include <spdlog/spdlog.h>
void PhysicsModule::TranslatePhysicsObject(entt::registry& registry)
{
auto view = registry.view<Position, Velocity const>();
for (auto [entity, pos, vel] : view.each())
{
pos.x += vel.x;
pos.y += vel.y;
}
}
void PhysicsModule::PropagatePosition(entt::registry& registry)
{
auto root_transform_view = registry.view<Position const, WorldPosition>(entt::exclude<Parent>);
auto transform_view = registry.view<Position const, WorldPosition, Parent const>();
for (auto [entity, pos, world_pos] : root_transform_view.each())
{
world_pos.x = pos.x;
world_pos.y = pos.y;
}
for (auto [entity, pos, world_pos, parent] : transform_view.each())
{
auto parent_pos = registry.get<WorldPosition const>(parent.parent);
world_pos.x = parent_pos.x + pos.x;
world_pos.y = parent_pos.y + pos.y;
}
}
void PhysicsModule::RemoveCollisionMarker(entt::registry& registry)
{
auto view = registry.view<Collided const>();
for (auto [entity] : view.each())
{
registry.remove<Collided>(entity);
}
}
void PhysicsModule::CollisionCheck(entt::registry& registry)
{
auto view = registry.view<WorldPosition const, Size const, Parent const, CollisionBox>(
entt::exclude<BasketCollisionBox>);
auto basket_cb_view = registry.view<WorldPosition const, Size const, BasketCollisionBox>();
for (auto [e, world_pos, size, parent] : view.each())
{
auto fruit = parent.parent;
for (auto [basket, basket_world_pos, basket_size] : basket_cb_view.each())
{
if (basket_world_pos.x + basket_size.w >= world_pos.x &&
basket_world_pos.x <= world_pos.x + size.w &&
basket_world_pos.y + basket_size.h >= world_pos.y &&
basket_world_pos.y <= world_pos.y + size.h)
{
registry.emplace<Collided>(fruit);
}
}
}
}
PhysicsModule::PhysicsModule(entt::registry& registry)
{
}

55
src/physics.hpp Normal file
View File

@@ -0,0 +1,55 @@
#pragma once
#include <entt/entt.hpp>
struct WorldPosition
{
int x;
int y;
};
struct Position
{
int x;
int y;
};
struct Velocity
{
int x;
int y;
};
struct Size
{
int w;
int h;
};
struct Parent
{
entt::entity parent;
};
struct Children
{
std::vector<entt::entity> children;
};
struct CollisionBox
{
};
struct Collided
{
};
struct PhysicsModule
{
PhysicsModule(entt::registry& registry);
static void TranslatePhysicsObject(entt::registry& registry);
static void PropagatePosition(entt::registry& registry);
static void RemoveCollisionMarker(entt::registry& registry);
static void CollisionCheck(entt::registry& registry);
};

72
src/render.cpp Normal file
View File

@@ -0,0 +1,72 @@
#include "render.hpp"
#include "definitions.hpp"
#include "level.hpp"
#include "physics.hpp"
#include "sprite.hpp"
#include <format>
RenderModule::RenderModule(entt::registry& registry)
{
}
void RenderModule::RenderSprites(entt::registry& registry)
{
auto const& sdl_handles = registry.ctx().get<SdlHandles>();
auto const& game = registry.ctx().get<Game>();
auto sprites_view =
registry.view<Position const, Size const, Sprite const>(entt::exclude<Background>);
auto background_view = registry.view<Position const, Size const, Sprite const, Background>();
for (auto [entity, pos, size, sprite] : background_view.each())
{
TextureAtlasLayout layout = sprite.texture->texture_atlas_layout;
uint8_t row = sprite.texture_atlas_index / layout.columns;
uint8_t column = sprite.texture_atlas_index % layout.columns;
SDL_FRect srcrect{static_cast<float>(column * layout.width),
static_cast<float>(row * layout.height),
static_cast<float>(layout.width),
static_cast<float>(layout.height)};
SDL_FRect dstrect{static_cast<float>(pos.x),
static_cast<float>(pos.y),
static_cast<float>(size.w),
static_cast<float>(size.h)};
SDL_RenderTexture(sdl_handles.renderer, sprite.texture->sdl_texture, &srcrect, &dstrect);
}
for (auto [entity, pos, size, sprite] : sprites_view.each())
{
TextureAtlasLayout layout = sprite.texture->texture_atlas_layout;
uint8_t row = sprite.texture_atlas_index / layout.columns;
uint8_t column = sprite.texture_atlas_index % layout.columns;
SDL_FRect srcrect{static_cast<float>(column * layout.width),
static_cast<float>(row * layout.height),
static_cast<float>(layout.width),
static_cast<float>(layout.height)};
SDL_FRect dstrect{static_cast<float>(pos.x),
static_cast<float>(pos.y),
static_cast<float>(size.w),
static_cast<float>(size.h)};
SDL_RenderTexture(sdl_handles.renderer, sprite.texture->sdl_texture, &srcrect, &dstrect);
}
}
void RenderModule::RenderScore(entt::registry& registry)
{
auto const& sdl_handles = registry.ctx().get<SdlHandles>();
auto const& game = registry.ctx().get<Game>();
auto const& font_assets = registry.ctx().get<FontAssets>();
auto score_string = std::format("Score: {}\nTime: {}", game.score, game.time);
auto text = TTF_CreateText(sdl_handles.text_engine,
font_assets.default_font.font,
score_string.c_str(),
score_string.length());
TTF_DrawRendererText(text, 0.0, 0.0);
TTF_DestroyText(text);
}

11
src/render.hpp Normal file
View File

@@ -0,0 +1,11 @@
#pragma once
#include <entt/entt.hpp>
struct RenderModule
{
RenderModule(entt::registry& registry);
static void RenderSprites(entt::registry& registry);
static void RenderScore(entt::registry& registry);
};

View File

@@ -5,7 +5,8 @@
#include <SDL3/SDL.h>
#include <cstdint>
struct Sprite {
Texture const *texture;
uint16_t texture_atlas_index;
struct Sprite
{
Texture const* texture;
uint16_t texture_atlas_index;
};

7
src/util.hpp Normal file
View File

@@ -0,0 +1,7 @@
#pragma once
struct Vec2
{
int x;
int y;
};

View File

@@ -1,6 +0,0 @@
#pragma once
struct Vec2 {
int x;
int y;
};

View File

@@ -1,8 +0,0 @@
{
"dependencies": [
"spdlog",
"sdl3",
"spdlog",
"flecs"
]
}