Last active
September 28, 2017 19:14
-
-
Save kim366/e3a0055e88af9a88ce3fc24336977dbf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SFML/Graphics.hpp> | |
// #define CATCH_CONFIG_MAIN | |
// #include <catch.hpp> | |
void draw_lines(const std::vector<sf::Vector2f>& vector, sf::RenderWindow& window, sf::Color color = sf::Color::White) | |
{ | |
for (auto it{vector.cbegin()}; it != vector.cend();) | |
{ | |
auto current_it{it}; | |
if (++it != vector.cend()) | |
{ | |
sf::Vertex line[2] | |
{ | |
{*current_it, color}, | |
{*it, color} | |
}; | |
window.draw(line, 2, sf::Lines); | |
} | |
} | |
} | |
float interpolate(float t, float a, float b) | |
{ | |
return (b - a) * t + a; | |
} | |
sf::Vector2f vinterpolate(float t, sf::Vector2f a, sf::Vector2f b) | |
{ | |
return {interpolate(t, a.x, b.x), interpolate(t, a.y, b.y)}; | |
} | |
// TEST_CASE("Interpolation") | |
// { | |
// CHECK(interpolate(.1f, 0, 100) == 10); | |
// CHECK(interpolate(.1f, 0, 200) == 20); | |
// CHECK(interpolate(.1f, 100, 200) == 110); | |
// } | |
int main() | |
{ | |
sf::RenderWindow window({350, 350}, "SFML", sf::Style::Default, sf::ContextSettings{0, 0, 8}); | |
std::vector<sf::Vector2f> points; | |
while (true) | |
{ | |
sf::Event event; | |
while (window.pollEvent(event)) | |
{ | |
if (event.type == sf::Event::Closed || (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)) | |
return 0; | |
if (event.type == sf::Event::MouseButtonPressed) | |
points.emplace_back(event.mouseButton.x, event.mouseButton.y); | |
} | |
std::vector<sf::Vector2f> curve; | |
for (float n{50}, t{0}; t <= 1.01; t += 1 / n) | |
{ | |
std::vector<sf::Vector2f> remaining_points{points}; | |
while (remaining_points.size() > 1) | |
{ | |
std::vector<sf::Vector2f> current_remaining_points; | |
for (auto it{remaining_points.cbegin()}; it != remaining_points.cend();) | |
{ | |
auto current_it{it}; | |
if (++it != remaining_points.cend()) | |
current_remaining_points.push_back(vinterpolate(t, *current_it, *it)); | |
} | |
remaining_points = current_remaining_points; | |
} | |
if (!remaining_points.empty()) | |
curve.push_back(remaining_points[0]); | |
} | |
window.clear(); | |
draw_lines(points, window, {100, 100, 100}); | |
draw_lines(curve, window); | |
window.display(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment