Dawn/src/dawn/scene/components/display/TiledSprite.cpp

95 lines
2.4 KiB
C++

// Copyright (c) 2022 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include "TiledSprite.hpp"
#include "scene/SceneItem.hpp"
using namespace Dawn;
TiledSprite::TiledSprite(SceneItem *item) :
SceneItemComponent(item),
tile(-1),
tileset(nullptr),
meshHost(nullptr),
flip(TILED_SPRITE_FLIP_Y),
sizeType(TILED_SPRITE_SIZE_TYPE_SCALE),
size(1.0f)
{
}
std::vector<SceneItemComponent*> TiledSprite::getDependencies() {
if(this->meshHost == nullptr) {
this->meshHost = this->item->getComponent<QuadMeshHost>();
}
return {
this->meshHost
};
}
void TiledSprite::onStart() {
SceneItemComponent::onStart();
useEffect([&]{
if(this->meshHost == nullptr || this->tileset == nullptr) return;
auto tile = this->tileset->getTile(this->tile);
this->meshHost->uv0 = glm::vec2(
(((flag_t)this->flip) & TILED_SPRITE_FLIP_X) == 0 ? tile.uv0.x : tile.uv1.x,
(((flag_t)this->flip) & TILED_SPRITE_FLIP_Y) == 0 ? tile.uv0.y : tile.uv1.y
);
this->meshHost->uv1 = glm::vec2(
(((flag_t)this->flip) & TILED_SPRITE_FLIP_X) == 0 ? tile.uv1.x : tile.uv0.x,
(((flag_t)this->flip) & TILED_SPRITE_FLIP_Y) == 0 ? tile.uv1.y : tile.uv0.y
);
}, {
&this->tile,
&this->meshHost,
&this->tileset,
&this->flip
})();
useEffect([&]{
if(this->meshHost == nullptr || this->tileset == nullptr) return;
auto tile = this->tileset->getTile(this->tile);
glm::vec2 quadSize;
switch(this->sizeType) {
case TILED_SPRITE_SIZE_TYPE_SCALE: {
quadSize = glm::vec2(
this->tileset->getTileWidth(this->tile),
this->tileset->getTileHeight(this->tile)
) * (float_t)this->size;
break;
}
case TILED_SPRITE_SIZE_TYPE_WIDTH_RATIO: {
float_t rw = this->tileset->getTileHeight(this->tile) / this->tileset->getTileWidth(this->tile);
quadSize.x = (float_t)this->size;
quadSize.y = quadSize.x * rw;
break;
}
case TILED_SPRITE_SIZE_TYPE_HEIGHT_RATIO: {
float_t rh = this->tileset->getTileWidth(this->tile) / this->tileset->getTileHeight(this->tile);
quadSize.y = (float_t)this->size;
quadSize.x = quadSize.y * rh;
break;
}
default:
assertUnreachable();
}
this->meshHost->xy0 = -quadSize;
this->meshHost->xy1 = quadSize;
}, {
&this->tile,
&this->meshHost,
&this->tileset,
&this->size
})();
}