feat: improved sprite rendering
parent
44a5d7e87c
commit
36637b1f8a
|
@ -1,12 +1,13 @@
|
|||
#include "sprite.hpp"
|
||||
#include "core/canvas_engine.hpp"
|
||||
#include "core/math/transform.hpp"
|
||||
#include "core/math/vector.hpp"
|
||||
#include <SDL2/SDL_render.h>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
|
||||
namespace ce {
|
||||
Sprite::Sprite(std::string name, std::string texture)
|
||||
Sprite::Sprite(std::string const &name, std::string texture)
|
||||
: Node2D(name) {
|
||||
std::optional<std::shared_ptr<Texture>> asset{CanvasEngine::get_singleton()->get_assets().get_asset<Texture>(texture)};
|
||||
if(asset.has_value())
|
||||
|
@ -23,15 +24,33 @@ void Sprite::_draw(SDL_Renderer *render, ce::Transform const &view_transform) {
|
|||
SDL_QueryTexture(this->texture->get(), NULL, NULL, &w, &h);
|
||||
Transform transform{this->get_global_transform() * view_transform};
|
||||
assert(transform.scale.x != 0 && transform.scale.y != 0); // !!!
|
||||
float fw{transform.scale.x * (w > h ? float(w) / float(h) : 1.f)};
|
||||
float fh{transform.scale.y * (w < h ? float(h) / float(w) : 1.f)};
|
||||
assert(fw != 0.f && fh != 0.f);
|
||||
ce::Vecf size{this->get_size()};
|
||||
size.scale(view_transform.scale);
|
||||
assert(size.x != 0.f && size.y != 0.f);
|
||||
//float fw(w), fh(h);
|
||||
SDL_Rect src{0, 0, w, h};
|
||||
SDL_FRect dst{transform.position.x - fw/2.f, transform.position.y - fh/2.f, fw, fh};
|
||||
SDL_Rect src{.x=0, .y=0, .w=w, .h=h};
|
||||
SDL_FRect dst{.x=transform.position.x - size.x/2.f, .y=transform.position.y - size.y/2.f, .w=size.x, .h=size.y};
|
||||
SDL_RenderCopyExF(render, this->texture->get(),
|
||||
&src, &dst,
|
||||
transform.rotation * 57.2958f,NULL,
|
||||
SDL_FLIP_NONE);
|
||||
}
|
||||
|
||||
void Sprite::set_texture(std::shared_ptr<Texture> texture) {
|
||||
this->texture = texture;
|
||||
}
|
||||
|
||||
std::shared_ptr<Texture> Sprite::get_texture() const {
|
||||
return this->texture;
|
||||
}
|
||||
|
||||
ce::Vecf Sprite::get_size() const {
|
||||
int w, h;
|
||||
SDL_QueryTexture(this->texture->get(), NULL, NULL, &w, &h);
|
||||
ce::Transform const &transform{this->get_global_transform()};
|
||||
return {
|
||||
transform.scale.x * (w < h ? float(w) / float(h) : 1.f),
|
||||
transform.scale.y * (w > h ? float(h) / float(w) : 1.f)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,8 +8,13 @@ namespace ce {
|
|||
class Sprite : public Node2D {
|
||||
std::shared_ptr<Texture> texture{nullptr};
|
||||
public:
|
||||
Sprite(std::string name, std::string texture);
|
||||
Sprite(std::string const &name, std::string texture);
|
||||
virtual void _draw(SDL_Renderer *render, ce::Transform const &view_transform) override;
|
||||
|
||||
void set_texture(std::shared_ptr<Texture> texture);
|
||||
std::shared_ptr<Texture> get_texture() const;
|
||||
|
||||
ce::Vecf get_size() const;
|
||||
};
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue