Compare commits

3 Commits
Author SHA1 Message Date
Daniel-Garmig 692812a710 Unificar Encoding.
Revisado que todos los archivos son UTF-8 y espacios como indentación.
2022-08-11 16:47:50 +02:00
Daniel-Garmig 006d223f57 Nueva Clase Engine.
Se ha eliminado la antigua clase Game y movido a la nueva clase Engine.
La clase Engine, encargada de iniciar las cosas, ahora está en el Engine
Además, tiene seguridad en la inicialización.
Ya no se inicia el juego si hay error al cargar libs o sistemas.
2022-08-11 15:16:23 +02:00
Daniel-Garmig b2d6a31275 Nuevo sistema de Escenas.
Nos quitamos del medio la cosa rara del SceneBuilder.
Simplificamos la estructura y la hacemos más o menos segura.
2022-08-11 12:57:40 +02:00
34 changed files with 1676 additions and 1491 deletions
+4 -1
View File
@@ -38,4 +38,7 @@ Repositorio principal de UberEngine. Sin mucho más.
- [X] AssetManager: Creo que también hay que limpiar las fonts cargadas....
### JSON / AssetManager
- [ ] Crear un sistema sencillo (un método o algo común para todas las veces que sea necesario) para añadir seguridad al parse y uso de los JSON. De tal forma que se devuelva el error por consola pero no salten exepciones ni mierdas.
- [ ] Crear un sistema sencillo (un método o algo común para todas las veces que sea necesario) para añadir seguridad al parse y uso de los JSON. De tal forma que se devuelva el error por consola pero no salten exepciones ni mierdas.
### Sistema de Escenas.
- [ ] Revisar los métodos para carga/descarga y de cambio de escenas. Creo que se pueden estructurar mejor.
+48 -48
View File
@@ -9,48 +9,48 @@ using json = nlohmann::ordered_json;
namespace UE
{
/* All types of Assets that can be loadedand stored by an AssetManager */
enum class AssetType
{
Texture = 0, Font, Sound, Other, Unvalid = 15
};
/* Asset struct. Contains info regarding Assets para ser cargados. */
struct Asset
{
public:
Asset() {};
/* All types of Assets that can be loadedand stored by an AssetManager */
enum class AssetType
{
Texture = 0, Font, Sound, Other, Unvalid = 15
};
/* Asset struct. Contains info regarding Assets para ser cargados. */
struct Asset
{
public:
Asset() {};
Asset(std::string name,
std::string path,
AssetType type)
: _name(name), _path(path), _type(type) {}
Asset(std::string name,
std::string path,
AssetType type)
: _name(name), _path(path), _type(type) {}
std::string _name = "";
std::string _path = "";
std::string _name = "";
std::string _path = "";
AssetType _type = AssetType::Unvalid;
};
AssetType _type = AssetType::Unvalid;
};
/* Conversi�n de una struct Asset a JSON */
inline void to_json(nlohmann::ordered_json& j, const Asset& as)
{
j = nlohmann::ordered_json
{
{"name", as._name},
{"Path", as._path},
{"Type", as._type},
};
}
/* Conversi�n de una struct Asset a JSON */
inline void to_json(nlohmann::ordered_json& j, const Asset& as)
{
j = nlohmann::ordered_json
{
{"name", as._name},
{"Path", as._path},
{"Type", as._type},
};
}
/* Conversi�n de un JSON a una struct Asset */
inline void from_json(const nlohmann::ordered_json& j, Asset& as)
{
j.at("name").get_to(as._name);
j.at("Path").get_to(as._path);
j.at("Type").get_to(as._type);
}
/* Conversi�n de un JSON a una struct Asset */
inline void from_json(const nlohmann::ordered_json& j, Asset& as)
{
j.at("name").get_to(as._name);
j.at("Path").get_to(as._path);
j.at("Type").get_to(as._type);
}
}
@@ -62,20 +62,20 @@ namespace UE
/* 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}
};
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);
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);
}
+154 -177
View File
@@ -1,4 +1,4 @@
#include <fstream>
#include <fstream>
#include <iostream>
#include "Logging/Logger.h"
@@ -10,209 +10,186 @@
namespace UE
{
void AssetManager::InitAssetManager()
{
if (IMG_Init(IMG_INIT_PNG))
{
UE_LOG_INFO("SDL_Image Init.");
}
else
{
UE_LOG_ERROR("SDL_Image - Error al inicarse: {0}", IMG_GetError());
}
void AssetManager::InitAssetManager()
{
UE_LOG_INFO("AssetManager Iniciado con éxito.");
}
if (!TTF_Init()) //Retorna 0 si está correcto.
{
UE_LOG_INFO("SDL_TTF se ha inicializado correctamente.");
}
else
{
UE_LOG_ERROR("SDL_TTF - Error al inicarse: {0}", TTF_GetError());
}
void AssetManager::CleanAssetManager()
{
//Destruye todas las texturas de SDL.
for (auto i = _textures.begin(); i != _textures.end(); i++)
{
i->second->~Texture();
}
UE_LOG_INFO("AssetManager Iniciado con éxito.");
}
//Limpiamos las fuentes.
for (auto i = _fonts.begin(); i != _fonts.end(); i++)
{
//Limpiamos las fuentes.
delete i->second;
}
void AssetManager::CleanAssetManager()
{
//Destruye todas las texturas de SDL.
for (auto i = _textures.begin(); i != _textures.end(); i++)
{
i->second->~Texture();
}
//CPP se debería de encargar de ellos, pero bueno.
_assetQueue.clear();
_textures.clear();
//Limpiamos las fuentes.
for (auto i = _fonts.begin(); i != _fonts.end(); i++)
{
//Limpiamos las fuentes.
delete i->second;
}
//CPP se debería de encargar de ellos, pero bueno.
_assetQueue.clear();
_textures.clear();
UE_LOG_INFO("AssetManager Cleaned");
}
IMG_Quit();
void AssetManager::LoadAssetsFromFile(std::string filePath)
{
std::fstream file(filePath.c_str());
UE_LOG_INFO("AssetManager Cleaned");
}
if (!file.is_open())
{
UE_LOG_ERROR("No se ha podido abrir la lista de assets: {0}", filePath);
}
//Load Asset data from JSON.
json jread = json::parse(file);
json Textures = jread["Textures"];
json Fonts = jread["Fonts"];
json Sounds = jread["Sounds"];
json Others = jread["Others"];
/* 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 < Fonts.size(); i++)
{
_assetQueue.push_back(Fonts.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));
}
file.close();
}
void AssetManager::LoadAsset(Asset& as)
{
_assetQueue.push_back(as);
}
void AssetManager::ProcessAssetQueue(int amount)
{
int cantidad = amount;
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 = _assetQueue.front();
switch (as._type)
{
case AssetType::Texture:
{
LoadTexture(as._name, as._path);
break;
}
case AssetType::Font:
{
LoadFont(as._name, as._path);
break;
}
default:
{
UE_LOG_WARN("Asset {0}, Type {1} Cannot be loaded from {2}", as._name, as._type, as._path);
break;
}
}
_assetQueue.pop_front();
}
}
void AssetManager::LoadAssetsFromFile(std::string filePath)
{
std::fstream file(filePath.c_str());
void AssetManager::LoadTexture(std::string name, std::string txPath)
{
Texture* tx = new Texture(txPath, _SDL_Renderer);
_textures.insert(std::make_pair(name, tx));
if (!file.is_open())
{
UE_LOG_ERROR("No se ha podido abrir la lista de assets: {0}", filePath);
}
//std::fstream file(txPath.c_str());
//Load Asset data from JSON.
json jread = json::parse(file);
//json jread = json::parse(file);
//std::string path = jread["TexturePath"];
json Textures = jread["Textures"];
json Fonts = jread["Fonts"];
json Sounds = jread["Sounds"];
json Others = jread["Others"];
////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);
/* 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 < Fonts.size(); i++)
{
_assetQueue.push_back(Fonts.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));
}
////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();
}
//file.close();
}
void AssetManager::LoadAsset(Asset& as)
{
_assetQueue.push_back(as);
}
void AssetManager::RemoveTexture(std::string name)
{
//Se supone que el erase del map llama al destructor del objeto...
//Pero no lo he comprobado del todo.
_textures.erase(name);
}
void AssetManager::ProcessAssetQueue(int amount)
{
int cantidad = amount;
void AssetManager::LoadFont(std::string name, std::string fontPath)
{
Font* fo = new Font(fontPath);
_fonts.insert(std::make_pair(name, fo));
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 = _assetQueue.front();
switch (as._type)
{
case AssetType::Texture:
{
LoadTexture(as._name, as._path);
break;
}
case AssetType::Font:
{
LoadFont(as._name, as._path);
break;
}
default:
{
UE_LOG_WARN("Asset {0}, Type {1} Cannot be loaded from {2}", as._name, as._type, as._path);
break;
}
}
_assetQueue.pop_front();
}
}
}
void AssetManager::RemoveFont(std::string name)
{
//Se supone que el erase del map llama al destructor del objeto...
//Pero no lo he comprobado del todo.
_fonts.erase(name);
}
void AssetManager::LoadTexture(std::string name, std::string txPath)
{
Texture* tx = new Texture(txPath, _SDL_Renderer);
_textures.insert(std::make_pair(name, tx));
//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>());
//}
//////////DEBUG//////////
//file.close();
}
void AssetManager::PrintAssetInfo()
{
std::cout << "AM - Debug INFO: " << std::endl;
for (int i = 0; i < _assetQueue.size(); i++) {
std::cout << _assetQueue[i]._name << " - " << _assetQueue[i]._path << std::endl;
}
}
void AssetManager::RemoveTexture(std::string name)
{
//Se supone que el erase del map llama al destructor del objeto...
//Pero no lo he comprobado del todo.
_textures.erase(name);
}
void AssetManager::LoadFont(std::string name, std::string fontPath)
{
Font* fo = new Font(fontPath);
_fonts.insert(std::make_pair(name, fo));
}
void AssetManager::RemoveFont(std::string name)
{
//Se supone que el erase del map llama al destructor del objeto...
//Pero no lo he comprobado del todo.
_fonts.erase(name);
}
//////////DEBUG//////////
void AssetManager::PrintAssetInfo()
{
std::cout << "AM - Debug INFO: " << std::endl;
for (int i = 0; i < _assetQueue.size(); i++) {
std::cout << _assetQueue[i]._name << " - " << _assetQueue[i]._path << std::endl;
}
}
/////////////////////////
/////////////////////////
}
+120 -121
View File
@@ -11,20 +11,19 @@
#include <SDL_image.h>
/*UberEngine Includes*/
//#include "Assets\Asset.h"
#include "Assets/Asset.h"
#include "Assets/Texture.h"
#include "Assets/Font.h"
#include "Assets/Asset.h"
using json = nlohmann::ordered_json;
///
/// TODO:
/// TODO:
/// - Modificar las funciones de Carga para quitar la queue o implementar una que tenga sentido.
/// Por ejemplo, se puede crear una cola (std::deque) y cargar un asset cada gameLoop en vez de
/// procesar toda la cola de golpe. Optimizar�a la carga de assets.
/// - Terminar la implementaci�n del tipo de carga (queue/now).
/// Por ejemplo, se puede crear una cola (std::deque) y cargar un asset cada gameLoop en vez de
/// procesar toda la cola de golpe. Optimizar�a la carga de assets.
/// - Terminar la implementaci�n del tipo de carga (queue/now).
/// - Modificar los for en la carga de archivo, as� como la estructura del archivo JSON. El tipo de Asset est� repetido.
/// - Logging.
/// - ERROR HANDLING
@@ -33,151 +32,151 @@ using json = nlohmann::ordered_json;
namespace UE
{
/* Gestiona todos assets primitivos, almacenando sus ptrs en un lugar seguro. */
class AssetManager
{
public:
/* Constructor. */
AssetManager(SDL_Renderer* SDLrenderer)
: _SDL_Renderer(SDLrenderer) {}
/* Gestiona todos assets primitivos, almacenando sus ptrs en un lugar seguro. */
class AssetManager
{
public:
/* Constructor. */
AssetManager(SDL_Renderer* SDLrenderer)
: _SDL_Renderer(SDLrenderer) {}
/**
* Init AssetManager y todo lo necesario para funcionar correctamente.
* - Inicia SDL_IMG.
*/
void InitAssetManager();
/**
* Init AssetManager y todo lo necesario para funcionar correctamente.
* - Inicia SDL_IMG.
*/
void InitAssetManager();
/**
*
* Clean AssetManager Data on exit
* - Elimina todos los assets de sus contenedores.
* - Descarga SDL_IMG
*/
void CleanAssetManager();
/**
*
* Clean AssetManager Data on exit
* - Elimina todos los assets de sus contenedores.
* - Descarga SDL_IMG
*/
void CleanAssetManager();
/* Carga de Assets */
/**
* Carga los datos de los Assets desde un fichero JSON seg�n par�metros.
*
* \param filePath: Ubicaci�n del archivo JSON.
* \param loadMethod: Forma de carga. Procesado al momento o a�adido a la cola de carga.
*
*/
void LoadAssetsFromFile(std::string filePath);
/* Carga de Assets */
/**
* Carga los datos de los Assets desde un fichero JSON seg�n par�metros.
*
* \param filePath: Ubicaci�n del archivo JSON.
* \param loadMethod: Forma de carga. Procesado al momento o a�adido a la cola de carga.
*
*/
void LoadAssetsFromFile(std::string filePath);
/**
* Carga el Asset pasado por par�metro.
*
* \param as: Asset que cargar.
* \param loadMethod: Forma de carga. Procesado al momento o a�adido a la cola de carga.
*
*/
void LoadAsset(Asset& as);
/**
* Carga el Asset pasado por par�metro.
*
* \param as: Asset que cargar.
* \param loadMethod: Forma de carga. Procesado al momento o a�adido a la cola de carga.
*
*/
void LoadAsset(Asset& as);
/**
* Procesa la cola de carga de Assets.
*
* \param Amount: N�mero de Assets de la cola a procesar. Si vale -1 se procesar�n todos.
*
*/
void ProcessAssetQueue(int amount = -1);
/**
* Procesa la cola de carga de Assets.
*
* \param Amount: N�mero de Assets de la cola a procesar. Si vale -1 se procesar�n todos.
*
*/
void ProcessAssetQueue(int amount = -1);
/**
* Devuelve la cantidad de Assets que quedan sin procesar en la cola.
* De esta forma, se puede hacer un bucle hasta que la cola sea <= 0.
*
*/
inline int GetAssetQueueSize() { return _assetQueue.size(); }
/**
* Devuelve la cantidad de Assets que quedan sin procesar en la cola.
* De esta forma, se puede hacer un bucle hasta que la cola sea <= 0.
*
*/
inline int GetAssetQueueSize() { return _assetQueue.size(); }
/// <summary>
/// Comprueba si la cola de carga de Assets est� vac�a.
/// </summary>
/// <returns>El resultado de la cola.</returns>
inline bool IsAssetQueueEmpty() { return _assetQueue.empty(); }
/// <summary>
/// Comprueba si la cola de carga de Assets est� vac�a.
/// </summary>
/// <returns>El resultado de la cola.</returns>
inline bool IsAssetQueueEmpty() { return _assetQueue.empty(); }
/*--------------------------------------/
* M�todos para manejar las texturas. *
*--------------------------------------*/
/*--------------------------------------/
* M�todos para manejar las texturas. *
*--------------------------------------*/
//Crea una textura de SDL y la a�ade al mapa de texturas identificada por su nombre.
void LoadTexture(std::string name, std::string txPath);
//Crea una textura de SDL y la a�ade al mapa de texturas identificada por su nombre.
void LoadTexture(std::string name, std::string txPath);
//Elimina una textura del mapa a partir de su nombre.
void RemoveTexture(std::string name);
//Elimina una textura del mapa a partir de su nombre.
void RemoveTexture(std::string name);
//Obtiene una textura del mapa a partir de su nombre.
//inline SDL_Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
inline Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
//Obtiene una textura del mapa a partir de su nombre.
//inline SDL_Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
inline Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
//inline std::vector<SDL_Rect>* getTexureRects(std::string textureName) { return &_textureRects.at(textureName); }
//inline std::vector<SDL_Rect>* getTexureRects(std::string textureName) { return &_textureRects.at(textureName); }
/*------------------------------------/
* M�todos para manejar las fuentes. *
*------------------------------------*/
/*------------------------------------/
* M�todos para manejar las fuentes. *
*------------------------------------*/
/**
* Crea un objeto UE:Font y lo a�ade al mapa de fuentes.
*
* @param name : Nombre del asset (key para el mapa de fuentes).
* @param fontPath : Ubicaci�n del archivo de datos sobre la fuente.
*
*/
void LoadFont(std::string name, std::string fontPath);
/**
* Crea un objeto UE:Font y lo a�ade al mapa de fuentes.
*
* @param name : Nombre del asset (key para el mapa de fuentes).
* @param fontPath : Ubicaci�n del archivo de datos sobre la fuente.
*
*/
void LoadFont(std::string name, std::string fontPath);
/**
* Elimina una fuente (y en teor�a limpia la fuente) dado su nombre de Asset.
*
* @param name : Nombre del Asset (key del mapa de fuentes).
*
*/
void RemoveFont(std::string name);
/**
* Elimina una fuente (y en teor�a limpia la fuente) dado su nombre de Asset.
*
* @param name : Nombre del Asset (key del mapa de fuentes).
*
*/
void RemoveFont(std::string name);
/**
* Obtiene y devuelve el ptr a una fuente dado su nombre de asset.
*
* @param fontName : Nombre del Asset.
* @return UE::Font* : El ptr a la fuente solicitada.
*
*/
inline Font* GetFont(std::string fontName) { return _fonts.at(fontName); }
/**
* Obtiene y devuelve el ptr a una fuente dado su nombre de asset.
*
* @param fontName : Nombre del Asset.
* @return UE::Font* : El ptr a la fuente solicitada.
*
*/
inline Font* GetFont(std::string fontName) { return _fonts.at(fontName); }
///////DEBUG////////
void PrintAssetInfo();
///////////////////
///////DEBUG////////
void PrintAssetInfo();
///////////////////
private:
//----------------------
//VARIABLES
//---------------------
private:
//----------------------
//VARIABLES
//---------------------
//std::string _assetPath;
//std::vector<UE::Asset> _assets = {};
std::deque<UE::Asset> _assetQueue = {};
//std::string _assetPath;
//std::vector<UE::Asset> _assets = {};
std::deque<UE::Asset> _assetQueue = {};
/* Almacenes de asssets */
/* Almacenes de asssets */
//Almac�n de SDL_Texture* (ptrs, pues lo gestiona SDL).
//std::unordered_map<std::string, SDL_Texture*> _textures = {};
//std::unordered_map<std::string, std::vector<SDL_Rect>> _textureRects = {};
std::unordered_map <std::string, Texture*> _textures = {};
//Almac�n de SDL_Texture* (ptrs, pues lo gestiona SDL).
//std::unordered_map<std::string, SDL_Texture*> _textures = {};
//std::unordered_map<std::string, std::vector<SDL_Rect>> _textureRects = {};
std::unordered_map <std::string, Texture*> _textures = {};
//Almacen de TTF_Fonts* (Para las fuentes de SDL_TTF).
std::unordered_map<std::string, Font*> _fonts = {};
//Almacen de TTF_Fonts* (Para las fuentes de SDL_TTF).
std::unordered_map<std::string, Font*> _fonts = {};
//Necesario para crear las SDL_Texture a partir de SDL_Surface.
SDL_Renderer* _SDL_Renderer = NULL;
};
//Necesario para crear las SDL_Texture a partir de SDL_Surface.
SDL_Renderer* _SDL_Renderer = NULL;
};
}
+45 -45
View File
@@ -10,70 +10,70 @@ using json = nlohmann::ordered_json;
TTF_Font* UE::Font::GetFont(int size)
{
TTF_Font* font;
TTF_Font* font;
auto it = _fonts.find(size);
if (it == _fonts.end())
{
//El tama�o pedido no est� disponible.
//La creamos nueva.
font = CreateFontSize(size);
return font;
}
//En caso de estar disponible, lo retornamos.
font = it->second;
return font;
auto it = _fonts.find(size);
if (it == _fonts.end())
{
//El tama�o pedido no est� disponible.
//La creamos nueva.
font = CreateFontSize(size);
return font;
}
//En caso de estar disponible, lo retornamos.
font = it->second;
return font;
}
void UE::Font::InitFont()
{
//Cargamos los datos desde el archivo.
std::fstream file(_dataPath.c_str());
//Cargamos los datos desde el archivo.
std::fstream file(_dataPath.c_str());
if (!file.is_open())
{
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de fuente: {0}", _fontPath);
return;
}
if (!file.is_open())
{
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de fuente: {0}", _fontPath);
return;
}
json jread = json::parse(file);
json jread = json::parse(file);
_fontPath = jread["FontPath"].get<std::string>();
_fontPath = jread["FontPath"].get<std::string>();
//Obtenemos los tama�os que crear de inicio.
std::vector<int> vect = jread["FontSizes"].get<std::vector<int>>();
for (auto it : vect)
{
CreateFontSize(it);
}
//Obtenemos los tama�os que crear de inicio.
std::vector<int> vect = jread["FontSizes"].get<std::vector<int>>();
for (auto it : vect)
{
CreateFontSize(it);
}
file.close();
file.close();
}
void UE::Font::CleanFont()
{
//Eliminamos todos los tama�os de las fuentes.
for (auto i = _fonts.begin(); i != _fonts.end(); i++)
{
TTF_CloseFont(i->second);
}
//Eliminamos todos los tama�os de las fuentes.
for (auto i = _fonts.begin(); i != _fonts.end(); i++)
{
TTF_CloseFont(i->second);
}
}
TTF_Font* UE::Font::CreateFontSize(int size)
{
//Creamos la fuente del tama�o requerido.
TTF_Font* font = TTF_OpenFont(_fontPath.c_str(), size);
if (font == nullptr)
{
UE_LOG_ERROR("No se ha podido crear la fuente: {0} - Size: {1}", _fontPath, size);
return nullptr;
}
//Creamos la fuente del tama�o requerido.
TTF_Font* font = TTF_OpenFont(_fontPath.c_str(), size);
if (font == nullptr)
{
UE_LOG_ERROR("No se ha podido crear la fuente: {0} - Size: {1}", _fontPath, size);
return nullptr;
}
//La a�adimos al mapa.
_fonts.insert(std::make_pair(size, font));
//La a�adimos al mapa.
_fonts.insert(std::make_pair(size, font));
UE_LOG_TRACE("Font: {0} se ha creado con tamanho: {1}", _fontPath, size);
UE_LOG_TRACE("Font: {0} se ha creado con tamanho: {1}", _fontPath, size);
return font;
return font;
}
+59 -59
View File
@@ -7,79 +7,79 @@
namespace UE
{
/**
* Clase Wrapper para las SDL_Fonts.
* También sirve de "cache" para los diferentes tamaños de la fuente, de esta forma
* reducimos las veces que generamos las fuentes y podemos utilizar múltiples tamaños de forma sencilla.
*
*/
class Font
{
public:
//-----------------------
//----- Constructor -----
//-----------------------
/**
* Clase Wrapper para las SDL_Fonts.
* Tambi�n sirve de "cache" para los diferentes tama�os de la fuente, de esta forma
* reducimos las veces que generamos las fuentes y podemos utilizar m�ltiples tama�os de forma sencilla.
*
*/
class Font
{
public:
//-----------------------
//----- Constructor -----
//-----------------------
Font(std::string dataPath)
: _dataPath(dataPath)
{
InitFont();
}
Font(std::string dataPath)
: _dataPath(dataPath)
{
InitFont();
}
~Font()
{
CleanFont();
}
~Font()
{
CleanFont();
}
//-----------------------
//------- Methods -------
//-----------------------
//-----------------------
//------- Methods -------
//-----------------------
/**
* Devuelve la fuente del tamaño pedido.
* En caso de no estar disponible, la genera y la añade al cache antes de devolverla.
*
* @param size : tamaño de la fuente.
* @return TTF_Font* : Fuente del tamaño solicitado.
*/
TTF_Font* GetFont(int size);
/**
* Devuelve la fuente del tama�o pedido.
* En caso de no estar disponible, la genera y la a�ade al cache antes de devolverla.
*
* @param size : tama�o de la fuente.
* @return TTF_Font* : Fuente del tama�o solicitado.
*/
TTF_Font* GetFont(int size);
private:
/**
* Crea la fuente a partir del archivo de datos.
*/
void InitFont();
private:
/**
* Crea la fuente a partir del archivo de datos.
*/
void InitFont();
/**
* Limpia la fuente, eliminando todos sus tamaños y vaciando toda la memoria.
*/
void CleanFont();
/**
* Limpia la fuente, eliminando todos sus tama�os y vaciando toda la memoria.
*/
void CleanFont();
/**
* Se encarga de generar el tamaño de fuente deseado.
*
* @param size : tamaño a generar.
* @return TTF_Font* : Ptr al nuevo tamaño generado. Hay que guardarlo en algún sitio.
*/
TTF_Font* CreateFontSize(int size);
/**
* Se encarga de generar el tama�o de fuente deseado.
*
* @param size : tama�o a generar.
* @return TTF_Font* : Ptr al nuevo tama�o generado. Hay que guardarlo en alg�n sitio.
*/
TTF_Font* CreateFontSize(int size);
//-----------------------
//------ Variables ------
//-----------------------
//-----------------------
//------ Variables ------
//-----------------------
private:
//Ubicación del archivo de datos (.json).
std::string _dataPath = "";
private:
//Ubicaci�n del archivo de datos (.json).
std::string _dataPath = "";
//Ubicación de la tipografía (.ttf).
std::string _fontPath = "";
//Ubicaci�n de la tipograf�a (.ttf).
std::string _fontPath = "";
//Caché de los diferentes tamaños de la fuente.
std::unordered_map<int, TTF_Font*> _fonts = {};
//Cach� de los diferentes tama�os de la fuente.
std::unordered_map<int, TTF_Font*> _fonts = {};
};
};
}
+34 -34
View File
@@ -10,61 +10,61 @@ using json = nlohmann::ordered_json;
SDL_Rect* UE::Texture::GetTextureRect(int i)
{
try
{
SDL_Rect* rect = &_txRects.at(i);
return rect;
}
catch (const std::out_of_range&)
{
UE_LOG_ERROR("La textura {0} no tiene rect {1}", _txPath, i);
return &_txRects.at(0);
}
try
{
SDL_Rect* rect = &_txRects.at(i);
return rect;
}
catch (const std::out_of_range&)
{
UE_LOG_ERROR("La textura {0} no tiene rect {1}", _txPath, i);
return &_txRects.at(0);
}
}
void UE::Texture::InitTexture()
{
std::fstream file(_dataPath);
//Comprobamos si el archivo se ha abierto.
if (!file.is_open())
{
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de textura: {0}", _dataPath);
return;
}
std::fstream file(_dataPath);
//Comprobamos si el archivo se ha abierto.
if (!file.is_open())
{
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de textura: {0}", _dataPath);
return;
}
json jread = json::parse(file);
_txPath = jread["TexturePath"].get<std::string>();
json jread = json::parse(file);
_txPath = jread["TexturePath"].get<std::string>();
//Creamos la textura.
CreateTexture();
//Creamos la textura.
CreateTexture();
//Cargamos los Rects.
json textureRects = jread["TextureRects"];
//Cargamos los Rects.
json textureRects = jread["TextureRects"];
for (int i = 0; i < textureRects.size(); i++)
{
AddRect(textureRects.at(i).get<SDL_Rect>());
}
for (int i = 0; i < textureRects.size(); i++)
{
AddRect(textureRects.at(i).get<SDL_Rect>());
}
file.close();
file.close();
}
void UE::Texture::CleanTexture()
{
SDL_DestroyTexture(_texture);
_txRects.clear();
SDL_DestroyTexture(_texture);
_txRects.clear();
}
void UE::Texture::CreateTexture()
{
SDL_Surface* loadSurface = IMG_Load(_txPath.c_str());
_texture = SDL_CreateTextureFromSurface(_SDL_Renderer, loadSurface);
SDL_FreeSurface(loadSurface);
SDL_Surface* loadSurface = IMG_Load(_txPath.c_str());
_texture = SDL_CreateTextureFromSurface(_SDL_Renderer, loadSurface);
SDL_FreeSurface(loadSurface);
}
void UE::Texture::AddRect(SDL_Rect newRect)
{
_txRects.push_back(newRect);
_txRects.push_back(newRect);
}
+67 -67
View File
@@ -9,93 +9,93 @@
namespace UE
{
class Texture
{
public:
//-----------------------
//----- Constructor -----
//-----------------------
class Texture
{
public:
//-----------------------
//----- Constructor -----
//-----------------------
Texture(std::string dataPath, SDL_Renderer* renderer)
: _dataPath(dataPath), _SDL_Renderer(renderer)
{
InitTexture();
}
Texture(std::string dataPath, SDL_Renderer* renderer)
: _dataPath(dataPath), _SDL_Renderer(renderer)
{
InitTexture();
}
~Texture()
{
CleanTexture();
}
~Texture()
{
CleanTexture();
}
//-----------------------
//------- Methods -------
//-----------------------
//-----------------------
//------- Methods -------
//-----------------------
/**
* Retorna la textura.
*/
inline SDL_Texture* GetTexture() { return _texture; }
/**
* Retorna la textura.
*/
inline SDL_Texture* GetTexture() { return _texture; }
/**
* Retorna los Rects de la textura.
*/
inline std::vector<SDL_Rect>* GetRectsVector() { return &_txRects; }
/**
* Retorna los Rects de la textura.
*/
inline std::vector<SDL_Rect>* GetRectsVector() { return &_txRects; }
/**
* Retorna el Rect pedido. Comprobando que está disponible.
* Si no está disponible, devuelve el rect de index 0 (que debería ser el por defecto).
*
* @param i : Índice del rect.
* @return El SDL_Rect* solicitado (o el por defecto en caso de error).
*/
SDL_Rect* GetTextureRect(int i);
/**
* Retorna el Rect pedido. Comprobando que est� disponible.
* Si no est� disponible, devuelve el rect de index 0 (que deber�a ser el por defecto).
*
* @param i : �ndice del rect.
* @return El SDL_Rect* solicitado (o el por defecto en caso de error).
*/
SDL_Rect* GetTextureRect(int i);
private:
/**
* Carga los datos desde el archivo de datos y crea la textura y sus rects.
*/
void InitTexture();
private:
/**
* Carga los datos desde el archivo de datos y crea la textura y sus rects.
*/
void InitTexture();
/**
* Limpia todos los datos guardados.
*/
void CleanTexture();
/**
* Limpia todos los datos guardados.
*/
void CleanTexture();
/**
* Método encargado de generar la textura a partir de los valores de la clase.
*/
void CreateTexture();
/**
* M�todo encargado de generar la textura a partir de los valores de la clase.
*/
void CreateTexture();
/**
* Método que añade un SDL_Rect al vector correspondiente.
* @param newRect : Nuevo Rect que añadir al vector de Rects.
*/
void AddRect(SDL_Rect newRect);
/**
* M�todo que a�ade un SDL_Rect al vector correspondiente.
* @param newRect : Nuevo Rect que a�adir al vector de Rects.
*/
void AddRect(SDL_Rect newRect);
//-----------------------
//------ Variables ------
//-----------------------
//-----------------------
//------ Variables ------
//-----------------------
private:
//Ubicación del archivo de datos (.json).
std::string _dataPath = "";
private:
//Ubicaci�n del archivo de datos (.json).
std::string _dataPath = "";
//El propio renderer de SDL. Es necesario para crear y operar con las SDL_Textures.
SDL_Renderer* _SDL_Renderer = nullptr;
//El propio renderer de SDL. Es necesario para crear y operar con las SDL_Textures.
SDL_Renderer* _SDL_Renderer = nullptr;
//Ubicación de la textura (.png).
std::string _txPath = "";
//Ubicaci�n de la textura (.png).
std::string _txPath = "";
//La propia textura.
SDL_Texture* _texture = nullptr;
//Conjunto de rects que hay en la textura.
std::vector<SDL_Rect> _txRects = {};
//La propia textura.
SDL_Texture* _texture = nullptr;
//Conjunto de rects que hay en la textura.
std::vector<SDL_Rect> _txRects = {};
};
};
}
+19 -19
View File
@@ -9,45 +9,45 @@
void UE::Sprite::SetTextureRect(int textureID)
{
SDL_Rect* newRect = _texture->GetTextureRect(textureID);
SDL_Rect* newRect = _texture->GetTextureRect(textureID);
if (newRect != nullptr)
{
_actualTxRect = newRect;
}
if (newRect != nullptr)
{
_actualTxRect = newRect;
}
}
void UE::Sprite::SetActive(bool active)
{
isActive = active;
isActive = active;
}
bool UE::Sprite::IsActive()
{
return isActive;
return isActive;
}
void UE::Sprite::Draw(Renderer* renderer)
{
//Convertimos a ScreenCoords.
glm::ivec2 screenCoords = renderer->WorldToSreenCoords(_pos);
//Convertimos a ScreenCoords.
glm::ivec2 screenCoords = renderer->WorldToSreenCoords(_pos);
SDL_Rect position = { screenCoords.x, screenCoords.y, _size.x, _size.y };
SDL_Rect position = { screenCoords.x, screenCoords.y, _size.x, _size.y };
//destination.x = _pos.x;
//destination.y = _pos.y;
//
//destination.w = _size.x;
//destination.h = _size.y;
//destination.x = _pos.x;
//destination.y = _pos.y;
//
//destination.w = _size.x;
//destination.h = _size.y;
//std::cout << "Sprite Rendered to: " << destination.x << "-" << destination.y << std::endl;
renderer->QueueDrawCall(_renderLayer, position, _texture->GetTexture(), *_actualTxRect);
//std::cout << "Sprite Rendered to: " << destination.x << "-" << destination.y << std::endl;
renderer->QueueDrawCall(_renderLayer, position, _texture->GetTexture(), *_actualTxRect);
}
SDL_Rect UE::Sprite::getPositionRect()
{
SDL_Rect position = { _pos.x, _pos.y, _size.x, _size.y };
return position;
SDL_Rect position = { _pos.x, _pos.y, _size.x, _size.y };
return position;
}
+49 -49
View File
@@ -21,80 +21,80 @@
namespace UE
{
class Renderer;
class Renderer;
class Sprite : public Drawable, public Transformable
{
class Sprite : public Drawable, public Transformable
{
public:
public:
/*
// --------------
// Constructores.
// --------------
*/
/*
// --------------
// Constructores.
// --------------
*/
/*
Se establecen todos los par�metos.
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.
/*
Se establecen todos los par�metos.
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(UE::Texture* texture,
int textureRectID = 0,
int renderLayer = 1,
glm::vec2 position = glm::vec2(0, 0),
glm::vec2 size = glm::vec2(100, 100))
\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(UE::Texture* texture,
int textureRectID = 0,
int renderLayer = 1,
glm::vec2 position = glm::vec2(0, 0),
glm::vec2 size = glm::vec2(100, 100))
: _texture(texture)
{
SetTextureRect(textureRectID);
: _texture(texture)
{
SetTextureRect(textureRectID);
SetLayer(renderLayer);
SetLayer(renderLayer);
SetPosition(position);
SetSize(size);
}
SetPosition(position);
SetSize(size);
}
~Sprite() {}
~Sprite() {}
//-----------
//- Setters -
//-----------
//-----------
//- Setters -
//-----------
void SetTextureRect(int textureID);
void SetTextureRect(int textureID);
void SetActive(bool active);
bool IsActive();
void SetActive(bool active);
bool IsActive();
//Implementa el Draw de Drawable.
void Draw(Renderer* renderer) override;
//Implementa el Draw de Drawable.
void Draw(Renderer* renderer) override;
SDL_Rect getPositionRect();
SDL_Rect getPositionRect();
private:
private:
//Datos de la textura. Sirven para pedirla al AssetManager.
//Datos de la textura. Sirven para pedirla al AssetManager.
UE::Texture* _texture = nullptr;
UE::Texture* _texture = nullptr;
//El que se va a renderizar.
SDL_Rect* _actualTxRect = nullptr;
//El que se va a renderizar.
SDL_Rect* _actualTxRect = nullptr;
bool isActive = true;
bool isActive = true;
};
};
}
+47 -47
View File
@@ -5,28 +5,28 @@
void UE::TextBox::SetText(std::string newText)
{
_text = newText;
RenderTextTexture();
_text = newText;
RenderTextTexture();
}
void UE::TextBox::SetSize(int newSize)
{
_textSize = newSize;
RenderTextTexture();
_textSize = newSize;
RenderTextTexture();
}
void UE::TextBox::SetColor(UE_Color newColor)
{
_textColor = newColor;
RenderTextTexture();
_textColor = newColor;
RenderTextTexture();
}
void UE::TextBox::SetColor(int r, int g, int b, int a)
{
UE_Color c = UE_Color(r, g, b, a);
_textColor = c;
RenderTextTexture();
UE_Color c = UE_Color(r, g, b, a);
_textColor = c;
RenderTextTexture();
}
@@ -34,56 +34,56 @@ void UE::TextBox::SetColor(int r, int g, int b, int a)
void UE::TextBox::Draw(Renderer* renderer)
{
//Si a�n no tenemos renderer, lo guardamos y procesamos.
if (_sdlRenderer == nullptr)
{
_sdlRenderer = renderer->GetSDLRenderer();
RenderTextTexture();
}
if (_textTexture == nullptr)
{
UE_LOG_WARN("El texto: {0} ; No se est� renderizando. La textura no existe.", _text);
return;
}
//Si a�n no tenemos renderer, lo guardamos y procesamos.
if (_sdlRenderer == nullptr)
{
_sdlRenderer = renderer->GetSDLRenderer();
RenderTextTexture();
}
if (_textTexture == nullptr)
{
UE_LOG_WARN("El texto: {0} ; No se est� renderizando. La textura no existe.", _text);
return;
}
//Generamos el SDL_Rect destino.
SDL_Rect dest = { _pos.x, _pos.y, _size.x, _size.y };
//Generamos el SDL_Rect destino.
SDL_Rect dest = { _pos.x, _pos.y, _size.x, _size.y };
renderer->QueueDrawCall(_renderLayer, dest, _textTexture);
renderer->QueueDrawCall(_renderLayer, dest, _textTexture);
}
void UE::TextBox::RenderTextTexture()
{
//No podemos continuar hasta que no tengamos un renderer.
if (_sdlRenderer == nullptr) { return; }
//No podemos continuar hasta que no tengamos un renderer.
if (_sdlRenderer == nullptr) { return; }
SDL_DestroyTexture(_textTexture);
SDL_DestroyTexture(_textTexture);
//Creamos el SDL_Color a partir del vec4 que contiene el color.
SDL_Color color = { _textColor.x,_textColor.y, _textColor.z, _textColor.w };
//Creamos el SDL_Color a partir del vec4 que contiene el color.
SDL_Color color = { _textColor.x,_textColor.y, _textColor.z, _textColor.w };
//Tomamos la TTF_Font del tama�o que queremos de UE::Font.
TTF_Font* fn = _font->GetFont(_textSize);
//Tomamos la TTF_Font del tama�o que queremos de UE::Font.
TTF_Font* fn = _font->GetFont(_textSize);
SDL_Surface* loader = TTF_RenderText_Solid(fn, _text.c_str(), color);
if (loader == NULL)
{
UE_LOG_ERROR("No se ha podido crear el texto: {0} ; Error: {1}",
_text, TTF_GetError());
return;
}
SDL_Surface* loader = TTF_RenderText_Solid(fn, _text.c_str(), color);
if (loader == NULL)
{
UE_LOG_ERROR("No se ha podido crear el texto: {0} ; Error: {1}",
_text, TTF_GetError());
return;
}
_textTexture = SDL_CreateTextureFromSurface(_sdlRenderer, loader);
if (_textTexture == NULL)
{
UE_LOG_ERROR("No se ha podido crear la textura del texto: {0} ; Error: {1}",
_text, SDL_GetError());
return;
}
_size.x = loader->w;
_size.y = loader->h;
_textTexture = SDL_CreateTextureFromSurface(_sdlRenderer, loader);
if (_textTexture == NULL)
{
UE_LOG_ERROR("No se ha podido crear la textura del texto: {0} ; Error: {1}",
_text, SDL_GetError());
return;
}
_size.x = loader->w;
_size.y = loader->h;
SDL_FreeSurface(loader);
SDL_FreeSurface(loader);
}
+39 -39
View File
@@ -14,57 +14,57 @@
namespace UE
{
typedef glm::tvec4<int> UE_Color;
typedef glm::tvec4<int> UE_Color;
class TextBox : public Drawable, public Transformable
{
class TextBox : public Drawable, public Transformable
{
public:
public:
TextBox(UE::Font* font,
std::string text = "Texto por defecto",
int textSize = 18,
UE_Color textColor = UE_Color(0, 0, 0, 255),
int renderLayer = 1,
glm::vec2 position = glm::vec2(0, 0))
: _font(font), _text(text), _textSize(textSize)
{
SetColor(textColor);
TextBox(UE::Font* font,
std::string text = "Texto por defecto",
int textSize = 18,
UE_Color textColor = UE_Color(0, 0, 0, 255),
int renderLayer = 1,
glm::vec2 position = glm::vec2(0, 0))
: _font(font), _text(text), _textSize(textSize)
{
SetColor(textColor);
SetLayer(renderLayer);
SetPosition(position);
SetLayer(renderLayer);
SetPosition(position);
RenderTextTexture();
}
RenderTextTexture();
}
//Se generar� una textura y todo eso...
void SetText(std::string newText);
void SetSize(int newSize);
//Se generar� una textura y todo eso...
void SetText(std::string newText);
void SetSize(int newSize);
void SetColor(UE_Color newColor);
void SetColor(int r, int g, int b, int a);
void SetColor(UE_Color newColor);
void SetColor(int r, int g, int b, int a);
//Implementa el Draw de Drawable.
void Draw(Renderer* renderer) override;
//Implementa el Draw de Drawable.
void Draw(Renderer* renderer) override;
private:
void RenderTextTexture();
private:
void RenderTextTexture();
private:
UE::Font* _font = nullptr;
std::string _text = "Texto por defecto";
int _textSize = 18;
UE_Color _textColor;
private:
UE::Font* _font = nullptr;
std::string _text = "Texto por defecto";
int _textSize = 18;
UE_Color _textColor;
SDL_Texture* _textTexture = nullptr;
SDL_Texture* _textTexture = nullptr;
//Esto est� muy mal hecho, no deber�a de ser as�.
//Necesito un renderer para crear la textura del texto, pero no puedo conseguirlo con la arquitectura actual.
//No quiero regenerar la textura en cada frame de forma innecesaria...
//Por ello, me toca forzar un poco el sistema.
SDL_Renderer* _sdlRenderer = nullptr;
};
//Esto est� muy mal hecho, no deber�a de ser as�.
//Necesito un renderer para crear la textura del texto, pero no puedo conseguirlo con la arquitectura actual.
//No quiero regenerar la textura en cada frame de forma innecesaria...
//Por ello, me toca forzar un poco el sistema.
SDL_Renderer* _sdlRenderer = nullptr;
};
}
+152
View File
@@ -0,0 +1,152 @@
#include "Engine.h"
#include "Logging/Logger.h"
#include "Render/Renderer.h"
#include "Assets/AssetManager.h"
#include "Scene/SceneManager.h"
namespace UE
{
//Le decimos a C++ que son objetos static y que los cree cuando vea.
Renderer* Engine::_renderer;
AssetManager* Engine::_assetManager;
SceneManager* Engine::_sceneManager;
int Engine::Init()
{
//Lo primero, es iniciar el Logger, para poder imprimir errores.
UE::Logger::InitLogger();
//Etapa de carga de librerías.
if(InitLibs() < 0) //Retorna negativos en caso de error.
{
UE_LOG_CRITICAL("Engine - Error al inicial las librerías");
return -1;
}
//Iniciamos los sistemas del motor.
if(InitRenderer() < 0)
{
UE_LOG_CRITICAL("Engine - Error al iniciar el renderer.");
return -2;
}
if(InitAssetManager() < 0)
{
UE_LOG_CRITICAL("Engine - Error al inicial el AssetManager.");
return -3;
}
if(InitSceneManager() < 0)
{
UE_LOG_CRITICAL("Engine - Error al inicial el SceneManager.");
return -4;
}
UE_LOG_INFO("Engine - El motor se ha iniciado correctamente.");
return 0;
}
void Engine::Clean()
{
//Etapa para limpiar los sistemas del motor.
_sceneManager->CleanSceneManager();
delete _sceneManager;
_assetManager->CleanAssetManager();
delete _assetManager;
_renderer->CleanRenderer();
delete _renderer;
//Etapa para desactivar y limpiar todas las librerías.
QuitLibs();
}
int Engine::InitLibs()
{
//Iniciamos SDL.
SDL_HINT_RENDER_DRIVER "opengl";
Uint32 SDL_Flags = SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_EVENTS;
if (SDL_Init(SDL_Flags) < 0)
{
UE_LOG_CRITICAL("Engine - SDL: Error al iniciar SDL: {0}", SDL_GetError());
return -1;
}
UE_LOG_TRACE("Engine - SDL se ha iniciado correctamente");
//Iniciamos SDL_Image
if (IMG_Init(IMG_INIT_PNG) == 0) //Retorna 0 en caso de fallo.
{
UE_LOG_ERROR("Engine - SDL_Image: Error al iniciarse: {0}", IMG_GetError());
return -2;
}
UE_LOG_TRACE("Engine - SDL_Image se ha iniciado correctamente");
//Iniciamos el SDL_TTF
if (TTF_Init() < 0) //Retorna -1 en caso de error.
{
UE_LOG_ERROR("Engine - SDL_TTF: Error al inicarse: {0}", TTF_GetError());
return -3;
}
UE_LOG_TRACE("Engine - SDL_TTF se ha iniciado correctamente");
return 0;
}
int Engine::InitRenderer()
{
//Cargamos el Renderer.
//Hay que implementar un sistema de flags o
// una struct de configuración para la inicialización del renderer.
_renderer = new UE::Renderer(640, 480, 5);
if(_renderer->InitRenderer() < 0)
{
return -1;
}
UE_LOG_TRACE("Engine - Renderer: Se ha iniciado correctamente");
return 0;
}
int Engine::InitAssetManager()
{
//Cargamos el AssetManager
//Faltaría control de errores en caso de haberlo.
_assetManager = new UE::AssetManager(_renderer->GetSDLRenderer());
_assetManager->InitAssetManager();
UE_LOG_TRACE("Engine - AssetManager: Se ha iniciado correctamente");
return 0;
}
int Engine::InitSceneManager()
{
//Cargamos el SceneManager
//Faltaría control de errores en caso de haberlo.
_sceneManager = new UE::SceneManager();
UE_LOG_TRACE("Engine - SceneManager: Se ha iniciado correctamente.");
return 0;
}
int Engine::QuitLibs()
{
TTF_Quit();
IMG_Quit();
SDL_Quit();
return 0;
}
}
+80
View File
@@ -0,0 +1,80 @@
#pragma once
namespace UE
{
//Declaraciones de clases de UberEngine
class Renderer;
class AssetManager;
class SceneManager;
/* Clase Principal del motor.
* Carga todas los sistemas y librerías al inicio y los descarga al final.
* Contiene ptrs a los sistemas principales.
*/
class Engine
{
public:
/*
* Inicia todos los sistemas y librerías necesarias.
* Retornará 0 o un código de error negativo.
*/
static int Init();
/*
* Limpia todas las cosas del motor.
*/
static void Clean();
inline static UE::Renderer* GetRenderer() { return _renderer; }
inline static UE::AssetManager* GetAssetManager() { return _assetManager; }
inline static UE::SceneManager* GetSceneManager() { return _sceneManager; }
private:
//Vamos a crear un método para la inicialización de cada sistema.
// de esta forma, debería ser más fácil modificar la inicialización cuando sea necesario.
/*
* Inicializa las librerías de SDL.
* Retorna códigos de error negativos.
*/
static int InitLibs();
/*
* Inicializa el renderer.
* En un futuro, debería ser configurable, además de soportar distintos backends.
*/
static int InitRenderer();
/*
* Inicializa el AssetManager.
* Es necesario iniciar primero el Renderer para poder acceder al SDL_Renderer.
* (al menos, mientras usemos el SDL_Renderer.)
*/
static int InitAssetManager();
/*
* Inicializa el SceneManager.
*/
static int InitSceneManager();
/*
* Al igual que se inician, hay que limpiar las libs.
*/
static int QuitLibs();
/*
* Ptrs de los sistemas.
*/
static Renderer* _renderer;
static AssetManager* _assetManager;
static SceneManager* _sceneManager;
};
}
+10 -10
View File
@@ -5,18 +5,18 @@
namespace UE
{
std::shared_ptr<spdlog::logger> Logger::_engineLogger;
std::shared_ptr<spdlog::logger> Logger::_gameLogger;
std::shared_ptr<spdlog::logger> Logger::_engineLogger;
std::shared_ptr<spdlog::logger> Logger::_gameLogger;
void Logger::InitLogger()
{
spdlog::set_pattern("%^[%T]: %l - %n: %v %$");
void Logger::InitLogger()
{
spdlog::set_pattern("%^[%T]: %l - %n: %v %$");
_engineLogger = spdlog::stdout_color_mt("UberEngine");
_engineLogger->set_level(spdlog::level::trace);
_engineLogger = spdlog::stdout_color_mt("UberEngine");
_engineLogger->set_level(spdlog::level::trace);
_gameLogger = spdlog::stdout_color_mt("UberGame1");
_gameLogger->set_level(spdlog::level::trace);
_gameLogger = spdlog::stdout_color_mt("UberGame1");
_gameLogger->set_level(spdlog::level::trace);
}
}
}
+24 -24
View File
@@ -7,35 +7,35 @@
namespace UE
{
class Logger
{
public:
static void InitLogger();
class Logger
{
public:
static void InitLogger();
inline static std::shared_ptr<spdlog::logger>& GetGameLogger() { return _gameLogger; }
inline static std::shared_ptr<spdlog::logger>& GetEngineLogger() { return _engineLogger; }
inline static std::shared_ptr<spdlog::logger>& GetGameLogger() { return _gameLogger; }
inline static std::shared_ptr<spdlog::logger>& GetEngineLogger() { return _engineLogger; }
private:
static std::shared_ptr<spdlog::logger> _engineLogger;
static std::shared_ptr<spdlog::logger> _gameLogger;
private:
static std::shared_ptr<spdlog::logger> _engineLogger;
static std::shared_ptr<spdlog::logger> _gameLogger;
};
};
//Macros para el Logging. Es m�s c�modo que estar poniendo la l�nea entera cada vez...
#define UE_LOG_TRACE(...) ::UE::Logger::GetEngineLogger()->trace(__VA_ARGS__)
#define UE_LOG_DEBUG(...) ::UE::Logger::GetEngineLogger()->debug(__VA_ARGS__)
#define UE_LOG_INFO(...) ::UE::Logger::GetEngineLogger()->info(__VA_ARGS__)
#define UE_LOG_WARN(...) ::UE::Logger::GetEngineLogger()->warn(__VA_ARGS__)
#define UE_LOG_ERROR(...) ::UE::Logger::GetEngineLogger()->error(__VA_ARGS__)
#define UE_LOG_CRITICAL(...) ::UE::Logger::GetEngineLogger()->critical(__VA_ARGS__)
#define GAME_LOG_TRACE(...) ::UE::Logger::GetEngineLogger()->trace(__VA_ARGS__)
#define GAME_LOG_DEBUG(...) ::UE::Logger::GetEngineLogger()->debug(__VA_ARGS__)
#define GAME_LOG_INFO(...) ::UE::Logger::GetEngineLogger()->info(__VA_ARGS__)
#define GAME_LOG_WARN(...) ::UE::Logger::GetEngineLogger()->warn(__VA_ARGS__)
#define GAME_LOG_ERROR(...) ::UE::Logger::GetEngineLogger()->error(__VA_ARGS__)
#define GAME_LOG_CRITICAL(...) ::UE::Logger::GetEngineLogger()->critical(__VA_ARGS__)
//Macros para el Logging. Es más cómodo que estar poniendo la línea entera cada vez...
#define UE_LOG_TRACE(...) ::UE::Logger::GetEngineLogger()->trace(__VA_ARGS__)
#define UE_LOG_DEBUG(...) ::UE::Logger::GetEngineLogger()->debug(__VA_ARGS__)
#define UE_LOG_INFO(...) ::UE::Logger::GetEngineLogger()->info(__VA_ARGS__)
#define UE_LOG_WARN(...) ::UE::Logger::GetEngineLogger()->warn(__VA_ARGS__)
#define UE_LOG_ERROR(...) ::UE::Logger::GetEngineLogger()->error(__VA_ARGS__)
#define UE_LOG_CRITICAL(...) ::UE::Logger::GetEngineLogger()->critical(__VA_ARGS__)
#define GAME_LOG_TRACE(...) ::UE::Logger::GetEngineLogger()->trace(__VA_ARGS__)
#define GAME_LOG_DEBUG(...) ::UE::Logger::GetEngineLogger()->debug(__VA_ARGS__)
#define GAME_LOG_INFO(...) ::UE::Logger::GetEngineLogger()->info(__VA_ARGS__)
#define GAME_LOG_WARN(...) ::UE::Logger::GetEngineLogger()->warn(__VA_ARGS__)
#define GAME_LOG_ERROR(...) ::UE::Logger::GetEngineLogger()->error(__VA_ARGS__)
#define GAME_LOG_CRITICAL(...) ::UE::Logger::GetEngineLogger()->critical(__VA_ARGS__)
}
+16 -16
View File
@@ -2,26 +2,26 @@
namespace UE
{
class Renderer;
class Renderer;
class Drawable
{
class Drawable
{
public:
Drawable() {}
virtual ~Drawable() {};
public:
Drawable() {}
virtual ~Drawable() {};
//Get-Set del renderLayer.
inline void SetLayer(int newLayer) { _renderLayer = newLayer; }
inline int GetLayer() { return _renderLayer; }
//Get-Set del renderLayer.
inline void SetLayer(int newLayer) { _renderLayer = newLayer; }
inline int GetLayer() { return _renderLayer; }
public:
virtual void Draw(Renderer* renderer) = 0;
public:
virtual void Draw(Renderer* renderer) = 0;
protected:
//renderLayer usada en el renderer como "profundidad".
int _renderLayer = 0;
};
protected:
//renderLayer usada en el renderer como "profundidad".
int _renderLayer = 0;
};
}
+187 -198
View File
@@ -3,7 +3,7 @@
#include <ImGui/imgui.h>
#include <ImGui/imgui_impl_sdl.h>
#include <ImGui/imgui_impl_sdlrenderer.h>
//#include <ImGui\imgui_impl_opengl3.h>
//#include <ImGui/imgui_impl_opengl3.h>
#include <SDL_opengl.h>
@@ -13,257 +13,246 @@
namespace UE
{
//class Game;
int Renderer::InitRenderer()
{
//Configuramos los par�metros de la ventana de SDL.
Uint32 windowFlags = (SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE);
int Renderer::InitRenderer()
{
//Iniciamos SDL.
SDL_HINT_RENDER_DRIVER "opengl";
//Creamos la ventana de SDL.
_window = SDL_CreateWindow("UberGame1", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenSize.x, screenSize.y, windowFlags);
if (_window == NULL)
{
UE_LOG_CRITICAL("Renderer - CreateWindow: No se ha podido crear la ventana con OpenGL: {0}", SDL_GetError());
return -1;
}
Uint32 SDL_Flags = SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_EVENTS;
if (SDL_Init(SDL_Flags) < 0)
{
UE_LOG_CRITICAL("No se ha podido iniciar SDL, sufre mam�n: {0}", SDL_GetError());
return 1;
}
//Configuramos los par�metros de la ventana de SDL.
Uint32 windowFlags = (SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE);
//Creamos la ventana de SDL.
_window = SDL_CreateWindow("UberGame1", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenSize.x, screenSize.y, windowFlags);
if (_window == NULL)
{
UE_LOG_CRITICAL("No se ha podido crear la ventana de SDL con OpenGL y esas mierdas: {0}", SDL_GetError());
return 1;
}
//Creamos el Renderer de SDL.
main_Renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED);
if (main_Renderer == NULL)
{
UE_LOG_CRITICAL("No se ha podido crear el Renderer de SDL: {0}", SDL_GetError());
}
SDL_SetRenderDrawColor(main_Renderer, 0xFF, 0xFF, 0xFF, 0xFF);
//Creamos el Renderer de SDL.
main_Renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED);
if (main_Renderer == NULL)
{
UE_LOG_CRITICAL("Renderer - SDL_Renderer: No se ha podido crear el Renderer de SDL: {0}", SDL_GetError());
return -2;
}
SDL_SetRenderDrawColor(main_Renderer, 0xFF, 0xFF, 0xFF, 0xFF);
#pragma region ImGui.
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
(void)io; //Evita que de un Warning por variable no usada.
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
(void)io; //Evita que de un Warning por variable no usada.
ImGui::StyleColorsDark();
ImGui::StyleColorsDark();
ImGui_ImplSDL2_InitForSDLRenderer(_window, main_Renderer);
ImGui_ImplSDLRenderer_Init(main_Renderer);
ImGui_ImplSDL2_InitForSDLRenderer(_window, main_Renderer);
ImGui_ImplSDLRenderer_Init(main_Renderer);
#pragma endregion
//Init layers.
for (int i = 0; i < LAYER_AMOUNT; i++)
{
renderLayers.push_back(std::vector<DrawCall>());
}
}
//Init layers.
for (int i = 0; i <= LAYER_AMOUNT; i++)
{
renderLayers.push_back(std::vector<DrawCall>());
}
}
void Renderer::CleanRenderer()
{
renderQueue.empty();
void Renderer::CleanRenderer()
{
renderQueue.empty();
ImGui_ImplSDLRenderer_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
ImGui_ImplSDLRenderer_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
SDL_DestroyRenderer(main_Renderer);
SDL_DestroyWindow(_window);
}
SDL_DestroyRenderer(main_Renderer);
SDL_DestroyWindow(_window);
}
void Renderer::RenderFrame()
{
NewFrame();
RenderData();
EndFrame();
}
void Renderer::RenderFrame()
{
NewFrame();
RenderData();
EndFrame();
}
void Renderer::NewFrame()
{
SDL_RenderClear(main_Renderer);
void Renderer::NewFrame()
{
SDL_RenderClear(main_Renderer);
ImGui_ImplSDLRenderer_NewFrame();
ImGui_ImplSDL2_NewFrame();
ImGui::NewFrame();
ImGui_ImplSDLRenderer_NewFrame();
ImGui_ImplSDL2_NewFrame();
ImGui::NewFrame();
//Quiz�s deber�amos limpiar la cola y las Layers aqu� para eliminar residuos...
//callCounter = 0;
//rendererCounter = 0;
}
//Quiz�s deber�amos limpiar la cola y las Layers aqu� para eliminar residuos...
//callCounter = 0;
//rendererCounter = 0;
}
void Renderer::RenderData()
{
//Add items to their layer.
for (int i = 0; i < renderQueue.size(); i++)
{
DrawCall item = renderQueue.at(i);
void Renderer::RenderData()
{
//Add items to their layer.
for (int i = 0; i < renderQueue.size(); i++)
{
DrawCall item = renderQueue.at(i);
//Add item i to layer number i.layer.
if (item.layer > LAYER_AMOUNT)
{
UE_LOG_ERROR("Error rendering data: Can't render item to Layer {0} -> out of range\n", item.layer);
return;
}
renderLayers.at(item.layer).push_back(item);
}
renderQueue.clear();
//Add item i to layer number i.layer.
if (item.layer > LAYER_AMOUNT)
{
UE_LOG_ERROR("Error rendering data: Can't render item to Layer {0} -> out of range\n", item.layer);
return;
}
renderLayers.at(item.layer).push_back(item);
}
renderQueue.clear();
//Iterate layers.
for (int j = 0; j < renderLayers.size(); j++)
{
std::vector<DrawCall>& layer = renderLayers.at(j);
//Render items from layer j.
for (int k = 0; k < layer.size(); k++)
{
DrawCall item = layer.at(k);
if (item.fullTexture)
{
SDL_RenderCopy(main_Renderer, item.tx, NULL, &item.pos_rect);
continue;
}
SDL_RenderCopy(main_Renderer, item.tx, &item.tx_rect, &item.pos_rect);
}
layer.clear();
}
}
//Iterate layers.
for (int j = 0; j < renderLayers.size(); j++)
{
std::vector<DrawCall>& layer = renderLayers.at(j);
//Render items from layer j.
for (int k = 0; k < layer.size(); k++)
{
DrawCall item = layer.at(k);
if (item.fullTexture)
{
SDL_RenderCopy(main_Renderer, item.tx, NULL, &item.pos_rect);
continue;
}
SDL_RenderCopy(main_Renderer, item.tx, &item.tx_rect, &item.pos_rect);
}
layer.clear();
}
}
void Renderer::EndFrame()
{
//SDL_UpdateWindowSurface(window);
//SDL_RenderPresent(main_Renderer);
//SDL_RenderClear(main_Renderer);
ImGui::Render();
ImGui_ImplSDLRenderer_RenderDrawData(ImGui::GetDrawData());
void Renderer::EndFrame()
{
//SDL_UpdateWindowSurface(window);
//SDL_RenderPresent(main_Renderer);
//SDL_RenderClear(main_Renderer);
ImGui::Render();
ImGui_ImplSDLRenderer_RenderDrawData(ImGui::GetDrawData());
SDL_RenderPresent(main_Renderer);
SDL_RenderPresent(main_Renderer);
//UE_LOG_INFO("CallCounter: {0} ; Renderer: {1}", callCounter, rendererCounter);
}
//UE_LOG_INFO("CallCounter: {0} ; Renderer: {1}", callCounter, rendererCounter);
}
void Renderer::SetScreenSize(int newWidth, int newHeight)
{
screenSize.x = newWidth;
screenSize.y = newHeight;
SDL_SetWindowSize(_window, newWidth, newHeight);
glViewport(0, 0, newWidth, newHeight);
void Renderer::SetScreenSize(int newWidth, int newHeight)
{
screenSize.x = newWidth;
screenSize.y = newHeight;
SDL_SetWindowSize(_window, newWidth, newHeight);
glViewport(0, 0, newWidth, newHeight);
UE_LOG_TRACE("Screen size chaged to: {0}x{1}", newWidth, newHeight);
}
UE_LOG_TRACE("Screen size chaged to: {0}x{1}", newWidth, newHeight);
}
void Renderer::SetCamPosition(int posX, int posY)
{
camPosition.x = posX;
camPosition.y = posY;
//UE_LOG_TRACE("Cam position chaged to: {0}x{1}", posX, posY);
}
void Renderer::SetCamPosition(int posX, int posY)
{
camPosition.x = posX;
camPosition.y = posY;
//UE_LOG_TRACE("Cam position chaged to: {0}x{1}", posX, posY);
}
glm::ivec2 Renderer::WorldToSreenCoords(glm::ivec2 worldCoord)
{
//Convertimos las coordenas de WorldCoords a ScreenCoords relativas a la camPosition.
glm::ivec2 fPos = worldCoord - camPosition;
glm::ivec2 Renderer::WorldToSreenCoords(glm::ivec2 worldCoord)
{
//Convertimos las coordenas de WorldCoords a ScreenCoords relativas a la camPosition.
glm::ivec2 fPos = worldCoord - camPosition;
return fPos;
}
return fPos;
}
glm::ivec2 Renderer::ScreenToWorldCoords(glm::ivec2 screenCoord)
{
//Convertimos las coordenas de ScreenCoords a WorldCoords relativas a la camPosition.
glm::ivec2 fPos = screenCoord + camPosition;
glm::ivec2 Renderer::ScreenToWorldCoords(glm::ivec2 screenCoord)
{
//Convertimos las coordenas de ScreenCoords a WorldCoords relativas a la camPosition.
glm::ivec2 fPos = screenCoord + camPosition;
return fPos;
}
return fPos;
}
//CREO QUE ESTE M�TODO NO FUNCIONA.
//LAS COORDS QUE USAMOS EN LA COMPROBACI�N NO SON LAS ADECUADAS.
bool Renderer::IsObjectVisible(SDL_Rect* objectRect)
{
//CREO QUE ESTE M�TODO NO FUNCIONA.
//LAS COORDS QUE USAMOS EN LA COMPROBACI�N NO SON LAS ADECUADAS.
bool Renderer::IsObjectVisible(SDL_Rect* objectRect)
{
//Generamos un rect que representa la pantalla.
SDL_Rect screen{ camPosition.x, camPosition.y, screenSize.x, screenSize.y };
//Comprobamos si hay intersecci�n entre ambos.
if (!SDL_HasIntersection(&screen, objectRect))
{
//UE_LOG_TRACE("Se omite el renderizado de un objeto al estar fuera de la c�mara.");
return false;
}
return true;
}
//Generamos un rect que representa la pantalla.
SDL_Rect screen{ camPosition.x, camPosition.y, screenSize.x, screenSize.y };
//Comprobamos si hay intersecci�n entre ambos.
if (!SDL_HasIntersection(&screen, objectRect))
{
//UE_LOG_TRACE("Se omite el renderizado de un objeto al estar fuera de la c�mara.");
return false;
}
return true;
}
//�Deber�amos operar la posici�n para que tenga en cuenta la c�mara?
void Renderer::DrawObject(SDL_Rect* position, SDL_Rect* texture_pos, SDL_Texture* texture)
{
SDL_RenderCopy(main_Renderer, texture, texture_pos, position);
}
//�Deber�amos operar la posici�n para que tenga en cuenta la c�mara?
void Renderer::DrawObject(SDL_Rect* position, SDL_Rect* texture_pos, SDL_Texture* texture)
{
SDL_RenderCopy(main_Renderer, texture, texture_pos, position);
}
void Renderer::QueueDrawCall(DrawCall drawCall)
{
//callCounter++;
//Add item i to layer number i.layer.
if (drawCall.layer > LAYER_AMOUNT)
{
UE_LOG_ERROR("Can't add DrawCall to Layer {0} -> out of range\n", drawCall.layer);
return;
}
//Comprobamos si el objeto es visible.
//
//Generamos un rect que representa la pantalla.
SDL_Rect screen{ 0, 0, screenSize.x, screenSize.y };
//Comprobamos si hay intersecci�n entre ambos.
if (!SDL_HasIntersection(&screen, &drawCall.pos_rect))
{
//UE_LOG_TRACE("Se omite el renderizado de un objeto al estar fuera de la c�mara.");
return;
}
void Renderer::QueueDrawCall(DrawCall drawCall)
{
//callCounter++;
//Add item i to layer number i.layer.
if (drawCall.layer > LAYER_AMOUNT)
{
UE_LOG_ERROR("Can't add DrawCall to Layer {0} -> out of range\n", drawCall.layer);
return;
}
//Comprobamos si el objeto es visible.
//
//Generamos un rect que representa la pantalla.
SDL_Rect screen{ 0, 0, screenSize.x, screenSize.y };
//Comprobamos si hay intersecci�n entre ambos.
if (!SDL_HasIntersection(&screen, &drawCall.pos_rect))
{
//UE_LOG_TRACE("Se omite el renderizado de un objeto al estar fuera de la c�mara.");
return;
}
renderLayers.at(drawCall.layer).push_back(drawCall);
//rendererCounter++;
//renderQueue.push_back(drawCall);
}
renderLayers.at(drawCall.layer).push_back(drawCall);
//rendererCounter++;
//renderQueue.push_back(drawCall);
}
void Renderer::QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position)
{
DrawCall dc = DrawCall(layer, position, texture, texture_position);
QueueDrawCall(dc);
}
void Renderer::QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position)
{
DrawCall dc = DrawCall(layer, position, texture, texture_position);
QueueDrawCall(dc);
}
void Renderer::QueueDrawCall(int layer, SDL_Rect & position, SDL_Texture* texture)
{
//std::cout << "Drawable added to queue";
DrawCall dc = DrawCall(layer, position, texture);
QueueDrawCall(dc);
}
void Renderer::QueueDrawCall(int layer, SDL_Rect & position, SDL_Texture* texture)
{
//std::cout << "Drawable added to queue";
DrawCall dc = DrawCall(layer, position, texture);
QueueDrawCall(dc);
}
void Renderer::Render(Drawable& drawable)
{
drawable.Draw(this);
}
void Renderer::Render(Drawable& drawable)
{
drawable.Draw(this);
}
}
+107 -107
View File
@@ -19,155 +19,155 @@
namespace UE
{
struct DrawCall;
struct DrawCall;
class Renderer
{
class Renderer
{
public:
/* Constructor */
Renderer(int windowWidth,
int windowHeight,
int renderingLayers = 10)
public:
/* Constructor */
Renderer(int windowWidth,
int windowHeight,
int renderingLayers = 10)
: LAYER_AMOUNT(renderingLayers)
{
screenSize.x = windowWidth;
screenSize.y = windowHeight;
//UE_LOG_INFO("Game Renderer Created.");
}
: LAYER_AMOUNT(renderingLayers)
{
screenSize.x = windowWidth;
screenSize.y = windowHeight;
//UE_LOG_INFO("Game Renderer Created.");
}
/* Inicializa los componentes necesarios:
- Inicializa SDL
- Crea la ventana.
- Crea el renderer.
- ...
*/
int InitRenderer();
/* Inicializa los componentes necesarios:
- Inicializa SDL
- Crea la ventana.
- Crea el renderer.
- ...
*/
int InitRenderer();
/* Limpia todo antes de salir. */
void CleanRenderer();
/* Limpia todo antes de salir. */
void CleanRenderer();
//Hace el SDL_RenderClear() para limpiar el buffer al principio de un nuevo frame.
void NewFrame();
//Hace el SDL_RenderClear() para limpiar el buffer al principio de un nuevo frame.
void NewFrame();
//Ordena por layer todos los objetos de la renderQueue y los dibuja en orden.
//Se puede mover el proceso de ordenado a otra funci�n, con el objeto de ir vaciando la Queue.
void RenderData();
//Ordena por layer todos los objetos de la renderQueue y los dibuja en orden.
//Se puede mover el proceso de ordenado a otra funci�n, con el objeto de ir vaciando la Queue.
void RenderData();
//Hace el swap del render buffer (tras dibujar todos los objetos). Termina el renderizado.
void EndFrame();
//Hace el swap del render buffer (tras dibujar todos los objetos). Termina el renderizado.
void EndFrame();
//A�ade un DrawCall al renderQueue.
void QueueDrawCall(DrawCall drawCall);
void QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position);
void QueueDrawCall(int layer, SDL_Rect & position, SDL_Texture* texture);
//A�ade un DrawCall al renderQueue.
void QueueDrawCall(DrawCall drawCall);
void QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position);
void QueueDrawCall(int layer, SDL_Rect & position, SDL_Texture* texture);
//Le pasamos este renderer al Drawable para que haga lo que quiera.
//Como si quiere usar el SDL_Renderer, es libre.
void Render(Drawable& drawable);
//Le pasamos este renderer al Drawable para que haga lo que quiera.
//Como si quiere usar el SDL_Renderer, es libre.
void Render(Drawable& drawable);
/* Get SDL Renderer. */
SDL_Renderer* GetSDLRenderer() { return main_Renderer; }
/* Get SDL Renderer. */
SDL_Renderer* GetSDLRenderer() { return main_Renderer; }
inline glm::ivec2 GetScreenSize() { return screenSize; }
void SetScreenSize(int newWidth, int newHeight);
inline glm::ivec2 GetScreenSize() { return screenSize; }
void SetScreenSize(int newWidth, int newHeight);
inline glm::ivec2 GetCamPosition() { return camPosition; }
void SetCamPosition(int posX, int posY);
inline glm::ivec2 GetCamPosition() { return camPosition; }
void SetCamPosition(int posX, int posY);
/* M�todos para transformar las coordenadas entre Screen y Wolrd. */
//WorldCoords = ScreenPos + CamPos -> ScreenPos = WorldCoords - CamPos;
//Convierte coordenadas de mundo a la pantalla (en funci�n de la c�mara).
glm::ivec2 WorldToSreenCoords(glm::ivec2 worldCoord);
//Convierte coordenadas de la pantalla al mundo.
glm::ivec2 ScreenToWorldCoords(glm::ivec2 screenCoord);
/* M�todos para transformar las coordenadas entre Screen y Wolrd. */
//WorldCoords = ScreenPos + CamPos -> ScreenPos = WorldCoords - CamPos;
//Convierte coordenadas de mundo a la pantalla (en funci�n de la c�mara).
glm::ivec2 WorldToSreenCoords(glm::ivec2 worldCoord);
//Convierte coordenadas de la pantalla al mundo.
glm::ivec2 ScreenToWorldCoords(glm::ivec2 screenCoord);
//Comprueba si un objeto est� dentro del rect�ngulo de la c�mara.
//Usada para saber si un objeto se deber�a de renderizar o no.
bool IsObjectVisible(SDL_Rect* objectRect);
//Comprueba si un objeto est� dentro del rect�ngulo de la c�mara.
//Usada para saber si un objeto se deber�a de renderizar o no.
bool IsObjectVisible(SDL_Rect* objectRect);
//DEBUG
//Funci�n para renderizar un objeto un objeto en concreto directamente en el SDL_Renderer.
void DrawObject(SDL_Rect* position, SDL_Rect* texture_pos, SDL_Texture* texture);
//DEBUG
//Funci�n para renderizar un objeto un objeto en concreto directamente en el SDL_Renderer.
void DrawObject(SDL_Rect* position, SDL_Rect* texture_pos, SDL_Texture* texture);
private:
//Realizar RenderClear(), RenderDraw() y RenderUpdate();
//Es decir, todo lo necesario para renderizar un frame.
void RenderFrame();
private:
//Realizar RenderClear(), RenderDraw() y RenderUpdate();
//Es decir, todo lo necesario para renderizar un frame.
void RenderFrame();
private:
/* Objetos de SDL para el rendering. */
SDL_Window* _window = nullptr;
SDL_Surface* screenSurface = nullptr;
SDL_Renderer* main_Renderer = nullptr;
private:
/* Objetos de SDL para el rendering. */
SDL_Window* _window = nullptr;
SDL_Surface* screenSurface = nullptr;
SDL_Renderer* main_Renderer = nullptr;
//SDL_GLContext _glContext = nullptr;
//SDL_GLContext _glContext = nullptr;
//Almacena todas las "draw calls" para luego ordenar los objetos por layers y dibujarlos.
//Se podr�a sustituir por un std::queue o std::deque si fuera necesario.
std::vector<DrawCall> renderQueue;
//Las capas en las que se organizan los diferentes objetos.
//Permite dibujar unos sprites sobre otros.
const int LAYER_AMOUNT = 10;
std::vector<std::vector<DrawCall>> renderLayers;
//Almacena todas las "draw calls" para luego ordenar los objetos por layers y dibujarlos.
//Se podr�a sustituir por un std::queue o std::deque si fuera necesario.
std::vector<DrawCall> renderQueue;
//Las capas en las que se organizan los diferentes objetos.
//Permite dibujar unos sprites sobre otros.
const int LAYER_AMOUNT = 10;
std::vector<std::vector<DrawCall>> renderLayers;
//int screenWidth = 640;
//int screenHeight = 480;
//int screenWidth = 640;
//int screenHeight = 480;
glm::ivec2 screenSize{ 640,480 };
glm::ivec2 camPosition{ 0,0 };
glm::ivec2 screenSize{ 640,480 };
glm::ivec2 camPosition{ 0,0 };
//DEBUG
int callCounter = 0;
int rendererCounter = 0;
//DEBUG
int callCounter = 0;
int rendererCounter = 0;
};
};
/*
Contiene los valores necesarios para realizar el renderizado con SDL_RenderCopy();
Se almacena en la renderQueue y luego son ordenados por las renderLayers.
*/
struct DrawCall
{
DrawCall(int layer,
SDL_Rect position,
SDL_Texture* texture,
SDL_Rect texture_position)
/*
Contiene los valores necesarios para realizar el renderizado con SDL_RenderCopy();
Se almacena en la renderQueue y luego son ordenados por las renderLayers.
*/
struct DrawCall
{
DrawCall(int layer,
SDL_Rect position,
SDL_Texture* texture,
SDL_Rect texture_position)
: layer(layer), tx(texture), tx_rect(texture_position), pos_rect(position)
{}
: layer(layer), tx(texture), tx_rect(texture_position), pos_rect(position)
{}
DrawCall(int layer,
SDL_Rect position,
SDL_Texture* texture)
: layer(layer), tx(texture), pos_rect(position)
{
tx_rect = SDL_Rect();
fullTexture = true;
}
DrawCall(int layer,
SDL_Rect position,
SDL_Texture* texture)
: layer(layer), tx(texture), pos_rect(position)
{
tx_rect = SDL_Rect();
fullTexture = true;
}
int layer;
int layer;
bool fullTexture = false;
bool fullTexture = false;
SDL_Texture* tx;
SDL_Rect tx_rect;
SDL_Texture* tx;
SDL_Rect tx_rect;
SDL_Rect pos_rect;
};
SDL_Rect pos_rect;
};
}
+25 -25
View File
@@ -7,41 +7,41 @@
namespace UE
{
/*
Clase que contiene lo necesario para crear un objeto con posici�n en el espacio y modificarlo.
*/
class Transformable
{
public:
/*
Clase que contiene lo necesario para crear un objeto con posici�n en el espacio y modificarlo.
*/
class Transformable
{
public:
//-----------
//- Setters -
//-----------
//-----------
//- 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 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; }
//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 -
//-----------
//-----------
//- Getters -
//-----------
inline glm::vec2 GetPosition() { return _pos; }
inline glm::vec2 GetSize() { return _size; }
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;
};
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;
};
}
+15 -13
View File
@@ -1,23 +1,25 @@
#include "Scene.h"
#include "Logging/Logger.h"
#include <iostream>
namespace UE
{
void Scene::SceneInit()
{
//id = currentID++;
std::cout << "Scene has been init!" << std::endl;
}
void Scene::SceneInit()
{
UE_LOG_TRACE("Scene {0} has been init!", _sceneName);
}
void Scene::SceneClean()
{
std::cout << "Scene has been cleaned!" << std::endl;
if (loaded)
{
SceneUnload();
}
}
void Scene::SceneClean()
{
UE_LOG_TRACE("Scene {0} has been Cleaned!", _sceneName);
if (loaded)
{
SceneUnload();
}
}
}
+66 -35
View File
@@ -5,7 +5,6 @@
///
/// TODO:
/// - Scene debería ser serializable y cargable desde archivos, al menos para las clases derivadas. ( o quizás no....)
///
///
union SDL_Event;
@@ -13,49 +12,81 @@ union SDL_Event;
namespace UE
{
/*
Estructura básica de una escena. Almacena los datos mínimos.
Se utilizará como clase base para las clases Scene específicas.
Esta clase será heredada por las escenas del usuario.
*/
class Scene
{
public:
/*
Estructura básica de una escena.
Se utiliza como clase base para las clases Scene específicas del Game.
Esta clase será heredada por las escenas del usuario.
*/
class Scene
{
public:
Scene(std::string name)
: _sceneName(name)
{}
Scene(std::string name)
: _sceneName(name)
{
SceneInit();
}
/* Funciones "internas" de la clase para inicialización y cierre. */
void SceneInit(); //Te calienta y prepara la casa al llegar.
void SceneClean(); //Te deja todo limpio y reluciente al salir.
~Scene()
{
SceneClean();
}
/* Funciones que habrán de sobrecargar las escenas del usuario. */
virtual void SceneLoad() { std::cout << "EMPTY SCENE CREATED" << std::endl; }
virtual void SceneRender() {}
virtual void SceneUpdate() {}
virtual void SceneHandleEvents(SDL_Event* event) {}
virtual void SceneUnload() { std::cout << "EMPTY SCENE DESCARGADA" << std::endl; }
/* Funciones "internas" de la clase para inicialización y cierre. */
void SceneInit(); //Te calienta y prepara la casa al llegar.
void SceneClean(); //Te deja todo limpio y reluciente al salir.
// ¿Esto sirve para algo?
//void loadDataFromFile(std::string path);
/*
Métodos de los estados de la escena.
Habrán de ser sobrecargardos por las escenas del usuario.
*/
//Se crean todos los objetos y se carga todo lo necesario para la escena.
virtual void SceneLoad() = 0;
/*
* Render de los objetos de la escena.
* Se ejecuta en cada frame.
*/
virtual void SceneRender() = 0;
/*
* Update para los objetos de la escena.
* Utilizado para las físicas y otros componentes similares.
* Se ejecuta en cada frame.
*/
virtual void SceneUpdate() = 0;
/*
* Gestor de eventos para la escena.
* Utilizado para capturar los eventos que necesita la escena.
*/
virtual void SceneHandleEvents(SDL_Event* event) = 0;
/*
* Descarga y limpia todos los elementos de la escena.
* Utilizado también para guardado o lo que sea conveniente.
*/
virtual void SceneUnload() = 0;
//Obtener el nombre de la escena.
inline std::string GetName() { return _sceneName; }
/*
* Permite comprobar si la escena está cargada o no.
* TODO: Útil si queremos hacer carga asincrona o similar. Al menos para assets o algo.
*/
inline bool IsLoaded() { return loaded; }
inline std::string GetName() { return _sceneName; }
protected:
inline bool IsLoaded() { return loaded; }
//Nombre de la escena. Para identificarla en el SceneManager.
std::string _sceneName = "NullScene";
bool loaded = false;
protected:
//Almacena el ID actual, permitiendo generar un ID nuevo para cada Scene que se instancie.
//static uint16_t currentID;
std::string _sceneName;
//std::vector<Entity> _entidades;
bool loaded = false;
};
};
}
-18
View File
@@ -1,18 +0,0 @@
#pragma once
namespace UE
{
class Scene;
/*
Será sobrecargado por el juego, de tal forma que cuando se le pida crear una escena, sepa qué objeto crear.
*/
class SceneBuilder
{
public:
virtual inline Scene* InstanciateScene(int sceneID) { return nullptr; }
};
}
+121 -79
View File
@@ -1,8 +1,5 @@
#include "SceneManager.h"
#include "Scene.h"
#include "SceneBuilder.h"
#include "Logging/Logger.h"
#include <iostream>
@@ -10,91 +7,136 @@
namespace UE
{
void SceneManager::InitSceneManager(SceneBuilder* sceneBuilder)
{
_sceneBuilder = sceneBuilder;
void SceneManager::InitSceneManager()
{
UE_LOG_INFO("Se ha inicializado el SceneManager.");
}
UE_LOG_INFO("Se ha inicializado el SceneManager.");
}
void SceneManager::CleanSceneManager()
{
for (auto& it : _loadedScenes)
{
Scene* sc = it.second;
sc->SceneClean();
delete sc;
}
void SceneManager::CleanSceneManager()
{
if (_currentScene != nullptr)
{
_currentScene->SceneUnload();
delete _currentScene;
}
_loadedScenes.clear();
//for (auto& it : _scenes)
//{
// Scene* sc = it.second;
// sc->SceneClean();
// delete sc;
//}
if (_currentScene != nullptr)
{
_currentScene = nullptr;
}
//_scenes.clear();
UE_LOG_INFO("El ScenenManager se ha descargado correctamente.");
}
void SceneManager::LoadScene(Scene* sceneToLoad)
{
std::string name = sceneToLoad->GetName();
//Comprobamos si la escena ya está cargada en la lista.
if(IsSceneLoaded(name))
{
//Si lo está, la descargamos para volverla a cargar.
//En caso de no estar activa, claro está.
UnloadScene(name);
}
//Cargamos la escena en cuestión.
sceneToLoad->SceneLoad();
//Añadimos la escena a la lista de escenas cargadas.
_loadedScenes.insert(std::make_pair(name, sceneToLoad));
}
void SceneManager::LoadAndSwitchScene(Scene* sceneToLoad)
{
LoadScene(sceneToLoad);
SwitchScene(sceneToLoad->GetName());
}
void SceneManager::SwitchScene(std::string name)
{
//Comprobamos si existe la escena indicada.
if(!IsSceneLoaded(name))
{
UE_LOG_WARN("SceneManager: Scene {0}, No se puede cambiar de escena. No está cargada.", name);
return;
}
//Cambiamos la escena actual por la indicada.
_currentScene = _loadedScenes.at(name);
}
void SceneManager::SwitchAndUnloadScene(std::string name)
{
//Comprobamos si existe la escena indicada.
if(!IsSceneLoaded(name))
{
UE_LOG_WARN("SceneManager: Scene {0}, No se puede cambiar de escena. No está cargada.", name);
return;
}
//Descargamos la escena anterior en caso de haberla.
if(_currentScene != nullptr && IsSceneLoaded(_currentScene->GetName()))
{
_currentScene->SceneUnload();
}
//Cambiamos la escena activa por la nueva.
_currentScene = _loadedScenes.at(name);
}
void SceneManager::UnloadScene(std::string name)
{
//Comprobamos si existe la escena indicada.
if(!IsSceneLoaded(name))
{
UE_LOG_WARN("SceneManager: Scene {0}, no se puede descargar. No está cargada.", name);
return;
}
//Comprobamos si se trata de la escena actual.
if(GetCurrentSceneName() == name)
{
//No hacemos nada, no se puede recargar la escena actual así como así.
UE_LOG_WARN("SceneManager: Scene {0}, no se puede descargar. Es la escena actual.", name);
return;
}
//Si todo está correcto.
//Si tenemos campo libre, pista libre, punto rojo.
//Descargamos.
_loadedScenes.at(name)->SceneUnload();
_loadedScenes.erase(name);
}
}
bool SceneManager::IsSceneLoaded(std::string name)
{
//Comprobamos si existe la escena indicada.
if(_loadedScenes.find(name) != _loadedScenes.end())
{
//Si la encontramos, existe.
return true;
}
return false;
}
std::string SceneManager::GetCurrentSceneName()
{
return _currentScene->GetName();
}
//void SceneManager::AddScene(Scene* sceneToAdd)
//{
// _scenes.insert(std::make_pair(sceneToAdd->GetName(), sceneToAdd));
// sceneToAdd->SceneInit();
Scene* SceneManager::GetCurrentScenePtr()
{
return _currentScene;
}
// UE_LOG_INFO("Se ha a�adido la escena {0} al SceneManager.", sceneToAdd->GetName());
//}
//Scene* SceneManager::GetScenePtr(std::string sceneName)
//{
// if (_scenes.find(sceneName) == _scenes.end())
// {
// UE_LOG_ERROR("No se ha encontrado la escena indicada.");
// return nullptr;
// }
// return _scenes.at(sceneName);
//}
std::string SceneManager::GetActiveSceneName()
{
return _currentScene->GetName();
}
//void SceneManager::LoadScene(std::string sceneName)
//{
// if (_currentScene != nullptr)
// {
// _currentScene->SceneUnload();
// delete _currentScene;
// }
// _currentScene = _scenes.at(sceneName);
// _currentScene->SceneLoad();
//}
void SceneManager::NewLoadScene(int sceneID)
{
if (_currentScene != nullptr)
{
_currentScene->SceneUnload();
delete _currentScene;
}
_currentScene = _sceneBuilder->InstanciateScene(sceneID);
_currentScene->SceneLoad();
}
void SceneManager::UpdateScene()
{
_currentScene->SceneUpdate();
}
void SceneManager::UpdateScene()
{
_currentScene->SceneUpdate();
}
}
+88 -49
View File
@@ -1,72 +1,111 @@
#pragma once
#include "Scene/Scene.h"
#include <string>
#include <vector>
#include <unordered_map>
//
// Habría que implemetar un sistema para cambiar de escena.
// La cuestión sería almecenar el ID actual o algo así.
// Las escenas que no están cargadas se pueden mantener construidas en el vector, pues el espacio que ocupan en memoria debería ser mínimo.
// Cuando cargas una escena, se descarga la anterior mediante Scene.unload y se carga la nueva con Scene.Load. De esta forma,
// si cada escena gestiona bien sus recursos en la carga y descarga, no debería generar ningún problema y no ocupar espacio cuando esté descargada.
// Quizás se puede añadir una opción para mantener cargada una escena o algo.
//
// Quizás es innecesaria la ID interna de la escena....
//
//
// TODO:
// - Se podría plantear un sistema de carga asincrona para las escenas.
// - La variable "loaded" de las escenas no tiene mucha utilidad en este momento.
namespace UE
{
class Scene;
class SceneBuilder;
/* Gestiona todas escenas. Las carga, descargar y ejecuta. */
class SceneManager
{
/* Gestiona todas escenas. Las carga, descargar y ejecuta. */
class SceneManager
{
public:
/* Constructor */
SceneManager() {}
public:
void InitSceneManager(SceneBuilder* sceneBuilder);
void CleanSceneManager();
/* Constructor */
SceneManager()
{
InitSceneManager();
}
//Añade una escena a la lista y retorna su ID. Son Ptrs, por lo que poco importa donde los almacenamos.
//void AddScene(Scene* sceneToAdd);
~SceneManager()
{
CleanSceneManager();
}
//Inicializa el ScenenManager (En caso de haber algo que iniciar.)
void InitSceneManager();
//Limpia los contenedores de Scenes y descarga las escenas cargadas.
void CleanSceneManager();
//Devuelve un ptr a la escena del ID especificado.
//Scene* GetScenePtr(std::string sceneName);
std::string GetActiveSceneName();
/*
* Carga una nueva escena.
* Se almacena en la lista de escenas cargadas.
* Para cambiar de escena, usar SwitchScene();
* Si la escena ya estuvise cargada, se descargará la anterior y se cargará la nueva.
*/
void LoadScene(Scene* sceneToLoad);
//Devuelve la escena activa.
inline Scene* GetActiveScenePtr() { return _currentScene; }
/*
* Cambia la escena activa por la indicada.
* Si la indicada no está cargada, no hace nada.
*/
void SwitchScene(std::string name);
//Descarga la escena activa y carga la escena indicada.
//void LoadScene(std::string sceneName);
/*
* Carga la escena indicada.
* Cambia la escena actual por la nueva escena.
*/
void LoadAndSwitchScene(Scene* sceneToLoad);
//Descarga la escena activa y carga la escena indicada. Para ello llama al builder que tiene y este le devuelve un ptr a la nueva escena.
void NewLoadScene(int sceneID);
//Pasa el Update a la escena actual.
//¿Necesita hacer algo más?
void UpdateScene();
// ¿Esto sirve para algo?
//void LoadSceneDataFromFile(std::string filePath);
/*
* Cambia la escena activa por la indicada.
* Descarga completamente la escena activa anterior.
* Si la escena indicada no está cargarda, no hace nada.
* Si no hay una escena activa, no la descarga.
*/
void SwitchAndUnloadScene(std::string name);
private:
Scene* _currentScene = nullptr;
/*
* Descarga la escena con el nombre indicado.
* Si la escena no está en la lista, no hace nada.
*/
void UnloadScene(std::string name);
SceneBuilder* _sceneBuilder = nullptr;
//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::unordered_map<std::string, Scene*> _scenes;
//std::vector<Scene*> _scenes;
/*
* Comprueba si la escena indicada está en la lista de escenas cargadas.
* Retorna true si está cargada, false si no.
*/
bool IsSceneLoaded(std::string name);
};
/*
* Devuelve el nombre de la escena activa.
*/
std::string GetCurrentSceneName();
/*
* Devuelve el ptr de la escena activa.
*/
Scene* GetCurrentScenePtr();
/*
* Update para la escena activa.
* Se ha de llamar en cada frame para pasar el update a la escena activa.
* TODO: No se usa... O añadimos para las otras fases o quitamos esta.
*/
void UpdateScene();
private:
//Ptr a la escena que está activa en ese momento.
Scene* _currentScene = nullptr;
//Almacenamos un ptr a todas las escenas cargadas en ese momento.
//o, al menos, lo intentamos.
std::unordered_map<std::string, Scene*> _loadedScenes;
};
}
+19 -19
View File
@@ -8,36 +8,36 @@ uint32_t UE::Time::_startTime;
void UE::Time::StartFrame()
{
_startTime = SDL_GetTicks();
_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;
// 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;
//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);
}
//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.
//Calculamos el deltaTime, que s� ser� el tiempo real que ha pasado, pues hemos esperado.
frameTime = SDL_GetTicks() - _startTime;
frameTime = SDL_GetTicks() - _startTime;
//Convertimos deltaTime a segundos pues es lo usado en los cálculos.
deltaTime = frameTime / 1000.0f;
//Convertimos deltaTime a segundos pues es lo usado en los c�lculos.
deltaTime = frameTime / 1000.0f;
//++countedFrames;
//++countedFrames;
}
+22 -22
View File
@@ -2,42 +2,42 @@
#include <cstdint>
/*
TODO:
- Buscar una mejor forma de calcular la media de FPS.
TODO:
- Buscar una mejor forma de calcular la media de FPS.
*/
namespace UE
{
class Time
{
public:
class Time
{
public:
//-------------------
//---- Métodos ------
//-------------------
static void StartFrame();
//-------------------
//---- Métodos ------
//-------------------
static void StartFrame();
static void EndFrame();
static void EndFrame();
//-------------------
//---- Variables ----
//-------------------
static double deltaTime;
//-------------------
//---- Variables ----
//-------------------
static double deltaTime;
private:
static uint32_t _startTime;
//uint16_t countedFrames = 0;
float _avgFPS;
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;
};
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;
};
}
-48
View File
@@ -1,48 +0,0 @@
#pragma once
#include "Scene/SceneBuilder.h"
#include "Scene/Scene.h"
#include "Scenes/MainScene.hpp"
#include "Scenes/TestScene2.hpp"
//#include "Logging\Logger.h"
enum LasEscenas
{
mainMenu = 0, nivel1
};
class GameScenes : public UE::SceneBuilder
{
public:
GameScenes()
{
}
UE::Scene* InstanciateScene(int sceneID) override
{
switch (sceneID)
{
case LasEscenas::mainMenu:
{
UE::Scene* sc = new MainScene("Main");
return sc;
break;
}
case LasEscenas::nivel1:
{
UE::Scene* sc = new TestScene2("Test2");
return sc;
break;
}
default:
return nullptr;
break;
}
}
};
+42 -32
View File
@@ -6,9 +6,8 @@
#include <ImGui/imgui_impl_sdl.h>
#include <ImGui/imgui_impl_opengl3.h>
#include "UberGame1.h"
#include "GameScenes.hpp"
#include "Engine.h"
#include "UberEngine.h"
@@ -17,7 +16,7 @@
static bool _quit = false;
void Init();
int Init();
void Load();
void Loop();
void Clean();
@@ -25,7 +24,9 @@ void Clean();
int main(int argc, char* args[])
{
Init();
//Si falla la inicialización, terminamos el juego.
if(Init() < 0) { return -1; }
Load();
Loop();
Clean();
@@ -33,25 +34,28 @@ int main(int argc, char* args[])
return 0;
}
void Init()
int Init()
{
UE::Logger::InitLogger();
Game::InitGame();
if(UE::Engine::Init() < 0)
{
GAME_LOG_CRITICAL("No se ha podido cargar el motor.");
return -1;
}
return 0;
}
void Load()
{
Game::GetAssetManager()->LoadAssetsFromFile("resources/AssetList/MainAssets.json");
Game::GetAssetManager()->ProcessAssetQueue();
UE::Engine::GetAssetManager()->LoadAssetsFromFile("resources/AssetList/MainAssets.json");
UE::Engine::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.
//Game::GetSceneManager()->LoadScene("Main");
Game::GetSceneManager()->NewLoadScene(LasEscenas::mainMenu);
UE::Engine::GetSceneManager()->LoadScene(new MainScene());
UE::Engine::GetSceneManager()->SwitchScene("MainScene");
}
@@ -83,10 +87,17 @@ void Loop()
#pragma endregion
//Almacenamos el renderer para ya tenerlo por aquí.
UE::Renderer* UE_Renderer = UE::Engine::GetRenderer();
while (!_quit)
{
UE::Time::StartFrame();
//Almacenamos la escena actual.
UE::Scene* currentScene = UE::Engine::GetSceneManager()->GetCurrentScenePtr();
//TEMP Event Handler:
SDL_Event eventHandler;
while (SDL_PollEvent(&eventHandler) != 0)
@@ -98,7 +109,7 @@ void Loop()
if (io.WantCaptureMouse) { continue; }
Game::GetSceneManager()->GetActiveScenePtr()->SceneHandleEvents(&eventHandler);
currentScene->SceneHandleEvents(&eventHandler);
if (eventHandler.type == SDL_QUIT)
{
_quit = true;
@@ -106,17 +117,17 @@ void Loop()
if (eventHandler.type == SDL_WINDOWEVENT && eventHandler.window.event == SDL_WINDOWEVENT_RESIZED)
{
//GAME_LOG_CRITICAL("Window Size chaged {0}x{1}", eventHandler.window.data1, eventHandler.window.data2);
Game::GetRenderer()->SetScreenSize(eventHandler.window.data1, eventHandler.window.data2);
UE_Renderer->SetScreenSize(eventHandler.window.data1, eventHandler.window.data2);
}
if (eventHandler.type == SDL_KEYDOWN)
{
switch (eventHandler.key.keysym.sym)
{
case SDLK_1:
Game::GetSceneManager()->NewLoadScene(LasEscenas::mainMenu);
UE::Engine::GetSceneManager()->LoadAndSwitchScene(new MainScene());
break;
case SDLK_2:
Game::GetSceneManager()->NewLoadScene(LasEscenas::nivel1);
UE::Engine::GetSceneManager()->LoadAndSwitchScene(new TestScene2());
break;
default:
break;
@@ -134,32 +145,33 @@ void Loop()
GAME_LOG_TRACE("FPS: NULL / dT: {1}", UE::Time::deltaTime);
}
if (keyStates[SDL_SCANCODE_W])
{
glm::ivec2 camPos = Game::GetRenderer()->GetCamPosition();
glm::ivec2 camPos = UE_Renderer->GetCamPosition();
camPos.y -= 5;
Game::GetRenderer()->SetCamPosition(camPos.x, camPos.y);
UE_Renderer->SetCamPosition(camPos.x, camPos.y);
}
if (keyStates[SDL_SCANCODE_S])
{
glm::ivec2 camPos = Game::GetRenderer()->GetCamPosition();
glm::ivec2 camPos = UE_Renderer->GetCamPosition();
camPos.y += 5;
Game::GetRenderer()->SetCamPosition(camPos.x, camPos.y);
UE_Renderer->SetCamPosition(camPos.x, camPos.y);
}
if (keyStates[SDL_SCANCODE_D])
{
glm::ivec2 camPos = Game::GetRenderer()->GetCamPosition();
glm::ivec2 camPos = UE_Renderer->GetCamPosition();
camPos.x += 5;
Game::GetRenderer()->SetCamPosition(camPos.x, camPos.y);
UE_Renderer->SetCamPosition(camPos.x, camPos.y);
}
if (keyStates[SDL_SCANCODE_A])
{
glm::ivec2 camPos = Game::GetRenderer()->GetCamPosition();
glm::ivec2 camPos = UE_Renderer->GetCamPosition();
camPos.x -= 5;
Game::GetRenderer()->SetCamPosition(camPos.x, camPos.y);
UE_Renderer->SetCamPosition(camPos.x, camPos.y);
}
Game::GetSceneManager()->GetActiveScenePtr()->SceneUpdate();
currentScene->SceneUpdate();
//Game::GetRenderer()->QueueDrawCall(4, DestR2, test1);
//Game::GetRenderer()->QueueDrawCall(1, DestR, background);
@@ -170,20 +182,20 @@ void Loop()
//
//Iniciamos un nuevo Frame.
Game::GetRenderer()->NewFrame();
UE_Renderer->NewFrame();
//Renderiza la escena.
Game::GetSceneManager()->GetActiveScenePtr()->SceneRender();
currentScene->SceneRender();
//As� podemos renderizar cosas de ImGui cuando estemos entre NewFrame y EndFrame.
bool show = true;
ImGui::ShowDemoWindow(&show);
//Dibuja las cosas del Renderer.
Game::GetRenderer()->RenderData();
UE_Renderer->RenderData();
//Terminamos el Frame.
Game::GetRenderer()->EndFrame();
UE_Renderer->EndFrame();
UE::Time::EndFrame();
@@ -194,7 +206,5 @@ void Loop()
void Clean()
{
Game::CleanGame();
SDL_Quit();
UE::Engine::Clean();
}
+10 -7
View File
@@ -23,21 +23,24 @@ class MainScene : public UE::Scene
{
public:
MainScene(std::string sceneName) : Scene(sceneName) {}
MainScene() : Scene("MainScene")
{
//_sceneName = "MainScene";
}
void SceneLoad() override
{
UE_LOG_INFO("Escena {0} ha sido cargada", _sceneName);
UE::AssetManager* as = Game::GetAssetManager();
UE::AssetManager* as = UE::Engine::GetAssetManager();
UE::Texture* test1Texture = as->getTexture("test1");
UE::Sprite sp1(test1Texture, 0, 2, glm::vec2(55, 60), glm::vec2(100, 100));
UE::Sprite sp2(test1Texture, 0, 1, glm::vec2(50, 45), glm::vec2(145, 145));
UE::Sprite bg(as->getTexture("bg1"), 1, 0, glm::vec2(0, 0), Game::GetRenderer()->GetScreenSize());
UE::Sprite bg(as->getTexture("bg1"), 1, 0, glm::vec2(0, 0), UE::Engine::GetRenderer()->GetScreenSize());
UE::Sprite mapSP(as->getTexture("PruebaMap"), 0, 2, glm::vec2(50, 45), glm::vec2(145, 145));
@@ -62,9 +65,9 @@ public:
//UE_LOG_INFO("Escena {0} UPDATE", _sceneName);
UE::Renderer* renderer;
renderer = Game::GetRenderer();
renderer = UE::Engine::GetRenderer();
glm::vec2 screenSize = Game::GetRenderer()->GetScreenSize();
glm::vec2 screenSize = UE::Engine::GetRenderer()->GetScreenSize();
UE::Sprite& sp1 = sprites.at(0);
glm::vec2 pos = sp1.GetPosition();
@@ -78,7 +81,7 @@ public:
void SceneRender() override
{
UE::Renderer* renderer;
renderer = Game::GetRenderer();
renderer = UE::Engine::GetRenderer();
for (UE::Sprite& sp : sprites)
{
@@ -236,7 +239,7 @@ private:
void AssetMngGUI()
{
UE::AssetManager* asmng = Game::GetAssetManager();
UE::AssetManager* asmng = UE::Engine::GetAssetManager();
ImGui::Begin("Asset Manager Inspector", &assetMngGUI);
+7 -4
View File
@@ -18,7 +18,10 @@ class TestScene2 : public UE::Scene
{
public:
TestScene2(std::string sceneName) : Scene(sceneName) {}
TestScene2() : Scene("TestScene")
{
//_sceneName = "TestScene";
}
void SceneLoad() override
{
@@ -26,7 +29,7 @@ public:
srand(255);
UE::AssetManager* as = Game::GetAssetManager();
UE::AssetManager* as = UE::Engine::GetAssetManager();
UE::Texture* tx = as->getTexture("PruebaMap");
@@ -55,7 +58,7 @@ public:
void SceneRender() override
{
UE::Renderer* renderer;
renderer = Game::GetRenderer();
renderer = UE::Engine::GetRenderer();
for (UE::Sprite& sp : sprites)
{
@@ -85,7 +88,7 @@ public:
}
if (event->type == SDL_MOUSEBUTTONDOWN)
{
UE::Renderer* rend = Game::GetRenderer();
UE::Renderer* rend = UE::Engine::GetRenderer();
glm::ivec2 mPos(event->button.x, event->button.y);
glm::ivec2 wPos = rend->ScreenToWorldCoords(mPos);
GAME_LOG_TRACE("Posicion del raton: \n\tPantalla: {0}x{1}, Mundo: {2}x{3}: ", mPos.x, mPos.y, wPos.x, wPos.y);
-49
View File
@@ -1,49 +0,0 @@
#include "UberGame1.h"
#include "Logging/Logger.h"
#include "Render/Renderer.h"
#include "Assets/AssetManager.h"
#include "Scene/SceneManager.h"
#include "Scene/SceneBuilder.h"
#include "GameScenes.hpp"
//Sobrecarga de SceneBuilder que devuelve las escenas correctas para este juego.
//#include "GameScenes.hpp"
UE::Renderer* Game::mainRenderer;
UE::AssetManager* Game::asManager;
UE::SceneManager* Game::scManager;
GameScenes Game::_sceneBuilder;
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.");
//Creamos el SceneBuilder de este juego.
_sceneBuilder = GameScenes();
scManager = new UE::SceneManager();
scManager->InitSceneManager(&_sceneBuilder);
}
void Game::CleanGame()
{
asManager->CleanAssetManager();
delete asManager;
mainRenderer->CleanRenderer();
delete mainRenderer;
scManager->CleanSceneManager();
delete scManager;
}
-30
View File
@@ -1,30 +0,0 @@
#pragma once
namespace UE
{
class Renderer;
class AssetManager;
class SceneManager;
class SceneBuilder;
}
class GameScenes;
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;
static GameScenes _sceneBuilder;
};