Dawn/src/dawnrpg/component/RPGEntity.cpp

79 lines
1.8 KiB
C++

// Copyright (c) 2024 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include "RPGEntity.hpp"
#include "scene/Scene.hpp"
#include "display/mesh/QuadMesh.hpp"
#include "asset/loader/TextureLoader.hpp"
#include "display/tileset/TilesetGrid.hpp"
using namespace Dawn;
void RPGEntity::onInit() {
const glm::vec2 size = { RPG_ENTITY_SIZE, RPG_ENTITY_SIZE };
const glm::vec2 position = -size;
mesh = std::make_shared<Mesh>();
mesh->createBuffers(QUAD_VERTICE_COUNT, QUAD_INDICE_COUNT);
QuadMesh::buffer(
mesh,
glm::vec4(position.x, position.y, size.x, size.y),
glm::vec4(0, 1.0f, 1, 0.75f),
0, 0, 0
);
getItem()->getComponent<MeshRenderer>()->mesh = mesh;
updateSprite();
}
void RPGEntity::onDispose() {
mesh = nullptr;
}
enum RPGEntityDirection RPGEntity::getFacingDirection() {
return facingDirection;
}
void RPGEntity::setFacingDirection(const enum RPGEntityDirection dir) {
if(facingDirection == dir) return;
facingDirection = dir;
updateSprite();
}
void RPGEntity::updateSprite() {
auto material = getItem()->getComponent<SimpleTexturedMaterial>();
struct TilesetGrid tileset(
3, 4,
material->getTexture()->getWidth(), material->getTexture()->getHeight(),
1, 1
);
int32_t row, col;
row = col = 0;
switch(this->facingDirection) {
case RPGEntityDirection::NORTH:
row = 0;
break;
case RPGEntityDirection::SOUTH:
row = 1;
break;
case RPGEntityDirection::WEST:
row = 2;
break;
case RPGEntityDirection::EAST:
row = 3;
break;
}
// Convert row/col to UV coordinates.
glm::vec4 tile = tileset.getTile(col, row);
tile = glm::vec4(tile.x, tile.w, tile.z, tile.y);// swap Y axis.
QuadMesh::bufferCoordinates(mesh, tile, 0);
}