1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
|
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <algorithm>
#include <array>
#include <iostream>
#include <limits>
#include <memory>
#include <vector>
#include <cmath>
#include <cstdlib>
namespace
{
constexpr auto windowWidth = 800u;
constexpr auto windowHeight = 600u;
constexpr auto pi = 3.14159265359f;
constexpr auto sqrt2 = 2.0f * 0.707106781186547524401f;
std::filesystem::path resourcesDir()
{
#ifdef SFML_SYSTEM_IOS
return "";
#else
return "resources";
#endif
}
} // namespace
////////////////////////////////////////////////////////////
// Base class for effects
////////////////////////////////////////////////////////////
class Effect : public sf::Drawable
{
public:
static void setFont(const sf::Font& font)
{
s_font = &font;
}
[[nodiscard]] const std::string& getName() const
{
return m_name;
}
void update(float time, float x, float y)
{
onUpdate(time, x, y);
}
void draw(sf::RenderTarget& target, sf::RenderStates states) const override
{
onDraw(target, states);
}
void start()
{
onStart();
}
void stop()
{
onStop();
}
void handleKey(sf::Keyboard::Key key)
{
onKey(key);
}
protected:
explicit Effect(std::string name) : m_name(std::move(name))
{
}
static const sf::Font& getFont()
{
assert(s_font != nullptr && "Cannot get font until setFont() is called");
return *s_font;
}
private:
// Virtual functions to be implemented in derived effects
virtual void onUpdate(float time, float x, float y) = 0;
virtual void onDraw(sf::RenderTarget& target, sf::RenderStates states) const = 0;
virtual void onStart() = 0;
virtual void onStop() = 0;
virtual void onKey(sf::Keyboard::Key)
{
}
std::string m_name;
// NOLINTNEXTLINE(readability-identifier-naming)
static inline const sf::Font* s_font{nullptr};
};
////////////////////////////////////////////////////////////
// Surround Sound / Positional Audio Effect / Attenuation
////////////////////////////////////////////////////////////
class Surround : public Effect
{
public:
Surround() : Effect("Surround / Attenuation")
{
m_listener.setPosition({(windowWidth - 20.f) / 2.f, (windowHeight - 20.f) / 2.f});
m_listener.setFillColor(sf::Color::Red);
// Load the music file
if (!m_music.openFromFile(resourcesDir() / "doodle_pop.ogg"))
{
std::cerr << "Failed to load " << (resourcesDir() / "doodle_pop.ogg").string() << std::endl;
std::abort();
}
// Set the music to loop
m_music.setLooping(true);
// Set attenuation to a nice value
m_music.setAttenuation(0.04f);
}
void onUpdate(float /*time*/, float x, float y) override
{
m_position = {windowWidth * x - 10.f, windowHeight * y - 10.f};
m_music.setPosition({m_position.x, m_position.y, 0.f});
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const override
{
auto statesCopy(states);
statesCopy.transform = sf::Transform::Identity;
statesCopy.transform.translate(m_position);
target.draw(m_listener, states);
target.draw(m_soundShape, statesCopy);
}
void onStart() override
{
// Synchronize listener audio position with graphical position
sf::Listener::setPosition({m_listener.getPosition().x, m_listener.getPosition().y, 0.f});
m_music.play();
}
void onStop() override
{
m_music.stop();
}
private:
sf::CircleShape m_listener{20.f};
sf::CircleShape m_soundShape{20.f};
sf::Vector2f m_position;
sf::Music m_music;
};
////////////////////////////////////////////////////////////
// Pitch / Volume Effect
////////////////////////////////////////////////////////////
class PitchVolume : public Effect
{
public:
PitchVolume() :
Effect("Pitch / Volume"),
m_pitchText(getFont(), "Pitch: " + std::to_string(m_pitch)),
m_volumeText(getFont(), "Volume: " + std::to_string(m_volume))
{
// Load the music file
if (!m_music.openFromFile(resourcesDir() / "doodle_pop.ogg"))
{
std::cerr << "Failed to load " << (resourcesDir() / "doodle_pop.ogg").string() << std::endl;
std::abort();
}
// Set the music to loop
m_music.setLooping(true);
// We don't care about attenuation in this effect
m_music.setAttenuation(0.f);
// Set initial pitch
m_music.setPitch(m_pitch);
// Set initial volume
m_music.setVolume(m_volume);
m_pitchText.setPosition({windowWidth / 2.f - 120.f, windowHeight / 2.f - 80.f});
m_volumeText.setPosition({windowWidth / 2.f - 120.f, windowHeight / 2.f - 30.f});
}
void onUpdate(float /*time*/, float x, float y) override
{
m_pitch = std::clamp(2.f * x, 0.f, 2.f);
m_volume = std::clamp(100.f * (1.f - y), 0.f, 100.f);
m_music.setPitch(m_pitch);
m_music.setVolume(m_volume);
m_pitchText.setString("Pitch: " + std::to_string(m_pitch));
m_volumeText.setString("Volume: " + std::to_string(m_volume));
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const override
{
target.draw(m_pitchText, states);
target.draw(m_volumeText, states);
}
void onStart() override
{
// We set the listener position back to the default
// so that the music is right on top of the listener
sf::Listener::setPosition({0.f, 0.f, 0.f});
m_music.play();
}
void onStop() override
{
m_music.stop();
}
private:
float m_pitch{1.f};
float m_volume{100.f};
sf::Text m_pitchText;
sf::Text m_volumeText;
sf::Music m_music;
};
////////////////////////////////////////////////////////////
// Attenuation Effect
////////////////////////////////////////////////////////////
class Attenuation : public Effect
{
public:
Attenuation() : Effect("Attenuation"), m_text(getFont())
{
m_listener.setPosition({(windowWidth - 20.f) / 2.f, (windowHeight - 20.f) / 2.f + 100.f});
m_listener.setFillColor(sf::Color::Red);
m_soundShape.setFillColor(sf::Color::Magenta);
// Sound cone parameters
static constexpr auto coneHeight = windowHeight * 2.f;
static constexpr auto outerConeAngle = sf::degrees(120.f);
static constexpr auto innerConeAngle = sf::degrees(30.f);
// Set common properties of both cones
for (auto* cone : {&m_soundConeOuter, &m_soundConeInner})
{
cone->setPointCount(3);
cone->setPoint(0, {0.f, 0.f});
cone->setPosition({20.f, 20.f});
}
m_soundConeOuter.setFillColor(sf::Color::Black);
m_soundConeInner.setFillColor(sf::Color::Cyan);
// Make each cone based on their angle and height
static constexpr auto makeCone = [](auto& shape, const auto& angle)
{
const auto theta = sf::degrees(90.f) - (angle / 2);
const auto x = coneHeight / std::tan(theta.asRadians());
shape.setPoint(1, {-x, coneHeight});
shape.setPoint(2, {x, coneHeight});
};
makeCone(m_soundConeOuter, outerConeAngle);
makeCone(m_soundConeInner, innerConeAngle);
// Load the music file
if (!m_music.openFromFile(resourcesDir() / "doodle_pop.ogg"))
{
std::cerr << "Failed to load " << (resourcesDir() / "doodle_pop.ogg").string() << std::endl;
std::abort();
}
// Set the music to loop
m_music.setLooping(true);
// Set attenuation factor
m_music.setAttenuation(m_attenuation);
// Set direction to face "downwards"
m_music.setDirection({0.f, 1.f, 0.f});
// Set cone
m_music.setCone({innerConeAngle, outerConeAngle, 0.f});
m_text.setString(
"Attenuation factor dampens full volume of sound while within inner cone based on distance to "
"listener.\nCone outer gain determines "
"volume of sound while outside outer cone.\nWhen within outer cone, volume is linearly interpolated "
"between "
"inner and outer volumes.");
m_text.setCharacterSize(18);
m_text.setPosition({20.f, 20.f});
}
void onUpdate(float /*time*/, float x, float y) override
{
m_position = {windowWidth * x - 10.f, windowHeight * y - 10.f};
m_music.setPosition({m_position.x, m_position.y, 0.f});
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const override
{
auto statesCopy(states);
statesCopy.transform = sf::Transform::Identity;
statesCopy.transform.translate(m_position);
target.draw(m_soundConeOuter, statesCopy);
target.draw(m_soundConeInner, statesCopy);
target.draw(m_soundShape, statesCopy);
target.draw(m_listener, states);
target.draw(m_text, states);
}
void onStart() override
{
// Synchronize listener audio position with graphical position
sf::Listener::setPosition({m_listener.getPosition().x, m_listener.getPosition().y, 0.f});
m_music.play();
}
void onStop() override
{
m_music.stop();
}
private:
sf::CircleShape m_listener{20.f};
sf::CircleShape m_soundShape{20.f};
sf::ConvexShape m_soundConeOuter;
sf::ConvexShape m_soundConeInner;
sf::Text m_text;
sf::Vector2f m_position;
sf::Music m_music;
float m_attenuation{0.01f};
};
////////////////////////////////////////////////////////////
// Tone Generator
////////////////////////////////////////////////////////////
class Tone : public sf::SoundStream, public Effect
{
public:
Tone() :
Effect("Tone Generator"),
m_instruction(getFont(), "Press up and down arrows to change the current wave type"),
m_currentType(getFont(), "Wave Type: Triangle"),
m_currentAmplitude(getFont(), "Amplitude: 0.05"),
m_currentFrequency(getFont(), "Frequency: 200 Hz")
{
m_instruction.setPosition({windowWidth / 2.f - 370.f, windowHeight / 2.f - 200.f});
m_currentType.setPosition({windowWidth / 2.f - 150.f, windowHeight / 2.f - 100.f});
m_currentAmplitude.setPosition({windowWidth / 2.f - 150.f, windowHeight / 2.f - 50.f});
m_currentFrequency.setPosition({windowWidth / 2.f - 150.f, windowHeight / 2.f});
sf::SoundStream::initialize(1, sampleRate, {sf::SoundChannel::Mono});
}
void onUpdate(float /*time*/, float x, float y) override
{
m_amplitude = std::clamp(0.2f * (1.f - y), 0.f, 0.2f);
m_frequency = std::clamp(500.f * x, 0.f, 500.f);
m_currentAmplitude.setString("Amplitude: " + std::to_string(m_amplitude));
m_currentFrequency.setString("Frequency: " + std::to_string(m_frequency) + " Hz");
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const override
{
target.draw(m_instruction, states);
target.draw(m_currentType, states);
target.draw(m_currentAmplitude, states);
target.draw(m_currentFrequency, states);
}
void onStart() override
{
// We set the listener position back to the default
// so that the tone is right on top of the listener
sf::Listener::setPosition({0.f, 0.f, 0.f});
play();
}
void onStop() override
{
SoundStream::stop();
}
void onKey(sf::Keyboard::Key key) override
{
auto ticks = 0;
if (key == sf::Keyboard::Key::Down)
ticks = 1; // Forward
else if (key == sf::Keyboard::Key::Up)
ticks = 3; // Reverse
while (ticks--)
{
switch (m_type)
{
case Type::Sine:
m_type = Type::Square;
m_currentType.setString("Wave Type: Square");
break;
case Type::Square:
m_type = Type::Triangle;
m_currentType.setString("Wave Type: Triangle");
break;
case Type::Triangle:
m_type = Type::Sawtooth;
m_currentType.setString("Wave Type: Sawtooth");
break;
case Type::Sawtooth:
m_type = Type::Sine;
m_currentType.setString("Wave Type: Sine");
break;
}
}
}
private:
bool onGetData(sf::SoundStream::Chunk& chunk) override
{
const auto period = 1.f / m_frequency;
for (auto i = 0u; i < chunkSize; ++i)
{
auto value = 0.f;
switch (m_type)
{
case Type::Sine:
{
value = m_amplitude * std::sin(2 * pi * m_frequency * m_time);
break;
}
case Type::Square:
{
value = m_amplitude *
(2 * (2 * std::floor(m_frequency * m_time) - std::floor(2 * m_frequency * m_time)) + 1);
break;
}
case Type::Triangle:
{
value = 4 * m_amplitude / period *
std::abs(std::fmod(((std::fmod((m_time - period / 4), period)) + period), period) -
period / 2) -
m_amplitude;
break;
}
case Type::Sawtooth:
{
value = m_amplitude * 2 * (m_time / period - std::floor(0.5f + m_time / period));
break;
}
}
m_sampleBuffer[i] = static_cast<std::int16_t>(std::lround(value * std::numeric_limits<std::int16_t>::max()));
m_time += timePerSample;
}
chunk.sampleCount = chunkSize;
chunk.samples = m_sampleBuffer.data();
return true;
}
void onSeek(sf::Time) override
{
// It doesn't make sense to seek in a tone generator
}
enum class Type
{
Sine,
Square,
Triangle,
Sawtooth
};
static constexpr unsigned int sampleRate{44100};
static constexpr std::size_t chunkSize{sampleRate / 100};
static constexpr float timePerSample{1.f / float{sampleRate}};
std::vector<std::int16_t> m_sampleBuffer = std::vector<std::int16_t>(chunkSize, 0);
Type m_type{Type::Triangle};
float m_amplitude{0.05f};
float m_frequency{220};
float m_time{};
sf::Text m_instruction;
sf::Text m_currentType;
sf::Text m_currentAmplitude;
sf::Text m_currentFrequency;
};
////////////////////////////////////////////////////////////
// Dopper Shift Effect
////////////////////////////////////////////////////////////
class Doppler : public sf::SoundStream, public Effect
{
public:
Doppler() :
Effect("Doppler Shift"),
m_currentVelocity(getFont(), "Velocity: " + std::to_string(m_velocity)),
m_currentFactor(getFont(), "Doppler Factor: " + std::to_string(m_factor))
{
m_listener.setPosition({(windowWidth - 20.f) / 2.f, (windowHeight - 20.f) / 2.f});
m_listener.setFillColor(sf::Color::Red);
m_position.y = (windowHeight - 20.f) / 2.f - 40.f;
m_currentVelocity.setPosition({windowWidth / 2.f - 150.f, windowHeight * 3.f / 4.f - 50.f});
m_currentFactor.setPosition({windowWidth / 2.f - 150.f, windowHeight * 3.f / 4.f});
// Set attenuation to a nice value
setAttenuation(0.05f);
sf::SoundStream::initialize(1, sampleRate, {sf::SoundChannel::Mono});
}
void onUpdate(float time, float x, float y) override
{
m_velocity = std::clamp(150.f * (1.f - y), 0.f, 150.f);
m_factor = std::clamp(x, 0.f, 1.f);
m_currentVelocity.setString("Velocity: " + std::to_string(m_velocity));
m_currentFactor.setString("Doppler Factor: " + std::to_string(m_factor));
m_position.x = std::fmod(time, 8.f) * windowWidth / 8.f;
setPosition({m_position.x, m_position.y, 0.f});
setVelocity({m_velocity, 0.f, 0.f});
setDopplerFactor(m_factor);
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const override
{
auto statesCopy(states);
statesCopy.transform = sf::Transform::Identity;
statesCopy.transform.translate(m_position - sf::Vector2f({20.f, 0.f}));
target.draw(m_listener, states);
target.draw(m_soundShape, statesCopy);
target.draw(m_currentVelocity, states);
target.draw(m_currentFactor, states);
}
void onStart() override
{
// Synchronize listener audio position with graphical position
sf::Listener::setPosition({m_listener.getPosition().x, m_listener.getPosition().y, 0.f});
play();
}
void onStop() override
{
SoundStream::stop();
}
private:
bool onGetData(sf::SoundStream::Chunk& chunk) override
{
const auto period = 1.f / m_frequency;
for (auto i = 0u; i < chunkSize; ++i)
{
const auto value = m_amplitude * 2 * (m_time / period - std::floor(0.5f + m_time / period));
m_sampleBuffer[i] = static_cast<std::int16_t>(std::lround(value * std::numeric_limits<std::int16_t>::max()));
m_time += timePerSample;
}
chunk.sampleCount = chunkSize;
chunk.samples = m_sampleBuffer.data();
return true;
}
void onSeek(sf::Time) override
{
// It doesn't make sense to seek in a tone generator
}
static constexpr unsigned int sampleRate{44100};
static constexpr std::size_t chunkSize{sampleRate / 100};
static constexpr float timePerSample{1.f / float{sampleRate}};
std::vector<std::int16_t> m_sampleBuffer = std::vector<std::int16_t>(chunkSize, 0);
float m_amplitude{0.05f};
float m_frequency{220};
float m_time{};
float m_velocity{0.f};
float m_factor{1.f};
sf::CircleShape m_listener{20.f};
sf::CircleShape m_soundShape{20.f};
sf::Vector2f m_position;
sf::Text m_currentVelocity;
sf::Text m_currentFactor;
};
////////////////////////////////////////////////////////////
// Processing base class
////////////////////////////////////////////////////////////
class Processing : public Effect
{
public:
void onUpdate([[maybe_unused]] float time, float x, float y) override
{
m_position = {windowWidth * x - 10.f, windowHeight * y - 10.f};
m_music.setPosition({m_position.x, m_position.y, 0.f});
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const override
{
auto statesCopy(states);
statesCopy.transform = sf::Transform::Identity;
statesCopy.transform.translate(m_position);
target.draw(m_listener, states);
target.draw(m_soundShape, statesCopy);
target.draw(m_enabledText);
target.draw(m_instructions);
}
void onStart() override
{
// Synchronize listener audio position with graphical position
sf::Listener::setPosition({m_listener.getPosition().x, m_listener.getPosition().y, 0.f});
m_music.play();
}
void onStop() override
{
m_music.stop();
}
protected:
explicit Processing(std::string name) :
Effect(std::move(name)),
m_enabledText(getFont(), "Processing: Enabled"),
m_instructions(getFont(), "Press Space to enable/disable processing")
{
m_listener.setPosition({(windowWidth - 20.f) / 2.f, (windowHeight - 20.f) / 2.f});
m_listener.setFillColor(sf::Color::Red);
m_enabledText.setPosition({windowWidth / 2.f - 120.f, windowHeight * 3.f / 4.f - 50.f});
m_instructions.setPosition({windowWidth / 2.f - 250.f, windowHeight * 3.f / 4.f});
// Load the music file
if (!m_music.openFromFile(resourcesDir() / "doodle_pop.ogg"))
{
std::cerr << "Failed to load " << (resourcesDir() / "doodle_pop.ogg").string() << std::endl;
std::abort();
}
// Set the music to loop
m_music.setLooping(true);
// Set attenuation to a nice value
m_music.setAttenuation(0.0f);
}
sf::Music& getMusic()
{
return m_music;
}
const std::shared_ptr<bool>& getEnabled() const
{
return m_enabled;
}
private:
void onKey(sf::Keyboard::Key key) override
{
if (key == sf::Keyboard::Key::Space)
*m_enabled = !*m_enabled;
m_enabledText.setString(*m_enabled ? "Processing: Enabled" : "Processing: Disabled");
}
sf::CircleShape m_listener{20.f};
sf::CircleShape m_soundShape{20.f};
sf::Vector2f m_position;
sf::Music m_music;
std::shared_ptr<bool> m_enabled{std::make_shared<bool>(true)};
sf::Text m_enabledText;
sf::Text m_instructions;
};
////////////////////////////////////////////////////////////
// Biquad Filter (https://github.com/dimtass/DSP-Cpp-filters)
////////////////////////////////////////////////////////////
class BiquadFilter : public Processing
{
protected:
struct Coefficients
{
float a0{};
float a1{};
float a2{};
float b1{};
float b2{};
float c0{};
float d0{};
};
using Processing::Processing;
void setCoefficients(const Coefficients& coefficients)
{
auto& music = getMusic();
struct State
{
float xnz1{};
float xnz2{};
float ynz1{};
float ynz2{};
};
// We use a mutable lambda to tie the lifetime of the state and coefficients to the lambda itself
// This is necessary since the Echo object will be destroyed before the Music object
// While the Music object exists, it is possible that the audio engine will try to call
// this lambda hence we need to always have usable coefficients and state until the Music and the
// associated lambda are destroyed
music.setEffectProcessor(
[coefficients,
enabled = getEnabled(),
state = std::vector<State>()](const float* inputFrames,
unsigned int& inputFrameCount,
float* outputFrames,
unsigned int& outputFrameCount,
unsigned int frameChannelCount) mutable
{
// IMPORTANT: The channel count of the audio engine currently sourcing data from this sound
// will always be provided in frameChannelCount, this can be different from the channel count
// of the audio source so make sure to size your buffers according to the engine and not the source
// Ensure we have as many state objects as the audio engine has channels
if (state.size() < frameChannelCount)
state.resize(frameChannelCount - state.size());
for (auto frame = 0u; frame < outputFrameCount; ++frame)
{
for (auto channel = 0u; channel < frameChannelCount; ++channel)
{
auto& channelState = state[channel];
const auto xn = inputFrames ? inputFrames[channel] : 0.f; // Read silence if no input data available
const auto yn = coefficients.a0 * xn + coefficients.a1 * channelState.xnz1 +
coefficients.a2 * channelState.xnz2 - coefficients.b1 * channelState.ynz1 -
coefficients.b2 * channelState.ynz2;
channelState.xnz2 = channelState.xnz1;
channelState.xnz1 = xn;
channelState.ynz2 = channelState.ynz1;
channelState.ynz1 = yn;
outputFrames[channel] = *enabled ? yn : xn;
}
inputFrames += (inputFrames ? frameChannelCount : 0u);
outputFrames += frameChannelCount;
}
// We processed data 1:1
inputFrameCount = outputFrameCount;
});
}
};
////////////////////////////////////////////////////////////
// High-pass Filter (https://github.com/dimtass/DSP-Cpp-filters)
////////////////////////////////////////////////////////////
struct HighPassFilter : BiquadFilter
{
HighPassFilter() : BiquadFilter("High-pass Filter")
{
static constexpr auto cutoffFrequency = 2000.f;
const auto c = std::tan(pi * cutoffFrequency / static_cast<float>(getMusic().getSampleRate()));
Coefficients coefficients;
coefficients.a0 = 1.f / (1.f + sqrt2 * c + std::pow(c, 2.f));
coefficients.a1 = -2.f * coefficients.a0;
coefficients.a2 = coefficients.a0;
coefficients.b1 = 2.f * coefficients.a0 * (std::pow(c, 2.f) - 1.f);
coefficients.b2 = coefficients.a0 * (1.f - sqrt2 * c + std::pow(c, 2.f));
setCoefficients(coefficients);
}
};
////////////////////////////////////////////////////////////
// Low-pass Filter (https://github.com/dimtass/DSP-Cpp-filters)
////////////////////////////////////////////////////////////
struct LowPassFilter : BiquadFilter
{
LowPassFilter() : BiquadFilter("Low-pass Filter")
{
static constexpr auto cutoffFrequency = 500.f;
const auto c = 1.f / std::tan(pi * cutoffFrequency / static_cast<float>(getMusic().getSampleRate()));
Coefficients coefficients;
coefficients.a0 = 1.f / (1.f + sqrt2 * c + std::pow(c, 2.f));
coefficients.a1 = 2.f * coefficients.a0;
coefficients.a2 = coefficients.a0;
coefficients.b1 = 2.f * coefficients.a0 * (1.f - std::pow(c, 2.f));
coefficients.b2 = coefficients.a0 * (1.f - sqrt2 * c + std::pow(c, 2.f));
setCoefficients(coefficients);
}
};
////////////////////////////////////////////////////////////
// Echo (miniaudio implementation)
////////////////////////////////////////////////////////////
struct Echo : Processing
{
Echo() : Processing("Echo")
{
auto& music = getMusic();
static constexpr auto delay = 0.2f;
static constexpr auto decay = 0.75f;
static constexpr auto wet = 0.8f;
static constexpr auto dry = 1.f;
const auto sampleRate = music.getSampleRate();
const auto delayInFrames = static_cast<unsigned int>(static_cast<float>(sampleRate) * delay);
// We use a mutable lambda to tie the lifetime of the state to the lambda itself
// This is necessary since the Echo object will be destroyed before the Music object
// While the Music object exists, it is possible that the audio engine will try to call
// this lambda hence we need to always have a usable state until the Music and the
// associated lambda are destroyed
music.setEffectProcessor(
[delayInFrames,
enabled = getEnabled(),
buffer = std::vector<float>(),
cursor = 0u](const float* inputFrames,
unsigned int& inputFrameCount,
float* outputFrames,
unsigned int& outputFrameCount,
unsigned int frameChannelCount) mutable
{
// IMPORTANT: The channel count of the audio engine currently sourcing data from this sound
// will always be provided in frameChannelCount, this can be different from the channel count
// of the audio source so make sure to size your buffers according to the engine and not the source
// Ensure we have enough space to store the delayed frames for all of the audio engine's channels
if (buffer.size() < delayInFrames * frameChannelCount)
buffer.resize(delayInFrames * frameChannelCount - buffer.size(), 0.f);
for (auto frame = 0u; frame < outputFrameCount; ++frame)
{
for (auto channel = 0u; channel < frameChannelCount; ++channel)
{
const auto input = inputFrames ? inputFrames[channel] : 0.f; // Read silence if no input data available
const auto bufferIndex = (cursor * frameChannelCount) + channel;
buffer[bufferIndex] = (buffer[bufferIndex] * decay) + (input * dry);
outputFrames[channel] = *enabled ? buffer[bufferIndex] * wet : input;
}
cursor = (cursor + 1) % delayInFrames;
inputFrames += (inputFrames ? frameChannelCount : 0u);
outputFrames += frameChannelCount;
}
// We processed data 1:1
inputFrameCount = outputFrameCount;
});
}
};
////////////////////////////////////////////////////////////
// Reverb (https://github.com/sellicott/DSP-FFMpeg-Reverb)
////////////////////////////////////////////////////////////
class Reverb : public Processing
{
public:
Reverb() : Processing("Reverb")
{
auto& music = getMusic();
static constexpr auto sustain = 0.7f; // [0.f; 1.f]
// We use a mutable lambda to tie the lifetime of the state to the lambda itself
// This is necessary since the Echo object will be destroyed before the Music object
// While the Music object exists, it is possible that the audio engine will try to call
// this lambda hence we need to always have a usable state until the Music and the
// associated lambda are destroyed
music.setEffectProcessor(
[sampleRate = music.getSampleRate(),
filters = std::vector<ReverbFilter<float>>(),
enabled = getEnabled()](const float* inputFrames,
unsigned int& inputFrameCount,
float* outputFrames,
unsigned int& outputFrameCount,
unsigned int frameChannelCount) mutable
{
// IMPORTANT: The channel count of the audio engine currently sourcing data from this sound
// will always be provided in frameChannelCount, this can be different from the channel count
// of the audio source so make sure to size your buffers according to the engine and not the source
// Ensure we have as many filter objects as the audio engine has channels
while (filters.size() < frameChannelCount)
filters.emplace_back(sampleRate, sustain);
for (auto frame = 0u; frame < outputFrameCount; ++frame)
{
for (auto channel = 0u; channel < frameChannelCount; ++channel)
{
const auto input = inputFrames ? inputFrames[channel] : 0.f; // Read silence if no input data available
outputFrames[channel] = *enabled ? filters[channel](input) : input;
}
inputFrames += (inputFrames ? frameChannelCount : 0u);
outputFrames += frameChannelCount;
}
// We processed data 1:1
inputFrameCount = outputFrameCount;
});
}
private:
template <typename T>
class AllPassFilter
{
public:
AllPassFilter(std::size_t delay, float theGain) : m_buffer(delay, {}), m_gain(theGain)
{
}
T operator()(T input)
{
const auto output = m_buffer[m_cursor];
input = static_cast<T>(input + m_gain * output);
m_buffer[m_cursor] = input;
m_cursor = (m_cursor + 1) % m_buffer.size();
return static_cast<T>(-m_gain * input + output);
}
private:
std::vector<T> m_buffer;
std::size_t m_cursor{};
const float m_gain{};
};
template <typename T>
class FIRFilter
{
public:
explicit FIRFilter(std::vector<float> taps) : m_taps(std::move(taps))
{
}
T operator()(T input)
{
m_buffer[m_cursor] = input;
m_cursor = (m_cursor + 1) % m_buffer.size();
T output{};
for (auto i = 0u; i < m_taps.size(); ++i)
output += static_cast<T>(m_taps[i] * m_buffer[(m_cursor + i) % m_buffer.size()]);
return output;
}
private:
const std::vector<float> m_taps;
std::vector<T> m_buffer = std::vector<T>(m_taps.size(), {});
std::size_t m_cursor{};
};
template <typename T>
class ReverbFilter
{
public:
ReverbFilter(unsigned int sampleRate, float feedbackGain) :
m_allPass{{{sampleRate / 10, 0.6f}, {sampleRate / 30, -0.6f}, {sampleRate / 90, 0.6f}, {sampleRate / 270, -0.6f}}},
m_fir({0.003369f, 0.002810f, 0.001758f, 0.000340f, -0.001255f, -0.002793f, -0.004014f, -0.004659f,
-0.004516f, -0.003464f, -0.001514f, 0.001148f, 0.004157f, 0.006986f, 0.009003f, 0.009571f,
0.008173f, 0.004560f, -0.001120f, -0.008222f, -0.015581f, -0.021579f, -0.024323f, -0.021933f,
-0.012904f, 0.003500f, 0.026890f, 0.055537f, 0.086377f, 0.115331f, 0.137960f, 0.150407f,
0.150407f, 0.137960f, 0.115331f, 0.086377f, 0.055537f, 0.026890f, 0.003500f, -0.012904f,
-0.021933f, -0.024323f, -0.021579f, -0.015581f, -0.008222f, -0.001120f, 0.004560f, 0.008173f,
0.009571f, 0.009003f, 0.006986f, 0.004157f, 0.001148f, -0.001514f, -0.003464f, -0.004516f,
-0.004659f, -0.004014f, -0.002793f, -0.001255f, 0.000340f, 0.001758f, 0.002810f, 0.003369f}),
m_buffer(sampleRate / 5, {}), // sample rate / 5 = 200ms buffer size
m_feedbackGain(feedbackGain)
{
}
T operator()(T input)
{
auto output = static_cast<T>(0.7f * input + m_feedbackGain * m_buffer[m_cursor]);
for (auto& f : m_allPass)
output = f(output);
output = m_fir(output);
m_buffer[m_cursor] = output;
m_cursor = (m_cursor + 1) % m_buffer.size();
output += 0.5f * m_buffer[(m_cursor + 1 * m_interval - 1) % m_buffer.size()];
output += 0.25f * m_buffer[(m_cursor + 2 * m_interval - 1) % m_buffer.size()];
output += 0.125f * m_buffer[(m_cursor + 3 * m_interval - 1) % m_buffer.size()];
return 0.6f * output + input;
}
private:
std::array<AllPassFilter<T>, 4> m_allPass;
FIRFilter<T> m_fir;
std::vector<T> m_buffer;
std::size_t m_cursor{};
const std::size_t m_interval{m_buffer.size() / 3};
const float m_feedbackGain{};
};
};
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Create the main window
sf::RenderWindow window(sf::VideoMode({windowWidth, windowHeight}),
"SFML Sound Effects",
sf::Style::Titlebar | sf::Style::Close);
window.setVerticalSyncEnabled(true);
// Open the application font and pass it to the Effect class
const sf::Font font(resourcesDir() / "tuffy.ttf");
Effect::setFont(font);
// Create the effects
Surround surroundEffect;
PitchVolume pitchVolumeEffect;
Attenuation attenuationEffect;
Tone toneEffect;
Doppler dopplerEffect;
HighPassFilter highPassFilterEffect;
LowPassFilter lowPassFilterEffect;
Echo echoEffect;
Reverb reverbEffect;
const std::array<Effect*, 9> effects{&surroundEffect,
&pitchVolumeEffect,
&attenuationEffect,
&toneEffect,
&dopplerEffect,
&highPassFilterEffect,
&lowPassFilterEffect,
&echoEffect,
&reverbEffect};
std::size_t current = 0;
effects[current]->start();
// Create the messages background
const sf::Texture textBackgroundTexture(resourcesDir() / "text-background.png");
sf::Sprite textBackground(textBackgroundTexture);
textBackground.setPosition({0.f, 520.f});
textBackground.setColor(sf::Color(255, 255, 255, 200));
// Create the description text
sf::Text description(font, "Current effect: " + effects[current]->getName(), 20);
description.setPosition({10.f, 522.f});
description.setFillColor(sf::Color(80, 80, 80));
// Create the instructions text
sf::Text instructions(font, "Press left and right arrows to change the current effect", 20);
instructions.setPosition({280.f, 544.f});
instructions.setFillColor(sf::Color(80, 80, 80));
// Create the playback device text
auto playbackDeviceName = sf::PlaybackDevice::getDevice();
sf::Text playbackDevice(font, "Current playback device: " + playbackDeviceName.value_or("None"), 20);
playbackDevice.setPosition({10.f, 566.f});
playbackDevice.setFillColor(sf::Color(80, 80, 80));
// Create the playback device instructions text
sf::Text playbackDeviceInstructions(font, "Press F1 to change device", 20);
playbackDeviceInstructions.setPosition({565.f, 566.f});
playbackDeviceInstructions.setFillColor(sf::Color(80, 80, 80));
// Start the game loop
const sf::Clock clock;
while (window.isOpen())
{
// Process events
while (const std::optional event = window.pollEvent())
{
// Close window: exit
if (event->is<sf::Event::Closed>())
window.close();
if (const auto* keyPressed = event->getIf<sf::Event::KeyPressed>())
{
switch (keyPressed->code)
{
// Escape key: exit
case sf::Keyboard::Key::Escape:
window.close();
break;
// Left arrow key: previous effect
case sf::Keyboard::Key::Left:
effects[current]->stop();
if (current == 0)
current = effects.size() - 1;
else
--current;
effects[current]->start();
description.setString("Current effect: " + effects[current]->getName());
break;
// Right arrow key: next effect
case sf::Keyboard::Key::Right:
effects[current]->stop();
if (current == effects.size() - 1)
current = 0;
else
++current;
effects[current]->start();
description.setString("Current effect: " + effects[current]->getName());
break;
// F1 key: change playback device
case sf::Keyboard::Key::F1:
{
// We need to query the list every time we want to change
// since new devices could have been added in the mean time
const auto devices = sf::PlaybackDevice::getAvailableDevices();
const auto currentDevice = sf::PlaybackDevice::getDevice();
auto next = currentDevice;
for (auto iter = devices.begin(); iter != devices.end(); ++iter)
{
if (*iter == currentDevice)
{
const auto nextIter = std::next(iter);
next = (nextIter == devices.end()) ? devices.front() : *nextIter;
break;
}
}
if (next)
{
if (!sf::PlaybackDevice::setDevice(*next))
std::cerr << "Failed to set the playback device to: " << *next << std::endl;
playbackDeviceName = sf::PlaybackDevice::getDevice();
playbackDevice.setString("Current playback device: " + playbackDeviceName.value_or("None"));
}
break;
}
default:
effects[current]->handleKey(keyPressed->code);
break;
}
}
}
// Update the current example
const auto [x, y] = sf::Vector2f(sf::Mouse::getPosition(window)).componentWiseDiv(sf::Vector2f(window.getSize()));
effects[current]->update(clock.getElapsedTime().asSeconds(), x, y);
// Clear the window
window.clear(sf::Color(50, 50, 50));
// Draw the current example
window.draw(*effects[current]);
// Draw the text
window.draw(textBackground);
window.draw(instructions);
window.draw(description);
window.draw(playbackDevice);
window.draw(playbackDeviceInstructions);
// Finally, display the rendered frame on screen
window.display();
}
// Stop effect so that tone generators don't have to keep generating data while being destroyed
effects[current]->stop();
}
|