diff --git a/CMakeLists.txt b/CMakeLists.txt index d1033d74..09eacbae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -589,5 +589,6 @@ if (FGE_BUILD_EXAMPLES) add_subdirectory(examples/shaderChain_009) if (FGE_BUILD_EXTENSIONS) add_subdirectory(examples/objChart_010) + add_subdirectory(examples/signals_011) endif() endif() diff --git a/examples/signals_011/CMakeLists.txt b/examples/signals_011/CMakeLists.txt new file mode 100644 index 00000000..ec9c600c --- /dev/null +++ b/examples/signals_011/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 3.10) +project(example_signals_011) + +add_executable(${PROJECT_NAME} main.cpp) +add_dependencies(${PROJECT_NAME} FgeClientExeDeps) + +target_link_libraries(${PROJECT_NAME} ${FGE_CLIENT_LIBS} FastEngine::ObjChart FastEngine::Signals) + +setMSVCDefaultWorkingDir(${PROJECT_NAME}) diff --git a/examples/signals_011/main.cpp b/examples/signals_011/main.cpp new file mode 100644 index 00000000..20a32de0 --- /dev/null +++ b/examples/signals_011/main.cpp @@ -0,0 +1,430 @@ +/* + * Copyright 2026 Guillaume Guillet + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "FastEngine/C_clock.hpp" +#include "FastEngine/C_random.hpp" +#include "FastEngine/C_scene.hpp" +#include "FastEngine/extensions/C_objChart.hpp" +#include "FastEngine/extensions/C_signalGenerator.hpp" +#include "FastEngine/graphic/C_renderWindow.hpp" +#include "FastEngine/manager/shader_manager.hpp" +#include "FastEngine/manager/texture_manager.hpp" +#include "FastEngine/object/C_objShape.hpp" +#include "FastEngine/object/C_objText.hpp" +#include "FastEngine/object/C_objWindow.hpp" +#include "SDL3/SDL.h" +#include "SDL3/SDL_main.h" +#include +#include +#include +#include +#include + +#define SIGNAL_DURATION 2.0 +#define SIGNAL_SAMPLE_INTERVAL 0.01 +#define SIGNAL_LIVE_DURATION 3.0 +#define SIGNAL_LIVE_SAMPLE_INTERVAL (1.0 / 30.0) +#define SIGNAL_SOFT_LIMIT_LOWER (-1.0) +#define SIGNAL_SOFT_LIMIT_UPPER 1.0 +#define SIGNAL_SOFT_LIMIT_SMOOTHNESS 4.0 +#define SIGNAL_RESAMPLE_RATE 20.0 +#define SIGNAL_TIME_STRETCH_FACTOR 0.5 +#define SIGNAL_CSV_FILE "signal.csv" +#define SIGNAL_MAX_DISPLAYED_WAVES 4 + +using WaveTypes = fge::SignalGeneratorD::WaveTypes; + +enum class Processings +{ + PROCESS_DERIVATIVE, + PROCESS_INTEGRAL, + PROCESS_SOFT_LIMIT, + PROCESS_SOFT_LIMIT_KEEP_AVERAGE, + PROCESS_RESAMPLE, + PROCESS_TIME_STRETCH, + + PROCESS_COUNT +}; + +char const* GetProcessingName(Processings processing) +{ + switch (processing) + { + case Processings::PROCESS_DERIVATIVE: + return "derivative()"; + case Processings::PROCESS_INTEGRAL: + return "integral()"; + case Processings::PROCESS_SOFT_LIMIT: + return "softLimit() in [-1, 1]"; + case Processings::PROCESS_SOFT_LIMIT_KEEP_AVERAGE: + return "softLimitKeepAverage() in [-1, 1]"; + case Processings::PROCESS_RESAMPLE: + return "resample() at 20 Hz"; + case Processings::PROCESS_TIME_STRETCH: + return "timeStretch() x0.5"; + default: + return "unknown"; + } +} + +char const* GetWaveName(WaveTypes type) +{ + switch (type) + { + case WaveTypes::WAVE_SINUSOID: + return "sinusoid"; + case WaveTypes::WAVE_RECTANGLE: + return "rectangle"; + case WaveTypes::WAVE_SAWTOOTH: + return "sawtooth"; + case WaveTypes::WAVE_TRIANGLE: + return "triangle"; + case WaveTypes::WAVE_CONTINUOUS: + return "continuous"; + default: + return "unknown"; + } +} + +fge::SignalGeneratorD::Wave CreateRandomWave(WaveTypes type) +{ + fge::SignalGeneratorD::Wave wave; + wave._type = type; + wave._amplitude = fge::_random.range(0.2, 1.0); + wave._frequency = fge::_random.range(0.5, 4.0); + wave._phaseDegrees = fge::_random.range(0.0, 360.0); + wave._dutyCycle = fge::_random.range(0.1, 0.9); + if (type == WaveTypes::WAVE_CONTINUOUS) + { + wave._offset = fge::_random.range(-0.5, 0.5); + } + return wave; +} + +fge::SignalD ApplyProcessing(fge::SignalD const& signal, Processings processing) +{ + switch (processing) + { + case Processings::PROCESS_DERIVATIVE: + return signal.derivative(); + case Processings::PROCESS_INTEGRAL: + return signal.integral(); + case Processings::PROCESS_SOFT_LIMIT: + return signal.softLimit(SIGNAL_SOFT_LIMIT_LOWER, SIGNAL_SOFT_LIMIT_UPPER, SIGNAL_SOFT_LIMIT_SMOOTHNESS); + case Processings::PROCESS_SOFT_LIMIT_KEEP_AVERAGE: + return signal.softLimitKeepAverage(SIGNAL_SOFT_LIMIT_LOWER, SIGNAL_SOFT_LIMIT_UPPER, + SIGNAL_SOFT_LIMIT_SMOOTHNESS); + case Processings::PROCESS_RESAMPLE: + return signal.resample(SIGNAL_RESAMPLE_RATE); + case Processings::PROCESS_TIME_STRETCH: + return signal.timeStretch(SIGNAL_TIME_STRETCH_FACTOR); + default: + return signal; + } +} + +//Create the MainScene class +class MainScene : public fge::Scene +{ +public: + void start(fge::RenderWindow& renderWindow) + { + fge::Event event(renderWindow); + fge::GuiElementHandler guiElementHandler(event, renderWindow); + guiElementHandler.setEventCallback(); + + this->setLinkedRenderTarget(&renderWindow); + + //Set default callback context + this->setCallbackContext({&event, &guiElementHandler}); + + //Init texture manager + if (!fge::texture::gManager.initialize()) + { + std::cout << "Failed to initialize texture manager" << std::endl; + return; + } + //Init font manager + if (!fge::font::gManager.initialize()) + { + std::cout << "Failed to initialize font manager" << std::endl; + return; + } + + //Load texture + fge::texture::gManager.loadFromFile("close", "resources/images/window/close.png"); + fge::texture::gManager.loadFromFile("minimize", "resources/images/window/minimize.png"); + fge::texture::gManager.loadFromFile("resize", "resources/images/window/resize.png"); + fge::texture::gManager.loadFromFile("window", "resources/images/window/window.png"); + + //Load font + fge::font::gManager.loadFromFile("base", "resources/fonts/SourceSansPro-Regular.ttf"); + + fge::Clock tick; + + //Create a text object with explanation + auto* explainText = this->newObject({FGE_SCENE_PLAN_HIGH_TOP + 1}, "", "base", + fge::Vector2f{10.0f, 5.0f}, 16); + explainText->setFillColor(fge::Color::Black); + + //Create a window containing a chart that fill it + auto const createChart = [this](fge::Vector2f const& position, fge::Vector2f const& size, fge::Color color) { + auto* objWindow = this->newObject({FGE_SCENE_PLAN_HIGH_TOP}); + objWindow->setTextureClose("close"); + objWindow->setTextureMinimize("minimize"); + objWindow->setTextureResize("resize"); + objWindow->setTexture("window"); + objWindow->setSize(size); + objWindow->setPosition(position); + objWindow->showExitButton(false); + + auto* objChart = objWindow->_windowScene.newObject(); + objChart->setFont("base"); + objChart->setDynamicSize( + {{0.0f, 0.0f}, {fge::DynamicSize::SizeModes::SIZE_AUTO, fge::DynamicSize::SizeModes::SIZE_AUTO}}); + objChart->setPointSize(3.0f); + objChart->setDefaultPointColor(color); + objChart->setLineColor(color); + return objChart; + }; + + auto* generatedChart = createChart({20.0f, 170.0f}, {570.0f, 300.0f}, fge::Color{30, 110, 220}); + auto* processedChart = createChart({610.0f, 170.0f}, {570.0f, 300.0f}, fge::Color{220, 70, 50}); + auto* liveChart = createChart({20.0f, 490.0f}, {1160.0f, 210.0f}, fge::Color{40, 160, 80}); + liveChart->enableAnimation(false); + + //Create the generator with some default waves + fge::SignalGeneratorD generator; + generator.addWave({WaveTypes::WAVE_SINUSOID, 1.0, 1.0, 0.0, 0.5, 0.0}); + generator.addWave({WaveTypes::WAVE_SINUSOID, 0.2, 6.0, 0.0, 0.5, 0.0}); + + auto processing = Processings::PROCESS_SOFT_LIMIT_KEEP_AVERAGE; + fge::SignalD signal; + std::string processingError; + std::string saveStatus; + + auto const updateExplainText = [&]() { + std::ostringstream waves; + waves << std::fixed << std::setprecision(2); + for (std::size_t i = 0; i < generator.getWaveCount() && i < SIGNAL_MAX_DISPLAYED_WAVES; ++i) + { + auto const& wave = generator.getWave(i); + waves << (i == 0 ? "" : ", ") << GetWaveName(wave._type); + if (wave._type == WaveTypes::WAVE_CONTINUOUS) + { + waves << ' ' << wave._offset; + } + else + { + waves << ' ' << wave._frequency << "Hz"; + } + } + if (generator.getWaveCount() > SIGNAL_MAX_DISPLAYED_WAVES) + { + waves << ", ..."; + } + + explainText->setString( + std::string{"Top left: generated signal, top right: processed signal, bottom: live value with " + "getValue()\n" + "1-5: add a random wave (sinusoid, rectangle, sawtooth, triangle, continuous)\n" + "BACKSPACE: remove the last wave, C: clear the waves\n" + "P: change the processing ("} + + GetProcessingName(processing) + + ")\n" + "S: save the generated signal in " SIGNAL_CSV_FILE + + saveStatus + "\nWaves (" + std::to_string(generator.getWaveCount()) + "): " + waves.str() + + (processingError.empty() ? "" : "\nProcessing error: " + processingError)); + }; + + //Generate the signal, process it and update the charts + auto const refresh = [&]() { + signal = generator.generate(SIGNAL_DURATION, SIGNAL_SAMPLE_INTERVAL); + generatedChart->setPoints(signal.getSamples()); + + processingError.clear(); + try + { + processedChart->setPoints(ApplyProcessing(signal, processing).getSamples()); + } + catch (fge::Exception const& e) + { + processingError = e.what(); + processedChart->clearPoints(); + } + + updateExplainText(); + }; + refresh(); + + event._onKeyDown.addLambda([&]([[maybe_unused]] fge::Event const& evt, SDL_KeyboardEvent const& keyEvent) { + saveStatus.clear(); + + switch (keyEvent.key) + { + case SDLK_1: + generator.addWave(CreateRandomWave(WaveTypes::WAVE_SINUSOID)); + break; + case SDLK_2: + generator.addWave(CreateRandomWave(WaveTypes::WAVE_RECTANGLE)); + break; + case SDLK_3: + generator.addWave(CreateRandomWave(WaveTypes::WAVE_SAWTOOTH)); + break; + case SDLK_4: + generator.addWave(CreateRandomWave(WaveTypes::WAVE_TRIANGLE)); + break; + case SDLK_5: + generator.addWave(CreateRandomWave(WaveTypes::WAVE_CONTINUOUS)); + break; + case SDLK_BACKSPACE: + if (generator.getWaveCount() > 0) + { + generator.removeWave(generator.getWaveCount() - 1); + } + break; + case SDLK_C: + generator.clearWaves(); + break; + case SDLK_P: + processing = static_cast((static_cast(processing) + 1) % + static_cast(Processings::PROCESS_COUNT)); + break; + case SDLK_S: + saveStatus = signal.saveToFile(SIGNAL_CSV_FILE) ? " (saved)" : " (failed to save)"; + updateExplainText(); + return; + default: + return; + } + refresh(); + }); + + fge::Clock liveClock; + double lastLiveTime = -SIGNAL_LIVE_SAMPLE_INTERVAL; + + //Begin loop + bool running = true; + while (running) + { + //Update event + event.process(); + if (event.isEventType(SDL_EVENT_QUIT)) + { + running = false; + } + if (event.isEventType(SDL_EVENT_WINDOW_RESIZED)) + { + auto view = renderWindow.getView(); + view.resizeFixCenter({event.getWindowSize().x, event.getWindowSize().y}); + renderWindow.setView(view); + guiElementHandler.checkViewSize(); + } + + //Evaluate the generator in real time, keeping only the last seconds + double const liveTime = std::chrono::duration(liveClock.getElapsedTime()).count(); + if (liveTime - lastLiveTime >= SIGNAL_LIVE_SAMPLE_INTERVAL) + { + lastLiveTime = liveTime; + liveChart->addPoint({liveTime, generator.getValue(liveTime)}); + while (liveChart->getPointCount() > 0 && liveChart->getPoint(0).x < liveTime - SIGNAL_LIVE_DURATION) + { + liveChart->removePoint(0); + } + } + + //Update scene + auto deltaTick = tick.restart(); + this->update(renderWindow, event, std::chrono::duration_cast(deltaTick)); + + //Drawing + auto imageIndex = renderWindow.prepareNextFrame(nullptr, FGE_RENDER_TIMEOUT_BLOCKING); + if (imageIndex != FGE_RENDER_BAD_IMAGE_INDEX) + { + fge::vulkan::GetActiveContext()._garbageCollector.setCurrentFrame(renderWindow.getCurrentFrame()); + + renderWindow.beginRenderPass(imageIndex); + + this->draw(renderWindow); + + renderWindow.endRenderPass(); + + renderWindow.display(imageIndex); + } + } + + fge::vulkan::GetActiveContext().waitIdle(); + + fge::vulkan::GetActiveContext()._garbageCollector.enable(false); + } +}; + +int main([[maybe_unused]] int argc, [[maybe_unused]] char* argv[]) +{ + using namespace fge::vulkan; + + auto instance = Context::init(SDL_INIT_VIDEO | SDL_INIT_EVENTS, "example 011: signals"); + Context::enumerateExtensions(); + + SurfaceSDLWindow window(instance, FGE_WINDOWPOS_CENTERED, {1200, 720}, SDL_WINDOW_RESIZABLE); + + // Check that the window was successfully created + if (!window.isCreated()) + { + // In the case that the window could not be made... + std::cout << "Could not create window: " << SDL_GetError() << std::endl; + return 1; + } + + Context vulkanContext(window); + vulkanContext._garbageCollector.enable(true); + + if (!fge::shader::gManager.initialize()) + { + std::cout << "Could not initialize shader manager" << std::endl; + return 1; + } + fge::shader::gManager.loadFromFile(FGE_OBJSHAPE_INSTANCES_SHADER_VERTEX, + "resources/shaders/objShapeInstances_vertex.vert", Shader::Type::SHADER_VERTEX, + fge::shader::ShaderInputTypes::SHADER_GLSL); + fge::shader::gManager.loadFromFile(FGE_OBJSPRITEBATCHES_SHADER_FRAGMENT, + "resources/shaders/objSpriteBatches_fragment.frag", + Shader::Type::SHADER_FRAGMENT, fge::shader::ShaderInputTypes::SHADER_GLSL); + fge::shader::gManager.loadFromFile(FGE_OBJSPRITEBATCHES_SHADER_VERTEX, + "resources/shaders/objSpriteBatches_vertex.vert", Shader::Type::SHADER_VERTEX, + fge::shader::ShaderInputTypes::SHADER_GLSL); + + fge::RenderWindow renderWindow(vulkanContext, window); + renderWindow.setClearColor(fge::Color::White); + + std::unique_ptr scene = std::make_unique(); + scene->start(renderWindow); + scene.reset(); + + fge::texture::gManager.uninitialize(); + fge::font::gManager.uninitialize(); + fge::shader::gManager.uninitialize(); + + renderWindow.destroy(); + + vulkanContext.destroy(); + + window.destroy(); + instance.destroy(); + SDL_Quit(); + + return 0; +} diff --git a/extensions/CMakeLists.txt b/extensions/CMakeLists.txt index 39883c94..89cfdb4a 100644 --- a/extensions/CMakeLists.txt +++ b/extensions/CMakeLists.txt @@ -1,4 +1,4 @@ -#FastEngine extensions -#Extensions are optional modules built on top of FastEngine, link the ones you need. +#FastEngine optional extensions add_subdirectory(objChart) +add_subdirectory(signals) diff --git a/extensions/README.md b/extensions/README.md index 96cb2413..2cd4af24 100644 --- a/extensions/README.md +++ b/extensions/README.md @@ -8,6 +8,7 @@ Extensions are enabled with the `FGE_BUILD_EXTENSIONS` CMake option (`ON` by def | Extension | CMake target | Description | |-----------|------------------------|-----------------------------------------------| | ObjChart | `FastEngine::ObjChart` | Point chart with linear axes and animated points | +| Signals | `FastEngine::Signals` | Waveform generator and sampled signal processing | ## ObjChart @@ -31,3 +32,29 @@ chart->setPoint(0, {1.0, 4.0}); // animated ``` See `examples/objChart_010` for a complete example. + +## Signals + +A header-only set of tools to generate and process sampled signals. Data can be stored as `float` +(`fge::SignalF`, `fge::SignalGeneratorF`) or `double` (`fge::SignalD`, `fge::SignalGeneratorD`). + +- `fge::SignalGenerator`: sum of waveforms (sinusoid, rectangle, sawtooth, triangle, continuous), + generated as a signal or evaluated in real time with `getValue()` +- `fge::Signal`: list of (time, value) samples with strictly increasing times +- Processing: `resample()`, `derivative()`, `integral()`, `softLimit()`, `softLimitKeepAverage()`, `timeStretch()` +- CSV save/load +- Samples are `fge::Vector2` (x = time, y = value) and can be given directly to a `fge::ObjChart` + +```cpp +#include "FastEngine/extensions/C_signalGenerator.hpp" + +fge::SignalGeneratorD generator; +generator.addWave({fge::SignalGeneratorD::WaveTypes::WAVE_SINUSOID, 1.0, 2.0}); // amplitude 1, 2 Hz +generator.addWave({fge::SignalGeneratorD::WaveTypes::WAVE_RECTANGLE, 0.3, 5.0}); + +auto const signal = generator.generate(2.0, 0.01); // 2 seconds, one sample every 10 ms +auto const limited = signal.softLimitKeepAverage(-1.0, 1.0, 4.0); +chart->setPoints(limited.getSamples()); +``` + +See `examples/signals_011` for a complete example. diff --git a/extensions/objChart/CMakeLists.txt b/extensions/objChart/CMakeLists.txt index 588ed8b6..f387555b 100644 --- a/extensions/objChart/CMakeLists.txt +++ b/extensions/objChart/CMakeLists.txt @@ -1,4 +1,3 @@ -#ObjChart extension (header only) set(FGE_EXT_OBJCHART_LIB_NAME "${PROJECT_NAME}ObjChart") add_library(${FGE_EXT_OBJCHART_LIB_NAME} INTERFACE) diff --git a/extensions/signals/CMakeLists.txt b/extensions/signals/CMakeLists.txt new file mode 100644 index 00000000..591d7df9 --- /dev/null +++ b/extensions/signals/CMakeLists.txt @@ -0,0 +1,18 @@ +set(FGE_EXT_SIGNALS_LIB_NAME "${PROJECT_NAME}Signals") + +add_library(${FGE_EXT_SIGNALS_LIB_NAME} INTERFACE) +add_library(${PROJECT_NAME}::Signals ALIAS ${FGE_EXT_SIGNALS_LIB_NAME}) +set_target_properties(${FGE_EXT_SIGNALS_LIB_NAME} PROPERTIES EXPORT_NAME Signals) + +target_sources(${FGE_EXT_SIGNALS_LIB_NAME} INTERFACE FILE_SET publicHeaders TYPE HEADERS + BASE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/includes + FILES + includes/FastEngine/extensions/C_signal.hpp + includes/FastEngine/extensions/C_signal.inl + includes/FastEngine/extensions/C_signalGenerator.hpp + includes/FastEngine/extensions/C_signalGenerator.inl) + +target_link_libraries(${FGE_EXT_SIGNALS_LIB_NAME} INTERFACE ${FGE_LIB_NAME}) + +install(TARGETS ${FGE_EXT_SIGNALS_LIB_NAME} EXPORT ${PROJECT_NAME}Targets + FILE_SET publicHeaders DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}) diff --git a/extensions/signals/includes/FastEngine/extensions/C_signal.hpp b/extensions/signals/includes/FastEngine/extensions/C_signal.hpp new file mode 100644 index 00000000..5153c574 --- /dev/null +++ b/extensions/signals/includes/FastEngine/extensions/C_signal.hpp @@ -0,0 +1,302 @@ +/* + * Copyright 2026 Guillaume Guillet + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _FGE_EXT_C_SIGNAL_HPP_INCLUDED +#define _FGE_EXT_C_SIGNAL_HPP_INCLUDED + +#include "FastEngine/C_vector.hpp" +#include "FastEngine/fge_except.hpp" +#include +#include +#include + +#define FGE_SIGNAL_CSV_HEADER "time_s,data" +#define FGE_SIGNAL_KEEP_AVERAGE_MAX_ITERATIONS 256 +#define FGE_SIGNAL_KEEP_AVERAGE_TOLERANCE 8 + +namespace fge +{ + +/** + * \brief The data types supported by Signal and SignalGenerator + */ +template +concept SignalValueType = std::same_as || std::same_as; + +/** + * \class Signal + * \ingroup extensions + * \brief A sampled signal, a list of (time, value) samples + * + * Each sample is stored as a fge::Vector2 where: + * - \b x is the time in seconds + * - \b y is the value + * + * Times are always strictly increasing, + * this is checked every time a sample is added. + * The time spacing between samples doesn't need to be constant. + * + * Every processing method (derivative(), integral(), softLimit(), ...) + * returns a new Signal and keeps the original one untouched. + * + * The samples can be directly given to a fge::ObjChart: + * \code + * chart->setPoints(signal.getSamples()); + * \endcode + * + * \tparam T The data type, float or double + */ +template +class Signal +{ +public: + using ValueType = T; + using Sample = fge::Vector2; + using const_iterator = typename std::vector::const_iterator; + + Signal() = default; + /** + * \brief Construct a signal from a list of samples + * + * If the times are not strictly increasing, + * a fge::Exception is thrown. + * + * \param samples The samples, x is the time and y the value + */ + explicit Signal(std::vector samples); + + //Samples + + /** + * \brief Add a sample at the end of the signal + * + * The time must be strictly greater than the time of the last sample, + * otherwise a fge::Exception is thrown. + * + * \param time The time in seconds + * \param value The value + */ + void addSample(T time, T value); + /** + * \brief Add a sample at the end of the signal + * + * \see addSample(T, T) + * + * \param sample The sample, x is the time and y the value + */ + void addSample(Sample const& sample); + /** + * \brief Change the value of an existing sample + * + * The time of the sample is not modified. + * + * \param index The index of the sample + * \param value The new value + */ + void setValue(std::size_t index, T value); + /** + * \brief Reserve memory for a number of samples + * + * \param count The number of samples + */ + void reserve(std::size_t count); + /** + * \brief Remove every samples + */ + void clear(); + + [[nodiscard]] std::size_t getSampleCount() const; + [[nodiscard]] bool isEmpty() const; + [[nodiscard]] Sample const& getSample(std::size_t index) const; + [[nodiscard]] std::vector const& getSamples() const; + + /** + * \brief Get the time of the first sample + * + * \return The start time, or 0 if the signal is empty + */ + [[nodiscard]] T getStartTime() const; + /** + * \brief Get the time of the last sample + * + * \return The end time, or 0 if the signal is empty + */ + [[nodiscard]] T getEndTime() const; + /** + * \brief Get the time between the first and the last sample + * + * \return The duration in seconds + */ + [[nodiscard]] T getDuration() const; + /** + * \brief Get the time-weighted average value of the signal + * + * The average is computed with the trapezoidal rule, + * this is the integral of the signal divided by its duration. + * + * An empty signal returns 0. + * A signal with only one sample returns the value of this sample. + * + * \return The average value + */ + [[nodiscard]] T getAverage() const; + + [[nodiscard]] const_iterator begin() const; + [[nodiscard]] const_iterator end() const; + + //Processing + + /** + * \brief Resample the signal with a fixed sample rate + * + * New samples are placed at: start + i / sampleRate, + * values are linearly interpolated from the original samples. + * + * The last original sample is only kept if it falls on the new time grid, + * values are never extrapolated. + * + * \warning When downsampling, no anti-aliasing filter is applied. + * + * A fge::Exception is thrown if the sample rate is not positive. + * + * \param sampleRate The new sample rate in samples per second + * \return The resampled signal + */ + [[nodiscard]] fge::Signal resample(T sampleRate) const; + /** + * \brief Compute the derivative of the signal + * + * A three-point derivative is used, boundaries included, + * an uneven time spacing is supported. + * + * With only two samples, the simple slope is used. + * With only one sample, the derivative is 0. + * + * \return The derivative, with the original times + */ + [[nodiscard]] fge::Signal derivative() const; + /** + * \brief Compute the cumulative integral of the signal + * + * The trapezoidal rule is used, + * the integral starts at 0 on the first sample. + * + * \return The integral, with the original times + */ + [[nodiscard]] fge::Signal integral() const; + /** + * \brief Smoothly compress the values toward the provided bounds + * + * With: + * - c = (lower + upper) / 2 + * - r = upper - c + * - p = smoothness + * + * every value x becomes: + * c + (x - c) / pow(1 + pow(abs(x - c) / r, p), 1 / p) + * + * A bigger smoothness gets closer to a hard clipping. + * + * A fge::Exception is thrown if lower is not smaller than upper + * or if the smoothness is not positive. + * + * \param lower The lower bound + * \param upper The upper bound + * \param smoothness The smoothness exponent, must be positive + * \return The limited signal, with the original times + */ + [[nodiscard]] fge::Signal softLimit(T lower, T upper, T smoothness) const; + /** + * \brief Same as softLimit() but keep the average value of the signal + * + * A soft limiter compresses the peaks, so the signal average can move. + * Here, the signal is shifted internally (by a constant bias found by bisection) + * before being limited, in order to keep the same average value + * and so the same area under the curve. + * + * The average value of the signal must be strictly between lower and upper, + * otherwise a fge::Exception is thrown. + * + * If the wanted precision can't be reached, + * the closest result found is returned. + * + * \see softLimit() + * + * \param lower The lower bound + * \param upper The upper bound + * \param smoothness The smoothness exponent, must be positive + * \return The limited signal, with the original times and the same average value + */ + [[nodiscard]] fge::Signal softLimitKeepAverage(T lower, T upper, T smoothness) const; + /** + * \brief Scale the elapsed time from the first sample + * + * Values are not modified. + * - A factor greater than 1 stretches the signal + * - A factor smaller than 1 compresses the signal + * + * A fge::Exception is thrown if the factor is not positive. + * + * \param factor The time factor, must be positive + * \return The stretched signal + */ + [[nodiscard]] fge::Signal timeStretch(T factor) const; + + //File + + /** + * \brief Save the signal in a two columns CSV file + * + * The first line is the header: "time_s,data". + * An existing file is overwritten. + * + * \param path The path of the file + * \return \b true if successful, \b false otherwise + */ + bool saveToFile(std::filesystem::path const& path) const; + /** + * \brief Load a signal from a two columns CSV file + * + * A header on the first line is skipped. + * Times must be strictly increasing. + * + * On failure, the signal is not modified. + * + * \param path The path of the file + * \return \b true if successful, \b false otherwise + */ + bool loadFromFile(std::filesystem::path const& path); + +private: + /** + * \brief Apply the soft limiter formula on the values of this signal into the result + * + * The bias is subtracted from every value before applying the formula. + * The result must have the same samples count as this signal. + */ + void applySoftLimit(fge::Signal& result, T lower, T upper, T smoothness, T bias) const; + + std::vector g_samples; +}; + +using SignalF = Signal; +using SignalD = Signal; + +} // namespace fge + +#include "C_signal.inl" + +#endif // _FGE_EXT_C_SIGNAL_HPP_INCLUDED diff --git a/extensions/signals/includes/FastEngine/extensions/C_signal.inl b/extensions/signals/includes/FastEngine/extensions/C_signal.inl new file mode 100644 index 00000000..aeb1ed24 --- /dev/null +++ b/extensions/signals/includes/FastEngine/extensions/C_signal.inl @@ -0,0 +1,477 @@ +/* + * Copyright 2026 Guillaume Guillet + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fge +{ + +template +Signal::Signal(std::vector samples) : + g_samples(std::move(samples)) +{ + for (std::size_t i = 1; i < this->g_samples.size(); ++i) + { + if (this->g_samples[i].x <= this->g_samples[i - 1].x) + { + throw fge::Exception("Signal : times must be strictly increasing"); + } + } +} + +template +void Signal::addSample(T time, T value) +{ + if (!this->g_samples.empty() && time <= this->g_samples.back().x) + { + throw fge::Exception("Signal : times must be strictly increasing"); + } + this->g_samples.emplace_back(time, value); +} +template +void Signal::addSample(Sample const& sample) +{ + this->addSample(sample.x, sample.y); +} +template +void Signal::setValue(std::size_t index, T value) +{ + this->g_samples[index].y = value; +} +template +void Signal::reserve(std::size_t count) +{ + this->g_samples.reserve(count); +} +template +void Signal::clear() +{ + this->g_samples.clear(); +} + +template +std::size_t Signal::getSampleCount() const +{ + return this->g_samples.size(); +} +template +bool Signal::isEmpty() const +{ + return this->g_samples.empty(); +} +template +typename Signal::Sample const& Signal::getSample(std::size_t index) const +{ + return this->g_samples[index]; +} +template +std::vector::Sample> const& Signal::getSamples() const +{ + return this->g_samples; +} + +template +T Signal::getStartTime() const +{ + return this->g_samples.empty() ? T{0} : this->g_samples.front().x; +} +template +T Signal::getEndTime() const +{ + return this->g_samples.empty() ? T{0} : this->g_samples.back().x; +} +template +T Signal::getDuration() const +{ + return this->getEndTime() - this->getStartTime(); +} +template +T Signal::getAverage() const +{ + if (this->g_samples.empty()) + { + return T{0}; + } + if (this->g_samples.size() == 1) + { + return this->g_samples.front().y; + } + + //Kahan summation of the trapezoids, weighted by their relative duration + T const duration = this->getDuration(); + T average{0}; + T correction{0}; + for (std::size_t i = 1; i < this->g_samples.size(); ++i) + { + Sample const& previous = this->g_samples[i - 1]; + Sample const& current = this->g_samples[i]; + + T const weight = (current.x - previous.x) / duration; + T const term = weight * std::midpoint(previous.y, current.y) - correction; + T const next = average + term; + correction = (next - average) - term; + average = next; + } + return average; +} + +template +typename Signal::const_iterator Signal::begin() const +{ + return this->g_samples.cbegin(); +} +template +typename Signal::const_iterator Signal::end() const +{ + return this->g_samples.cend(); +} + +template +fge::Signal Signal::resample(T sampleRate) const +{ + if (!(sampleRate > T{0})) + { + throw fge::Exception("Signal : sample rate must be positive"); + } + + fge::Signal result; + if (this->g_samples.empty()) + { + return result; + } + + T const interval = T{1} / sampleRate; + T const startTime = this->getStartTime(); + T const endTime = this->getEndTime(); + auto const count = static_cast(std::floor((endTime - startTime) / interval)) + 1; + result.reserve(count); + + std::size_t j = 0; + for (std::size_t i = 0; i < count; ++i) + { + T const time = std::fma(static_cast(i), interval, startTime); + //Floating-point rounding can place the last time just after the end + if (time > endTime) + { + break; + } + + while (j + 1 < this->g_samples.size() && this->g_samples[j + 1].x < time) + { + ++j; + } + + Sample const& previous = this->g_samples[j]; + if (time == previous.x || j + 1 == this->g_samples.size()) + { + result.addSample(time, previous.y); + } + else + { + Sample const& next = this->g_samples[j + 1]; + T const fraction = (time - previous.x) / (next.x - previous.x); + result.addSample(time, std::lerp(previous.y, next.y, fraction)); + } + } + return result; +} +template +fge::Signal Signal::derivative() const +{ + fge::Signal result = *this; + std::size_t const n = this->g_samples.size(); + + switch (n) + { + case 0: + return result; + case 1: + result.g_samples[0].y = T{0}; + return result; + case 2: + { + Sample const& a = this->g_samples[0]; + Sample const& b = this->g_samples[1]; + T const slope = (b.y - a.y) / (b.x - a.x); + result.g_samples[0].y = slope; + result.g_samples[1].y = slope; + return result; + } + default: + break; + } + + //Three-point derivative, the window is shifted at the boundaries + for (std::size_t i = 0; i < n; ++i) + { + std::size_t const j = i == 0 ? 0 : (i == n - 1 ? n - 3 : i - 1); + Sample const& s0 = this->g_samples[j]; + Sample const& s1 = this->g_samples[j + 1]; + Sample const& s2 = this->g_samples[j + 2]; + T const time = this->g_samples[i].x; + + T const h0 = s1.x - s0.x; + T const h1 = s2.x - s1.x; + T const slope0 = (s1.y - s0.y) / h0; + T const slope1 = (s2.y - s1.y) / h1; + T const curvature = (slope1 - slope0) / (h0 + h1); + result.g_samples[i].y = slope0 + curvature * ((time - s0.x) + (time - s1.x)); + } + return result; +} +template +fge::Signal Signal::integral() const +{ + fge::Signal result = *this; + if (result.g_samples.empty()) + { + return result; + } + + result.g_samples[0].y = T{0}; + for (std::size_t i = 1; i < this->g_samples.size(); ++i) + { + Sample const& previous = this->g_samples[i - 1]; + Sample const& current = this->g_samples[i]; + + T const dt = current.x - previous.x; + result.g_samples[i].y = result.g_samples[i - 1].y + std::midpoint(previous.y, current.y) * dt; + } + return result; +} +template +fge::Signal Signal::softLimit(T lower, T upper, T smoothness) const +{ + if (!(lower < upper)) + { + throw fge::Exception("Signal : soft limit lower bound must be smaller than the upper bound"); + } + if (!(smoothness > T{0})) + { + throw fge::Exception("Signal : soft limit smoothness must be positive"); + } + + fge::Signal result = *this; + this->applySoftLimit(result, lower, upper, smoothness, T{0}); + return result; +} +template +fge::Signal Signal::softLimitKeepAverage(T lower, T upper, T smoothness) const +{ + fge::Signal result = this->softLimit(lower, upper, smoothness); + if (this->g_samples.size() < 2) + { + return result; + } + + //Comparing averages is equivalent to comparing integrals + T const target = this->getAverage(); + if (!(target > lower && target < upper)) + { + throw fge::Exception("Signal : the average value must be between the soft limit bounds"); + } + + T const tolerance = static_cast(FGE_SIGNAL_KEEP_AVERAGE_TOLERANCE) * std::numeric_limits::epsilon() * + std::max(std::abs(lower), std::abs(upper)); + if (std::abs(result.getAverage() - target) <= tolerance) + { + return result; + } + + //A positive bias lowers the average, a negative one raises it. + //Find a [low, high] bias range that contains the target average. + T step = std::max(std::abs(lower), std::abs(upper)); + for (auto const& sample: this->g_samples) + { + step = std::max(step, std::abs(sample.y)); + } + + T const maxBias = std::numeric_limits::max(); + auto const expandBias = [&](T& bias, bool raiseAverage) { + for (std::size_t i = 0; i < FGE_SIGNAL_KEEP_AVERAGE_MAX_ITERATIONS; ++i) + { + this->applySoftLimit(result, lower, upper, smoothness, bias); + T const average = result.getAverage(); + if (raiseAverage ? average >= target : average <= target) + { + return; + } + T const magnitude = std::abs(bias); + if (magnitude == maxBias) + { + return; + } + bias = std::copysign(magnitude > maxBias / T{2} ? maxBias : magnitude * T{2}, bias); + } + }; + + T low = -step; + T high = step; + expandBias(low, true); + expandBias(high, false); + + //Bisection, the closest result is kept in case the tolerance is never reached + T bestBias = T{0}; + T bestError = std::numeric_limits::infinity(); + for (std::size_t i = 0; i < FGE_SIGNAL_KEEP_AVERAGE_MAX_ITERATIONS; ++i) + { + T const bias = std::midpoint(low, high); + this->applySoftLimit(result, lower, upper, smoothness, bias); + T const average = result.getAverage(); + T const error = std::abs(average - target); + if (error <= tolerance) + { + return result; + } + if (error < bestError) + { + bestError = error; + bestBias = bias; + } + + if (bias == low || bias == high) + { + break; + } + if (average > target) + { + low = bias; + } + else + { + high = bias; + } + } + + this->applySoftLimit(result, lower, upper, smoothness, bestBias); + return result; +} +template +fge::Signal Signal::timeStretch(T factor) const +{ + if (!(factor > T{0})) + { + throw fge::Exception("Signal : time stretch factor must be positive"); + } + + fge::Signal result; + result.reserve(this->g_samples.size()); + + T const startTime = this->getStartTime(); + for (auto const& sample: this->g_samples) + { + result.addSample(startTime + (sample.x - startTime) * factor, sample.y); + } + return result; +} + +template +bool Signal::saveToFile(std::filesystem::path const& path) const +{ + std::ofstream file(path); + if (!file) + { + return false; + } + + file << FGE_SIGNAL_CSV_HEADER << '\n'; + file << std::setprecision(std::numeric_limits::max_digits10); + for (auto const& sample: this->g_samples) + { + file << sample.x << ',' << sample.y << '\n'; + } + return static_cast(file); +} +template +bool Signal::loadFromFile(std::filesystem::path const& path) +{ + std::ifstream file(path); + if (!file) + { + return false; + } + + std::vector samples; + std::string line; + bool firstLine = true; + while (std::getline(file, line)) + { + if (!line.empty() && line.back() == '\r') + { + line.pop_back(); + } + if (line.empty()) + { + continue; + } + + std::istringstream stream(line); + Sample sample; + char separator = 0; + if (!(stream >> sample.x >> separator >> sample.y) || separator != ',') + { + if (firstLine) + { + //The first line can be a header + firstLine = false; + continue; + } + return false; + } + firstLine = false; + + if (!samples.empty() && sample.x <= samples.back().x) + { + return false; + } + samples.push_back(sample); + } + + this->g_samples = std::move(samples); + return true; +} + +template +void Signal::applySoftLimit(fge::Signal& result, T lower, T upper, T smoothness, T bias) const +{ + T const center = std::midpoint(lower, upper); + T const radius = upper - center; + + for (std::size_t i = 0; i < this->g_samples.size(); ++i) + { + T const offset = (this->g_samples[i].y - center) - bias; + T const magnitude = std::abs(offset); + + //Equivalent forms, keeping the inner power base in [0, 1] + T limited{0}; + if (radius > T{0}) + { + limited = magnitude <= radius + ? magnitude / std::pow(T{1} + std::pow(magnitude / radius, smoothness), T{1} / smoothness) + : radius / std::pow(T{1} + std::pow(radius / magnitude, smoothness), T{1} / smoothness); + } + result.g_samples[i].y = std::clamp(center + std::copysign(limited, offset), lower, upper); + } +} + +} // namespace fge diff --git a/extensions/signals/includes/FastEngine/extensions/C_signalGenerator.hpp b/extensions/signals/includes/FastEngine/extensions/C_signalGenerator.hpp new file mode 100644 index 00000000..f53b3be5 --- /dev/null +++ b/extensions/signals/includes/FastEngine/extensions/C_signalGenerator.hpp @@ -0,0 +1,174 @@ +/* + * Copyright 2026 Guillaume Guillet + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _FGE_EXT_C_SIGNALGENERATOR_HPP_INCLUDED +#define _FGE_EXT_C_SIGNALGENERATOR_HPP_INCLUDED + +#include "FastEngine/extensions/C_signal.hpp" +#include + +namespace fge +{ + +/** + * \class SignalGenerator + * \ingroup extensions + * \brief Generate a signal from a sum of waveforms + * + * Waves are added with addWave(), the generated value at a given time + * is the sum of every stored wave. + * + * A signal can be generated with: + * - generate() for a duration and a sample interval + * - generateSamples() for an exact number of samples and a sample rate + * + * The value can also be evaluated at any time with getValue(), + * useful to drive something in real time without generating a whole signal. + * + * \tparam T The data type, float or double + */ +template +class SignalGenerator +{ +public: + using ValueType = T; + + enum class WaveTypes + { + WAVE_SINUSOID, ///< Sine wave + WAVE_RECTANGLE, ///< Two-level wave, the high-time fraction is the duty cycle + WAVE_SAWTOOTH, ///< Linear rising ramp with an abrupt reset + WAVE_TRIANGLE, ///< Linear rise and fall, the rise-time fraction is the duty cycle + WAVE_CONTINUOUS ///< Constant value equal to the offset + }; + + /** + * \brief Parameters of one waveform + * + * WAVE_CONTINUOUS only uses the offset. + */ + struct Wave + { + WaveTypes _type{WaveTypes::WAVE_SINUSOID}; + T _amplitude{1}; ///< Scale of the waveform around the offset + T _frequency{1}; ///< Frequency in hertz + T _phaseDegrees{0}; ///< Phase shift in degrees + /** + * \brief Rectangle high-time fraction or triangle rise-time fraction + * + * The value is clamped in [0, 1]. + * A triangle is symmetric at 0.5. + * + * Ignored by the other waveforms. + */ + T _dutyCycle{0.5}; + T _offset{0}; ///< Additive offset, the constant value for WAVE_CONTINUOUS + }; + + SignalGenerator() = default; + + //Waves + + /** + * \brief Add a waveform + * + * The duty cycle is clamped in [0, 1]. + * + * \param wave The waveform parameters + * \return The index of the added wave + */ + std::size_t addWave(Wave const& wave); + /** + * \brief Replace an existing waveform + * + * The duty cycle is clamped in [0, 1]. + * + * \param index The index of the wave + * \param wave The new waveform parameters + */ + void setWave(std::size_t index, Wave const& wave); + /** + * \brief Remove a waveform + * + * Next waves indices are shifted down by one. + * + * \param index The index of the wave + */ + void removeWave(std::size_t index); + /** + * \brief Remove every waveforms + */ + void clearWaves(); + + [[nodiscard]] std::size_t getWaveCount() const; + [[nodiscard]] Wave const& getWave(std::size_t index) const; + [[nodiscard]] std::vector const& getWaves() const; + + //Generation + + /** + * \brief Compute the sum of every waves at a given time + * + * Without any wave, the value is 0. + * + * \param time The time in seconds + * \return The value + */ + [[nodiscard]] T getValue(T time) const; + /** + * \brief Generate an exact number of samples + * + * The first sample is at time 0, + * the next ones are spaced by 1 / sampleRate. + * + * A fge::Exception is thrown if the sample rate is not positive. + * + * \param count The number of samples + * \param sampleRate The sample rate in samples per second + * \return The generated signal + */ + [[nodiscard]] fge::Signal generateSamples(std::size_t count, T sampleRate) const; + /** + * \brief Generate a signal for a duration + * + * The first sample is at time 0 and the last one at the duration + * (rounded to the nearest sample interval). + * A duration of 0 returns one sample. + * + * A fge::Exception is thrown if the duration is negative + * or if the sample interval is not positive. + * + * \param duration The duration in seconds + * \param sampleInterval The time between two samples in seconds + * \return The generated signal + */ + [[nodiscard]] fge::Signal generate(T duration, T sampleInterval) const; + +private: + [[nodiscard]] static Wave sanitizeWave(Wave wave); + [[nodiscard]] fge::Signal generateImpl(std::size_t count, T sampleInterval) const; + + std::vector g_waves; +}; + +using SignalGeneratorF = SignalGenerator; +using SignalGeneratorD = SignalGenerator; + +} // namespace fge + +#include "C_signalGenerator.inl" + +#endif // _FGE_EXT_C_SIGNALGENERATOR_HPP_INCLUDED diff --git a/extensions/signals/includes/FastEngine/extensions/C_signalGenerator.inl b/extensions/signals/includes/FastEngine/extensions/C_signalGenerator.inl new file mode 100644 index 00000000..5da8c2a2 --- /dev/null +++ b/extensions/signals/includes/FastEngine/extensions/C_signalGenerator.inl @@ -0,0 +1,152 @@ +/* + * Copyright 2026 Guillaume Guillet + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +namespace fge +{ + +template +std::size_t SignalGenerator::addWave(Wave const& wave) +{ + this->g_waves.push_back(sanitizeWave(wave)); + return this->g_waves.size() - 1; +} +template +void SignalGenerator::setWave(std::size_t index, Wave const& wave) +{ + this->g_waves[index] = sanitizeWave(wave); +} +template +void SignalGenerator::removeWave(std::size_t index) +{ + this->g_waves.erase(this->g_waves.begin() + static_cast(index)); +} +template +void SignalGenerator::clearWaves() +{ + this->g_waves.clear(); +} + +template +std::size_t SignalGenerator::getWaveCount() const +{ + return this->g_waves.size(); +} +template +typename SignalGenerator::Wave const& SignalGenerator::getWave(std::size_t index) const +{ + return this->g_waves[index]; +} +template +std::vector::Wave> const& SignalGenerator::getWaves() const +{ + return this->g_waves; +} + +template +T SignalGenerator::getValue(T time) const +{ + T result{0}; + for (auto const& wave: this->g_waves) + { + if (wave._type == WaveTypes::WAVE_CONTINUOUS) + { + result += wave._offset; + continue; + } + + T const cycles = wave._frequency * time + wave._phaseDegrees / T{360}; + T const phase = cycles - std::floor(cycles); //[0, 1) + + T value{0}; + switch (wave._type) + { + case WaveTypes::WAVE_SINUSOID: + value = std::sin(T{2} * std::numbers::pi_v * phase); + break; + case WaveTypes::WAVE_RECTANGLE: + value = phase < wave._dutyCycle ? T{1} : T{-1}; + break; + case WaveTypes::WAVE_SAWTOOTH: + value = T{2} * phase - T{1}; + break; + case WaveTypes::WAVE_TRIANGLE: + if (phase < wave._dutyCycle) + { + value = T{2} * phase / wave._dutyCycle - T{1}; + } + else + { + value = T{1} - T{2} * (phase - wave._dutyCycle) / (T{1} - wave._dutyCycle); + } + break; + default: + break; + } + + result += wave._offset + wave._amplitude * value; + } + return result; +} +template +fge::Signal SignalGenerator::generateSamples(std::size_t count, T sampleRate) const +{ + if (!(sampleRate > T{0})) + { + throw fge::Exception("SignalGenerator : sample rate must be positive"); + } + return this->generateImpl(count, T{1} / sampleRate); +} +template +fge::Signal SignalGenerator::generate(T duration, T sampleInterval) const +{ + if (!(duration >= T{0})) + { + throw fge::Exception("SignalGenerator : duration must not be negative"); + } + if (!(sampleInterval > T{0})) + { + throw fge::Exception("SignalGenerator : sample interval must be positive"); + } + + auto const count = static_cast(std::round(duration / sampleInterval)) + 1; + return this->generateImpl(count, sampleInterval); +} + +template +typename SignalGenerator::Wave SignalGenerator::sanitizeWave(Wave wave) +{ + wave._dutyCycle = std::clamp(wave._dutyCycle, T{0}, T{1}); + return wave; +} +template +fge::Signal SignalGenerator::generateImpl(std::size_t count, T sampleInterval) const +{ + fge::Signal signal; + signal.reserve(count); + + for (std::size_t i = 0; i < count; ++i) + { + T const time = static_cast(i) * sampleInterval; + signal.addSample(time, this->getValue(time)); + } + return signal; +} + +} // namespace fge diff --git a/includes/FastEngine/fge_extern.hpp b/includes/FastEngine/fge_extern.hpp index 8284bdda..f1f8109d 100644 --- a/includes/FastEngine/fge_extern.hpp +++ b/includes/FastEngine/fge_extern.hpp @@ -68,4 +68,10 @@ * * \defgroup managers Global managers * \brief Everything related to global managers + * + * \defgroup extensions Extensions + * \brief Everything related to the optional extensions + * + * Extensions are optional modules built on top of FastEngine, + * they are not part of the core library (see the extensions/ directory). */ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8b46184a..539632c0 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -31,6 +31,10 @@ fge_add_test(fgeCallbackTests test_fge_callback.cpp "${TESTS_DEPENDENCIES}") fge_add_test(fgeTinyUtf8Tests test_fge_tinyutf8.cpp "${TESTS_DEPENDENCIES}") fge_add_test(fgeTinyUtf8NoExceptTests test_fge_tinyutf8_noexcept.cpp "${TESTS_DEPENDENCIES}") +if (FGE_BUILD_EXTENSIONS) + fge_add_test(fgeSignalsTests test_fge_signals.cpp "${TESTS_DEPENDENCIES};${PROJECT_NAME}::Signals") +endif() + # tiny_utf8 tests contain UTF-8 literals target_compile_options(fgeTinyUtf8Tests PRIVATE $<$:/utf-8>) target_compile_options(fgeTinyUtf8NoExceptTests PRIVATE $<$:/utf-8>) diff --git a/tests/test_fge_signals.cpp b/tests/test_fge_signals.cpp new file mode 100644 index 00000000..cf1bf525 --- /dev/null +++ b/tests/test_fge_signals.cpp @@ -0,0 +1,240 @@ +/* + * Copyright 2026 Guillaume Guillet + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "FastEngine/extensions/C_signalGenerator.hpp" +#include "doctest/doctest.h" +#include + +TEST_CASE("testing signal samples") +{ + fge::SignalD signal; + REQUIRE(signal.isEmpty()); + REQUIRE(signal.getAverage() == 0.0); + + signal.addSample(0.0, 1.0); + signal.addSample(1.0, 3.0); + signal.addSample({3.0, 3.0}); + REQUIRE(signal.getSampleCount() == 3); + REQUIRE(signal.getStartTime() == 0.0); + REQUIRE(signal.getEndTime() == 3.0); + REQUIRE(signal.getDuration() == 3.0); + + //(2 * 1 + 3 * 2) / 3 + CHECK(signal.getAverage() == doctest::Approx(8.0 / 3.0)); + + SUBCASE("times must be strictly increasing") + { + CHECK_THROWS_AS(signal.addSample(3.0, 0.0), fge::Exception); + CHECK_THROWS_AS(signal.addSample(2.0, 0.0), fge::Exception); + CHECK_THROWS_AS(fge::SignalD({{0.0, 0.0}, {0.0, 1.0}}), fge::Exception); + REQUIRE(signal.getSampleCount() == 3); + } + + SUBCASE("set value") + { + signal.setValue(1, -2.0); + CHECK(signal.getSample(1) == fge::SignalD::Sample{1.0, -2.0}); + } +} + +TEST_CASE("testing signal generator") +{ + using Generator = fge::SignalGeneratorD; + using WaveTypes = Generator::WaveTypes; + + Generator generator; + REQUIRE(generator.getValue(0.3) == 0.0); + + SUBCASE("sample count and times") + { + auto const signal = generator.generate(1.0, 0.1); + REQUIRE(signal.getSampleCount() == 11); + CHECK(signal.getEndTime() == doctest::Approx(1.0)); + + auto const samples = generator.generateSamples(5, 10.0); + REQUIRE(samples.getSampleCount() == 5); + CHECK(samples.getEndTime() == doctest::Approx(0.4)); + + CHECK(generator.generate(0.0, 0.1).getSampleCount() == 1); + CHECK(generator.generateSamples(0, 10.0).isEmpty()); + + CHECK_THROWS_AS((void) generator.generate(-1.0, 0.1), fge::Exception); + CHECK_THROWS_AS((void) generator.generate(1.0, 0.0), fge::Exception); + CHECK_THROWS_AS((void) generator.generateSamples(5, -1.0), fge::Exception); + } + + SUBCASE("sinusoid") + { + generator.addWave({WaveTypes::WAVE_SINUSOID, 2.0, 1.0, 0.0, 0.5, 0.0}); + auto const signal = generator.generateSamples(4, 4.0); + CHECK(signal.getSample(0).y == doctest::Approx(0.0)); + CHECK(signal.getSample(1).y == doctest::Approx(2.0)); + CHECK(signal.getSample(2).y == doctest::Approx(0.0)); + CHECK(signal.getSample(3).y == doctest::Approx(-2.0)); + + //90 degrees phase shift + generator.setWave(0, {WaveTypes::WAVE_SINUSOID, 1.0, 1.0, 90.0, 0.5, 0.0}); + CHECK(generator.getValue(0.0) == doctest::Approx(1.0)); + } + + SUBCASE("rectangle") + { + generator.addWave({WaveTypes::WAVE_RECTANGLE, 1.0, 1.0, 0.0, 0.25, 0.0}); + CHECK(generator.getValue(0.1) == 1.0); + CHECK(generator.getValue(0.3) == -1.0); + } + + SUBCASE("sawtooth and triangle") + { + generator.addWave({WaveTypes::WAVE_SAWTOOTH, 1.0, 1.0, 0.0, 0.5, 0.0}); + CHECK(generator.getValue(0.25) == doctest::Approx(-0.5)); + + generator.setWave(0, {WaveTypes::WAVE_TRIANGLE, 1.0, 1.0, 0.0, 0.5, 0.0}); + CHECK(generator.getValue(0.0) == doctest::Approx(-1.0)); + CHECK(generator.getValue(0.5) == doctest::Approx(1.0)); + CHECK(generator.getValue(0.75) == doctest::Approx(0.0)); + } + + SUBCASE("continuous and sum of waves") + { + generator.addWave({WaveTypes::WAVE_CONTINUOUS, 10.0, 10.0, 0.0, 0.5, 0.5}); + generator.addWave({WaveTypes::WAVE_SAWTOOTH, 1.0, 1.0, 0.0, 0.5, 0.0}); + CHECK(generator.getValue(0.25) == doctest::Approx(0.0)); + REQUIRE(generator.getWaveCount() == 2); + + generator.removeWave(1); + REQUIRE(generator.getWaveCount() == 1); + CHECK(generator.getValue(0.25) == doctest::Approx(0.5)); + + generator.clearWaves(); + REQUIRE(generator.getWaveCount() == 0); + } + + SUBCASE("duty cycle is clamped") + { + generator.addWave({WaveTypes::WAVE_TRIANGLE, 1.0, 1.0, 0.0, 2.0, 0.0}); + CHECK(generator.getWave(0)._dutyCycle == 1.0); + generator.setWave(0, {WaveTypes::WAVE_TRIANGLE, 1.0, 1.0, 0.0, -1.0, 0.0}); + CHECK(generator.getWave(0)._dutyCycle == 0.0); + } +} + +TEST_CASE("testing signal processing") +{ + SUBCASE("derivative") + { + //Exact for a quadratic, even with uneven time spacing + fge::SignalD signal({{0.0, 0.0}, {0.5, 0.25}, {1.5, 2.25}, {2.0, 4.0}, {3.5, 12.25}}); + auto const derivative = signal.derivative(); + REQUIRE(derivative.getSampleCount() == signal.getSampleCount()); + for (auto const& sample: derivative) + { + CHECK(sample.y == doctest::Approx(2.0 * sample.x)); + } + + CHECK(fge::SignalD{}.derivative().isEmpty()); + CHECK(fge::SignalD({{1.0, 5.0}}).derivative().getSample(0).y == 0.0); + CHECK(fge::SignalD({{0.0, 1.0}, {2.0, 5.0}}).derivative().getSample(1).y == doctest::Approx(2.0)); + } + + SUBCASE("integral") + { + fge::SignalD signal({{0.0, 2.0}, {1.0, 2.0}, {3.0, 2.0}}); + auto const integral = signal.integral(); + CHECK(integral.getSample(0).y == 0.0); + CHECK(integral.getSample(1).y == doctest::Approx(2.0)); + CHECK(integral.getSample(2).y == doctest::Approx(6.0)); + } + + SUBCASE("resample") + { + fge::SignalD signal({{0.0, 0.0}, {1.0, 10.0}, {3.0, 30.0}}); + auto const resampled = signal.resample(2.0); + REQUIRE(resampled.getSampleCount() == 7); + CHECK(resampled.getSample(1).y == doctest::Approx(5.0)); + CHECK(resampled.getSample(5).y == doctest::Approx(25.0)); + CHECK(resampled.getEndTime() == doctest::Approx(3.0)); + + CHECK(fge::SignalD({{0.0, 1.0}, {1.0, 2.0}}).resample(3.0).getSampleCount() == 4); + CHECK(fge::SignalD{}.resample(10.0).isEmpty()); + CHECK_THROWS_AS((void) signal.resample(0.0), fge::Exception); + } + + SUBCASE("soft limit") + { + fge::SignalD signal({{0.0, -10.0}, {1.0, -0.5}, {2.0, 0.0}, {3.0, 0.5}, {4.0, 10.0}}); + auto const limited = signal.softLimit(-1.0, 1.0, 4.0); + for (auto const& sample: limited) + { + CHECK(sample.y >= -1.0); + CHECK(sample.y <= 1.0); + } + CHECK(limited.getSample(2).y == 0.0); + CHECK(limited.getSample(1).y < limited.getSample(3).y); + + CHECK_THROWS_AS((void) signal.softLimit(1.0, -1.0, 4.0), fge::Exception); + CHECK_THROWS_AS((void) signal.softLimit(-1.0, 1.0, 0.0), fge::Exception); + } + + SUBCASE("soft limit keep average") + { + fge::SignalGeneratorD generator; + generator.addWave({fge::SignalGeneratorD::WaveTypes::WAVE_RECTANGLE, 3.0, 2.0, 0.0, 0.4, 0.0}); + generator.addWave({fge::SignalGeneratorD::WaveTypes::WAVE_CONTINUOUS, 0.0, 0.0, 0.0, 0.5, 0.3}); + auto const signal = generator.generate(2.0, 0.01); + + auto const limited = signal.softLimit(-1.0, 1.0, 3.0); + auto const limitedKeep = signal.softLimitKeepAverage(-1.0, 1.0, 3.0); + CHECK(limited.getAverage() != doctest::Approx(signal.getAverage())); + CHECK(limitedKeep.getAverage() == doctest::Approx(signal.getAverage())); + for (auto const& sample: limitedKeep) + { + CHECK(sample.y >= -1.0); + CHECK(sample.y <= 1.0); + } + + CHECK_THROWS_AS((void) signal.softLimitKeepAverage(0.5, 1.0, 3.0), fge::Exception); + } + + SUBCASE("time stretch") + { + fge::SignalD signal({{1.0, 4.0}, {2.0, 5.0}, {4.0, 6.0}}); + auto const stretched = signal.timeStretch(2.0); + CHECK(stretched.getSample(0) == fge::SignalD::Sample{1.0, 4.0}); + CHECK(stretched.getSample(1) == fge::SignalD::Sample{3.0, 5.0}); + CHECK(stretched.getSample(2) == fge::SignalD::Sample{7.0, 6.0}); + + CHECK_THROWS_AS((void) signal.timeStretch(0.0), fge::Exception); + } +} + +TEST_CASE("testing signal file") +{ + fge::SignalGeneratorF generator; + generator.addWave({}); + auto const signal = generator.generate(1.0f, 0.01f); + + auto const path = std::filesystem::temp_directory_path() / "fge_test_signal.csv"; + REQUIRE(signal.saveToFile(path)); + + fge::SignalF loaded; + REQUIRE(loaded.loadFromFile(path)); + REQUIRE(loaded.getSamples() == signal.getSamples()); + + std::filesystem::remove(path); + CHECK_FALSE(loaded.loadFromFile(path)); + CHECK(loaded.getSampleCount() == signal.getSampleCount()); +}