Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08f566fda6 | ||
|
|
724807e9f2 | ||
|
|
f2bf82e370 | ||
|
|
6b87711424 | ||
|
|
a0889e78f1 | ||
|
|
4ee1ccb47a |
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
call premake\premake5.exe vs2019
|
call premake\premake5.exe vs2022
|
||||||
PAUSE
|
PAUSE
|
||||||
@@ -15,6 +15,7 @@ namespace UE
|
|||||||
UE_LOG_INFO("AssetManager Iniciado con éxito.");
|
UE_LOG_INFO("AssetManager Iniciado con éxito.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::CleanAssetManager()
|
void AssetManager::CleanAssetManager()
|
||||||
{
|
{
|
||||||
//Destruye todas las texturas de SDL.
|
//Destruye todas las texturas de SDL.
|
||||||
@@ -38,6 +39,7 @@ namespace UE
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::LoadAssetsFromFile(std::string filePath)
|
void AssetManager::LoadAssetsFromFile(std::string filePath)
|
||||||
{
|
{
|
||||||
std::fstream file(filePath.c_str());
|
std::fstream file(filePath.c_str());
|
||||||
@@ -119,40 +121,10 @@ namespace UE
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::LoadTexture(std::string name, std::string txPath)
|
void AssetManager::LoadTexture(std::string name, std::string txPath)
|
||||||
{
|
{
|
||||||
Texture* tx = new Texture(txPath, _SDL_Renderer);
|
Texture* tx = new Texture(txPath, _SDL_Renderer);
|
||||||
_textures.insert(std::make_pair(name, tx));
|
_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>());
|
|
||||||
//}
|
|
||||||
|
|
||||||
|
|
||||||
//file.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -164,11 +136,37 @@ namespace UE
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Texture* AssetManager::getTexture(std::string textureName)
|
||||||
|
{
|
||||||
|
Texture* txPtr;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//Obtenemos la tx indicada.
|
||||||
|
txPtr = _textures.at(textureName);
|
||||||
|
}
|
||||||
|
catch (const std::out_of_range&)
|
||||||
|
{
|
||||||
|
//Si no existe, usamos la por defecto.
|
||||||
|
txPtr = _textures.at(defaultAsset);
|
||||||
|
}
|
||||||
|
|
||||||
|
return txPtr;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Texture* AssetManager::getDefaultTexture()
|
||||||
|
{
|
||||||
|
return _textures.at(defaultAsset);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::LoadFont(std::string name, std::string fontPath)
|
void AssetManager::LoadFont(std::string name, std::string fontPath)
|
||||||
{
|
{
|
||||||
Font* fo = new Font(fontPath);
|
Font* fo = new Font(fontPath);
|
||||||
_fonts.insert(std::make_pair(name, fo));
|
_fonts.insert(std::make_pair(name, fo));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -180,6 +178,29 @@ namespace UE
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Font* AssetManager::GetFont(std::string fontName)
|
||||||
|
{
|
||||||
|
Font* fontPtr;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//Obtenemos la tx indicada.
|
||||||
|
fontPtr = _fonts.at(fontName);
|
||||||
|
}
|
||||||
|
catch (const std::out_of_range&)
|
||||||
|
{
|
||||||
|
//Si no existe, usamos la por defecto.
|
||||||
|
fontPtr = _fonts.at(defaultAsset);
|
||||||
|
}
|
||||||
|
|
||||||
|
return fontPtr;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Font* AssetManager::getDefaultFont()
|
||||||
|
{
|
||||||
|
return _fonts.at(defaultAsset);
|
||||||
|
}
|
||||||
|
|
||||||
//////////DEBUG//////////
|
//////////DEBUG//////////
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -19,15 +19,16 @@ using json = nlohmann::ordered_json;
|
|||||||
|
|
||||||
|
|
||||||
///
|
///
|
||||||
/// TODO:
|
/// TODO AssetManager:
|
||||||
/// - Modificar las funciones de Carga para quitar la queue o implementar una que tenga sentido.
|
/// - 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
|
/// 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.
|
/// procesar toda la cola de golpe. Optimizar�a la carga de assets.
|
||||||
/// - Terminar la implementaci�n del tipo de carga (queue/now).
|
/// - Terminar la implementación del tipo de carga (queue/now). (O quizás no...)
|
||||||
/// - Modificar los for en la carga de archivo, as� como la estructura del archivo JSON. El tipo de Asset est� repetido.
|
/// - Modificar los for en la carga de archivo, as� como la estructura del archivo JSON. El tipo de Asset est� repetido.
|
||||||
/// - Logging.
|
/// - Logging.
|
||||||
/// - ERROR HANDLING
|
/// - ERROR HANDLING
|
||||||
/// - More asset types.
|
/// - More asset types.
|
||||||
|
/// - ¡¡Texturas y assets por defecto. Texturas completas en el txRect 0 y demás seguridad!!
|
||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
@@ -41,6 +42,9 @@ namespace UE
|
|||||||
: _SDL_Renderer(SDLrenderer) {}
|
: _SDL_Renderer(SDLrenderer) {}
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Init AssetManager y todo lo necesario para funcionar correctamente.
|
* Init AssetManager y todo lo necesario para funcionar correctamente.
|
||||||
* - Inicia SDL_IMG.
|
* - Inicia SDL_IMG.
|
||||||
@@ -56,6 +60,9 @@ namespace UE
|
|||||||
void CleanAssetManager();
|
void CleanAssetManager();
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
/* Carga de Assets */
|
/* Carga de Assets */
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -77,6 +84,9 @@ namespace UE
|
|||||||
void LoadAsset(Asset& as);
|
void LoadAsset(Asset& as);
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Procesa la cola de carga de Assets.
|
* Procesa la cola de carga de Assets.
|
||||||
*
|
*
|
||||||
@@ -92,30 +102,66 @@ namespace UE
|
|||||||
*/
|
*/
|
||||||
inline int GetAssetQueueSize() { return _assetQueue.size(); }
|
inline int GetAssetQueueSize() { return _assetQueue.size(); }
|
||||||
|
|
||||||
/// <summary>
|
/**
|
||||||
/// Comprueba si la cola de carga de Assets est� vac�a.
|
* Permite saber si la cola de carga de Assets está vacía.
|
||||||
/// </summary>
|
*
|
||||||
/// <returns>El resultado de la cola.</returns>
|
* @return True si está vacía; false si hay algún Asset.
|
||||||
|
*/
|
||||||
inline bool IsAssetQueueEmpty() { return _assetQueue.empty(); }
|
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.
|
/**
|
||||||
|
* Carga una textura dado su nombre y su Path.
|
||||||
|
*
|
||||||
|
* @param name: Nombre identificador de la tx.
|
||||||
|
* @param txPath: Ubicación de la tx que se quiere cargar.
|
||||||
|
*/
|
||||||
void LoadTexture(std::string name, std::string txPath);
|
void LoadTexture(std::string name, std::string txPath);
|
||||||
|
|
||||||
//Elimina una textura del mapa a partir de su nombre.
|
|
||||||
|
/**
|
||||||
|
* Descarga la textura con el nombre identificador indicado.
|
||||||
|
* NOTA AssetManager: Quizás queramos cambiar el nombre de los métodos de descarga: RemoveAsset -> UnloadAsset.
|
||||||
|
*
|
||||||
|
* @param name: Nombre identificador.
|
||||||
|
*/
|
||||||
void RemoveTexture(std::string name);
|
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.
|
||||||
|
*
|
||||||
|
* NOTA REWORK getTexture() -> La tx que se retorna habrá de ser const para evitar que modifiquen datos comunes.
|
||||||
|
* Así el TextureLoader o quien la cree podrá modificar lo que desee, pero no una vez metida aquí (hecha común).
|
||||||
|
*
|
||||||
|
* @param textureName: Nombre de la textura que se quiere.
|
||||||
|
*
|
||||||
|
* @return Ptr a la tx solicitada.
|
||||||
|
*/
|
||||||
|
Texture* getTexture(std::string textureName);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Devuelve un Ptr a la textura por defecto.
|
||||||
|
* Utilizado cuando no exista una textura específica.
|
||||||
|
*
|
||||||
|
* @return Ptr a la textura por defecto.
|
||||||
|
*/
|
||||||
|
Texture* getDefaultTexture();
|
||||||
|
|
||||||
//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. *
|
||||||
*------------------------------------*/
|
*------------------------------------*/
|
||||||
@@ -125,15 +171,13 @@ namespace UE
|
|||||||
*
|
*
|
||||||
* @param name : Nombre del asset (key para el 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.
|
* @param fontPath : Ubicaci�n del archivo de datos sobre la fuente.
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
void LoadFont(std::string name, std::string fontPath);
|
void LoadFont(std::string name, std::string fontPath);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Elimina una fuente (y en teor�a limpia la fuente) dado su nombre de Asset.
|
* Elimina una fuente dado su nombre identificador.
|
||||||
*
|
*
|
||||||
* @param name : Nombre del Asset (key del mapa de fuentes).
|
* @param name : Nombre del Asset (key del mapa de fuentes).
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
void RemoveFont(std::string name);
|
void RemoveFont(std::string name);
|
||||||
|
|
||||||
@@ -141,11 +185,21 @@ namespace UE
|
|||||||
* Obtiene y devuelve el ptr a una fuente dado su nombre de asset.
|
* Obtiene y devuelve el ptr a una fuente dado su nombre de asset.
|
||||||
*
|
*
|
||||||
* @param fontName : Nombre del Asset.
|
* @param fontName : Nombre del Asset.
|
||||||
* @return UE::Font* : El ptr a la fuente solicitada.
|
|
||||||
*
|
*
|
||||||
|
* @return UE::Font* : El ptr a la fuente solicitada.
|
||||||
*/
|
*/
|
||||||
inline Font* GetFont(std::string fontName) { return _fonts.at(fontName); }
|
Font* GetFont(std::string fontName);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Devuelve un Ptr a la fuente por defecto.
|
||||||
|
* Utilizado cuando no exista o no se indique una fuente específica.
|
||||||
|
*
|
||||||
|
* @return Ptr a la fuente por defecto.
|
||||||
|
*/
|
||||||
|
Font* getDefaultFont();
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
///////DEBUG////////
|
///////DEBUG////////
|
||||||
@@ -159,11 +213,24 @@ namespace UE
|
|||||||
//---------------------
|
//---------------------
|
||||||
|
|
||||||
|
|
||||||
//std::string _assetPath;
|
/**
|
||||||
|
* Nombre de los Assets por defecto.
|
||||||
|
* Sustituirá a un Asset no disponible.
|
||||||
|
* NOTA: UberEngine debería traer Assets por defecto para esta funcionalidad.
|
||||||
|
*/
|
||||||
|
const std::string defaultAsset = "default";
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//std::vector<UE::Asset> _assets = {};
|
//std::vector<UE::Asset> _assets = {};
|
||||||
std::deque<UE::Asset> _assetQueue = {};
|
std::deque<UE::Asset> _assetQueue = {};
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
/* Almacenes de asssets */
|
/* Almacenes de asssets */
|
||||||
|
|
||||||
//Almac�n de SDL_Texture* (ptrs, pues lo gestiona SDL).
|
//Almac�n de SDL_Texture* (ptrs, pues lo gestiona SDL).
|
||||||
@@ -175,6 +242,9 @@ namespace UE
|
|||||||
std::unordered_map<std::string, Font*> _fonts = {};
|
std::unordered_map<std::string, Font*> _fonts = {};
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//Necesario para crear las SDL_Texture a partir de SDL_Surface.
|
//Necesario para crear las SDL_Texture a partir de SDL_Surface.
|
||||||
SDL_Renderer* _SDL_Renderer = NULL;
|
SDL_Renderer* _SDL_Renderer = NULL;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ TTF_Font* UE::Font::GetFont(int size)
|
|||||||
auto it = _fonts.find(size);
|
auto it = _fonts.find(size);
|
||||||
if (it == _fonts.end())
|
if (it == _fonts.end())
|
||||||
{
|
{
|
||||||
//El tama�o pedido no est� disponible.
|
//El font size pedido no está disponible.
|
||||||
//La creamos nueva.
|
//Creamos el nuevo size.
|
||||||
font = CreateFontSize(size);
|
font = CreateFontSize(size);
|
||||||
return font;
|
return font;
|
||||||
}
|
}
|
||||||
@@ -62,18 +62,18 @@ void UE::Font::CleanFont()
|
|||||||
|
|
||||||
TTF_Font* UE::Font::CreateFontSize(int size)
|
TTF_Font* UE::Font::CreateFontSize(int size)
|
||||||
{
|
{
|
||||||
//Creamos la fuente del tama�o requerido.
|
//Creamos la font size requerida.
|
||||||
TTF_Font* font = TTF_OpenFont(_fontPath.c_str(), size);
|
TTF_Font* font = TTF_OpenFont(_fontPath.c_str(), size);
|
||||||
if (font == nullptr)
|
if (font == nullptr)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("No se ha podido crear la fuente: {0} - Size: {1}", _fontPath, size);
|
UE_LOG_ERROR("Font - No se ha podido crear la fuente: {0} - Size: {1}", _fontPath, size);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
//La a�adimos al mapa.
|
//Add to the map
|
||||||
_fonts.insert(std::make_pair(size, font));
|
_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 el Size: {1}", _fontPath, size);
|
||||||
|
|
||||||
return font;
|
return font;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,9 +9,10 @@ namespace UE
|
|||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Clase Wrapper para las SDL_Fonts.
|
* Clase Wrapper para las SDL_Fonts.
|
||||||
* Tambi�n sirve de "cache" para los diferentes tama�os de la fuente, de esta forma
|
* Dada una fuente ttf, carga los glyphos con los tamaños indicados y almacena el TTF_Font del tamaño correspondiente.
|
||||||
* reducimos las veces que generamos las fuentes y podemos utilizar m�ltiples tama�os de forma sencilla.
|
* Esta clase contiene todos los tamaños cargados.
|
||||||
*
|
* En caso de pedir un tamaño no cargado, lo cargará desde el archivo.
|
||||||
|
* REWORK Font -> Quizás se pueda sacar el loader a otro lado (Como en UE::Texture). Aunque en este caso, como es una especie de FontManager, no sé.
|
||||||
*/
|
*/
|
||||||
class Font
|
class Font
|
||||||
{
|
{
|
||||||
@@ -31,53 +32,67 @@ namespace UE
|
|||||||
CleanFont();
|
CleanFont();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//------- Methods -------
|
//------- Methods -------
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Devuelve la fuente del tama�o pedido.
|
* Devuelve la fuente del size pedido.
|
||||||
* En caso de no estar disponible, la genera y la a�ade al cache antes de devolverla.
|
* En caso de no estar disponible, la genera y la añade al cache antes de devolverla.
|
||||||
*
|
*
|
||||||
* @param size : tama�o de la fuente.
|
* @param size : tama�o de la fuente.
|
||||||
* @return TTF_Font* : Fuente del tama�o solicitado.
|
* @return TTF_Font* : Fuente del size solicitado. En caso de error, devuelve un nullptr.
|
||||||
*/
|
*/
|
||||||
TTF_Font* GetFont(int size);
|
TTF_Font* GetFont(int size);
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
/**
|
/**
|
||||||
* Crea la fuente a partir del archivo de datos.
|
* Crea la clase a partir del archivo de datos.
|
||||||
*/
|
*/
|
||||||
void InitFont();
|
void InitFont();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Limpia la fuente, eliminando todos sus tama�os y vaciando toda la memoria.
|
* Limpia la clase, eliminando todos los font sizes y vaciando toda la memoria.
|
||||||
*/
|
*/
|
||||||
void CleanFont();
|
void CleanFont();
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Se encarga de generar el tama�o de fuente deseado.
|
* Se encarga de generar el Font Size de fuente deseado.
|
||||||
*
|
*
|
||||||
* @param size : tama�o a generar.
|
* @param size : Font Size a generar.
|
||||||
* @return TTF_Font* : Ptr al nuevo tama�o generado. Hay que guardarlo en alg�n sitio.
|
* @return TTF_Font* : Ptr al nuevo Font Size generado.
|
||||||
*/
|
*/
|
||||||
TTF_Font* CreateFontSize(int size);
|
TTF_Font* CreateFontSize(int size);
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
private:
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//------ Variables ------
|
//------ Variables ------
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
private:
|
|
||||||
//Ubicaci�n del archivo de datos (.json).
|
|
||||||
std::string _dataPath = "";
|
|
||||||
|
|
||||||
//Ubicaci�n de la tipograf�a (.ttf).
|
//Path del archivo de datos (.json).
|
||||||
|
std::string _dataPath = "";
|
||||||
|
//Path de la tipografía (.ttf).
|
||||||
std::string _fontPath = "";
|
std::string _fontPath = "";
|
||||||
|
|
||||||
//Cach� de los diferentes tama�os de la fuente.
|
//Cache de los diferentes Font Sizes (glyphos).
|
||||||
std::unordered_map<int, TTF_Font*> _fonts = {};
|
std::unordered_map<int, TTF_Font*> _fonts = {};
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -8,28 +8,44 @@
|
|||||||
#include <json/json.hpp>
|
#include <json/json.hpp>
|
||||||
using json = nlohmann::ordered_json;
|
using json = nlohmann::ordered_json;
|
||||||
|
|
||||||
SDL_Rect* UE::Texture::GetTextureRect(int i)
|
SDL_Rect UE::Texture::GetTextureRect(int i)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
SDL_Rect* rect = &_txRects.at(i);
|
SDL_Rect rect = _txRects.at(i);
|
||||||
return rect;
|
return rect;
|
||||||
}
|
}
|
||||||
catch (const std::out_of_range&)
|
catch (const std::out_of_range&)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("La textura {0} no tiene rect {1}", _txPath, i);
|
UE_LOG_WARN("La textura {0} no tiene rect {1}", _txPath, i);
|
||||||
return &_txRects.at(0);
|
return _txRects.at(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void UE::Texture::SetTexture(SDL_Texture* newTexture)
|
||||||
|
{
|
||||||
|
//Destruimos la tx antigua. Esperomos no se haya hecho antes...
|
||||||
|
//Algo me dice que este if tiene más bien poco sentido...
|
||||||
|
if (_texture != nullptr)
|
||||||
|
{
|
||||||
|
SDL_DestroyTexture(_texture);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Cambiamos la tx por la nueva.
|
||||||
|
_texture = newTexture;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void UE::Texture::InitTexture()
|
void UE::Texture::InitTexture()
|
||||||
{
|
{
|
||||||
std::fstream file(_dataPath);
|
std::fstream file(_dataPath);
|
||||||
//Comprobamos si el archivo se ha abierto.
|
//Comprobamos si el archivo se ha abierto.
|
||||||
if (!file.is_open())
|
if (!file.is_open())
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de textura: {0}", _dataPath);
|
UE_LOG_ERROR("Texture - No se ha podido abrir el archivo de datos de textura: {0}", _dataPath);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,11 +53,22 @@ void UE::Texture::InitTexture()
|
|||||||
_txPath = jread["TexturePath"].get<std::string>();
|
_txPath = jread["TexturePath"].get<std::string>();
|
||||||
|
|
||||||
//Creamos la textura.
|
//Creamos la textura.
|
||||||
CreateTexture();
|
if (int error = CreateTexture() < 0)
|
||||||
|
{
|
||||||
|
UE_LOG_ERROR("Texture {0}: La textura no se ha cargado. Se esperan excepciones. Error {1}",
|
||||||
|
_txPath,
|
||||||
|
error);
|
||||||
|
|
||||||
|
//En principio, los Rects se pueden cargar. Por tanto, continuamos.
|
||||||
|
}
|
||||||
|
|
||||||
//Cargamos los Rects.
|
//Cargamos los Rects.
|
||||||
json textureRects = jread["TextureRects"];
|
json textureRects = jread["TextureRects"];
|
||||||
|
|
||||||
|
//Por defecto, el Rect 0 es la textura completa.
|
||||||
|
AddRect(SDL_Rect{ 0, 0, txSizeX, txSizeY });
|
||||||
|
|
||||||
|
//Este bucle debe empezar en 0, pues iteramos por los valores del JSON, no los de la textura.
|
||||||
for (int i = 0; i < textureRects.size(); i++)
|
for (int i = 0; i < textureRects.size(); i++)
|
||||||
{
|
{
|
||||||
AddRect(textureRects.at(i).get<SDL_Rect>());
|
AddRect(textureRects.at(i).get<SDL_Rect>());
|
||||||
@@ -57,14 +84,40 @@ void UE::Texture::CleanTexture()
|
|||||||
_txRects.clear();
|
_txRects.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Texture::CreateTexture()
|
int UE::Texture::CreateTexture()
|
||||||
{
|
{
|
||||||
SDL_Surface* loadSurface = IMG_Load(_txPath.c_str());
|
SDL_Surface* loadSurface = IMG_Load(_txPath.c_str());
|
||||||
_texture = SDL_CreateTextureFromSurface(_SDL_Renderer, loadSurface);
|
if (loadSurface == NULL)
|
||||||
SDL_FreeSurface(loadSurface);
|
{
|
||||||
|
UE_LOG_ERROR("Texture - No se ha podido cargar la tx en {0}: {1}",
|
||||||
|
_txPath,
|
||||||
|
IMG_GetError()
|
||||||
|
);
|
||||||
|
|
||||||
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Texture::AddRect(SDL_Rect newRect)
|
//Extraemos el Size de la tx.
|
||||||
|
txSizeX = loadSurface->w;
|
||||||
|
txSizeY = loadSurface->h;
|
||||||
|
|
||||||
|
_texture = SDL_CreateTextureFromSurface(_SDL_Renderer, loadSurface);
|
||||||
|
if (_texture == NULL)
|
||||||
|
{
|
||||||
|
UE_LOG_ERROR("Texture - No se ha podido crear la tx {0}: {1}",
|
||||||
|
_txPath,
|
||||||
|
SDL_GetError()
|
||||||
|
);
|
||||||
|
|
||||||
|
return -2;
|
||||||
|
}
|
||||||
|
|
||||||
|
SDL_FreeSurface(loadSurface);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void UE::Texture::AddRect(SDL_Rect& newRect)
|
||||||
{
|
{
|
||||||
_txRects.push_back(newRect);
|
_txRects.push_back(newRect);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,13 @@
|
|||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* Wrapper para SDL_Texture permitiendo Texturas "animadas" o "SpriteSheets".
|
||||||
|
* Contiene una SDL_Texture y un conjunto de SDL_Rects, indicando las distintas partes de la textura.
|
||||||
|
* El SDL_Rect index 0 indica la textura completa.
|
||||||
|
*
|
||||||
|
* REWORK Texture -> Separar los datos (sdl_tx, rects, ...) del loader. No me gusta que una textura se tenga que cargar a si misma.
|
||||||
|
*/
|
||||||
class Texture
|
class Texture
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
@@ -19,36 +25,77 @@ namespace UE
|
|||||||
Texture(std::string dataPath, SDL_Renderer* renderer)
|
Texture(std::string dataPath, SDL_Renderer* renderer)
|
||||||
: _dataPath(dataPath), _SDL_Renderer(renderer)
|
: _dataPath(dataPath), _SDL_Renderer(renderer)
|
||||||
{
|
{
|
||||||
|
//REWORK -> En el Loader, estaría bien poder saber si se ha cargado o no.
|
||||||
|
// Para no añadirla al mapa de texturas y hacer fallback en la por defecto.
|
||||||
InitTexture();
|
InitTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//HACK Texture() -> Lo utilizaremos únicamente para poder crear Texture vacias, hasta que separemos el loader.
|
||||||
|
Texture() {}
|
||||||
|
|
||||||
~Texture()
|
~Texture()
|
||||||
{
|
{
|
||||||
CleanTexture();
|
CleanTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//------- Methods -------
|
//------- Methods -------
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna la textura.
|
* Retorna la textura interna.
|
||||||
|
*
|
||||||
|
* @return Ptr a la SDL_Texture que contiene.
|
||||||
*/
|
*/
|
||||||
inline SDL_Texture* GetTexture() { return _texture; }
|
inline SDL_Texture* GetTexture() { return _texture; }
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna los Rects de la textura.
|
* Retorna los Rects de la textura.
|
||||||
|
*
|
||||||
|
* @return Vector con todos los Rects de la textura.
|
||||||
*/
|
*/
|
||||||
inline std::vector<SDL_Rect>* GetRectsVector() { return &_txRects; }
|
inline std::vector<SDL_Rect>* GetRectsVector() { return &_txRects; }
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna el Rect pedido. Comprobando que est� disponible.
|
* Retorna el Rect indicado, comprobando que esté disponible.
|
||||||
* Si no est� disponible, devuelve el rect de index 0 (que deber�a ser el por defecto).
|
* Si no está disponible, devuelve el rect de index 0.
|
||||||
*
|
*
|
||||||
* @param i : �ndice del rect.
|
* @param i : index del rect. (El index 0 es la textura completa).
|
||||||
* @return El SDL_Rect* solicitado (o el por defecto en caso de error).
|
* @return El SDL_Rect solicitado (o el por defecto si no está disponible).
|
||||||
*/
|
*/
|
||||||
SDL_Rect* GetTextureRect(int i);
|
SDL_Rect GetTextureRect(int i);
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
//HACK Tiene que ser posible hacer un SetTexture. Será necesario cuando no cree su propia textura.
|
||||||
|
// Pero habrá que pasarlo como const desde el AssetManager, para evitar modificar datos "comunes".
|
||||||
|
void SetTexture(SDL_Texture* newTexture);
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a SDL_Rect to the Rect Array.
|
||||||
|
*
|
||||||
|
* NOTA para REWORK -> Estaba en privado. Lo he movido aquí porque será público, pero no modificable si es const.
|
||||||
|
*
|
||||||
|
* @param newRect: New Rect to add. Lo enviamos como referencia para ahorrar copias. IDK if is better...
|
||||||
|
*/
|
||||||
|
void AddRect(SDL_Rect& newRect);
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -62,37 +109,51 @@ namespace UE
|
|||||||
*/
|
*/
|
||||||
void CleanTexture();
|
void CleanTexture();
|
||||||
|
|
||||||
/**
|
|
||||||
* 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.
|
* Genera la textura a partir de los valores de la clase.
|
||||||
* @param newRect : Nuevo Rect que a�adir al vector de Rects.
|
|
||||||
*/
|
*/
|
||||||
void AddRect(SDL_Rect newRect);
|
int CreateTexture();
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
private:
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//------ Variables ------
|
//------ Variables ------
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
private:
|
//Path del archivo de datos (.json).
|
||||||
//Ubicaci�n del archivo de datos (.json).
|
|
||||||
std::string _dataPath = "";
|
std::string _dataPath = "";
|
||||||
|
//Path de la textura (.png o formato de la imagen).
|
||||||
//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 = "";
|
std::string _txPath = "";
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//La propia textura.
|
//La propia textura.
|
||||||
SDL_Texture* _texture = nullptr;
|
SDL_Texture* _texture = nullptr;
|
||||||
//Conjunto de rects que hay en la textura.
|
//Conjunto de rects que hay en la textura.
|
||||||
std::vector<SDL_Rect> _txRects = {};
|
std::vector<SDL_Rect> _txRects = {};
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
//Size de la SDL_Texture. Por si se necesita para algo...
|
||||||
|
//NOTA Texture Size vars: Quizás haya que implementar algún método para estas vars.
|
||||||
|
int txSizeX = 0;
|
||||||
|
int txSizeY = 0;
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
//El propio renderer de SDL. Es necesario para crear y operar con las SDL_Textures.
|
||||||
|
//NOTA Texture: Para quitarlo de aquí, tenemos que mover el proceso de carga.
|
||||||
|
SDL_Renderer* _SDL_Renderer = nullptr;
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#include "Drawable.h"
|
||||||
|
|
||||||
|
#include "Assets/Texture.h"
|
||||||
|
#include "Logging/Logger.h"
|
||||||
|
|
||||||
|
namespace UE
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Interfaces/Transformable.h"
|
||||||
|
|
||||||
|
#include <SDL_rect.h>
|
||||||
|
|
||||||
|
namespace UE
|
||||||
|
{
|
||||||
|
class Renderer;
|
||||||
|
class Texture;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Clase base para renderizar objetos en el mundo.
|
||||||
|
* El renderer extrae los datos necesarios de esta clase para renderizar el objeto.
|
||||||
|
*/
|
||||||
|
class Drawable : public Transformable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
Drawable() {}
|
||||||
|
|
||||||
|
~Drawable() {}
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
//Get-Set del renderLayer.
|
||||||
|
inline void SetLayer(int newLayer) { _renderLayer = newLayer; }
|
||||||
|
inline int GetLayer() { return _renderLayer; }
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
inline bool IsActive() { return isActive; }
|
||||||
|
inline void SetActive(bool active) { isActive = active; }
|
||||||
|
|
||||||
|
|
||||||
|
//¿Añadir funciones para cambiar las variables? ¿Al menos, para actualizar el actualRect de alguna forma?
|
||||||
|
|
||||||
|
|
||||||
|
protected:
|
||||||
|
|
||||||
|
//Esto permite acceder a este método desde el Renderer, pero no será accesible desde fuera.
|
||||||
|
// de esta forma, me aseguro que ocurren las dos etapas del rendering.
|
||||||
|
friend class Renderer;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Esta función ha de ser sobrecargada por los Drawables.
|
||||||
|
* Sirve para actualizar la información que hay en el drawable para hacer el rendering.
|
||||||
|
* Constituye la primera parte del draw. En la que se actualizan los datos del Drawable.
|
||||||
|
* La segunda parte, ocurre en el renderer, que extraerá los datos del Drawable.
|
||||||
|
*/
|
||||||
|
virtual void Draw(Renderer* renderer) = 0;
|
||||||
|
|
||||||
|
|
||||||
|
protected:
|
||||||
|
|
||||||
|
//Ptr a la textura y los datos que está utilizando.
|
||||||
|
UE::Texture* _tx = nullptr;
|
||||||
|
|
||||||
|
//Sección de la textura que se utilizará.
|
||||||
|
SDL_Rect _txRect{0, 0, 0, 0};
|
||||||
|
|
||||||
|
//UE::Texture contiene una lista de rects, con esto, podemos seleccionar el rect que queramos.
|
||||||
|
//Pero es redundante con _txRect y para que sea seguro habría que encapsular todo.
|
||||||
|
//¿Es necesario que esté aquí? ¿Puedo simplemente tenerlo en aquellos Drawables en que lo necesite (animated ones)?
|
||||||
|
int _txRectID = 0;
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
//Indica en qué layer del renderer está el objeto (z order).
|
||||||
|
int _renderLayer = 0;
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
//Permite activar o desactivar el Drawable. Si está desactivado, no se debería de renderizar/ejecutar.
|
||||||
|
bool isActive = true;
|
||||||
|
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -9,31 +9,18 @@
|
|||||||
|
|
||||||
void UE::Sprite::SetTextureRect(int textureID)
|
void UE::Sprite::SetTextureRect(int textureID)
|
||||||
{
|
{
|
||||||
SDL_Rect* newRect = _texture->GetTextureRect(textureID);
|
_txRectID = textureID;
|
||||||
|
|
||||||
if (newRect != nullptr)
|
//Sabemos que en caso de no estar disponible, no devolverá el Rect 0 (Textura completa).
|
||||||
{
|
_txRect = _tx->GetTextureRect(textureID);
|
||||||
_actualTxRect = newRect;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Sprite::SetActive(bool active)
|
|
||||||
{
|
|
||||||
isActive = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool UE::Sprite::IsActive()
|
|
||||||
{
|
|
||||||
return isActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void UE::Sprite::Draw(Renderer* renderer)
|
void UE::Sprite::Draw(Renderer* renderer)
|
||||||
{
|
{
|
||||||
//Convertimos a ScreenCoords.
|
//Convertimos a ScreenCoords.
|
||||||
glm::ivec2 screenCoords = renderer->WorldToSreenCoords(_pos);
|
|
||||||
|
|
||||||
SDL_Rect position = { screenCoords.x, screenCoords.y, _size.x, _size.y };
|
|
||||||
|
|
||||||
//destination.x = _pos.x;
|
//destination.x = _pos.x;
|
||||||
//destination.y = _pos.y;
|
//destination.y = _pos.y;
|
||||||
@@ -42,12 +29,6 @@ void UE::Sprite::Draw(Renderer* renderer)
|
|||||||
//destination.h = _size.y;
|
//destination.h = _size.y;
|
||||||
|
|
||||||
//std::cout << "Sprite Rendered to: " << destination.x << "-" << destination.y << std::endl;
|
//std::cout << "Sprite Rendered to: " << destination.x << "-" << destination.y << std::endl;
|
||||||
renderer->QueueDrawCall(_renderLayer, position, _texture->GetTexture(), *_actualTxRect);
|
//renderer->QueueDrawCall(_renderLayer, position, _tx->GetTexture(), _txRect);
|
||||||
}
|
|
||||||
|
|
||||||
SDL_Rect UE::Sprite::getPositionRect()
|
|
||||||
{
|
|
||||||
SDL_Rect position = { _pos.x, _pos.y, _size.x, _size.y };
|
|
||||||
return position;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,12 +8,12 @@
|
|||||||
#include <glm/vec2.hpp>
|
#include <glm/vec2.hpp>
|
||||||
|
|
||||||
|
|
||||||
#include "Render/Drawable.h"
|
#include "Drawables/Drawable.h"
|
||||||
#include "Render/Transformable.h"
|
#include "Interfaces/Transformable.h"
|
||||||
#include "Assets/Texture.h"
|
#include "Assets/Texture.h"
|
||||||
|
|
||||||
//
|
//
|
||||||
// TODO:
|
// TODO Sprite:
|
||||||
// - Implementar soporte para SpriteSheets en los constructores.
|
// - Implementar soporte para SpriteSheets en los constructores.
|
||||||
//
|
//
|
||||||
//
|
//
|
||||||
@@ -23,7 +23,7 @@ namespace UE
|
|||||||
{
|
{
|
||||||
class Renderer;
|
class Renderer;
|
||||||
|
|
||||||
class Sprite : public Drawable, public Transformable
|
class Sprite : public Drawable
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
@@ -35,26 +35,29 @@ namespace UE
|
|||||||
// --------------
|
// --------------
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
//NOTA: Hay que implementar una textura por defecto, que será la que se usará cuando no se indique nada.
|
||||||
|
// De esta forma, podemos tener constructores por defecto.
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Se establecen todos los par�metos.
|
Se establecen todos los parámetos.
|
||||||
La textura es obligatoria, y puede ha de darse:
|
La textura es obligatoria, y puede ha de darse:
|
||||||
- En SDL_Texture* -> Sin m�s, se entiende.
|
- 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.
|
||||||
Los dem�s par�metros tienen un valor por defecto.
|
|
||||||
|
|
||||||
\param texturePtr: El pointer a la textura de SDL.
|
\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. Por defecto será 0 (La textura completa).
|
||||||
\param textureRectID: El n�mero de Rect del conjunto de rects.
|
\param renderLayer: La Layer en que se renderizará.
|
||||||
\param renderLayer: La Layer en que se renderizar�.
|
\param position: Posición del Sprite.
|
||||||
|
\param size: Tamaño del Sprite.
|
||||||
*/
|
*/
|
||||||
Sprite(UE::Texture* texture,
|
Sprite(UE::Texture* texture,
|
||||||
int textureRectID = 0,
|
int textureRectID = 0,
|
||||||
int renderLayer = 1,
|
int renderLayer = 1,
|
||||||
glm::vec2 position = glm::vec2(0, 0),
|
glm::vec2 position = glm::vec2(0, 0),
|
||||||
glm::vec2 size = glm::vec2(100, 100))
|
glm::vec2 size = glm::vec2(100, 100))
|
||||||
|
|
||||||
: _texture(texture)
|
|
||||||
{
|
{
|
||||||
|
_tx = texture;
|
||||||
|
|
||||||
SetTextureRect(textureRectID);
|
SetTextureRect(textureRectID);
|
||||||
|
|
||||||
SetLayer(renderLayer);
|
SetLayer(renderLayer);
|
||||||
@@ -63,36 +66,35 @@ namespace UE
|
|||||||
SetSize(size);
|
SetSize(size);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
~Sprite() {}
|
~Sprite() {}
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//-----------
|
//-----------
|
||||||
//- Setters -
|
//- Methods -
|
||||||
//-----------
|
//-----------
|
||||||
|
|
||||||
|
|
||||||
void SetTextureRect(int textureID);
|
void SetTextureRect(int textureID);
|
||||||
|
|
||||||
void SetActive(bool active);
|
|
||||||
bool IsActive();
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//Implementa el Draw de Drawable.
|
//Implementa el Draw de Drawable.
|
||||||
void Draw(Renderer* renderer) override;
|
void Draw(Renderer* renderer) override;
|
||||||
|
|
||||||
SDL_Rect getPositionRect();
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
//Datos de la textura. Sirven para pedirla al AssetManager.
|
|
||||||
|
|
||||||
UE::Texture* _texture = nullptr;
|
|
||||||
|
|
||||||
//El que se va a renderizar.
|
|
||||||
SDL_Rect* _actualTxRect = nullptr;
|
|
||||||
|
|
||||||
bool isActive = true;
|
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
#include "TextBox.h"
|
#include "TextBox.h"
|
||||||
|
|
||||||
|
#include "Engine.h"
|
||||||
#include "Logging/Logger.h"
|
#include "Logging/Logger.h"
|
||||||
#include "Render/Renderer.h"
|
#include "Render/Renderer.h"
|
||||||
|
|
||||||
|
#include <SDL_render.h>
|
||||||
|
|
||||||
void UE::TextBox::SetText(std::string newText)
|
void UE::TextBox::SetText(std::string newText)
|
||||||
{
|
{
|
||||||
_text = newText;
|
_text = newText;
|
||||||
@@ -34,31 +37,30 @@ void UE::TextBox::SetColor(int r, int g, int b, int a)
|
|||||||
|
|
||||||
void UE::TextBox::Draw(Renderer* renderer)
|
void UE::TextBox::Draw(Renderer* renderer)
|
||||||
{
|
{
|
||||||
//Si a�n no tenemos renderer, lo guardamos y procesamos.
|
|
||||||
if (_sdlRenderer == nullptr)
|
if (_tx->GetTexture() == nullptr)
|
||||||
{
|
|
||||||
_sdlRenderer = renderer->GetSDLRenderer();
|
|
||||||
RenderTextTexture();
|
|
||||||
}
|
|
||||||
if (_textTexture == nullptr)
|
|
||||||
{
|
{
|
||||||
UE_LOG_WARN("El texto: {0} ; No se est� renderizando. La textura no existe.", _text);
|
UE_LOG_WARN("El texto: {0} ; No se est� renderizando. La textura no existe.", _text);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Generamos el SDL_Rect destino.
|
//Generamos el SDL_Rect destino.
|
||||||
SDL_Rect dest = { _pos.x, _pos.y, _size.x, _size.y };
|
// Ya no es necesario....
|
||||||
|
//SDL_Texture* tx = _textTexture.GetTexture();
|
||||||
|
|
||||||
renderer->QueueDrawCall(_renderLayer, dest, _textTexture);
|
//renderer->QueueDrawCall(_renderLayer, dest, _textTexture);
|
||||||
|
|
||||||
|
//Actualizamos en cada frame el ptr a la textura que tiene que usar el drawable.
|
||||||
|
//no vaya a ser que se invalide por algo.
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::TextBox::RenderTextTexture()
|
void UE::TextBox::RenderTextTexture()
|
||||||
{
|
{
|
||||||
//No podemos continuar hasta que no tengamos un renderer.
|
// No podemos continuar sin un SDL_Renderer.
|
||||||
if (_sdlRenderer == nullptr) { return; }
|
// Si no hay SDL_Renderer, lo buscamos en el Engine.
|
||||||
|
if (_sdlRenderer == nullptr) { GetSDL_Renderer(); }
|
||||||
|
|
||||||
SDL_DestroyTexture(_textTexture);
|
|
||||||
|
|
||||||
//Creamos el SDL_Color a partir del vec4 que contiene el color.
|
//Creamos el SDL_Color a partir del vec4 que contiene el color.
|
||||||
SDL_Color color = { _textColor.x,_textColor.y, _textColor.z, _textColor.w };
|
SDL_Color color = { _textColor.x,_textColor.y, _textColor.z, _textColor.w };
|
||||||
@@ -74,8 +76,8 @@ void UE::TextBox::RenderTextTexture()
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_textTexture = SDL_CreateTextureFromSurface(_sdlRenderer, loader);
|
SDL_Texture* newTextTexture = SDL_CreateTextureFromSurface(_sdlRenderer, loader);
|
||||||
if (_textTexture == NULL)
|
if (newTextTexture == NULL)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("No se ha podido crear la textura del texto: {0} ; Error: {1}",
|
UE_LOG_ERROR("No se ha podido crear la textura del texto: {0} ; Error: {1}",
|
||||||
_text, SDL_GetError());
|
_text, SDL_GetError());
|
||||||
@@ -86,4 +88,22 @@ void UE::TextBox::RenderTextTexture()
|
|||||||
|
|
||||||
SDL_FreeSurface(loader);
|
SDL_FreeSurface(loader);
|
||||||
|
|
||||||
|
//Actualizamos la SDL_Texture en la Texture.
|
||||||
|
_tx->SetTexture(newTextTexture);
|
||||||
|
|
||||||
|
|
||||||
|
//Limpiamos los Rects antiguos.
|
||||||
|
_tx->GetRectsVector()->clear();
|
||||||
|
//Añadimos el Rect correspondiente.
|
||||||
|
SDL_Rect newRect = { 0, 0, _size.x, _size.y };
|
||||||
|
_tx->AddRect(newRect);
|
||||||
|
|
||||||
|
//Actualizamos el Rect en el Drawable.
|
||||||
|
_txRect = newRect;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void UE::TextBox::GetSDL_Renderer()
|
||||||
|
{
|
||||||
|
_sdlRenderer = Engine::GetRenderer()->GetSDLRenderer();
|
||||||
}
|
}
|
||||||
@@ -5,18 +5,20 @@
|
|||||||
#include <glm/vec4.hpp>
|
#include <glm/vec4.hpp>
|
||||||
|
|
||||||
|
|
||||||
#include "Render/Drawable.h"
|
#include "Drawable.h"
|
||||||
#include "Render/Transformable.h"
|
#include "Interfaces/Transformable.h"
|
||||||
|
|
||||||
#include "Assets/Font.h"
|
#include "Assets/Font.h"
|
||||||
|
#include "Assets/Texture.h"
|
||||||
|
|
||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
//NOTA: hay que mover esto a la lista de definiciones (defs.h). Algún día, lo crearemos.
|
||||||
typedef glm::tvec4<int> UE_Color;
|
typedef glm::tvec4<int> UE_Color;
|
||||||
|
|
||||||
class TextBox : public Drawable, public Transformable
|
|
||||||
|
class TextBox : public Drawable
|
||||||
{
|
{
|
||||||
|
|
||||||
public:
|
public:
|
||||||
@@ -30,6 +32,15 @@ namespace UE
|
|||||||
glm::vec2 position = glm::vec2(0, 0))
|
glm::vec2 position = glm::vec2(0, 0))
|
||||||
: _font(font), _text(text), _textSize(textSize)
|
: _font(font), _text(text), _textSize(textSize)
|
||||||
{
|
{
|
||||||
|
//Obtenemos el SDL_Renderer que necesitamos.
|
||||||
|
GetSDL_Renderer();
|
||||||
|
|
||||||
|
//Creamos la texture.
|
||||||
|
//_textTexture = new Texture();
|
||||||
|
|
||||||
|
//Le decimos al Drawable cual es la textura que tiene que usar.
|
||||||
|
_tx = new Texture();
|
||||||
|
|
||||||
SetColor(textColor);
|
SetColor(textColor);
|
||||||
|
|
||||||
SetLayer(renderLayer);
|
SetLayer(renderLayer);
|
||||||
@@ -38,28 +49,90 @@ namespace UE
|
|||||||
RenderTextTexture();
|
RenderTextTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
~TextBox()
|
||||||
|
{
|
||||||
|
//Hay que limpiar lo que ocupamos.
|
||||||
|
//delete _textTexture;
|
||||||
|
delete _tx;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Si se realiza una copia, necesitamos que esta utilice su propia textura.
|
||||||
|
// Así, si queremos copiar una para luego modificarla, no se modifican las dos.
|
||||||
|
// (Y si una se borra no se lleva consigo los ptrs de las 2).
|
||||||
|
TextBox(const TextBox& c)
|
||||||
|
: _font(c._font), _text(c._text), _textSize(c._textSize), _textColor(c._textColor)
|
||||||
|
{
|
||||||
|
//Le decimos al Drawable cual es la textura que tiene que usar.
|
||||||
|
_tx = new Texture();
|
||||||
|
|
||||||
|
SetLayer(c._renderLayer);
|
||||||
|
SetPosition(c._pos);
|
||||||
|
|
||||||
|
this->RenderTextTexture();
|
||||||
|
}
|
||||||
|
|
||||||
|
//TODO: Eliminar constructores de Copy y demás. No se debería permitir el copiar... Rompen la _textTexture.
|
||||||
|
//NOTA: Quizás, la solución esté en los Smart Pointers...
|
||||||
|
// Se me ocurre lo siguiente:
|
||||||
|
// Añadimos un almacén "estático" para texturas en algún sitio. Le puedes pedir que te de una textura,
|
||||||
|
// y te la almacena ahí. Tú recibes un ptr y lo conservas. Tendrás acceso a la tx mientras tengas el ptr a la misma.
|
||||||
|
// El sistema eliminará los ptrs que no se usen (smart pointers) porque no tengan referencias.
|
||||||
|
//
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//Se generar� una textura y todo eso...
|
//Se generar� una textura y todo eso...
|
||||||
void SetText(std::string newText);
|
void SetText(std::string newText);
|
||||||
void SetSize(int newSize);
|
void SetSize(int newSize);
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
void SetColor(UE_Color newColor);
|
void SetColor(UE_Color newColor);
|
||||||
void SetColor(int r, int g, int b, int a);
|
void SetColor(int r, int g, int b, int a);
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//Implementa el Draw de Drawable.
|
//Implementa el Draw de Drawable.
|
||||||
void Draw(Renderer* renderer) override;
|
void Draw(Renderer* renderer) override;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void RenderTextTexture();
|
void RenderTextTexture();
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
Obtiene el SDL_Renderer desde el Engine. (Magia estática).
|
||||||
|
*/
|
||||||
|
void GetSDL_Renderer();
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
UE::Font* _font = nullptr;
|
UE::Font* _font = nullptr;
|
||||||
std::string _text = "Texto por defecto";
|
std::string _text = "Texto por defecto";
|
||||||
int _textSize = 18;
|
int _textSize = 18;
|
||||||
UE_Color _textColor;
|
UE_Color _textColor = {255, 255, 255, 255};
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
//Creamos su propia textura, que le pasamos al Drawable.
|
||||||
|
//El Drawable no almacena una textura, sino un ptr (normalmente sacado del AssetManager).
|
||||||
|
//En este caso, esta es la textura a la que debe apuntar.
|
||||||
|
// Pero podemos, simplemente, crear la textura en el heap y apuntar ahí el ptr.
|
||||||
|
//Texture* _textTexture;
|
||||||
|
|
||||||
SDL_Texture* _textTexture = nullptr;
|
|
||||||
|
|
||||||
//Esto est� muy mal hecho, no deber�a de ser as�.
|
//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.
|
//Necesito un renderer para crear la textura del texto, pero no puedo conseguirlo con la arquitectura actual.
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
#include "Transformable.h"
|
||||||
|
|
||||||
|
#include "Logging/Logger.h"
|
||||||
|
|
||||||
|
#include <SDL_rect.h>
|
||||||
|
|
||||||
|
|
||||||
|
namespace UE
|
||||||
|
{
|
||||||
|
|
||||||
|
void Transformable::SetPosition(float x, float y)
|
||||||
|
{
|
||||||
|
_pos.x = x;
|
||||||
|
_pos.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Transformable::SetPosition(glm::vec<2, float> newPosition)
|
||||||
|
{
|
||||||
|
_pos = newPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Transformable::SetSize(float x, float y)
|
||||||
|
{
|
||||||
|
_size.x = x;
|
||||||
|
_size.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Transformable::SetSize(glm::vec<2, float> newSize)
|
||||||
|
{
|
||||||
|
_size = newSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Transformable::Move(float x, float y)
|
||||||
|
{
|
||||||
|
_pos.x += x;
|
||||||
|
_pos.y += y;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Transformable::Resize(float x, float y)
|
||||||
|
{
|
||||||
|
_size.x += x;
|
||||||
|
_size.y += y;
|
||||||
|
}
|
||||||
|
|
||||||
|
SDL_Rect Transformable::GetTransformRect()
|
||||||
|
{
|
||||||
|
SDL_Rect rect = { _pos.x, _pos.y, _size.x, _size.y };
|
||||||
|
return rect;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <glm/vec2.hpp>
|
||||||
|
|
||||||
|
|
||||||
|
struct SDL_Rect;
|
||||||
|
|
||||||
|
namespace UE
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
Almacena una posición y un tamaño.
|
||||||
|
Utilizado para representar objetos en algún espacio.
|
||||||
|
*/
|
||||||
|
class Transformable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
|
||||||
|
//-----------
|
||||||
|
//- Setters -
|
||||||
|
//-----------
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Establece una nueva posición para el objeto.
|
||||||
|
* Dados dos floats como nueva posición.
|
||||||
|
*/
|
||||||
|
void SetPosition(float x, float y);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Establece una nueva posición para el objeto.
|
||||||
|
* Dado un vector como nueva posición.
|
||||||
|
*/
|
||||||
|
void SetPosition(glm::vec<2, float> newPosition);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Establece un nuevo tamaño para el objeto (En principio, en pixeles).
|
||||||
|
* Dados dos floats como nuevo tamaño.
|
||||||
|
*/
|
||||||
|
void SetSize(float x, float y);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Establece un nuevo tamaño para el objeto (En principio, en pixeles).
|
||||||
|
* Dado un vector como nuevo tamaño.
|
||||||
|
*/
|
||||||
|
void SetSize(glm::vec<2, float> newSize);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//-----------
|
||||||
|
//- Getters -
|
||||||
|
//-----------
|
||||||
|
|
||||||
|
inline glm::vec2 GetPosition() { return _pos; }
|
||||||
|
inline glm::vec2 GetSize() { return _size; }
|
||||||
|
|
||||||
|
|
||||||
|
//-----------
|
||||||
|
//- Methods -
|
||||||
|
//-----------
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Mueve el objeto el offset indicado.
|
||||||
|
*/
|
||||||
|
void Move(float x, float y);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Cambia el tamaño la cantidad indicada.
|
||||||
|
*/
|
||||||
|
void Resize(float x, float y);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Devuelve el rect que representa/ocupa el objeto.
|
||||||
|
*/
|
||||||
|
SDL_Rect GetTransformRect();
|
||||||
|
|
||||||
|
|
||||||
|
protected:
|
||||||
|
//Almacenamos la posición y el tamaño del objeto. Esto representa un SDL_Rect.
|
||||||
|
glm::vec<2, float> _pos;
|
||||||
|
glm::vec<2, float> _size;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,16 +1,34 @@
|
|||||||
#include "Camera.h"
|
#include "Camera.h"
|
||||||
#include "Logging/Logger.h"
|
#include "Logging/Logger.h"
|
||||||
|
|
||||||
|
#include <SDL_rect.h>
|
||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
glm::vec2 Camera::WorldToSreenCoords(glm::vec<2, float> worldCoord)
|
||||||
void Camera::SetCamPosition(int posX, int posY)
|
|
||||||
{
|
{
|
||||||
camPosition.x = posX;
|
//Convertimos las coordenas de WorldCoords a ScreenCoords relativas a la camPosition.
|
||||||
camPosition.y = posY;
|
glm::ivec2 fPos = worldCoord - _pos;
|
||||||
|
|
||||||
UE_LOG_TRACE("Cam position chaged to: {0}x{1}", posX, posY);
|
return fPos;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
glm::vec2 Camera::ScreenToWorldCoords(glm::vec<2, float> screenCoord)
|
||||||
|
{
|
||||||
|
//Convertimos las coordenas de ScreenCoords a WorldCoords relativas a la camPosition.
|
||||||
|
glm::ivec2 fPos = screenCoord + _pos;
|
||||||
|
|
||||||
|
return fPos;
|
||||||
|
}
|
||||||
|
|
||||||
|
SDL_Rect Camera::WorldToScreenRect(SDL_Rect worldRect)
|
||||||
|
{
|
||||||
|
return SDL_Rect();
|
||||||
|
}
|
||||||
|
|
||||||
|
SDL_Rect Camera::ScreenToWorldRect(SDL_Rect screenRect)
|
||||||
|
{
|
||||||
|
return SDL_Rect();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -2,32 +2,55 @@
|
|||||||
|
|
||||||
#include <glm/vec2.hpp>
|
#include <glm/vec2.hpp>
|
||||||
|
|
||||||
|
#include "Interfaces/Transformable.h"
|
||||||
|
|
||||||
//
|
//
|
||||||
// ToDO:
|
// ToDO:
|
||||||
// - La cámara debería tener un tamaño definido.
|
// - La cámara debería tener un tamaño definido.
|
||||||
// para hacer zoom y esas cosas.
|
// para hacer zoom y esas cosas.
|
||||||
|
// - Pasará a utilizar transformable para almacenar su posición y su tamaño.
|
||||||
//
|
//
|
||||||
|
|
||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
class Camera
|
class Camera : public Transformable
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
|
|
||||||
Camera() {}
|
Camera() {}
|
||||||
|
|
||||||
Camera(int posX, int posY)
|
Camera(int posX, int posY)
|
||||||
: camPosition{posX, posY}
|
{
|
||||||
{}
|
_pos = { posX, posY };
|
||||||
|
}
|
||||||
|
|
||||||
inline glm::ivec2 GetCamPosition() { return camPosition; }
|
Camera(int posX, int posY, int sizeX, int sizeY)
|
||||||
void SetCamPosition(int posX, int posY);
|
{
|
||||||
|
_pos = { posX, posY };
|
||||||
|
_size = { sizeX, sizeY };
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
/* Métodos para transformar y proyectar coordenadas en función de la Camera. */
|
||||||
|
//WorldCoords = ScreenPos + CamPos -> ScreenPos = WorldCoords - CamPos;
|
||||||
|
|
||||||
|
//Proyecta las coordenadas de mundo a coordenadas de pantalla.
|
||||||
|
glm::vec2 WorldToSreenCoords(glm::vec<2, float> worldCoord);
|
||||||
|
|
||||||
|
//Proyecta coordenadas de pantalla al mundo.
|
||||||
|
glm::vec2 ScreenToWorldCoords(glm::vec<2, float> screenCoord);
|
||||||
|
|
||||||
|
|
||||||
|
SDL_Rect WorldToScreenRect(SDL_Rect worldRect);
|
||||||
|
SDL_Rect ScreenToWorldRect(SDL_Rect screenRect);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
glm::ivec2 camPosition { 0, 0 };
|
|
||||||
|
|
||||||
//glm::ivec2 camSize { 0, 0 };
|
//glm::ivec2 camSize { 0, 0 };
|
||||||
|
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
namespace UE
|
|
||||||
{
|
|
||||||
class Renderer;
|
|
||||||
|
|
||||||
class Drawable
|
|
||||||
{
|
|
||||||
|
|
||||||
public:
|
|
||||||
Drawable() {}
|
|
||||||
virtual ~Drawable() {};
|
|
||||||
|
|
||||||
//Get-Set del renderLayer.
|
|
||||||
inline void SetLayer(int newLayer) { _renderLayer = newLayer; }
|
|
||||||
inline int GetLayer() { return _renderLayer; }
|
|
||||||
|
|
||||||
public:
|
|
||||||
virtual void Draw(Renderer* renderer) = 0;
|
|
||||||
|
|
||||||
|
|
||||||
protected:
|
|
||||||
//renderLayer usada en el renderer como "profundidad".
|
|
||||||
int _renderLayer = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
|
|
||||||
|
|
||||||
#include "Renderer.h"
|
#include "Renderer.h"
|
||||||
|
#include "Assets/Texture.h"
|
||||||
#include "Logging/Logger.h"
|
#include "Logging/Logger.h"
|
||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
@@ -36,43 +37,42 @@ namespace UE
|
|||||||
SDL_SetRenderDrawColor(main_Renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
SDL_SetRenderDrawColor(main_Renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
||||||
|
|
||||||
|
|
||||||
#pragma region ImGui.
|
|
||||||
|
|
||||||
|
//Inicializamos Dear ImGui con el SDL_Renderer.
|
||||||
IMGUI_CHECKVERSION();
|
IMGUI_CHECKVERSION();
|
||||||
ImGui::CreateContext();
|
ImGui::CreateContext();
|
||||||
ImGuiIO& io = ImGui::GetIO();
|
ImGuiIO& io = ImGui::GetIO();
|
||||||
(void)io; //Evita que de un Warning por variable no usada.
|
(void)io; //Evita que de un Warning por variable no usada. Este C++ es demasiado avanzado.
|
||||||
|
|
||||||
ImGui::StyleColorsDark();
|
ImGui::StyleColorsDark();
|
||||||
|
|
||||||
ImGui_ImplSDL2_InitForSDLRenderer(_window, main_Renderer);
|
ImGui_ImplSDL2_InitForSDLRenderer(_window, main_Renderer);
|
||||||
ImGui_ImplSDLRenderer_Init(main_Renderer);
|
ImGui_ImplSDLRenderer_Init(main_Renderer);
|
||||||
|
|
||||||
#pragma endregion
|
|
||||||
|
|
||||||
|
|
||||||
//Init layers.
|
//Init layers for World Rendering.
|
||||||
for (int i = 0; i <= LAYER_AMOUNT; i++)
|
for (int i = 0; i <= LAYER_AMOUNT; i++)
|
||||||
{
|
{
|
||||||
renderLayers.push_back(std::vector<DrawCall>());
|
worldLayers.push_back(std::vector<Drawable*>());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Renderer::CleanRenderer()
|
void Renderer::CleanRenderer()
|
||||||
{
|
{
|
||||||
renderQueue.empty();
|
//Limpiamos ImGui
|
||||||
|
|
||||||
ImGui_ImplSDLRenderer_Shutdown();
|
ImGui_ImplSDLRenderer_Shutdown();
|
||||||
ImGui_ImplSDL2_Shutdown();
|
ImGui_ImplSDL2_Shutdown();
|
||||||
ImGui::DestroyContext();
|
ImGui::DestroyContext();
|
||||||
|
|
||||||
|
//Limpiamos SDL.
|
||||||
SDL_DestroyRenderer(main_Renderer);
|
SDL_DestroyRenderer(main_Renderer);
|
||||||
SDL_DestroyWindow(_window);
|
SDL_DestroyWindow(_window);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//NOTA No sé para qué sirve el método RenderFrame(), es privado. ¿Eliminar método?
|
||||||
void Renderer::RenderFrame()
|
void Renderer::RenderFrame()
|
||||||
{
|
{
|
||||||
NewFrame();
|
NewFrame();
|
||||||
@@ -89,51 +89,57 @@ namespace UE
|
|||||||
ImGui_ImplSDL2_NewFrame();
|
ImGui_ImplSDL2_NewFrame();
|
||||||
ImGui::NewFrame();
|
ImGui::NewFrame();
|
||||||
|
|
||||||
//Quiz�s deber�amos limpiar la cola y las Layers aqu� para eliminar residuos...
|
|
||||||
//callCounter = 0;
|
//Comprobamos que la cámara sigue existiendo.
|
||||||
//rendererCounter = 0;
|
if (activeCam == nullptr)
|
||||||
|
{
|
||||||
|
//Si no existe la cámara activa, utilizamos la por defecto.
|
||||||
|
ResetCamera();
|
||||||
|
}
|
||||||
|
|
||||||
//Actualizamos el rect que representa la pantalla.
|
//Actualizamos el rect que representa la pantalla.
|
||||||
glm::ivec2 camPos = activeCam->GetCamPosition();
|
glm::vec2 camPos = activeCam->GetPosition();
|
||||||
_screenRect = {camPos.x, camPos.y, screenSize.x, screenSize.y};
|
int x = camPos.x;
|
||||||
|
int y = camPos.y;
|
||||||
|
_screenRect = {x, y, screenSize.x, screenSize.y};
|
||||||
}
|
}
|
||||||
|
|
||||||
void Renderer::RenderData()
|
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.
|
//REWORK Probablemente sea más bonito separar en métodos el World Render del UI Render.
|
||||||
if (item.layer > LAYER_AMOUNT)
|
//Iterate world layers.
|
||||||
|
for (int j = 0; j < worldLayers.size(); j++)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("Error rendering data: Can't render item to Layer {0} -> out of range\n", item.layer);
|
//Extract layer j.
|
||||||
return;
|
std::vector<Drawable*>& layer = worldLayers.at(j);
|
||||||
}
|
|
||||||
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.
|
//Render items from layer j.
|
||||||
for (int k = 0; k < layer.size(); k++)
|
for (int k = 0; k < layer.size(); k++)
|
||||||
{
|
{
|
||||||
DrawCall item = layer.at(k);
|
//Extract Drawable k
|
||||||
if (item.fullTexture)
|
Drawable* item = layer.at(k);
|
||||||
{
|
|
||||||
SDL_RenderCopy(main_Renderer, item.tx, NULL, &item.pos_rect);
|
// FIX: Cuando la tx sea nullptr o salte except. -> Log y usar default tx.
|
||||||
continue;
|
// En definitiva, añadir seguridad aquí, se puede usar la tx default.
|
||||||
}
|
SDL_Texture* tx = item->_tx->GetTexture();
|
||||||
SDL_RenderCopy(main_Renderer, item.tx, &item.tx_rect, &item.pos_rect);
|
|
||||||
|
//Los están en WorldCoords. Convertimos la posición a ScreenCoords.
|
||||||
|
// NOTA: Se deberá transformar todo el Rect en función de la cam, no sólo la pos.
|
||||||
|
glm::ivec2 screenCoords = activeCam->WorldToSreenCoords(item->_pos);
|
||||||
|
SDL_Rect screenRect = { screenCoords.x, screenCoords.y, item->_size.x, item->_size.y };
|
||||||
|
|
||||||
|
//Le pasamos todo al SDL_Renderer.
|
||||||
|
SDL_RenderCopy(main_Renderer, item->_tx->GetTexture(), &(item->_txRect), &screenRect);
|
||||||
}
|
}
|
||||||
layer.clear();
|
layer.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//Renderizado de ImGui.
|
||||||
|
ImGui::Render();
|
||||||
|
ImGui_ImplSDLRenderer_RenderDrawData(ImGui::GetDrawData());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Renderer::EndFrame()
|
void Renderer::EndFrame()
|
||||||
@@ -141,9 +147,6 @@ namespace UE
|
|||||||
//SDL_UpdateWindowSurface(window);
|
//SDL_UpdateWindowSurface(window);
|
||||||
//SDL_RenderPresent(main_Renderer);
|
//SDL_RenderPresent(main_Renderer);
|
||||||
//SDL_RenderClear(main_Renderer);
|
//SDL_RenderClear(main_Renderer);
|
||||||
ImGui::Render();
|
|
||||||
|
|
||||||
ImGui_ImplSDLRenderer_RenderDrawData(ImGui::GetDrawData());
|
|
||||||
|
|
||||||
SDL_RenderPresent(main_Renderer);
|
SDL_RenderPresent(main_Renderer);
|
||||||
|
|
||||||
@@ -151,6 +154,31 @@ namespace UE
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void Renderer::Render(Drawable& drawable)
|
||||||
|
{
|
||||||
|
drawable.Draw(this);
|
||||||
|
|
||||||
|
int layer = drawable.GetLayer();
|
||||||
|
|
||||||
|
//Check Layer.
|
||||||
|
if (layer > LAYER_AMOUNT)
|
||||||
|
{
|
||||||
|
UE_LOG_ERROR("Can't add DrawCall to Layer {0} -> out of range\n", layer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// FIX Comprobamos si el objeto es visible.
|
||||||
|
// if(!IsObjectVisible(&drawCall.pos_rect))
|
||||||
|
// {
|
||||||
|
// //Si no es visible, no lo renderizaríamos.
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
//SDL_Texture* tx = drawable._tx->GetTexture();
|
||||||
|
|
||||||
|
|
||||||
|
//Add Item to Layer for being rendered.
|
||||||
|
worldLayers.at(layer).push_back(&drawable);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -170,24 +198,7 @@ namespace UE
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//CREO QUE ESTE MÉTODO NO FUNCIONA.
|
||||||
glm::ivec2 Renderer::WorldToSreenCoords(glm::ivec2 worldCoord)
|
|
||||||
{
|
|
||||||
//Convertimos las coordenas de WorldCoords a ScreenCoords relativas a la camPosition.
|
|
||||||
glm::ivec2 fPos = worldCoord - activeCam->GetCamPosition();
|
|
||||||
|
|
||||||
return fPos;
|
|
||||||
}
|
|
||||||
|
|
||||||
glm::ivec2 Renderer::ScreenToWorldCoords(glm::ivec2 screenCoord)
|
|
||||||
{
|
|
||||||
//Convertimos las coordenas de ScreenCoords a WorldCoords relativas a la camPosition.
|
|
||||||
glm::ivec2 fPos = screenCoord + activeCam->GetCamPosition();
|
|
||||||
|
|
||||||
return fPos;
|
|
||||||
}
|
|
||||||
|
|
||||||
//CREO QUE ESTE M�TODO NO FUNCIONA.
|
|
||||||
//LAS COORDS QUE USAMOS EN LA COMPROBACI�N NO SON LAS ADECUADAS.
|
//LAS COORDS QUE USAMOS EN LA COMPROBACI�N NO SON LAS ADECUADAS.
|
||||||
bool Renderer::IsObjectVisible(SDL_Rect* objectRect)
|
bool Renderer::IsObjectVisible(SDL_Rect* objectRect)
|
||||||
{
|
{
|
||||||
@@ -209,45 +220,4 @@ namespace UE
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
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.
|
|
||||||
// if(!IsObjectVisible(&drawCall.pos_rect))
|
|
||||||
// {
|
|
||||||
// //Si no es visible, no lo renderizaríamos.
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
|
|
||||||
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)
|
|
||||||
{
|
|
||||||
//std::cout << "Drawable added to queue";
|
|
||||||
DrawCall dc = DrawCall(layer, position, texture);
|
|
||||||
QueueDrawCall(dc);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Renderer::Render(Drawable& drawable)
|
|
||||||
{
|
|
||||||
drawable.Draw(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -7,12 +7,11 @@
|
|||||||
#include <SDL.h>
|
#include <SDL.h>
|
||||||
#include <glm/vec2.hpp>
|
#include <glm/vec2.hpp>
|
||||||
|
|
||||||
#include "Drawable.h"
|
#include "Drawables/Drawable.h"
|
||||||
#include "Camera.h"
|
#include "Camera.h"
|
||||||
|
|
||||||
//
|
//
|
||||||
// TODO:
|
// TODO Renderer:
|
||||||
// - Optimizar RenderDraw moviendo la ordenaci�n por capas a Queue, quitando renderQueue.
|
|
||||||
// - Limpiar las funciones moviendo c�digo a otras funciones.
|
// - Limpiar las funciones moviendo c�digo a otras funciones.
|
||||||
// - �Podr�a moverse todo a static? De esta forma, ya no har�an falta instancias.
|
// - �Podr�a moverse todo a static? De esta forma, ya no har�an falta instancias.
|
||||||
//
|
//
|
||||||
@@ -20,9 +19,6 @@
|
|||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
struct DrawCall;
|
|
||||||
|
|
||||||
|
|
||||||
class Renderer
|
class Renderer
|
||||||
{
|
{
|
||||||
|
|
||||||
@@ -36,72 +32,127 @@ namespace UE
|
|||||||
{
|
{
|
||||||
screenSize.x = windowWidth;
|
screenSize.x = windowWidth;
|
||||||
screenSize.y = windowHeight;
|
screenSize.y = windowHeight;
|
||||||
|
activeCam = &defaultCam;
|
||||||
//UE_LOG_INFO("Game Renderer Created.");
|
//UE_LOG_INFO("Game Renderer Created.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
/* Inicializa los componentes necesarios:
|
/* Inicializa los componentes necesarios:
|
||||||
- Inicializa SDL
|
|
||||||
- Crea la ventana.
|
- Crea la ventana.
|
||||||
- Crea el renderer.
|
- Crea el renderer.
|
||||||
- ...
|
- Inicia ImGUI.
|
||||||
|
- Genera las layers.
|
||||||
*/
|
*/
|
||||||
int InitRenderer();
|
int InitRenderer();
|
||||||
|
|
||||||
/* Limpia todo antes de salir. */
|
/* Limpia todo antes de salir.
|
||||||
|
* - Apaga ImGui.
|
||||||
|
* - Destruye el renderer.
|
||||||
|
* - Destruye la ventana.
|
||||||
|
*/
|
||||||
void CleanRenderer();
|
void CleanRenderer();
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//Hace el SDL_RenderClear() para limpiar el buffer al principio de un nuevo frame.
|
/*
|
||||||
|
* Hace el SDL_RenderClear() para limpiar el buffer al principio de un nuevo frame.
|
||||||
|
*/
|
||||||
void NewFrame();
|
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.
|
* Realiza el renderizado de los objetos.
|
||||||
|
* - Renderiza las layers.
|
||||||
|
* - Renderiza la UI.
|
||||||
|
* - Renderiza ImGui.
|
||||||
|
*/
|
||||||
void RenderData();
|
void RenderData();
|
||||||
|
|
||||||
|
|
||||||
//Hace el swap del render buffer (tras dibujar todos los objetos). Termina el renderizado.
|
/*
|
||||||
|
* Hace el swap del render buffer (tras dibujar todos los objetos).
|
||||||
|
* Termina el renderizado.
|
||||||
|
*/
|
||||||
void EndFrame();
|
void EndFrame();
|
||||||
|
|
||||||
|
|
||||||
//A�ade un DrawCall al renderQueue.
|
/*
|
||||||
void QueueDrawCall(DrawCall drawCall);
|
* Rendiriza el Objeto indicado.
|
||||||
void QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position);
|
* El proceso consta de dos partes:
|
||||||
void QueueDrawCall(int layer, SDL_Rect & position, SDL_Texture* texture);
|
* - 1º: El objeto hará las modificaciones necesarias a sus datos.
|
||||||
|
* - 2º: El Renderer extraerá los datos de Drawable y lo renderizará.
|
||||||
//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);
|
void Render(Drawable& drawable);
|
||||||
|
|
||||||
/* Get SDL Renderer. */
|
|
||||||
SDL_Renderer* GetSDLRenderer() { return main_Renderer; }
|
|
||||||
|
|
||||||
|
///////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
/* Get SDL Renderer. */
|
||||||
|
inline SDL_Renderer* GetSDLRenderer() { return main_Renderer; }
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get windows/screen size.
|
||||||
|
*/
|
||||||
inline glm::ivec2 GetScreenSize() { return screenSize; }
|
inline glm::ivec2 GetScreenSize() { return screenSize; }
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Permite cambiar el tamaño de la ventana.
|
||||||
|
* REWORK: Hay que mirar los métodos de SDL y aprender cómo funcionan las ventanas.
|
||||||
|
* Quizás, incluso, abstraer la ventana a su propia clase para facilitar Fullscreen y esas cosas.
|
||||||
|
*/
|
||||||
void SetScreenSize(int newWidth, int newHeight);
|
void SetScreenSize(int newWidth, int newHeight);
|
||||||
|
|
||||||
//Permite cambiar el color de fondo.
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Cambiar el color del fondo.
|
||||||
|
*/
|
||||||
void SetDrawingColor(SDL_Color& newColor);
|
void SetDrawingColor(SDL_Color& newColor);
|
||||||
|
|
||||||
//Cambia la cámara que se utiliza en el renderizado.
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Set the active cámera.
|
||||||
|
*/
|
||||||
inline void SetCamera(Camera* newCam) { activeCam = newCam; }
|
inline void SetCamera(Camera* newCam) { activeCam = newCam; }
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get a ptr to the active camera.
|
||||||
|
*/
|
||||||
inline Camera* GetCamera() { return activeCam; }
|
inline Camera* GetCamera() { return activeCam; }
|
||||||
|
|
||||||
|
|
||||||
/* M�todos para transformar las coordenadas entre Screen y Wolrd. */
|
/*
|
||||||
//WorldCoords = ScreenPos + CamPos -> ScreenPos = WorldCoords - CamPos;
|
* Cambia la cámara activa a la cámara por defecto.
|
||||||
|
* Utilizado el eliminar una cámara o cuando la activeCam ya no existe.
|
||||||
|
*/
|
||||||
|
inline void ResetCamera() { activeCam = &defaultCam; }
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
//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.
|
//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.
|
//Usada para saber si un objeto se deber�a de renderizar o no.
|
||||||
bool IsObjectVisible(SDL_Rect* objectRect);
|
bool IsObjectVisible(SDL_Rect* objectRect);
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//DEBUG
|
//DEBUG
|
||||||
//Funci�n para renderizar un objeto un objeto en concreto directamente en el SDL_Renderer.
|
//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);
|
void DrawObject(SDL_Rect* position, SDL_Rect* texture_pos, SDL_Texture* texture);
|
||||||
@@ -110,36 +161,42 @@ namespace UE
|
|||||||
private:
|
private:
|
||||||
//Realizar RenderClear(), RenderDraw() y RenderUpdate();
|
//Realizar RenderClear(), RenderDraw() y RenderUpdate();
|
||||||
//Es decir, todo lo necesario para renderizar un frame.
|
//Es decir, todo lo necesario para renderizar un frame.
|
||||||
|
//NOTA RenderFrame() es privado, por lo que no puede ser usado. En el renderer, tampoco se usa.
|
||||||
void RenderFrame();
|
void RenderFrame();
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
/* Objetos de SDL para el rendering. */
|
/* Objetos de SDL para el rendering. */
|
||||||
|
|
||||||
SDL_Window* _window = nullptr;
|
SDL_Window* _window = nullptr;
|
||||||
SDL_Surface* screenSurface = nullptr;
|
SDL_Surface* screenSurface = nullptr;
|
||||||
SDL_Renderer* main_Renderer = nullptr;
|
SDL_Renderer* main_Renderer = 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.
|
//Las capas en las que se organizan los diferentes objetos.
|
||||||
//Permite dibujar unos sprites sobre otros.
|
//Permite dibujar unos sprites sobre otros.
|
||||||
const int LAYER_AMOUNT = 10;
|
const int LAYER_AMOUNT = 10;
|
||||||
std::vector<std::vector<DrawCall>> renderLayers;
|
std::vector<std::vector<Drawable*>> worldLayers;
|
||||||
|
|
||||||
|
|
||||||
//int screenWidth = 640;
|
////////////////////////////////////////////////////////
|
||||||
//int screenHeight = 480;
|
|
||||||
|
|
||||||
glm::ivec2 screenSize{ 640,480 };
|
glm::ivec2 screenSize{ 640,480 };
|
||||||
|
|
||||||
|
SDL_Rect _screenRect{ 0, 0, screenSize.x, screenSize.y };
|
||||||
|
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
//glm::ivec2 camPosition{ 0,0 };
|
//glm::ivec2 camPosition{ 0,0 };
|
||||||
Camera* activeCam;
|
Camera* activeCam;
|
||||||
|
Camera defaultCam = Camera(0, 0);
|
||||||
|
|
||||||
SDL_Rect _screenRect{ 0, 0, screenSize.x, screenSize.y};
|
|
||||||
|
|
||||||
|
|
||||||
//DEBUG
|
//DEBUG
|
||||||
@@ -148,37 +205,4 @@ namespace UE
|
|||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/*
|
|
||||||
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)
|
|
||||||
{}
|
|
||||||
|
|
||||||
DrawCall(int layer,
|
|
||||||
SDL_Rect position,
|
|
||||||
SDL_Texture* texture)
|
|
||||||
: layer(layer), tx(texture), pos_rect(position)
|
|
||||||
{
|
|
||||||
tx_rect = SDL_Rect();
|
|
||||||
fullTexture = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
int layer;
|
|
||||||
|
|
||||||
bool fullTexture = false;
|
|
||||||
|
|
||||||
SDL_Texture* tx;
|
|
||||||
SDL_Rect tx_rect;
|
|
||||||
|
|
||||||
SDL_Rect pos_rect;
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include <glm/vec2.hpp>
|
|
||||||
|
|
||||||
namespace UE
|
|
||||||
{
|
|
||||||
/*
|
|
||||||
Clase que contiene lo necesario para crear un objeto con posici�n en el espacio y modificarlo.
|
|
||||||
*/
|
|
||||||
class Transformable
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
|
|
||||||
|
|
||||||
//-----------
|
|
||||||
//- Setters -
|
|
||||||
//-----------
|
|
||||||
|
|
||||||
|
|
||||||
//Modifica la posici�n del Objeto.
|
|
||||||
inline void SetPosition(float x, float y) { _pos = glm::vec<2, float>(x, y); }
|
|
||||||
inline void SetPosition(glm::vec<2, float> newPosition) { _pos = newPosition; }
|
|
||||||
|
|
||||||
//Modifica la escala de Objeto.
|
|
||||||
inline void SetSize(float x, float y) { _size = glm::vec<2, float>(x, y); }
|
|
||||||
inline void SetSize(glm::vec<2, float> newSize) { _size = newSize; }
|
|
||||||
|
|
||||||
//-----------
|
|
||||||
//- Getters -
|
|
||||||
//-----------
|
|
||||||
|
|
||||||
inline glm::vec2 GetPosition() { return _pos; }
|
|
||||||
inline glm::vec2 GetSize() { return _size; }
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
protected:
|
|
||||||
//Se almacena la posici�n y el tama�o del objeto. Con esto se puede crear un SDL_Rect.
|
|
||||||
glm::vec<2, float> _pos;
|
|
||||||
glm::vec<2, float> _size;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -3,10 +3,7 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
///
|
|
||||||
/// TODO:
|
|
||||||
///
|
|
||||||
///
|
|
||||||
union SDL_Event;
|
union SDL_Event;
|
||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
|
|||||||
@@ -9,8 +9,13 @@
|
|||||||
//
|
//
|
||||||
// TODO:
|
// TODO:
|
||||||
// - Se podría plantear un sistema de carga asincrona para las escenas.
|
// - Se podría plantear un sistema de carga asincrona para las escenas.
|
||||||
|
// - Añadir un método para recargar la escena actual. La descarga entera y la vuelve a cargar.
|
||||||
// - La variable "loaded" de las escenas no tiene mucha utilidad en este momento.
|
// - La variable "loaded" de las escenas no tiene mucha utilidad en este momento.
|
||||||
|
|
||||||
|
|
||||||
|
// ERROR SceneLoader: No se hace bien la carga y descarga de escenas. No parece estar limpiándose la memoria.
|
||||||
|
// Parece que no funciona lo de no recargar la escena en la que estás.
|
||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
|
||||||
@@ -41,7 +46,7 @@ namespace UE
|
|||||||
* Carga una nueva escena.
|
* Carga una nueva escena.
|
||||||
* Se almacena en la lista de escenas cargadas.
|
* Se almacena en la lista de escenas cargadas.
|
||||||
* Para cambiar de escena, usar SwitchScene();
|
* Para cambiar de escena, usar SwitchScene();
|
||||||
* Si la escena ya estuvise cargada, se descargará la anterior y se cargará la nueva.
|
* Si la escena ya estuvise cargada, se descargará la anterior y se cargará la nueva, siempre que no sea la activa.
|
||||||
*/
|
*/
|
||||||
void LoadScene(Scene* sceneToLoad);
|
void LoadScene(Scene* sceneToLoad);
|
||||||
|
|
||||||
|
|||||||
+9
-8
@@ -14,6 +14,7 @@
|
|||||||
#include "Scenes/MainScene.hpp"
|
#include "Scenes/MainScene.hpp"
|
||||||
#include "Scenes/TestScene2.hpp"
|
#include "Scenes/TestScene2.hpp"
|
||||||
|
|
||||||
|
|
||||||
static bool _quit = false;
|
static bool _quit = false;
|
||||||
|
|
||||||
int Init();
|
int Init();
|
||||||
@@ -149,27 +150,27 @@ void Loop()
|
|||||||
UE::Camera* cam = UE_Renderer->GetCamera();
|
UE::Camera* cam = UE_Renderer->GetCamera();
|
||||||
if (keyStates[SDL_SCANCODE_W])
|
if (keyStates[SDL_SCANCODE_W])
|
||||||
{
|
{
|
||||||
glm::ivec2 camPos = cam->GetCamPosition();
|
glm::ivec2 camPos = cam->GetPosition();
|
||||||
camPos.y -= 5;
|
camPos.y -= 5;
|
||||||
cam->SetCamPosition(camPos.x, camPos.y);
|
cam->SetPosition(camPos.x, camPos.y);
|
||||||
}
|
}
|
||||||
if (keyStates[SDL_SCANCODE_S])
|
if (keyStates[SDL_SCANCODE_S])
|
||||||
{
|
{
|
||||||
glm::ivec2 camPos = cam->GetCamPosition();
|
glm::ivec2 camPos = cam->GetPosition();
|
||||||
camPos.y += 5;
|
camPos.y += 5;
|
||||||
cam->SetCamPosition(camPos.x, camPos.y);
|
cam->SetPosition(camPos.x, camPos.y);
|
||||||
}
|
}
|
||||||
if (keyStates[SDL_SCANCODE_D])
|
if (keyStates[SDL_SCANCODE_D])
|
||||||
{
|
{
|
||||||
glm::ivec2 camPos = cam->GetCamPosition();
|
glm::ivec2 camPos = cam->GetPosition();
|
||||||
camPos.x += 5;
|
camPos.x += 5;
|
||||||
cam->SetCamPosition(camPos.x, camPos.y);
|
cam->SetPosition(camPos.x, camPos.y);
|
||||||
}
|
}
|
||||||
if (keyStates[SDL_SCANCODE_A])
|
if (keyStates[SDL_SCANCODE_A])
|
||||||
{
|
{
|
||||||
glm::ivec2 camPos = cam->GetCamPosition();
|
glm::ivec2 camPos = cam->GetPosition();
|
||||||
camPos.x -= 5;
|
camPos.x -= 5;
|
||||||
cam->SetCamPosition(camPos.x, camPos.y);
|
cam->SetPosition(camPos.x, camPos.y);
|
||||||
}
|
}
|
||||||
|
|
||||||
currentScene->SceneUpdate();
|
currentScene->SceneUpdate();
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ public:
|
|||||||
|
|
||||||
UE::Sprite bg(as->getTexture("bg1"), 1, 0, glm::vec2(0, 0), UE::Engine::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));
|
UE::Sprite mapSP(as->getTexture("PruebaMap"), 1, 2, glm::vec2(50, 45), glm::vec2(145, 145));
|
||||||
|
|
||||||
|
|
||||||
sprites.push_back(sp1);
|
sprites.push_back(sp1);
|
||||||
@@ -63,8 +63,10 @@ public:
|
|||||||
|
|
||||||
UE::TextBox text1(OP_Regular);
|
UE::TextBox text1(OP_Regular);
|
||||||
//UE::TextBox text2(OP_Bold, "Otro texto");
|
//UE::TextBox text2(OP_Bold, "Otro texto");
|
||||||
|
//UE::TextBox(OP_Regular)
|
||||||
|
|
||||||
texts.push_back(text1);
|
texts.push_back(text1); //Copiamos el text1.
|
||||||
|
//texts.emplace_back(OP_Regular); //Construimos el text1.
|
||||||
//texts.push_back(text2);
|
//texts.push_back(text2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ public:
|
|||||||
glm::vec2 size(100, 100);
|
glm::vec2 size(100, 100);
|
||||||
glm::vec2 pos = size * i;
|
glm::vec2 pos = size * i;
|
||||||
|
|
||||||
UE::Sprite sp(tx, rand()%5, 1, pos, size);
|
UE::Sprite sp(tx, (rand()%4)+1, 1, pos, size);
|
||||||
sprites.push_back(sp);
|
sprites.push_back(sp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,7 +90,7 @@ public:
|
|||||||
{
|
{
|
||||||
UE::Renderer* rend = UE::Engine::GetRenderer();
|
UE::Renderer* rend = UE::Engine::GetRenderer();
|
||||||
glm::ivec2 mPos(event->button.x, event->button.y);
|
glm::ivec2 mPos(event->button.x, event->button.y);
|
||||||
glm::ivec2 wPos = rend->ScreenToWorldCoords(mPos);
|
glm::ivec2 wPos = rend->GetCamera()->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);
|
GAME_LOG_TRACE("Posicion del raton: \n\tPantalla: {0}x{1}, Mundo: {2}x{3}: ", mPos.x, mPos.y, wPos.x, wPos.y);
|
||||||
ModificarSprite(wPos);
|
ModificarSprite(wPos);
|
||||||
}
|
}
|
||||||
@@ -112,10 +112,10 @@ private:
|
|||||||
for (int i = 0; i < sprites.size(); i++)
|
for (int i = 0; i < sprites.size(); i++)
|
||||||
{
|
{
|
||||||
UE::Sprite& sp = sprites.at(i);
|
UE::Sprite& sp = sprites.at(i);
|
||||||
SDL_Rect sp_Pos = sp.getPositionRect();
|
SDL_Rect sp_Pos = sp.GetTransformRect();
|
||||||
if (SDL_HasIntersection(&mouseRect, &sp_Pos))
|
if (SDL_HasIntersection(&mouseRect, &sp_Pos))
|
||||||
{
|
{
|
||||||
int i = rand() % 5;
|
int i = rand() % 4 +1;
|
||||||
sp.SetTextureRect(i);
|
sp.SetTextureRect(i);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -195,8 +195,8 @@ private:
|
|||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
const int vAmount = 10;
|
const int vAmount = 256;
|
||||||
const int hAmount = 10;
|
const int hAmount = 256;
|
||||||
|
|
||||||
|
|
||||||
std::vector<UE::Sprite> sprites = {};
|
std::vector<UE::Sprite> sprites = {};
|
||||||
|
|||||||
@@ -1,17 +1,5 @@
|
|||||||
{
|
{
|
||||||
"TexturePath": "resources/Sprites/Textures/Player.png",
|
"TexturePath": "resources/Sprites/Textures/Player.png",
|
||||||
"TextureRects": [
|
"TextureRects": [
|
||||||
{
|
|
||||||
"posX": 0,
|
|
||||||
"posY": 0,
|
|
||||||
"sizeX": 16,
|
|
||||||
"sizeY": 16
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"posX": 16,
|
|
||||||
"posY": 0,
|
|
||||||
"sizeX": 16,
|
|
||||||
"sizeY": 16
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,6 @@
|
|||||||
{
|
{
|
||||||
"TexturePath": "resources/Sprites/Textures/bc.png",
|
"TexturePath": "resources/Sprites/Textures/bc.png",
|
||||||
"TextureRects": [
|
"TextureRects": [
|
||||||
{
|
|
||||||
"posX": 0,
|
|
||||||
"posY": 0,
|
|
||||||
"sizeX": 320,
|
|
||||||
"sizeY": 240
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"posX": 80,
|
"posX": 80,
|
||||||
"posY": 60,
|
"posY": 60,
|
||||||
|
|||||||
Reference in New Issue
Block a user