holesome/src/sprites/sprite_factory.cpp

98 lines
3.1 KiB
C++
Raw Normal View History

#include "sprite_factory.hpp"
#include "../texture_config.h"
#include "texture_manager.hpp"
std::shared_ptr<SingleSprite> SpriteFactory::createSingleSprite(const std::string& name, sf::Vector2f size)
{
// Get sprite config
auto sprite_config = all_sprites.find(name);
if (sprite_config == all_sprites.end())
{
LOG(ERROR) << "Sprite " << name << " not found. Could not create single sprite.";
return nullptr;
}
// Construct sprite
auto config = sprite_config->second;
// Construct simply from texture
if (!config.isFromSheet)
{
auto texture = TextureManager::getInstance()->getTexture(config.resourceName);
if (texture == nullptr)
{
LOG(ERROR) << "Texture " << config.resourceName << " not found. Could not create single sprite.";
return nullptr;
}
LOG(INFO) << "Creating single sprite from texture " << config.resourceName;
return std::make_shared<SingleSprite>(texture, size);
}
// Construct from sheet
auto sheet = createSheet(config.resourceName);
if (sheet == nullptr)
{
LOG(ERROR) << "Sheet " << config.resourceName << " not found. Could not create single sprite.";
return nullptr;
}
LOG(INFO) << "Creating single sprite from sheet " << config.resourceName;
auto sprite = sheet->getSprite(config.sheetIndex);
sprite->setSize(size);
return sprite;
}
std::shared_ptr<AnimatedSprite> SpriteFactory::createAnimatedSprite(const std::string& name, sf::Vector2f size)
{
// Get animation config
auto animation_config = all_animations.find(name);
if (animation_config == all_animations.end())
{
LOG(ERROR) << "Animation " << name << " not found. Could not create animated sprite.";
return nullptr;
}
// Construct animation
auto config = animation_config->second;
auto sheet = createSheet(config.sheetName);
if (sheet == nullptr)
{
LOG(ERROR) << "Sheet " << config.sheetName << " not found. Could not create animated sprite.";
return nullptr;
}
LOG(INFO) << "Creating animated sprite from sheet " << config.sheetName;
auto animation = sheet->getAnimation(config.startingSheetIndex, config.frameCount);
animation->frameDuration = config.frameDuration;
animation->setSize(size);
return animation;
}
std::shared_ptr<SpriteSheet> SpriteFactory::createSheet(const std::string& name)
{
// Get config
auto sheet_config = all_sheets.find(name);
if (sheet_config == all_sheets.end())
{
LOG(ERROR) << "Sheet " << name << " not found. Could not create sheet.";
return nullptr;
}
// Construct sheet
auto config = sheet_config->second;
auto texture = TextureManager::getInstance()->getTexture(config.textureName);
if (texture == nullptr)
{
LOG(ERROR) << "Texture " << config.textureName << " not found. Could not create sheet.";
return nullptr;
}
LOG(INFO) << "Creating sheet " << name;
return std::make_shared<SpriteSheet>(texture, config.columns, config.rows);
}