animation and lights moved to graphics

This commit is contained in:
Zed A. Shaw 2026-02-27 13:57:44 -05:00
parent 229ad2dd95
commit 86a9f815c1
30 changed files with 36 additions and 36 deletions

314
src/graphics/animation.cpp Normal file
View file

@ -0,0 +1,314 @@
#include "graphics/animation.hpp"
#include <memory>
#include <chrono>
#include "dbc.hpp"
#include "algos/rand.hpp"
#include <iostream>
#include <fstream>
#include "sound.hpp"
#include "components.hpp"
constexpr float SUB_FRAME_SENSITIVITY = 0.999f;
namespace animation {
using namespace std::chrono_literals;
std::vector<sf::IntRect> Animation::calc_frames() {
dbc::check(sequence.frames.size() == sequence.durations.size(), "sequence.frames.size() != sequence.durations.size()");
std::vector<sf::IntRect> frames;
for(int frame_i : sequence.frames) {
dbc::check(frame_i < sheet.frames, "frame index greater than sheet frames");
frames.emplace_back(
sf::Vector2i{sheet.frame_width * frame_i, 0}, // NOTE: one row only for now
sf::Vector2i{sheet.frame_width,
sheet.frame_height});
}
return frames;
}
void Animation::play() {
dbc::check(!playing, "can't call play while playing?");
sequence.current = 0;
sequence.subframe = 0.0f;
sequence.loop_count = 0;
playing = true;
sequence.timer.start();
sequence.INVARIANT();
}
void Animation::stop() {
playing = false;
sequence.timer.reset();
}
// need one for each kind of thing to animate
// NOTE: possibly find a way to only run apply on frame change?
void Animation::apply(sf::Sprite& sprite) {
dbc::check(sequence.current < $frame_rects.size(), "current frame past $frame_rects");
// NOTE: pos is not updated yet
auto& rect = $frame_rects.at(sequence.current);
sprite.setTextureRect(rect);
}
/*
* Alternative mostly used in raycaster.cpp that
* DOES NOT setTextureRect() but just points
* the rect_io at the correct frame, but leaves
* it's size and base position alone.
*/
void Animation::apply(sf::Sprite& sprite, sf::IntRect& rect_io) {
dbc::check(sequence.current < $frame_rects.size(), "current frame past $frame_rects");
auto& rect = $frame_rects.at(sequence.current);
rect_io.position.x += rect.position.x;
rect_io.position.y += rect.position.y;
}
void Animation::motion(sf::Transformable& sprite, sf::Vector2f pos, sf::Vector2f scale) {
sequence.INVARIANT();
transform.apply(sequence, pos, scale);
if(transform.flipped) {
scale.x *= -1;
}
sprite.setPosition(pos);
if(transform.scaled) {
sprite.setScale(scale);
}
}
void Animation::motion(sf::View& view_out, sf::Vector2f pos, sf::Vector2f size) {
dbc::check(size.x > 1.0f && size.y > 1.0f, "motion size must be above 1.0 since it's not a ratio");
dbc::check(transform.flipped == false, "transform must be false, has no effect on View");
sf::Vector2f scale{transform.min_x, transform.min_y};
transform.apply(sequence, pos, scale);
view_out.setCenter(pos);
if(transform.scaled) {
view_out.setSize({size.x * scale.x, size.y * scale.y});
} else {
view_out.setSize(size);
}
}
void Animation::apply_effect(std::shared_ptr<sf::Shader> effect) {
dbc::check(effect != nullptr, "can't apply null effect");
effect->setUniform("u_time", sequence.timer.getElapsedTime().asSeconds());
sf::Vector2f u_resolution{float(sheet.frame_width), float(sheet.frame_height)};
effect->setUniform("u_resolution", u_resolution);
}
void Animation::play_sound() {
// BUG: this can be optimized way better
if(sounds.contains(form_name)) {
for(auto& [at_frame, sound_name] : sounds.at(form_name)) {
if(sequence.current == at_frame) {
sound::play(sound_name);
}
}
} else {
fmt::println("Animation has not sound {}", form_name);
}
}
/* REFACTOR: I believe this is wrong still. If ::commit() determines number of ticks+alpha since last
* render then update needs to be called 1/tick. The Timer will keep track of alpha as the error
* between commit calls, so this function only really needs to care about ticks. But, I'm still
* calling getElapsedTime() when I already did that in commit(), so should I just ignore that and assume
* elapsed is DELTA, or use elapsed here?
*/
void Animation::update() {
dbc::check(playing, "attempt to update animation that's not playing");
sequence.INVARIANT();
auto [ticks, alpha] = sequence.timer.commit();
int duration = sequence.durations.at(sequence.current);
sequence.subframe += ticks;
sequence.easing_position += ticks;
bool frame_change = false;
if(sequence.subframe >= duration) {
sequence.timer.restart();
sequence.current++;
sequence.subframe = 0;
frame_change = true;
}
if(sequence.current >= sequence.frame_count) {
sequence.loop_count++;
sequence.easing_position = 0;
playing = onLoop(sequence, transform);
sequence.INVARIANT();
}
if(frame_change) play_sound();
if(frame_change && onFrame != nullptr) onFrame();
}
void Timer::start() {
clock.start();
prev_time = clock.getElapsedTime().asSeconds();
}
void Timer::reset() {
elapsed_ticks = 0;
clock.reset();
}
void Timer::restart() {
elapsed_ticks = 0;
clock.restart();
prev_time = clock.getElapsedTime().asSeconds();
}
sf::Time Timer::getElapsedTime() {
return clock.getElapsedTime();
}
std::pair<int, double> Timer::commit() {
// determine frame duration based on previous time
current_time = clock.getElapsedTime().asSeconds();
frame_duration = current_time - prev_time;
// update prev_time for the next call
prev_time = current_time;
// update accumulator, retaining previous errors
accumulator += frame_duration;
// find the tick count based on DELTA
double tick_count = floor(accumulator / DELTA);
// reduce accumulator by the number of DELTAS
accumulator -= tick_count * DELTA;
// that leaves the remaining errors for next loop
elapsed_ticks += tick_count;
// alpha is then what we lerp...but WHY?!
alpha = accumulator / DELTA;
// return the number of even DELTA ticks and the alpha
return {int(tick_count), alpha};
}
void Transform::apply(Sequence& seq, sf::Vector2f& pos_out, sf::Vector2f& scale_out) {
float tick = easing_func(seq.easing_position / seq.easing_duration);
motion_func(*this, pos_out, scale_out, tick, relative);
}
bool Animation::has_form(const std::string& as_form) {
return forms.contains(as_form);
}
void Animation::set_form(const std::string& as_form) {
dbc::check(forms.contains(as_form),
fmt::format("form {} does not exist in animation", as_form));
stop();
const auto& [seq_name, tr_name] = forms.at(as_form);
dbc::check(sequences.contains(seq_name),
fmt::format("sequences do NOT have \"{}\" name", seq_name));
dbc::check(transforms.contains(tr_name),
fmt::format("transforms do NOT have \"{}\" name", tr_name));
// everything good, do the update
form_name = as_form;
sequence_name = seq_name;
transform_name = tr_name;
sequence = sequences.at(seq_name);
transform = transforms.at(tr_name);
sequence.frame_count = sequence.frames.size();
// BUG: should this be configurable instead?
for(auto duration : sequence.durations) {
sequence.easing_duration += float(duration);
}
dbc::check(sequence.easing_duration > 0.0, "bad easing duration");
$frame_rects = calc_frames();
transform.easing_func = ease2::get_easing(transform.easing);
transform.motion_func = ease2::get_motion(transform.motion);
sequence.INVARIANT();
}
Animation load(const std::string &file, const std::string &anim_name) {
using nlohmann::json;
std::ifstream infile(file);
auto data = json::parse(infile);
dbc::check(data.contains(anim_name),
fmt::format("{} animation config does not have animation {}", file, anim_name));
Animation anim;
animation::from_json(data[anim_name], anim);
anim.name = anim_name;
dbc::check(anim.forms.contains("idle"),
fmt::format("animation {} must have 'idle' form", anim_name));
anim.set_form("idle");
return anim;
}
void Sequence::INVARIANT(const std::source_location location) {
dbc::check(frames.size() == durations.size(),
fmt::format("frames.size={} doesn't match durations.size={}",
frames.size(), durations.size()), location);
dbc::check(easing_duration > 0.0,
fmt::format("bad easing duration: {}", easing_duration), location);
dbc::check(frame_count == frames.size(),
fmt::format("frame_count={} doesn't match frames.size={}", frame_count, frames.size()), location);
dbc::check(frame_count == durations.size(),
fmt::format("frame_count={} doesn't match durations.size={}", frame_count, durations.size()), location);
dbc::check(current < durations.size(),
fmt::format("current={} went past end of fame durations.size={}",
current, durations.size()), location);
}
// BUG: BAAADD REMOVE
bool has(const std::string& name) {
using nlohmann::json;
std::ifstream infile("assets/animation.json");
auto data = json::parse(infile);
return data.contains(name);
}
void configure(DinkyECS::World& world, DinkyECS::Entity entity) {
auto sprite = world.get_if<components::Sprite>(entity);
if(sprite != nullptr && has(sprite->name)) {
world.set<Animation>(entity, animation::load("assets/animation.json", sprite->name));
}
}
void animate_entity(DinkyECS::World &world, DinkyECS::Entity entity) {
auto anim = world.get_if<Animation>(entity);
if(anim != nullptr && !anim->playing) {
anim->play();
}
}
}

150
src/graphics/animation.hpp Normal file
View file

@ -0,0 +1,150 @@
#pragma once
#include <memory>
#include <chrono>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Shader.hpp>
#include <SFML/Graphics/View.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/System/Time.hpp>
#include <functional>
#include "easing.hpp"
#include <fmt/core.h>
#include "json_mods.hpp"
#include <source_location>
#include "dinkyecs.hpp"
namespace animation {
template <typename T> struct NameOf;
struct Sheet {
int frames{0};
int frame_width{0};
int frame_height{0};
};
struct Timer {
double DELTA = 1.0/60.0;
double accumulator = 0.0;
double prev_time = 0.0;
double current_time = 0.0;
double frame_duration = 0.0;
double alpha = 0.0;
int elapsed_ticks = 0;
sf::Clock clock{};
std::pair<int, double> commit();
void start();
void reset();
void restart();
sf::Time getElapsedTime();
};
struct Sequence {
std::vector<int> frames{};
std::vector<int> durations{}; // in ticks
size_t current{0};
int loop_count{0};
size_t frame_count{frames.size()};
Timer timer{};
int subframe{0};
float easing_duration{0.0f};
float easing_position{0.0f};
void INVARIANT(const std::source_location location = std::source_location::current());
};
struct Transform {
// how to know when a transform ends?
float min_x{1.0f};
float min_y{1.0f};
float max_x{1.0f};
float max_y{1.0f};
bool flipped{false};
bool scaled{false};
bool relative{false};
// handled by onLoop
bool toggled{false};
bool looped{false};
std::string easing{"in_out_back"};
std::string motion{"move_rush"};
// change to using a callback function for these
ease2::EaseFunc easing_func{ease2::get_easing(easing)};
ease2::MotionFunc motion_func{ease2::get_motion(motion)};
std::shared_ptr<sf::Shader> shader{nullptr};
void apply(Sequence& seq, sf::Vector2f& pos_out, sf::Vector2f& scale_out);
};
/* Gets the number of times it looped, and returns if it should stop. */
using OnLoopHandler = std::function<bool(Sequence& seq, Transform& tr)>;
using OnFrameHandler = std::function<void()>;
inline bool DefaultOnLoop(Sequence& seq, Transform& tr) {
if(tr.toggled) {
seq.current = seq.frame_count - 1;
} else {
seq.current = 0;
}
return tr.looped;
}
using Form = std::pair<std::string, std::string>;
using Sound = std::pair<size_t, std::string>;
class Animation {
public:
Sheet sheet;
std::unordered_map<std::string, Sequence> sequences;
std::unordered_map<std::string, Transform> transforms;
std::unordered_map<std::string, Form> forms;
std::unordered_map<std::string, std::vector<Sound>> sounds;
OnFrameHandler onFrame = nullptr;
Sequence sequence{};
Transform transform{};
std::vector<sf::IntRect> $frame_rects{calc_frames()};
OnLoopHandler onLoop = DefaultOnLoop;
bool playing = false;
// mostly for debugging purposes
std::string form_name="idle";
std::string sequence_name="";
std::string transform_name="";
std::string name="";
std::vector<sf::IntRect> calc_frames();
void play();
void play_sound();
void stop();
bool has_form(const std::string& as_form);
void set_form(const std::string& form);
void apply(sf::Sprite& sprite);
void apply(sf::Sprite& sprite, sf::IntRect& rect_io);
void apply_effect(std::shared_ptr<sf::Shader> effect);
void update();
void motion(sf::Transformable& sprite, sf::Vector2f pos, sf::Vector2f scale);
void motion(sf::View& view_out, sf::Vector2f pos, sf::Vector2f scale);
};
Animation load(const std::string &file, const std::string &anim_name);
// BUG: brought over from animation to finish the refactor, but these may not be needed or maybe they go in system.cpp?
bool has(const std::string& name);
void configure(DinkyECS::World& world, DinkyECS::Entity entity);
void animate_entity(DinkyECS::World &world, DinkyECS::Entity entity);
ENROLL_COMPONENT(Sheet, frames, frame_width, frame_height);
ENROLL_COMPONENT(Sequence, frames, durations);
ENROLL_COMPONENT(Transform, min_x, min_y, max_x, max_y,
flipped, scaled, relative, toggled, looped, easing, motion);
ENROLL_COMPONENT(Animation, sheet, sequences, transforms, forms, sounds);
}

87
src/graphics/lights.cpp Normal file
View file

@ -0,0 +1,87 @@
#include "graphics/lights.hpp"
#include "constants.hpp"
#include "graphics/textures.hpp"
#include <vector>
using std::vector;
namespace lighting {
LightRender::LightRender(Matrix& tiles) :
$width(matrix::width(tiles)),
$height(matrix::height(tiles)),
$lightmap(matrix::make($width, $height)),
$ambient(matrix::make($width, $height)),
$paths($width, $height),
$fow(matrix::make($width, $height))
{
auto& tile_ambient = textures::get_ambient_light();
for(matrix::each_cell it{tiles}; it.next();) {
size_t tile_id = tiles[it.y][it.x];
$ambient[it.y][it.x] = MIN + tile_ambient[tile_id];
}
}
void LightRender::render_square_light(LightSource source, Point at, PointList &has_light) {
for(matrix::box it{$lightmap, at.x, at.y, (size_t)floor(source.radius)}; it.next();) {
if($paths.$paths[it.y][it.x] != WALL_PATH_LIMIT) {
$lightmap[it.y][it.x] = light_level(source.strength, it.distance(), it.x, it.y);
has_light.emplace_back(it.x, it.y);
}
}
}
/*
* NOTE: This really doesn't need to calculate light all the time. It doesn't
* change around the light source until the lightsource is changed, so the
* light levels could be placed in a Matrix inside LightSource, calculated once
* and then simply "applied" to the area where the entity is located. The only
* thing that would need to be calculated each time is the walls.
*/
void LightRender::render_light(LightSource source, Point at) {
clear_light_target(at);
PointList has_light;
render_square_light(source, at, has_light);
for(auto point : has_light) {
for(matrix::compass it{$lightmap, point.x, point.y}; it.next();) {
if($paths.$paths[it.y][it.x] == WALL_PATH_LIMIT) {
$lightmap[it.y][it.x] = light_level(source.strength, 1.5f, point.x, point.y);
}
}
}
}
int LightRender::light_level(int strength, float distance, size_t x, size_t y) {
int boosted = strength + BOOST;
int new_level = distance <= 1.0f ? boosted : boosted / sqrt(distance);
int cur_level = $lightmap[y][x];
return cur_level < new_level ? new_level : cur_level;
}
void LightRender::reset_light() {
$lightmap = $ambient;
}
void LightRender::clear_light_target(const Point &at) {
$paths.clear_target(at);
}
void LightRender::set_light_target(const Point &at, int value) {
$paths.set_target(at, value);
}
void LightRender::update_fow(Point at, LightSource source) {
for(matrix::circle it{$lightmap, at, source.radius}; it.next();) {
for(auto x = it.left; x < it.right; x++) {
$fow[it.y][x] = $lightmap[it.y][x];
}
}
}
void LightRender::path_light(Matrix &walls) {
$paths.compute_paths(walls);
}
}

40
src/graphics/lights.hpp Normal file
View file

@ -0,0 +1,40 @@
#pragma once
#include <array>
#include "dbc.hpp"
#include "point.hpp"
#include <algorithm>
#include "algos/matrix.hpp"
#include "algos/pathing.hpp"
#include "components.hpp"
namespace lighting {
using components::LightSource;
// THESE ARE PERCENTAGES!
const int MIN = 20;
const int BOOST = 10;
class LightRender {
public:
size_t $width;
size_t $height;
Matrix $lightmap;
Matrix $ambient;
Pathing $paths;
matrix::Matrix $fow;
LightRender(Matrix& walls);
void reset_light();
void set_light_target(const Point &at, int value=0);
void clear_light_target(const Point &at);
void path_light(Matrix &walls);
void light_box(LightSource source, Point from, Point &min_out, Point &max_out);
int light_level(int level, float distance, size_t x, size_t y);
void render_light(LightSource source, Point at);
void render_square_light(LightSource source, Point at, PointList &has_light);
void update_fow(Point player_pos, LightSource source);
Matrix &lighting() { return $lightmap; }
Matrix &paths() { return $paths.paths(); }
};
}

189
src/graphics/scene.cpp Normal file
View file

@ -0,0 +1,189 @@
#include "graphics/scene.hpp"
#include "graphics/animation.hpp"
#include "graphics/shaders.hpp"
#include <fmt/core.h>
#include "dbc.hpp"
const bool DEBUG=false;
namespace scene {
Element Engine::config_scene_element(nlohmann::json& config, bool duped) {
std::string sprite_name = config["sprite"];
auto st = textures::get_sprite(sprite_name, duped);
float scale_x = config["scale_x"];
float scale_y = config["scale_y"];
float x = config["x"];
float y = config["y"];
bool flipped = config["flipped"];
// BUG: put the .json file to load as a default/optional arg
auto anim = animation::load("./assets/animation.json", sprite_name);
anim.play();
anim.transform.flipped = flipped;
std::string cell = config["cell"];
std::string name = config["name"];
bool at_mid = config["at_mid"];
sf::Text text(*$ui.$font, "", 60);
return {name, st, anim, cell, {scale_x, scale_y}, {x, y}, at_mid, flipped, nullptr, text};
}
Engine::Engine(components::AnimatedScene& scene) :
$scene(scene)
{
for(auto& config : $scene.actors) {
auto element = config_scene_element(config, false);
dbc::check(!$actor_name_ids.contains(element.name),
fmt::format("actors key {} already exists", element.name));
$actors.push_back(element);
$actor_name_ids.try_emplace(element.name, $actors.size() - 1);
}
for(auto& fixture : $scene.fixtures) {
auto element = config_scene_element(fixture, true);
$fixtures.push_back(element);
}
for(auto& line : $scene.layout) {
$layout.append(line);
}
}
void Engine::init() {
$ui.position(0,0, BOSS_VIEW_WIDTH, BOSS_VIEW_HEIGHT);
$ui.set<guecs::Background>($ui.MAIN, {$ui.$parser, guecs::THEME.TRANSPARENT});
auto& background = $ui.get<guecs::Background>($ui.MAIN);
background.set_sprite($scene.background, true);
$ui.layout($layout);
for(auto& actor : $actors) {
actor.pos = position_sprite(actor.st, actor.cell,
actor.scale, actor.at_mid, actor.pos.x, actor.pos.y);
}
for(auto& fixture : $fixtures) {
fixture.pos = position_sprite(fixture.st, fixture.cell,
fixture.scale, fixture.at_mid, fixture.pos.x, fixture.pos.y);
}
}
void Engine::apply_effect(const std::string& actor, const std::string& shader) {
auto& element = actor_config(actor);
element.effect = shaders::get(shader);
}
void Engine::attach_text(const std::string& actor, const std::string& text) {
auto& element = actor_config(actor);
element.text.setPosition(element.pos);
element.text.setScale(element.scale);
element.text.setFillColor(sf::Color::Red);
element.text.setOutlineThickness(2.0f);
element.text.setOutlineColor(sf::Color::Black);
element.text.setString(text);
}
bool Engine::mouse(float x, float y, guecs::Modifiers mods) {
return $ui.mouse(x, y, mods);
}
void Engine::render(sf::RenderTexture& view) {
$ui.render(view);
for(auto& fixture : $fixtures) {
view.draw(*fixture.st.sprite, fixture.effect.get());
}
for(auto& actor : $actors) {
view.draw(*actor.st.sprite, actor.effect.get());
if(actor.anim.playing) view.draw(actor.text);
}
$camera.render(view);
if(DEBUG) $ui.debug_layout(view);
}
Element& Engine::actor_config(const std::string& actor) {
dbc::check($actor_name_ids.contains(actor), fmt::format("scene does not contain actor {}", actor));
return $actors.at($actor_name_ids.at(actor));
}
void Engine::move_actor(const std::string& actor, const std::string& cell_name) {
auto& config = actor_config(actor);
config.cell = cell_name;
config.pos = position_sprite(config.st, config.cell, config.scale, config.at_mid);
}
void Engine::animate_actor(const std::string& actor, const std::string& form) {
auto& config = actor_config(actor);
config.anim.set_form(form);
if(!config.anim.playing) {
config.anim.play();
}
}
inline void this_is_stupid_refactor(std::vector<Element>& elements) {
for(auto& element : elements) {
if(element.anim.playing) {
element.anim.update();
element.anim.motion(*element.st.sprite, element.pos, element.scale);
element.anim.apply(*element.st.sprite);
if(element.effect != nullptr) element.anim.apply_effect(element.effect);
}
}
}
void Engine::update() {
this_is_stupid_refactor($fixtures);
this_is_stupid_refactor($actors);
}
sf::Vector2f Engine::position_sprite(textures::SpriteTexture& st, const std::string& cell_name, sf::Vector2f scale, bool at_mid, float x_diff, float y_diff) {
auto& cell = $ui.cell_for(cell_name);
float x = float(at_mid ? cell.mid_x : cell.x);
float y = float(at_mid ? cell.mid_y : cell.y);
sf::Vector2f pos{x + x_diff, y + y_diff};
st.sprite->setPosition(pos);
st.sprite->setScale(scale);
return pos;
}
void Engine::zoom(float mid_x, float mid_y, const std::string& style, float scale) {
$camera.style(style);
$camera.scale(scale);
$camera.move(mid_x, mid_y);
$camera.play();
}
void Engine::zoom(const std::string &actor, const std::string& style, float scale) {
auto& config = actor_config(actor);
auto bounds = config.st.sprite->getGlobalBounds();
float mid_x = config.pos.x + bounds.size.x / 2.0f;
float mid_y = config.pos.y + bounds.size.y / 2.0f;
zoom(mid_x, mid_y, style, scale);
}
void Engine::set_end_cb(std::function<void()> cb) {
for(auto& actor : $actors) {
actor.anim.onLoop = [&,cb](auto& seq, auto& tr) -> bool {
seq.current = tr.toggled ? seq.frame_count - 1 : 0;
cb();
actor.effect = nullptr;
return tr.looped;
};
}
}
void Engine::reset(sf::RenderTexture& view) {
$camera.reset(view);
}
}

60
src/graphics/scene.hpp Normal file
View file

@ -0,0 +1,60 @@
#pragma once
#include <memory>
#include <unordered_map>
#include "graphics/textures.hpp"
#include <SFML/Graphics/RenderWindow.hpp>
#include <guecs/ui.hpp>
#include "camera.hpp"
#include <functional>
#include "graphics/animation.hpp"
#include "components.hpp"
namespace scene {
using std::shared_ptr;
using namespace textures;
struct Element {
std::string name;
textures::SpriteTexture st;
animation::Animation anim;
std::string cell;
sf::Vector2f scale{1.0f, 1.0f};
sf::Vector2f pos{0.0f, 0.0f};
bool at_mid=false;
bool flipped=false;
std::shared_ptr<sf::Shader> effect = nullptr;
sf::Text text;
};
struct Engine {
sf::Clock $clock;
guecs::UI $ui;
components::AnimatedScene& $scene;
std::string $layout;
std::unordered_map<std::string, int> $actor_name_ids;
std::vector<Element> $fixtures;
std::vector<Element> $actors;
cinematic::Camera $camera{{BOSS_VIEW_WIDTH, BOSS_VIEW_HEIGHT}, "scene"};
Engine(components::AnimatedScene& scene);
void init();
void render(sf::RenderTexture& view);
void update();
bool mouse(float x, float y, guecs::Modifiers mods);
void attach_text(const std::string& actor, const std::string& text);
Element config_scene_element(nlohmann::json& config, bool duped);
sf::Vector2f position_sprite(textures::SpriteTexture& st, const std::string& cell_name, sf::Vector2f scale, bool at_mid, float x_diff=0.0f, float y_diff=0.0f);
void move_actor(const std::string& actor, const std::string& cell_name);
void animate_actor(const std::string& actor, const std::string& form);
void apply_effect(const std::string& actor, const std::string& shader);
Element& actor_config(const std::string& actor);
void zoom(const std::string& actor, const std::string& style, float scale=0.9f);
void zoom(float mid_x, float mid_y, const std::string& style, float scale);
void reset(sf::RenderTexture& view);
void set_end_cb(std::function<void()> cb);
};
}

78
src/graphics/shaders.cpp Normal file
View file

@ -0,0 +1,78 @@
#include "graphics/shaders.hpp"
#include <SFML/Graphics/Image.hpp>
#include "dbc.hpp"
#include <fmt/core.h>
#include "config.hpp"
#include "constants.hpp"
#include <memory>
namespace shaders {
using std::shared_ptr, std::make_shared;
static ShaderManager SMGR;
static bool INITIALIZED = false;
static int VERSION = 0;
inline void configure_shader_defaults(std::shared_ptr<sf::Shader> ptr) {
ptr->setUniform("source", sf::Shader::CurrentTexture);
}
bool load_shader(std::string name, nlohmann::json& settings) {
std::string file_name = settings["file_name"];
auto ptr = std::make_shared<sf::Shader>();
bool good = ptr->loadFromFile(file_name, sf::Shader::Type::Fragment);
if(good) {
configure_shader_defaults(ptr);
SMGR.shaders.try_emplace(name, name, file_name, ptr);
}
return good;
}
void init() {
if(!INITIALIZED) {
dbc::check(sf::Shader::isAvailable(), "no shaders?!");
INITIALIZED = true;
auto config = settings::get("shaders");
bool good = load_shader("ERROR", config["ERROR"]);
dbc::check(good, "Failed to load ERROR shader. Look in assets/shaders.json");
for(auto& [name, settings] : config.json().items()) {
if(name == "ERROR") continue;
dbc::check(!SMGR.shaders.contains(name),
fmt::format("shader name '{}' duplicated in assets/shaders.json", name));
good = load_shader(name, settings);
if(!good) {
dbc::log(fmt::format("failed to load shader {}", name));
SMGR.shaders.insert_or_assign(name, SMGR.shaders.at("ERROR"));
}
}
}
}
std::shared_ptr<sf::Shader> get(const std::string& name) {
dbc::check(INITIALIZED, "you forgot to shaders::init()");
dbc::check(SMGR.shaders.contains(name),
fmt::format("shader name '{}' not in assets/shaders.json", name));
auto& rec = SMGR.shaders.at(name);
return rec.ptr;
}
int reload() {
VERSION++;
INITIALIZED = false;
SMGR.shaders.clear();
init();
return VERSION;
}
bool updated(int my_version) {
return my_version != VERSION;
}
int version() {
return VERSION;
}
};

28
src/graphics/shaders.hpp Normal file
View file

@ -0,0 +1,28 @@
#pragma once
#include <cstdint>
#include <vector>
#include <string>
#include <SFML/Graphics.hpp>
#include <unordered_map>
#include <memory>
#include "algos/matrix.hpp"
#include <nlohmann/json.hpp>
namespace shaders {
struct Record {
std::string name;
std::string file_name;
std::shared_ptr<sf::Shader> ptr = nullptr;
};
struct ShaderManager {
std::unordered_map<std::string, Record> shaders;
};
std::shared_ptr<sf::Shader> get(const std::string& name);
void init();
bool load_shader(std::string& name, nlohmann::json& settings);
bool updated(int my_version);
int reload();
int version();
}