Skip to content

Commit

Permalink
Add jngl::UpdateModelview effect
Browse files Browse the repository at this point in the history
  • Loading branch information
jhasse committed Nov 27, 2024
1 parent e5b174e commit 511aa1b
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/jngl/Widget.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ void Widget::draw() const {
for (const auto& effect : effects) {
effect->beginDraw();
}
drawSelf(jngl::modelview());
auto mv = jngl::modelview();
for (const auto& effect : effects) {
effect->updateModelview(mv);
}
drawSelf(mv);
for (const auto& effect : effects) {
effect->endDraw();
}
Expand Down
22 changes: 22 additions & 0 deletions src/jngl/effects.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,28 @@ namespace jngl {

Effect::~Effect() = default;

void Effect::updateModelview(Mat3& modelview) const {
}

UpdateModelview::UpdateModelview(std::function<void(float t, Mat3&)> function)
: function(std::move(function)) {
}

auto UpdateModelview::step() -> Action {
time += 1.f / static_cast<float>(getStepsPerSecond());
return Action::NONE;
}

void UpdateModelview::beginDraw() const {
}

void UpdateModelview::endDraw() const {
}

void UpdateModelview::updateModelview(Mat3& modelview) const {
function(time, modelview);
}

Zoom::Zoom(std::function<float(float)> function) : function(std::move(function)) {
}

Expand Down
29 changes: 29 additions & 0 deletions src/jngl/effects.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

namespace jngl {

class Mat3;

/// Base class for effects that can be applied to jngl::Widget
class Effect {
public:
Expand All @@ -23,6 +25,33 @@ class Effect {
[[nodiscard]] virtual Action step() = 0;
virtual void beginDraw() const = 0;
virtual void endDraw() const = 0;

/// Called before drawing the widget
virtual void updateModelview(Mat3& modelview) const;
};

class UpdateModelview : public Effect {
public:
/// Pass a function that gets the time the effect is in use and a reference to the Modelview so
/// that it can update it
///
/// Wiggle effect example:
/// \code
/// widget->addEffect<jngl::UpdateModelview>([](float t, jngl::Mat3& modelview) {
/// float effectIntensity = std::max(std::sin(t * 3), 0.f);
/// modelview.rotate(std::sin(t * 50) * 0.08 * effectIntensity)
/// .scale(1 + effectIntensity * 0.1);
/// });
/// \endcode
explicit UpdateModelview(std::function<void(float t, Mat3&)>);
Action step() override;
void beginDraw() const override;
void endDraw() const override;
void updateModelview(Mat3& modelview) const override;

private:
std::function<void(float t, Mat3&)> function;
float time = 0;
};

/// Scales the ModelView matrix
Expand Down

0 comments on commit 511aa1b

Please sign in to comment.