Rediseño del sistema de Assets para simplificar las texturas y los "SpriteSheets" que ya no son una clase.

Modificada la clase Sprite para adaptarse al nuevo funcionamiento de las texturas.
Extraidas las clases Drawable y Transformable de Sprite, para poder hacer más objetos con esas características.
Implementada una clase Time que calcula DeltaTime y limita los FPS. Al fin limpiamos el Main y eliminamos todo este código temporal.
Cambios al sistema de escenas, pero se acerca un refactor completo al sistema.
Hace bastante desde el último Commit. Ahí va todo.
GLHF!
This commit is contained in:
2022-01-20 20:10:19 +01:00
parent a565bcfad2
commit a9180fde92
35 changed files with 619 additions and 414 deletions
+30 -4
View File
@@ -3,6 +3,9 @@
#include <json\json.hpp>
using json = nlohmann::ordered_json;
#include <SDL_rect.h>
namespace UE
{
@@ -15,6 +18,7 @@ namespace UE
/* Asset struct. Contains info regarding Assets para ser cargados. */
struct Asset
{
public:
Asset() {};
Asset(std::string name,
@@ -26,8 +30,6 @@ namespace UE
std::string _name = "";
std::string _path = "";
int _ID = NULL;
AssetType _type = AssetType::Unvalid;
};
@@ -39,7 +41,6 @@ namespace UE
{"name", as._name},
{"Path", as._path},
{"Type", as._type},
//{"ID", as._ID}
};
}
@@ -49,7 +50,32 @@ namespace UE
j.at("name").get_to(as._name);
j.at("Path").get_to(as._path);
j.at("Type").get_to(as._type);
//j.at("ID").get_to(as._ID);
}
}
//---------------
//Es necesario hacerlo fuera del namespace UE para que JSON no se enfade.
// Es importante mantener a tus librerías contentas.
//---------------
/* Conversión de un Struct SDL_Rect a JSON */
inline void to_json(nlohmann::ordered_json& j, const SDL_Rect& rect)
{
j = nlohmann::ordered_json
{
{"posX", rect.x},
{"posY", rect.y},
{"sizeX", rect.w},
{"sizeY", rect.h}
};
}
/* Conversión de un JSON a un struct SDL_Rect */
inline void from_json(const nlohmann::ordered_json& j, SDL_Rect& rect)
{
j.at("posX").get_to(rect.x);
j.at("posY").get_to(rect.y);
j.at("sizeX").get_to(rect.w);
j.at("sizeY").get_to(rect.h);
}
+94 -73
View File
@@ -1,33 +1,45 @@
#include <fstream>
#include <iostream>
#include "spdlog\logger.h"
#include "Logging\Logger.h"
#include "Assets\AssetManager.h"
#include "SDL_rect.h"
namespace UE
{
int AssetManager::InitAssetManager()
void AssetManager::InitAssetManager()
{
IMG_Init(IMG_INIT_PNG);
return 0;
if (IMG_Init(IMG_INIT_PNG))
{
UE_LOG_INFO("SDL_Image Init.");
}
else
{
UE_LOG_ERROR("SDL_Image Init ERROR.");
}
UE_LOG_INFO("AssetManager Iniciated");
}
int AssetManager::CleanAssetManager()
void AssetManager::CleanAssetManager()
{
//Destruye todas las texturas de SDL.
for (auto i = _textures.begin(); i != _textures.end(); i++)
{
SDL_DestroyTexture(i->second);
}
//CPP se debería de encargar de ellos, pero bueno.
_assets.clear();
_assetQueue.clear();
_textures.clear();
_SpriteSheets.clear();
_textureRects.clear();
IMG_Quit();
return 0;
UE_LOG_INFO("AssetManager Cleaned");
}
@@ -45,28 +57,47 @@ namespace UE
json Sounds = jread["Sounds"];
json Others = jread["Others"];
/* Add assets struct to asset map. */
for (int i = 0; i < Textures.size(); i++) {
_assets.push_back(Textures.at(i));
}
for (int i = 0; i < SpriteSheets.size(); i++)
if (loadMethod == LoadMethod::Queue)
{
_assets.push_back(SpriteSheets.at(i));
/* Add assets struct to asset map. */
for (int i = 0; i < Textures.size(); i++)
{
_assetQueue.push_back(Textures.at(i));
}
for (int i = 0; i < SpriteSheets.size(); i++)
{
_assetQueue.push_back(SpriteSheets.at(i));
}
for (int i = 0; i < Sounds.size(); i++)
{
_assetQueue.push_back(Sounds.at(i));
}
for (int i = 0; i < Others.size(); i++)
{
_assetQueue.push_back(Others.at(i));
}
}
for (int i = 0; i < Sounds.size(); i++)
if (loadMethod == LoadMethod::Now)
{
_assets.push_back(Sounds.at(i));
}
for (int i = 0; i < Others.size(); i++)
{
_assets.push_back(Others.at(i));
//TODO
}
file.close();
}
void AssetManager::LoadAsset(Asset& as, LoadMethod loadMethod)
{
_assets.push_back(as);
if (loadMethod == LoadMethod::Queue)
{
_assetQueue.push_back(as);
}
if (loadMethod == LoadMethod::Now)
{
//TODO
}
}
@@ -74,95 +105,85 @@ namespace UE
{
int cantidad = amount;
if (amount == -1 || cantidad >= _assets.size())
cantidad = _assets.size();
if (amount == -1 || cantidad >= _assetQueue.size())
cantidad = _assetQueue.size();
//Load Assets from files, depending on the type.
for (int i = 0; i < cantidad; i++)
{
Asset& as = _assets.at(0);
Asset& as = _assetQueue.front();
switch (as._type)
{
case AssetType::Texture:
{
AddTexture(as._name, as._path);
break;
}
case AssetType::SpriteSheet:
{
LoadTexture(as._name, as._path);
break;
}
default:
{
std::cout << "Can't load Assets." << std::endl;
UE_LOG_WARN("Asset {0}, Type {1} Cannot be loaded from {2}", as._name, as._type, as._path);
break;
}
}
_assets.erase(_assets.begin());
_assetQueue.pop_front();
}
}
void AssetManager::AddTexture(std::string name, std::string txPath)
void AssetManager::LoadTexture(std::string name, std::string txPath)
{
SDL_Surface* loadSurface = IMG_Load(txPath.c_str());
std::fstream file(txPath.c_str());
json jread = json::parse(file);
std::string path = jread["TexturePath"];
//Cargamos la textura.
SDL_Surface* loadSurface = IMG_Load(path.c_str());
SDL_Texture* tx = SDL_CreateTextureFromSurface(_mainRenderer, loadSurface);
_textures.insert(std::make_pair(name, tx));
SDL_FreeSurface(loadSurface);
//Almacenamos los Rects (sprites) de esa textura.
json textureRects = jread["TextureRects"];
_textureRects.insert(std::make_pair(name, std::vector<SDL_Rect>()));
std::vector<SDL_Rect>& vector = _textureRects.at(name);
for (int i = 0; i < textureRects.size(); i++)
{
//json rectData = textureRects.at(i);
//SDL_Rect rect;
//rect.x = rectData.at()
vector.push_back(textureRects.at(i).get<SDL_Rect>());
}
file.close();
}
int AssetManager::RemoveTexture(std::string name)
void AssetManager::RemoveTexture(std::string name)
{
SDL_DestroyTexture(_textures.at(name));
_textures.erase(name);
return 0;
SDL_Rect rect();
}
SDL_Texture* AssetManager::getTexture(std::string TextureName)
{
return _textures.at(TextureName);
}
int AssetManager::GetAssetQueueSize()
{
return _assets.size();
}
void AssetManager::AddSpriteSheet(std::string name, std::string spPath)
{
std::fstream file(spPath.c_str());
json jread = json::parse(file);
int amount = jread.at("TextureAmount").get<int>();
int width = jread.at("TextureWidth").get<int>();
int height = jread.at("TextureHeight").get<int>();
SpriteSheet sp(name, getTexture(name), amount, width, height);
_SpriteSheets.insert(std::make_pair(name, sp));
_SpriteSheets.at(name).CalculateRects();
}
SpriteSheet& AssetManager::getSpriteSheet(std::string name)
{
return _SpriteSheets.at(name);
}
//////////DEBUG//////////
void AssetManager::PrintAssetInfo()
{
std::cout << "AM - Debug INFO: " << std::endl;
for (int i = 0; i < _assets.size(); i++) {
std::cout << _assets[i]._name << " - " << _assets[i]._path << std::endl;
for (int i = 0; i < _assetQueue.size(); i++) {
std::cout << _assetQueue[i]._name << " - " << _assetQueue[i]._path << std::endl;
}
}
+21 -22
View File
@@ -4,16 +4,16 @@
/*STD Includes*/
#include <filesystem>
#include <deque>
#include <vector>
#include <unordered_map>
/*LIB Includes*/
#include <SDL_render.h>
#include <SDL_image.h>
/*UberEngine Includes*/
#include "Assets\Asset.h"
#include "Assets\SpriteSheet.h"
///
/// TODO:
@@ -52,7 +52,7 @@ namespace UE
* Init AssetManager y todo lo necesario para funcionar correctamente.
* - Inicia SDL_IMG.
*/
int InitAssetManager();
void InitAssetManager();
/**
*
@@ -60,7 +60,7 @@ namespace UE
* - Elimina todos los assets de sus contenedores.
* - Descarga SDL_IMG
*/
int CleanAssetManager();
void CleanAssetManager();
/* Carga de Assets */
@@ -97,7 +97,9 @@ namespace UE
* De esta forma, se puede hacer un bucle hasta que la cola sea <= 0.
*
*/
int GetAssetQueueSize();
inline int GetAssetQueueSize() { return _assetQueue.size(); }
inline bool IsAssetQueueEmpty() { return _assetQueue.empty(); }
/*
@@ -105,24 +107,15 @@ namespace UE
*/
//Crea una textura de SDL y la añade al mapa de texturas identificada por su nombre.
void AddTexture(std::string name, std::string txPath);
void LoadTexture(std::string name, std::string txPath);
//Elimina una textura del mapa a partir de su nombre.
int RemoveTexture(std::string name);
void RemoveTexture(std::string name);
//Obtiene una textura del mapa a partir de su nombre.
SDL_Texture* getTexture(std::string TextureName);
inline SDL_Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
/*
Métodos para manejar los SpriteSheets.
*/
//Crea un SpriteSheet y lo almacena en el mapa de SpriteSheets, identificado por su nombre.
void AddSpriteSheet(std::string name, std::string spPath);
//Elimina un SpriteSheet del mapa a partir de su nombre.
int RemoveSpriteSheet(std::string name);
//Obtiene un SpriteSheet del mapa a partir de su nombre.
SpriteSheet& getSpriteSheet(std::string name);
inline std::vector<SDL_Rect>* getTexureRects(std::string textureName) { return &_textureRects.at(textureName); }
///////DEBUG////////
@@ -130,16 +123,22 @@ namespace UE
///////////////////
private:
/* Variables internas */
//----------------------
//VARIABLES
//---------------------
//std::string _assetPath;
std::vector<UE::Asset> _assets = {};
//std::vector<UE::Asset> _assets = {};
std::deque<UE::Asset> _assetQueue = {};
/* Almacenes de asssets */
//Almacén de SDL_Texture* (ptrs, pues lo gestiona SDL).
std::unordered_map<std::string, SDL_Texture*> _textures = {};
//Almacén de SpriteSheets.
std::unordered_map<std::string, SpriteSheet> _SpriteSheets = {};
std::unordered_map<std::string, std::vector<SDL_Rect>> _textureRects = {};
//Necesario para crear las SDL_Texture a partir de SDL_Surface.
-15
View File
@@ -1,15 +0,0 @@
#include "SpriteSheet.h"
void UE::SpriteSheet::CalculateRects()
{
for (int i = 0; i < _textureAmount; i++)
{
int posX = _textureWidth * i;
int posY = 0; //Siempre vale 0 en una textura de 1 dimensión.
SDL_Rect rect = {posX, posY, _textureWidth, _textureHeight};
_txRects.push_back(rect);
}
}
-65
View File
@@ -1,65 +0,0 @@
#pragma once
#include <SDL_render.h>
#include <vector>
#include <string>
#include <json\json.hpp>
//using json = nlohmann::ordered_json;
namespace UE
{
//Tipo de Asset que contiene los datos de un SpriteSheet.
// Contiene los SDL_Rect de origen y un ptr a la textura correspondiente.
// No almacena su propia textura; está todo en el AssetManager.
//Se carga desde un archivo JSON. (Se incluye también un método para guardarlo)
class SpriteSheet
{
public:
SpriteSheet(std::string name,
SDL_Texture* texture,
int textureAmount,
int textureWidth,
int textureHeight)
: _spriteSheetName(name), _texture(texture),
_textureAmount(textureAmount), _textureWidth(textureWidth), _textureHeight(textureHeight)
{}
//Calcula los rects y los almacena en un vector.
//De tal forma que los objetos almacenen un ptr a ese vector en vez de calcular de continuo.
void CalculateRects();
//Debe coincicidir con el nombre de la textura a la que se asocia.
std::string _spriteSheetName = "";
int _textureAmount = 1;
int _textureWidth = 16;
int _textureHeight = 16;
private:
SDL_Texture* _texture = NULL;
std::vector<SDL_Rect> _txRects = {};
};
inline void to_json(nlohmann::ordered_json& j, const SpriteSheet& sp)
{
j = nlohmann::ordered_json
{
{"Name", sp._spriteSheetName},
{"TextureAmount", sp._textureAmount},
{"TextureWidth", sp._textureWidth},
{"TextureHeight", sp._textureHeight}
};
}
inline void from_json(const nlohmann::ordered_json& j, SpriteSheet& sp)
{
j.at("Name").get_to(sp._spriteSheetName);
j.at("TextureAmount").get_to(sp._textureAmount);
j.at("TextureWidth").get_to(sp._textureWidth);
j.at("TextureHeight").get_to(sp._textureHeight);
}
}
+4 -38
View File
@@ -1,41 +1,14 @@
#include "Sprite.h"
#include "Render\Renderer.h"
#include "Assets\AssetManager.h"
#include <iostream>
void UE::Sprite::SetTexturePtr(SDL_Texture* texture)
void UE::Sprite::SetTextureRect(int textureID)
{
_spriteTx = texture;
}
void UE::Sprite::SetPosition(float x, float y)
{
_pos = glm::vec2(x, y);
}
void UE::Sprite::SetPosition(glm::vec<2, float> newPosition)
{
_pos = newPosition;
}
void UE::Sprite::SetSize(float x, float y)
{
_size = glm::vec2(x, y);
}
void UE::Sprite::SetSize(glm::vec<2,float> newSize)
{
_size = newSize;
}
void UE::Sprite::SetLayer(int newLayer)
{
_layer = newLayer;
_actualTxRect = &_txRects->at(textureID);
}
@@ -49,13 +22,6 @@ void UE::Sprite::Draw(Renderer* renderer)
//destination.h = _size.y;
//std::cout << "Sprite Rendered to: " << destination.x << "-" << destination.y << std::endl;
if (_txRect == nullptr)
{
renderer->QueueDrawCall(_layer, position, _spriteTx);
}
else
{
renderer->QueueDrawCall(_layer, position, _spriteTx, *_txRect);
}
renderer->QueueDrawCall(_renderLayer, position, _txPtr, *_actualTxRect);
}
+31 -37
View File
@@ -1,12 +1,14 @@
#pragma once
#include <string>
#include <SDL.h>
#include <string>
#include <vector>
//#include <glm.hpp>
#include <glm\vec2.hpp>
#include "Render\Drawable.h"
#include "Render\Transformable.h"
//
// TODO:
@@ -18,9 +20,8 @@
namespace UE
{
class Renderer;
class AssetManager;
class Sprite : public Drawable
class Sprite : public Drawable, public Transformable
{
@@ -34,64 +35,57 @@ namespace UE
/*
Se establecen todos los parámetos.
La textura es obligatoria, y puede darse:
- En std::string nombre y assetManager* -> Va a buscarse al assetManager especificado.
La textura es obligatoria, y puede ha de darse:
- En SDL_Texture* -> Sin más, se entiende.
En ambos casos se llama al método SetTexturePtr.
Los demás parámetros tienen un valor por defecto.
\param texturePtr: El pointer a la textura de SDL.
\param textureRects: El pointer al conjunto de SDL_Rects de la textura.
\param textureRectID: El número de Rect del conjunto de rects.
\param renderLayer: La Layer en que se renderizará.
*/
Sprite(SDL_Texture* texturePtr,
std::vector<SDL_Rect>* textureRects,
int textureRectID = 0,
int renderLayer = 1,
glm::vec2 position = glm::vec2(0, 0),
glm::vec2 size = glm::vec2(100, 100))
Sprite(SDL_Texture* texture,
int renderLayer = 1,
glm::vec2 position = glm::vec2(0, 0),
glm::vec2 size = glm::vec2(100, 100))
: _layer(renderLayer), _pos(position), _size(size)
: _txPtr(texturePtr), _txRects(textureRects)
{
SetTexturePtr(texture);
SetTextureRect(textureRectID);
SetLayer(renderLayer);
SetPosition(position);
SetSize(size);
}
~Sprite() {}
/*
//-----------
// Setters
//- Setters -
//-----------
*/
//Establece la textura a _spriteTx.
//Lo llama el constructor.
// ¿Queremos darle acceso al usuario? ¿Lo movemos a private / protected?
void SetTexturePtr(SDL_Texture* texture);
//Modifica la posición del Sprite.
void SetPosition(float x, float y);
void SetPosition(glm::vec<2, float> newPosition);
//Modifica la escala de sprite ¿(en relación a la textura)?.
void SetSize(float x, float y);
void SetSize(glm::vec<2,float> newSize);
//Set rendering layer.
void SetLayer(int newLayer);
void SetTextureRect(int textureID);
//Implementa el Draw de Drawable.
void Draw(Renderer* renderer) override;
private:
SDL_Texture* _spriteTx = nullptr;
SDL_Rect* _txRect = nullptr;
glm::vec<2, float> _pos = glm::vec2(25, 25);
glm::vec<2, float> _size = glm::vec2(100, 100);
//Datos de la textura. Sirven para pedirla al AssetManager.
int _layer = 1;
SDL_Texture* _txPtr = nullptr;
std::vector<SDL_Rect>* _txRects = nullptr;
//El que se va a renderizar.
SDL_Rect* _actualTxRect = nullptr;
};
+8
View File
@@ -11,9 +11,17 @@ namespace UE
Drawable() {}
virtual ~Drawable() {};
//Get-Set del renderLayer.
inline void SetLayer(int newLayer) { _renderLayer = newLayer; }
inline int GetLayer() { return _renderLayer; }
public:
virtual void Draw(Renderer* renderer) = 0;
protected:
//renderLayer usada en el renderer como "profundidad".
int _renderLayer = 0;
};
}
+2 -6
View File
@@ -91,11 +91,7 @@ namespace UE
for (int k = 0; k < layer.size(); k++)
{
DrawCall item = layer.at(k);
if (!item.fullTexture)
{
SDL_RenderCopy(main_Renderer, item.tx, &item.tx_rect, &item.pos_rect);
}
SDL_RenderCopy(main_Renderer, item.tx, NULL, &item.pos_rect);
SDL_RenderCopy(main_Renderer, item.tx, &item.tx_rect, &item.pos_rect);
}
layer.clear();
}
@@ -135,7 +131,7 @@ namespace UE
void Renderer::QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position)
{
DrawCall dc = DrawCall(layer, position, texture, texture_position, false);
DrawCall dc = DrawCall(layer, position, texture, texture_position);
//Add item i to layer number i.layer.
if (layer > LAYER_AMOUNT)
+8 -8
View File
@@ -4,8 +4,10 @@
#include <stdio.h>
#include <string>
#include <vector>
#include <glm\vec2.hpp>
#include "Drawable.h"
#include "Logging\Logger.h"
//
// TODO:
@@ -14,6 +16,7 @@
//
//
namespace UE
{
struct DrawCall;
@@ -30,7 +33,7 @@ namespace UE
: SCREEN_WIDTH(windowWidth), SCREEN_HEIGHT(windowHeight), LAYER_AMOUNT(renderingLayers)
{
printf("Renderer Created");
UE_LOG_INFO("Game Renderer Created.");
}
@@ -63,6 +66,8 @@ namespace UE
/* Get SDL Renderer. */
SDL_Renderer* GetSDLRenderer() { return main_Renderer; }
inline glm::ivec2 GetScreenSize() { return glm::ivec2(SCREEN_WIDTH, SCREEN_HEIGHT); }
//DEBUG
//Función para renderizar un objeto un objeto en concreto.
@@ -112,17 +117,12 @@ namespace UE
DrawCall(int layer,
SDL_Rect position,
SDL_Texture* texture,
SDL_Rect texture_position = SDL_Rect(),
bool renderFullTexture = true)
SDL_Rect texture_position = SDL_Rect())
: layer(layer), fullTexture(renderFullTexture), tx(texture), tx_rect(texture_position), pos_rect(position)
: layer(layer), tx(texture), tx_rect(texture_position), pos_rect(position)
{}
int layer;
/*Es necesario saber si es la textura completa o sólo una parte.
//De tal forma, el renderer puede pasar un NULL o el tx_rect al SDL_RenderCopy().
*/
bool fullTexture;
SDL_Texture* tx;
SDL_Rect tx_rect;
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#include <string>
#include <vector>
#include <glm\vec2.hpp>
namespace UE
{
/*
Clase que contiene lo necesario para crear un objeto con posición en el espacio y modificarlo.
*/
class Transformable
{
public:
//-----------
//- Setters -
//-----------
//Modifica la posición del Objeto.
inline void SetPosition(float x, float y) { _pos = glm::vec<2, float>(x, y); }
inline void SetPosition(glm::vec<2, float> newPosition) { _pos = newPosition; }
//Modifica la escala de Objeto.
inline void SetSize(float x, float y) { _size = glm::vec<2, float>(x, y); }
inline void SetSize(glm::vec<2, float> newSize) { _size = newSize; }
//-----------
//- Getters -
//-----------
inline glm::vec2 GetPosition() { return _pos; }
inline glm::vec2 GetSize() { return _size; }
protected:
//Se almacena la posición y el tamaño del objeto. Con esto se puede crear un SDL_Rect.
glm::vec<2, float> _pos;
glm::vec<2, float> _size;
};
}
+4 -10
View File
@@ -14,16 +14,10 @@ namespace UE
void Scene::SceneClean()
{
std::cout << "Scene has been cleaned!" << std::endl;
}
int Scene::GetID()
{
return id;
}
void Scene::SetID(int newID)
{
id = newID;
if (loaded)
{
SceneUnload();
}
}
}
+11 -6
View File
@@ -22,7 +22,9 @@ namespace UE
{
public:
Scene() {}
Scene(std::string name)
: _sceneName(name)
{}
/* Funciones "internas" de la clase para inicialización y cierre. */
void SceneInit(); //Te calienta y prepara la casa al llegar.
@@ -32,23 +34,26 @@ namespace UE
/* Funciones que habrán de sobrecargar las escenas del usuario. */
virtual void SceneLoad() { std::cout << "EMPTY SCENE CREATED" << std::endl; }
virtual void SceneUpdate() {}
virtual void SceneUnload() {}
virtual void SceneUnload() { std::cout << "EMPTY SCENE DESCARGADA" << std::endl; }
// ¿Esto sirve para algo?
//void loadDataFromFile(std::string path);
//Retorna el ID de la Scene.
int GetID();
void SetID(int newID);
inline std::string GetName() { return _sceneName; }
inline bool IsLoaded() { return loaded; }
protected:
//Almacena el ID actual, permitiendo generar un ID nuevo para cada Scene que se instancie.
//static uint16_t currentID;
int id = 0;
std::string _sceneName;
//std::vector<Entity> _entidades;
bool loaded = false;
};
}
+20 -24
View File
@@ -1,16 +1,15 @@
#include "SceneManager.h"
#include "Logging\Logger.h"
#include <iostream>
namespace UE
{
void SceneManager::InitSceneManager()
{
std::cout << "SceneManager Inicializado!" << std::endl;
UE_LOG_INFO("Se ha inicializado el SceneManager.");
}
void SceneManager::CleanSceneManager()
@@ -20,9 +19,9 @@ namespace UE
_currentScene->SceneUnload();
}
for (int i = 0; i < _scenes.size(); i++)
for (auto& it : _scenes)
{
Scene* sc = _scenes.at(i);
Scene* sc = it.second;
sc->SceneClean();
delete sc;
}
@@ -30,41 +29,38 @@ namespace UE
_scenes.clear();
}
int SceneManager::AddScene(Scene* sceneToAdd)
void SceneManager::AddScene(Scene* sceneToAdd)
{
_scenes.push_back(sceneToAdd);
_scenes.insert(std::make_pair(sceneToAdd->GetName(), sceneToAdd));
sceneToAdd->SceneInit();
sceneToAdd->SetID(_scenes.size() - 1);
return sceneToAdd->GetID();
UE_LOG_INFO("Se ha añadido la escena {0} al SceneManager.", sceneToAdd->GetName());
}
Scene* SceneManager::GetScenePtr(int ID)
Scene* SceneManager::GetScenePtr(std::string sceneName)
{
if (ID >= _scenes.size())
if (_scenes.find(sceneName) == _scenes.end())
{
std::cout << "El ID de Scene no existe (demasiado grande)." << std::endl;
UE_LOG_ERROR("No se ha encontrado la escena indicada.");
return nullptr;
}
return _scenes.at(ID);
return _scenes.at(sceneName);
}
int SceneManager::GetActiveSceneID()
{
return 0;
}
Scene* SceneManager::GetActiveScenePtr()
{
return _currentScene;
}
void SceneManager::LoadScene(int ID)
void SceneManager::LoadScene(std::string sceneName)
{
if (_currentScene != nullptr)
{
_currentScene->SceneUnload();
}
_currentScene = _scenes.at(ID);
_currentScene = _scenes.at(sceneName);
_currentScene->SceneLoad();
}
+8 -6
View File
@@ -1,6 +1,7 @@
#pragma once
#include <string>
#include <vector>
#include <unordered_map>
#include "Scene.h"
//
@@ -29,17 +30,17 @@ namespace UE
void CleanSceneManager();
//Añade una escena a la lista y retorna su ID. Son Ptrs, por lo que poco importa donde los almacenamos.
int AddScene(Scene* sceneToAdd);
void AddScene(Scene* sceneToAdd);
//Devuelve un ptr a la escena del ID especificado.
Scene* GetScenePtr(int ID);
Scene* GetScenePtr(std::string sceneName);
//Devuelve la escena activa.
int GetActiveSceneID(); //NOT WORKING YET!
Scene* GetActiveScenePtr();
inline std::string GetActiveSceneName() { return _currentScene->GetName(); }
inline Scene* GetActiveScenePtr() { return _currentScene; }
//Descarga la escena activa y carga la escena indicada.
void LoadScene(int ID);
void LoadScene(std::string sceneName);
//Pasa el Update a la escena actual.
//¿Necesita hacer algo más?
@@ -55,7 +56,8 @@ namespace UE
//Almacenamos un ptr a las diferentes escenas disponibles.
//Otra opción es trabajar con Templates para instanciar la clase pretinente sin necesidad de almacenar nada.
//De cualquier forma, son ptr en el Stack y deberían de eliminar todo al hacer scene.Unload().
std::vector<Scene*> _scenes;
std::unordered_map<std::string, Scene*> _scenes;
//std::vector<Scene*> _scenes;
};
+43
View File
@@ -0,0 +1,43 @@
#include "Time.h"
#include <SDL.h>
double UE::Time::deltaTime;
uint32_t UE::Time::_startTime;
void UE::Time::StartFrame()
{
_startTime = SDL_GetTicks();
}
void UE::Time::EndFrame()
{
// Calculamos el tiempo que llevamos de Frame, para que si nos quedamos cortos, esperemos.
//FrameTime es el tiempo que ha tardado el frame (el deltaTime) en MS.
uint32_t frameTime = SDL_GetTicks() - _startTime;
//Frames totales / segundos totales.
//_avgFPS = countedFrames / (SDL_GetTicks() / 1000.f);
//std::cout << "FPS: " << avgFPS << " / " << "dT: " << deltaTime << std::endl;
//Limitamos los FPS haciendo esperar al programa el tiempo extra que quede.
//En vez de sólo esperar, se podrían hacer tareas como cargar Assets o realizar cálculos pesados.
if (frameTime < MS_PER_FRAME)
{
SDL_Delay(MS_PER_FRAME - frameTime);
}
//Calculamos el deltaTime, que sí será el tiempo real que ha pasado, pues hemos esperado.
frameTime = SDL_GetTicks() - _startTime;
//Convertimos deltaTime a segundos pues es lo usado en los cálculos.
deltaTime = frameTime / 1000.0f;
//++countedFrames;
}
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#include <cstdint>
/*
TODO:
- Buscar una mejor forma de calcular la media de FPS.
*/
namespace UE
{
class Time
{
public:
//-------------------
//---- Métodos ------
//-------------------
static void StartFrame();
static void EndFrame();
//-------------------
//---- Variables ----
//-------------------
static double deltaTime;
private:
static uint32_t _startTime;
//uint16_t countedFrames = 0;
float _avgFPS;
static const int FPS = 60;
//Milisegundos que tiene que tener un frame para poder hacer el número de FPS por segundo.
static const int MS_PER_FRAME = 1000 / FPS;
};
}
+3 -1
View File
@@ -1,5 +1,7 @@
#pragma once
#include "Logging\Logger.h"
#include "Render\Renderer.h"
#include "Drawables\Sprite.h"
@@ -7,4 +9,4 @@
#include "Scene\SceneManager.h"
#include "Logging\Logger.h"
#include "Time\Time.h"
+37 -87
View File
@@ -2,16 +2,14 @@
#include <glm\glm.hpp>
#include "UberGame1.h"
#include "UberEngine.h"
#include "Scenes\MainScene.hpp"
#include "Scenes\TestScene2.hpp"
static UE::Renderer* mainRenderer;
static UE::AssetManager* asManager;
static UE::SceneManager* scManager;
static bool _quit = false;
void Init();
@@ -34,37 +32,26 @@ int main(int argc, char* args[])
void Init()
{
UE::Logger::InitLogger();
mainRenderer = new UE::Renderer(640, 480, 5);
mainRenderer->InitRenderer();
UE_LOG_INFO("Renderer Created.");
asManager = new UE::AssetManager(mainRenderer->GetSDLRenderer());
asManager->InitAssetManager();
UE_LOG_INFO("AssetManager Created.");
scManager = new UE::SceneManager();
scManager->InitSceneManager();
Game::InitGame();
//Añadimos todas las escenas al Manager. No pasa nada, porque el Manager lo iniciamos después
MainScene* scene1 = new MainScene();
TestScene2* scene2 = new TestScene2();
scManager->AddScene(scene1);
scManager->AddScene(scene2);
MainScene* scene1 = new MainScene("Main");
TestScene2* scene2 = new TestScene2("Test2");
Game::GetSceneManager()->AddScene(scene1);
Game::GetSceneManager()->AddScene(scene2);
}
void Load()
{
asManager->LoadAssetsFromFile("resources\\AssetList\\MainAssets.json");
asManager->ProcessAssetQueue();
Game::GetAssetManager()->LoadAssetsFromFile("resources\\AssetList\\MainAssets.json");
Game::GetAssetManager()->ProcessAssetQueue();
//Cargamos la escena que queramos tras tener todos los Assets pertinentes cargados.
//Si la escena contiene su propio AssetManager y los carga ella misma, no será necesario.
scManager->LoadScene(0);
//scManager->LoadScene(0);
Game::GetSceneManager()->LoadScene("Main");
}
@@ -73,49 +60,34 @@ void Loop()
#pragma region TEMP_REDERING
//SDL_Surface* loaderSurface;
SDL_Texture* background;
SDL_Texture* test1;
//SDL_Texture* background;
//SDL_Texture* test1;
SDL_Rect DestR;
DestR.x = 0;
DestR.y = 0;
DestR.w = 640;
DestR.h = 480;
//SDL_Rect DestR;
//DestR.x = 0;
//DestR.y = 0;
//DestR.w = 640;
//DestR.h = 480;
SDL_Rect DestR2;
DestR2.x = 48;
DestR2.y = 48;
DestR2.w = 128;
DestR2.h = 128;
//SDL_Rect DestR2;
//DestR2.x = 48;
//DestR2.y = 48;
//DestR2.w = 128;
//DestR2.h = 128;
background = asManager->getTexture("bg1");
test1 = asManager->getTexture("test1");
//background = Game::GetAssetManager()->getTexture("bg1");
//test1 = Game::GetAssetManager()->getTexture("test1");
glm::vec2 sp1_pos(48, 48);
glm::vec2 sp1_size(145, 145);
//Sprite sp1("test1", assetManager, 5, sp1_pos, sp1_size);
//Sprite sp2("test1", assetManager, 7, sp1_pos);
UE::Sprite sp3(test1);
#pragma endregion
#pragma region TEMP_FPS_Timer
Uint32 startTime = SDL_GetTicks();
Uint16 countedFrames = 0;
double deltaTime = 0;
const int FPS = 60;
const int MS_PER_FRAME = 1000 / FPS;
float avgFPS;
#pragma endregion
while (!_quit)
{
startTime = SDL_GetTicks();
UE::Time::StartFrame();
//TEMP Event Handler:
SDL_Event eventHandler;
while (SDL_PollEvent(&eventHandler) != 0)
@@ -127,47 +99,31 @@ void Loop()
}
const Uint8* keyStates = SDL_GetKeyboardState(NULL);
if (keyStates[SDL_SCANCODE_W])
{
DestR2.y -= (25 * deltaTime);
}
if (keyStates[SDL_SCANCODE_S])
{
DestR2.y -= (50 * deltaTime);
//std::cout << "S PRESS" << std::endl;
}
if (keyStates[SDL_SCANCODE_ESCAPE])
{
_quit = true;
}
if (keyStates[SDL_SCANCODE_F])
{
GAME_LOG_TRACE("FPS: {0} / dT: {1}", avgFPS, deltaTime);
GAME_LOG_TRACE("FPS: {0} / dT: {1}", 60, UE::Time::deltaTime);
}
//FRAME PHYSICS
//TICK ALL OBJECTS.
mainRenderer->QueueDrawCall(4, DestR2, test1);
mainRenderer->QueueDrawCall(1, DestR, background);
//Game::GetRenderer()->QueueDrawCall(4, DestR2, test1);
//Game::GetRenderer()->QueueDrawCall(1, DestR, background);
//renderer->Render(sp1);
//sp2.Draw(renderer);
sp3.Draw(mainRenderer);
//sp3.Draw(Game::GetRenderer());
//
Game::GetSceneManager()->GetActiveScenePtr()->SceneUpdate();
mainRenderer->RenderFrame();
Uint32 frameTime = SDL_GetTicks() - startTime;
deltaTime = frameTime / 1000.f;
//Frames totales / segundos totales.
avgFPS = countedFrames / (SDL_GetTicks() / 1000.f);
//std::cout << "FPS: " << avgFPS << " / " << "dT: " << deltaTime << std::endl;
Game::GetRenderer()->RenderFrame();
//FPS CAP
if (frameTime < MS_PER_FRAME)
{
SDL_Delay(MS_PER_FRAME - frameTime);
}
UE::Time::EndFrame();
++countedFrames;
}
}
@@ -175,13 +131,7 @@ void Loop()
void Clean()
{
asManager->CleanAssetManager();
delete asManager;
mainRenderer->CleanRenderer();
delete mainRenderer;
scManager->CleanSceneManager();
Game::CleanGame();
SDL_Quit();
}
+45 -4
View File
@@ -1,27 +1,68 @@
#include "Scene\Scene.h"
#include "Render\Renderer.h"
#include "Drawables\Sprite.h"
#include <iostream>
#include <vector>
class MainScene : public UE::Scene
{
public:
MainScene(std::string sceneName) : Scene(sceneName) {}
void SceneLoad() override
{
std::cout << "Hey! MainScene! - ID: " << id << std::endl;
UE_LOG_INFO("Escena {0} ha sido cargada", _sceneName);
UE::AssetManager* as = Game::GetAssetManager();
SDL_Texture* test1Texture = as->getTexture("test1");
UE::Sprite sp1(test1Texture, as->getTexureRects("test1"), 0, 2, glm::vec2(55, 60), glm::vec2(100, 100));
UE::Sprite sp2(test1Texture, as->getTexureRects("test1"), 0, 1, glm::vec2(50, 45), glm::vec2(145, 145));
UE::Sprite bg(as->getTexture("bg1"), as->getTexureRects("bg1"), 1, 0, glm::vec2(0, 0), Game::GetRenderer()->GetScreenSize());
sprites.push_back(sp1);
sprites.push_back(sp2);
sprites.push_back(bg);
}
void SceneUpdate() override
{
std::cout << "MainScene actualizandose! - ID: " << id << std::endl;
UE_LOG_INFO("Escena {0} UPDATE", _sceneName);
UE::Renderer* renderer;
renderer = Game::GetRenderer();
glm::vec2 screenSize = Game::GetRenderer()->GetScreenSize();
UE::Sprite& sp1 = sprites.at(0);
glm::vec2 pos = sp1.GetPosition();
if (pos.x > screenSize.x) { pos.x -= 1000; } else { pos.x += 200 * UE::Time::deltaTime; }
sp1.SetPosition(pos);
for (UE::Sprite sp : sprites)
{
renderer->Render(sp);
}
}
void SceneUnload() override
{
std::cout << "MainScene descnsando! - ID: " << id << std::endl;
UE_LOG_INFO("Escena {0} se ha descargado.", _sceneName);
sprites.clear();
}
private:
std::vector<UE::Sprite> sprites;
};
+6 -3
View File
@@ -5,20 +5,23 @@
class TestScene2 : public UE::Scene
{
public:
using Scene::Scene;
void SceneLoad() override
{
std::cout << "Scena de prueba 2 cargada" << id << std::endl;
UE_LOG_INFO("Escena {0} ha sido cargada", _sceneName);
}
void SceneUpdate() override
{
std::cout << "TestScene2 actualizandose!" << id << std::endl;
UE_LOG_INFO("Escena {0} UPDATE", _sceneName);
}
void SceneUnload() override
{
std::cout << "Scene2 descansando." << id << std::endl;
UE_LOG_INFO("Escena {0} se ha descargado.", _sceneName);
}
};
+37
View File
@@ -0,0 +1,37 @@
#include "UberGame1.h"
#include "Logging\Logger.h"
#include "Render\Renderer.h"
#include "Assets\AssetManager.h"
#include "Scene\SceneManager.h"
UE::Renderer* Game::mainRenderer;
UE::AssetManager* Game::asManager;
UE::SceneManager* Game::scManager;
void Game::InitGame()
{
mainRenderer = new UE::Renderer(640, 480, 5);
mainRenderer->InitRenderer();
UE_LOG_INFO("Renderer Created.");
asManager = new UE::AssetManager(mainRenderer->GetSDLRenderer());
asManager->InitAssetManager();
UE_LOG_INFO("AssetManager Created.");
scManager = new UE::SceneManager();
scManager->InitSceneManager();
}
void Game::CleanGame()
{
asManager->CleanAssetManager();
delete asManager;
mainRenderer->CleanRenderer();
delete mainRenderer;
scManager->CleanSceneManager();
delete scManager;
}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
namespace UE
{
class Renderer;
class AssetManager;
class SceneManager;
}
class Game
{
public:
static void InitGame();
static void CleanGame();
inline static UE::Renderer* GetRenderer() { return mainRenderer; }
inline static UE::AssetManager* GetAssetManager() { return asManager; }
inline static UE::SceneManager* GetSceneManager() { return scManager; }
private:
static UE::Renderer* mainRenderer;
static UE::AssetManager* asManager;
static UE::SceneManager* scManager;
};
+5 -5
View File
@@ -2,27 +2,27 @@
"Textures": [
{
"name": "bg1",
"Path": "resources/Sprites/bc.png",
"Path": "resources/Sprites/Data/TX_bg1.json",
"Type": 0
},
{
"name": "test1",
"Path": "resources/Sprites/Test1.png",
"Path": "resources/Sprites/Data/TX_Text1.json",
"Type": 0
},
{
"name": "Player",
"Path": "resources/Sprites/Player.png",
"Path": "resources/Sprites/Data/TX_Player.json",
"Type": 0
},
{
"name": "Button",
"Path": "resources/Sprites/Button.png",
"Path": "resources/Sprites/Data/TX_Button.json",
"Type": 0
},
{
"name": "Tilemap",
"Path": "resources/Sprites/Tilemap2.png",
"Path": "resources/Sprites/Data/TX_Tilemap.json",
"Type": 0
}
],
+17
View File
@@ -0,0 +1,17 @@
{
"TexturePath": "resources/Sprites/Textures/Button.png",
"TextureRects": [
{
"posX": 0,
"posY": 0,
"sizeX": 32,
"sizeY": 32
},
{
"posX": 32,
"posY": 0,
"sizeX": 16,
"sizeY": 16
}
]
}
+17
View File
@@ -0,0 +1,17 @@
{
"TexturePath": "resources/Sprites/Textures/Player.png",
"TextureRects": [
{
"posX": 0,
"posY": 0,
"sizeX": 16,
"sizeY": 16
},
{
"posX": 16,
"posY": 0,
"sizeX": 16,
"sizeY": 16
}
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"TexturePath": "resources/Sprites/Textures/Test1.png",
"TextureRects": [
{
"posX": 0,
"posY": 0,
"sizeX": 16,
"sizeY": 16
}
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"TexturePath": "resources/Sprites/Textures/Tilemap2.png",
"TextureRects": [
{
"posX": 0,
"posY": 0,
"sizeX": 8,
"sizeY": 8
},
{
"posX": 8,
"posY": 0,
"sizeX": 8,
"sizeY": 8
},
{
"posX": 16,
"posY": 0,
"sizeX": 8,
"sizeY": 8
}
]
}
+17
View File
@@ -0,0 +1,17 @@
{
"TexturePath": "resources/Sprites/Textures/bc.png",
"TextureRects": [
{
"posX": 0,
"posY": 0,
"sizeX": 320,
"sizeY": 240
},
{
"posX": 80,
"posY": 60,
"sizeX": 160,
"sizeY": 120
}
]
}

Before

Width:  |  Height:  |  Size: 474 B

After

Width:  |  Height:  |  Size: 474 B

Before

Width:  |  Height:  |  Size: 599 B

After

Width:  |  Height:  |  Size: 599 B

Before

Width:  |  Height:  |  Size: 630 B

After

Width:  |  Height:  |  Size: 630 B

Before

Width:  |  Height:  |  Size: 170 B

After

Width:  |  Height:  |  Size: 170 B

Before

Width:  |  Height:  |  Size: 236 B

After

Width:  |  Height:  |  Size: 236 B

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB