[refactor]: formatting

This commit is contained in:
2023-08-08 23:24:26 +04:00
parent a445fc44b3
commit 268103d7da
14 changed files with 495 additions and 384 deletions

216
.clang-format Normal file
View File

@@ -0,0 +1,216 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: false
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortEnumsOnASingleLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
QualifierAlignment: Leave
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
PackConstructorInitializers: BinPack
BasedOnStyle: ''
ConstructorInitializerAllOnOneLineOrOnePerLine: false
AllowAllConstructorInitializersOnNextLine: true
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseLabels: true
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentExternBlock: AfterExternBlock
IndentRequiresClause: true
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertBraces: false
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
LambdaBodyIndentation: Signature
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PenaltyIndentedWhitespace: 0
PointerAlignment: Left
PPIndentWidth: -1
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
RequiresClausePosition: OwnLine
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterOverloadedOperator: false
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceAroundPointerQualifiers: Default
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
BitFieldColonSpacing: Both
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseCRLF: false
UseTab: Never
WhitespaceSensitiveMacros:
- STRINGIZE
- PP_STRINGIZE
- BOOST_PP_STRINGIZE
- NS_SWIFT_NAME
- CF_SWIFT_NAME
...

View File

@@ -1,24 +1,22 @@
#pragma once
#include <vector>
#include "Oscillator.h"
#include "Settings.h"
#include <numeric>
#include <vector>
struct Adder
{
static std::vector<float> & SumOscillators(const std::vector<Oscillator*> & oscillators, float duration)
{
struct Adder {
static std::vector<float>&
SumOscillators(const std::vector<Oscillator*>& oscillators,
float duration) {
size_t sample_count = (size_t)(duration * SAMPLE_RATE);
std::vector<float>* output = new std::vector<float>();
output->reserve(sample_count);
for (size_t i = 0; i < sample_count; i++)
{
for (size_t i = 0; i < sample_count; i++) {
float sample = 0.0f;
for (Oscillator* osc : oscillators)
{
for (Oscillator* osc : oscillators) {
sample += osc->GenerateSample(duration);
}

View File

@@ -1,14 +1,13 @@
#pragma once
#include "Note.h"
#include "Synth.h"
#include "raylib.h"
#include "RingBuffer.h"
#include "Renderer.h"
#include "RingBuffer.h"
#include "Synth.h"
#include "SynthGuiState.h"
#include "raylib.h"
class Application
{
private:
class Application {
private:
Synth m_synth;
SynthGuiState m_synth_gui_state;
RingBuffer<float>* m_ring_buffer;
@@ -24,9 +23,8 @@ private:
void play_buffered_audio();
void fill_audio_buffer();
public:
public:
Application(/* args */);
~Application();
void Run();
};

View File

@@ -1,22 +1,23 @@
#pragma once
#include "Settings.h"
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <cstring>
#include <string>
class KeyBoard
{
private:
class KeyBoard {
private:
/* data */
static int get_semitone_shift_internal(const char* root_note, char* target_note) {
const char* pitch_classes[12] =
{ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
static int get_semitone_shift_internal(const char* root_note,
char* target_note) {
const char* pitch_classes[12] = {"C", "C#", "D", "D#", "E", "F",
"F#", "G", "G#", "A", "A#", "B"};
// Extract the note number and pitch class for the root note
int root_note_num = (int)root_note[strlen(root_note) - 1] - '0';
char* root_pitch_class_str = (char*)malloc((strlen(root_note) - 1) * sizeof(char));
char* root_pitch_class_str =
(char*)malloc((strlen(root_note) - 1) * sizeof(char));
strncpy(root_pitch_class_str, root_note, strlen(root_note) - 1);
int root_pitch_class = -1;
@@ -50,11 +51,12 @@ private:
// Calculate the semitone shift using the formula
return (target_note_num - root_note_num) * 12 +
(target_pitch_class - root_pitch_class);
(target_pitch_class - root_pitch_class);
}
public:
public:
KeyBoard(/* args */);
~KeyBoard();
~KeyBoard();
static float GetHzBySemitone(int semitone) {
return PITCH_STANDARD * powf(powf(2.f, (1.f / 12.f)), semitone);
@@ -63,18 +65,14 @@ public:
static int GetSemitoneShift(const std::string& target_note) {
char* target_note_cstr = new char[target_note.length() + 1];
strcpy(target_note_cstr, target_note.c_str());
int result = get_semitone_shift_internal("A4", target_note_cstr);
delete[] target_note_cstr;
return result;
}
};
KeyBoard::KeyBoard(/* args */)
{
}
KeyBoard::KeyBoard(/* args */) {}
KeyBoard::~KeyBoard()
{
}
KeyBoard::~KeyBoard() {}

View File

@@ -1,40 +1,35 @@
#pragma once
#include<vector>
#include "OscillatorType.h"
#include <vector>
class Oscillator {
private:
OscillatorType m_osc;
float m_freq;
float m_volume;
float m_phase;
float m_phase_dt;
float (Oscillator::*m_osc_function)(void);
float (Oscillator::*m_dt_function)(float freq);
void sine_osc_phase_incr();
void saw_osc_phase_incr();
float calc_saw_phase_delta(float freq);
float calc_sine_phase_delta(float freq);
float sawosc();
float triangleosc();
float squareosc();
float sign(float v);
float sineosc();
class Oscillator
{
//typedef float (Oscillator::*OscFunction)(void);
//typedef float (Oscillator::*DtFunction)(float);
private:
OscillatorType m_osc;
float m_freq;
float m_volume;
float m_phase;
float m_phase_dt;
//значение типа "float (Oscillator::*)()" нельзя присвоить сущности типа "float (*)()"
float (Oscillator::*m_osc_function)(void);
float (Oscillator::*m_dt_function)(float freq);
void sine_osc_phase_incr();
void saw_osc_phase_incr();
float calc_saw_phase_delta(float freq);
float calc_sine_phase_delta(float freq);
float sawosc();
float triangleosc();
float squareosc();
float sign(float v);
float sineosc();
public:
Oscillator(OscillatorType osc, float freq, float volume);
~Oscillator();
OscillatorType GetType() { return m_osc; }
void SetType(OscillatorType osc);
float GetVolume() { return m_volume; }
void SetVolume(float volume) { m_volume = volume; }
float GetFreq() { return m_freq; }
void SetFreq(float freq);
void Reset();
float GenerateSample(float duration);
public:
Oscillator(OscillatorType osc, float freq, float volume);
~Oscillator();
OscillatorType GetType() { return m_osc; }
void SetType(OscillatorType osc);
float GetVolume() { return m_volume; }
void SetVolume(float volume) { m_volume = volume; }
float GetFreq() { return m_freq; }
void SetFreq(float freq);
void Reset();
float GenerateSample(float duration);
};

View File

@@ -1,7 +1,2 @@
#pragma once
typedef enum {
Sine,
Triangle,
Saw,
Square
} OscillatorType;
typedef enum { Sine, Triangle, Saw, Square } OscillatorType;

View File

@@ -1,27 +1,26 @@
#pragma once
#include "Synth.h"
#include "SynthGuiState.h"
#include <vector>
#include "raylib.h"
#include <vector>
class Renderer
{
private:
class Renderer {
private:
void DrawMainPanel(const Rectangle& panel_bounds);
void DrawAddOscillatorButton(Synth & synth, SynthGuiState & synthGui, Rectangle panel_bounds);
void DrawOscillatorsPanels(const std::vector<Oscillator*>& oscillators,
void DrawAddOscillatorButton(Synth& synth, SynthGuiState& synthGui,
Rectangle panel_bounds);
void DrawOscillatorsPanels(
const std::vector<Oscillator*>& oscillators,
const std::vector<OscillatorGuiState*>& guiOscillators,
const Rectangle& panel_bounds);
void DrawOscillatorsShapeInputs(const std::vector<Oscillator*>& oscillators,
void DrawOscillatorsShapeInputs(
const std::vector<Oscillator*>& oscillators,
const std::vector<OscillatorGuiState*>& guiOscillators);
void DrawUi(Synth & synth, SynthGuiState & synthGui);
void DrawSignal(Synth & synth, SynthGuiState & synthGui);
public:
void DrawUi(Synth& synth, SynthGuiState& synthGui);
void DrawSignal(Synth& synth, SynthGuiState& synthGui);
public:
Renderer(/* args */);
~Renderer();
void Draw(Synth& synth, SynthGuiState & synthGui);
void Draw(Synth& synth, SynthGuiState& synthGui);
};

View File

@@ -1,10 +1,8 @@
#pragma once
#include <cstddef>
#include "Logger.h"
template <typename T>
class RingBuffer
{
private:
#include <cstddef>
template <typename T> class RingBuffer {
private:
T* m_items; /* data */
std::size_t m_head;
std::size_t m_tail;
@@ -13,7 +11,8 @@ private:
std::size_t m_size;
void advance_pointer();
void retreat_pointer();
public:
public:
RingBuffer(std::size_t size);
~RingBuffer();
bool IsFull() { return m_is_full; }
@@ -26,8 +25,7 @@ public:
void Print();
};
template <typename T> RingBuffer<T>::RingBuffer(std::size_t size)
{
template <typename T> RingBuffer<T>::RingBuffer(std::size_t size) {
m_items = new T[size];
m_head = 0;
m_tail = 0;
@@ -36,50 +34,42 @@ template <typename T> RingBuffer<T>::RingBuffer(std::size_t size)
m_size = size;
}
template <typename T> RingBuffer<T>::~RingBuffer()
{
delete[] m_items;
}
template <typename T> RingBuffer<T>::~RingBuffer() { delete[] m_items; }
template <typename T> void RingBuffer<T>::Reset()
{
template <typename T> void RingBuffer<T>::Reset() {
m_head = 0;
m_tail = 0;
m_is_full = 0;
}
template <typename T> void RingBuffer<T>::advance_pointer()
{
template <typename T> void RingBuffer<T>::advance_pointer() {
if (m_is_full) {
m_tail++;
if (m_tail == m_size) {
m_tail = 0;
}
}
if (m_tail == m_size) {
m_tail = 0;
}
}
m_head++;
if (m_head == m_size) {
m_head = 0;
}
if (m_head == m_size) {
m_head = 0;
}
std::size_t p_is_full = m_head == m_tail ? 1 : 0;
m_is_full = p_is_full;
m_is_full = p_is_full;
}
template <typename T> void RingBuffer<T>::retreat_pointer()
{
m_is_full = 0;
template <typename T> void RingBuffer<T>::retreat_pointer() {
m_is_full = 0;
m_tail++;
if (m_tail == m_size) {
m_tail = 0;
}
if (m_tail == m_size) {
m_tail = 0;
}
}
template <typename T> void RingBuffer<T>::Write(T* data, std::size_t count)
{
template <typename T> void RingBuffer<T>::Write(T* data, std::size_t count) {
if (m_is_full || m_head + count > m_size) {
write_log("[WARN] Trying to overfill the ring buffer: \n\tIsFull:%d\n\tHead:%zu\n\tCount:%zu\n\t",
m_is_full,
m_head,
count);
write_log("[WARN] Trying to overfill the ring buffer: "
"\n\tIsFull:%d\n\tHead:%zu\n\tCount:%zu\n\t",
m_is_full, m_head, count);
return;
}
m_is_empty = 0;
@@ -88,11 +78,10 @@ template <typename T> void RingBuffer<T>::Write(T* data, std::size_t count)
m_items[m_head] = data[i];
advance_pointer();
}
//m_is_empty = m_is_full && (m_head == m_tail);
// m_is_empty = m_is_full && (m_head == m_tail);
}
template <typename T> bool RingBuffer<T>::Read(T* output, std::size_t count)
{
template <typename T> bool RingBuffer<T>::Read(T* output, std::size_t count) {
if (m_is_empty) {
write_log("[WARN] Trying to read empty buffer");
return 0;
@@ -106,26 +95,21 @@ template <typename T> bool RingBuffer<T>::Read(T* output, std::size_t count)
return 1;
}
template <typename T> std::size_t RingBuffer<T>::GetSize()
{
size_t p_size = m_size;
if(!m_is_full) {
if(m_head >= m_tail) {
p_size = (m_head - m_tail);
}
else {
p_size = (m_size + m_head - m_tail);
}
}
template <typename T> std::size_t RingBuffer<T>::GetSize() {
size_t p_size = m_size;
if (!m_is_full) {
if (m_head >= m_tail) {
p_size = (m_head - m_tail);
} else {
p_size = (m_size + m_head - m_tail);
}
}
return p_size;
return p_size;
}
template <typename T> void RingBuffer<T>::Print()
{
write_log("[INFO] The ring buffer: \n\tIsFull:%d\n\tIsEmpty:%d\n\tHead:%zu\n\tTail:%zu\n\t",
m_is_full,
m_is_empty,
m_head,
m_tail);
template <typename T> void RingBuffer<T>::Print() {
write_log("[INFO] The ring buffer: "
"\n\tIsFull:%d\n\tIsEmpty:%d\n\tHead:%zu\n\tTail:%zu\n\t",
m_is_full, m_is_empty, m_head, m_tail);
}

View File

@@ -1,26 +1,25 @@
#pragma once
#include <vector>
#include "Oscillator.h"
#include "Note.h"
#include "Adder.h"
#include "Note.h"
#include "Oscillator.h"
#include "Settings.h"
class Synth
{
private:
#include <vector>
class Synth {
private:
std::vector<Oscillator*> m_oscillators;
Adder m_adder;
//OscillatorUI* ui_oscillators;
//Note m_current_note;
// OscillatorUI* ui_oscillators;
// Note m_current_note;
std::vector<float> m_out_signal;
std::vector<float> & get_note(int semitone, float beats);
public:
std::vector<float>& get_note(int semitone, float beats);
public:
Synth(/* args */);
~Synth();
void ProduceNoteSound(Note input);
void AddOscillator();
const std::vector<float> & GetOutSignal() { return m_out_signal; }
const std::vector<float>& GetOutSignal() { return m_out_signal; }
const std::vector<Oscillator*>& GetOscillators() { return m_oscillators; }
};

View File

@@ -5,7 +5,7 @@
struct OscillatorGuiState {
float volume;
float freq;//todo: remove or change to pitch shift
float freq; // todo: remove or change to pitch shift
OscillatorType waveshape;
bool is_dropdown_open;
Rectangle shape_dropdown_rect;

View File

@@ -1,32 +1,29 @@
#include "Application.h"
#include "Settings.h"
#include "Logger.h"
#include "Settings.h"
#include <string>
Application::Application(/* args */)
{
Application::Application(/* args */) {
m_ring_buffer = new RingBuffer<float>((std::size_t)STREAM_BUFFER_SIZE);
m_temp_buffer = new float[STREAM_BUFFER_SIZE];
init_synth();
init_audio();
}
Application::~Application()
{
Application::~Application() {
StopAudioStream(m_synth_stream);
UnloadAudioStream(m_synth_stream);
UnloadAudioStream(m_synth_stream);
CloseAudioDevice();
CloseWindow();
delete m_ring_buffer;
delete[] m_temp_buffer;
// todo: move to gui state class destructor (make it a class)
for(int i = 0; i < m_synth_gui_state.oscillators.size(); i++) {
for (int i = 0; i < m_synth_gui_state.oscillators.size(); i++) {
delete m_synth_gui_state.oscillators[i];
}
}
void Application::init_audio()
{
void Application::init_audio() {
m_sound_played_count = 0;
InitAudioDevice();
@@ -38,69 +35,54 @@ void Application::init_audio()
PlayAudioStream(m_synth_stream);
}
void Application::init_synth()
{
//todo: move that variables to Synth declaration
std::string* nameString = new std::string(std::string(new char[3]));
m_current_note = new Note
{
.length = 1,
.name = (*nameString)
};
void Application::init_synth() {
// todo: move that variables to Synth declaration
std::string* nameString = new std::string(std::string(new char[3]));
m_current_note = new Note{.length = 1, .name = (*nameString)};
//todo: move somewhere in initialization
// todo: move somewhere in initialization
std::vector<Oscillator*> oscillators = m_synth.GetOscillators();
m_synth_gui_state.oscillators.reserve(oscillators.size());
for (size_t i = 0; i < oscillators.size(); i++)
{
for (size_t i = 0; i < oscillators.size(); i++) {
Oscillator* osc = oscillators[i];
assert(osc);
OscillatorGuiState* ui = new OscillatorGuiState {
.freq = osc->GetFreq(),
.waveshape = osc->GetType(),
.volume = osc->GetVolume()
};
OscillatorGuiState* ui =
new OscillatorGuiState{.freq = osc->GetFreq(),
.waveshape = osc->GetType(),
.volume = osc->GetVolume()};
m_synth_gui_state.oscillators.push_back(ui);
}
}
std::size_t Application::detect_note_pressed(Note* note)
{
std::size_t Application::detect_note_pressed(Note* note) {
std::size_t is_pressed = 0;
note->length = 8;
if (IsKeyPressed(KEY_A))
{
if (IsKeyPressed(KEY_A)) {
note->name.assign("A4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_B))
{
if (IsKeyPressed(KEY_B)) {
note->name.assign("B4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_C))
{
if (IsKeyPressed(KEY_C)) {
note->name.assign("C4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_D))
{
if (IsKeyPressed(KEY_D)) {
note->name.assign("D4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_E))
{
if (IsKeyPressed(KEY_E)) {
note->name.assign("E4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_F))
{
if (IsKeyPressed(KEY_F)) {
note->name.assign("F4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_G))
{
if (IsKeyPressed(KEY_G)) {
note->name.assign("G4");
is_pressed = 1;
}
@@ -108,10 +90,8 @@ std::size_t Application::detect_note_pressed(Note* note)
}
// Update On Input
void Application::update_on_note_input()
{
if (detect_note_pressed(m_current_note))
{
void Application::update_on_note_input() {
if (detect_note_pressed(m_current_note)) {
m_synth.ProduceNoteSound((*m_current_note));
m_sound_played_count = 0;
write_log("Note played: %s\n", m_current_note->name.c_str());
@@ -119,61 +99,54 @@ void Application::update_on_note_input()
}
// Play ring-buffered audio
void Application::play_buffered_audio()
{
if (IsAudioStreamProcessed(m_synth_stream) && !m_ring_buffer->IsEmpty())
{
void Application::play_buffered_audio() {
if (IsAudioStreamProcessed(m_synth_stream) && !m_ring_buffer->IsEmpty()) {
std::size_t size_to_read = m_ring_buffer->GetSize();
write_log("Samples to play:%zu \n", size_to_read);
//todo: try to start reading directly from ring buffer, avoiding temp_buffer
// todo: try to start reading directly from ring buffer, avoiding
// temp_buffer
m_ring_buffer->Read(m_temp_buffer, size_to_read);
// can try the SetAudioStreamCallback
UpdateAudioStream(m_synth_stream, m_temp_buffer, size_to_read);
// can overwrite the ring buffer to avoid that
if (m_synth.GetOutSignal().size() == m_sound_played_count)
{
if (m_synth.GetOutSignal().size() == m_sound_played_count) {
m_ring_buffer->Reset();
}
}
}
// Fill ring buffer from current sound
void Application::fill_audio_buffer()
{
if (!m_ring_buffer->IsFull() && m_synth.GetOutSignal().size() != m_sound_played_count)
{
write_log("[INFO] IsFull:%d Samples:%zu Played:%d\n",
m_ring_buffer->IsFull(),
m_synth.GetOutSignal().size(),
m_sound_played_count);
void Application::fill_audio_buffer() {
if (!m_ring_buffer->IsFull() &&
m_synth.GetOutSignal().size() != m_sound_played_count) {
write_log("[INFO] IsFull:%d Samples:%zu Played:%d\n",
m_ring_buffer->IsFull(), m_synth.GetOutSignal().size(),
m_sound_played_count);
// how many samples need write
std::size_t size_to_fill = 0;
if ((m_synth.GetOutSignal().size() - m_sound_played_count) > m_ring_buffer->GetCapacity())
{
if ((m_synth.GetOutSignal().size() - m_sound_played_count) >
m_ring_buffer->GetCapacity()) {
size_to_fill = m_ring_buffer->GetCapacity();
} else
{
} else {
size_to_fill = m_synth.GetOutSignal().size() - m_sound_played_count;
}
write_log("[INFO] SizeToFill:%zu\n", size_to_fill);
for (size_t i = 0; i < size_to_fill; i++)
{
for (size_t i = 0; i < size_to_fill; i++) {
m_temp_buffer[i] = m_synth.GetOutSignal()[i];
}
m_ring_buffer->Write(m_temp_buffer, size_to_fill);
m_sound_played_count += size_to_fill;
}
}
void Application::Run()
{
void Application::Run() {
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
while (!WindowShouldClose()) // Detect window close button or ESC key
{
fill_audio_buffer();
play_buffered_audio();

View File

@@ -1,28 +1,23 @@
#include "Oscillator.h"
#include "Settings.h"
#define TWO_PI 2*SYNTH_PI
#define TWO_PI 2 * SYNTH_PI
Oscillator::Oscillator(OscillatorType osc, float freq, float volume)
{
Oscillator::Oscillator(OscillatorType osc, float freq, float volume) {
SetType(osc);
m_freq = freq;
m_volume = volume;
}
Oscillator::~Oscillator()
{
}
Oscillator::~Oscillator() {}
void Oscillator::Reset()
{
void Oscillator::Reset() {
m_volume = 0;
m_phase = 0;
m_phase_dt = 0;
}
void Oscillator::SetType(OscillatorType osc)
{
void Oscillator::SetType(OscillatorType osc) {
m_osc = osc;
switch (m_osc) {
case Sine:
@@ -44,68 +39,53 @@ void Oscillator::SetType(OscillatorType osc)
}
}
void Oscillator::SetFreq(float freq)
{
void Oscillator::SetFreq(float freq) {
m_freq = freq;
m_phase = 0;
m_phase_dt = (this->*m_dt_function)(freq);
}
float Oscillator::GenerateSample(float duration)
{
float Oscillator::GenerateSample(float duration) {
return (this->*m_osc_function)() * m_volume;
}
void Oscillator::sine_osc_phase_incr()
{
void Oscillator::sine_osc_phase_incr() {
m_phase += m_phase_dt;
if (m_phase >= TWO_PI)
m_phase -= TWO_PI;
}
void Oscillator::saw_osc_phase_incr()
{
void Oscillator::saw_osc_phase_incr() {
m_phase += m_phase_dt;
if (m_phase >= 1.0f)
m_phase -= 1.0f;
}
float Oscillator::calc_saw_phase_delta(float freq)
{
float Oscillator::calc_saw_phase_delta(float freq) {
return freq / SAMPLE_RATE;
}
float Oscillator::calc_sine_phase_delta(float freq)
{
float Oscillator::calc_sine_phase_delta(float freq) {
return (TWO_PI * freq) / SAMPLE_RATE;
}
float Oscillator::sineosc()
{
float Oscillator::sineosc() {
float result = sinf(m_phase);
sine_osc_phase_incr();
return result;
}
float Oscillator::sign(float v)
{
return (v > 0.0) ? 1.f : -1.f;
}
float Oscillator::sign(float v) { return (v > 0.0) ? 1.f : -1.f; }
float Oscillator::squareosc()
{
return sign(sineosc());
}
float Oscillator::squareosc() { return sign(sineosc()); }
float Oscillator::triangleosc()
{
float Oscillator::triangleosc() {
float result = 1.f - fabsf(m_phase - 0.5f) * 4.f;
saw_osc_phase_incr();
return result;
}
float Oscillator::sawosc()
{
float Oscillator::sawosc() {
float result = m_phase * 2.f - 1.f;
saw_osc_phase_incr();
return result;

View File

@@ -1,55 +1,51 @@
#include "Renderer.h"
#define RAYGUI_IMPLEMENTATION
#include "raygui.h"
#include "Settings.h"
#include "Logger.h"
#include "Settings.h"
#include "raygui.h"
Renderer::Renderer(/* args */)
{
Renderer::Renderer(/* args */) {
InitWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "SeeSynth - v0.2");
SetTargetFPS(60);
}
Renderer::~Renderer()
{
}
Renderer::~Renderer() {}
void Renderer::Draw(Synth& synth, SynthGuiState& synthGui)
{
void Renderer::Draw(Synth& synth, SynthGuiState& synthGui) {
BeginDrawing();
ClearBackground(RAYWHITE);
//todo: implement renderer
DrawUi(synth, synthGui);
DrawSignal(synth, synthGui);
//DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY);
//DrawFPS(0,0);
ClearBackground(RAYWHITE);
// todo: implement renderer
DrawUi(synth, synthGui);
DrawSignal(synth, synthGui);
// DrawText("Congrats! You created your first window!", 190, 200, 20,
// LIGHTGRAY); DrawFPS(0,0);
EndDrawing();
}
void Renderer::DrawSignal(Synth & synth, SynthGuiState & synthGui)
{
GuiGrid((Rectangle){0, 0, WINDOW_WIDTH, WINDOW_HEIGHT}, "", WINDOW_HEIGHT / 8, 2);
void Renderer::DrawSignal(Synth& synth, SynthGuiState& synthGui) {
GuiGrid((Rectangle){0, 0, WINDOW_WIDTH, WINDOW_HEIGHT}, "",
WINDOW_HEIGHT / 8, 2);
auto signal = synth.GetOutSignal();
Vector2* signal_points = new Vector2[signal.size()];
const float screen_vertical_midpoint = (WINDOW_HEIGHT/2);
for (int point_idx = 0; point_idx < signal.size(); point_idx++)
{
const float screen_vertical_midpoint = (WINDOW_HEIGHT / 2);
for (int point_idx = 0; point_idx < signal.size(); point_idx++) {
signal_points[point_idx].x = (float)point_idx + OSCILLATOR_PANEL_WIDTH;
signal_points[point_idx].y = screen_vertical_midpoint + (int)(signal[point_idx] * 300);
signal_points[point_idx].y =
screen_vertical_midpoint + (int)(signal[point_idx] * 300);
}
DrawLineStrip(signal_points, signal.size(), RED);
delete[] signal_points;
}
void Renderer::DrawOscillatorsShapeInputs(const std::vector<Oscillator*>& oscillators, const std::vector<OscillatorGuiState*>& guiOscillators)
{
#define WAVE_SHAPE_OPTIONS "Sine;Triangle;Sawtooth;Square"
void Renderer::DrawOscillatorsShapeInputs(
const std::vector<Oscillator*>& oscillators,
const std::vector<OscillatorGuiState*>& guiOscillators) {
#define WAVE_SHAPE_OPTIONS "Sine;Triangle;Sawtooth;Square"
// DRAW OSCILLATOR SHAPE INPUTS
for (int i = 0; i < oscillators.size(); i += 1)
{
for (int i = 0; i < oscillators.size(); i += 1) {
OscillatorGuiState* ui_osc = guiOscillators[i];
assert(ui_osc);
@@ -58,31 +54,28 @@ void Renderer::DrawOscillatorsShapeInputs(const std::vector<Oscillator*>& oscill
// Shape select
int shape_index = (int)(ui_osc->waveshape);
bool is_dropdown_click = GuiDropdownBox(ui_osc->shape_dropdown_rect,
WAVE_SHAPE_OPTIONS,
&shape_index,
ui_osc->is_dropdown_open
);
if (is_dropdown_click)
{
bool is_dropdown_click =
GuiDropdownBox(ui_osc->shape_dropdown_rect, WAVE_SHAPE_OPTIONS,
&shape_index, ui_osc->is_dropdown_open);
if (is_dropdown_click) {
write_log("Dropdown clicked!\n");
ui_osc->is_dropdown_open = !ui_osc->is_dropdown_open;
ui_osc->waveshape = (OscillatorType)(shape_index);
// APPLY STATE TO REAL OSC
osc->SetType(ui_osc->waveshape);
}
if (ui_osc->is_dropdown_open) break;
if (ui_osc->is_dropdown_open)
break;
}
}
void Renderer::DrawOscillatorsPanels(const std::vector<Oscillator*>& oscillators,
void Renderer::DrawOscillatorsPanels(
const std::vector<Oscillator*>& oscillators,
const std::vector<OscillatorGuiState*>& guiOscillators,
const Rectangle& panel_bounds)
{
const Rectangle& panel_bounds) {
float panel_y_offset = 0;
for (int i = 0; i < oscillators.size(); i++)
{
for (int i = 0; i < oscillators.size(); i++) {
OscillatorGuiState* ui_osc = guiOscillators[i];
assert(ui_osc);
@@ -90,46 +83,36 @@ void Renderer::DrawOscillatorsPanels(const std::vector<Oscillator*>& oscillators
assert(osc);
const bool has_shape_param = (ui_osc->waveshape == Square);
// Draw Oscillator Panel
const int osc_panel_width = panel_bounds.width - 20;
const int osc_panel_height = has_shape_param ? 130 : 100;
const int osc_panel_x = panel_bounds.x + 10;
const int osc_panel_y = panel_bounds.y + 50 + panel_y_offset;
panel_y_offset += osc_panel_height + 5;
GuiPanel((Rectangle){
(float)osc_panel_x,
(float)osc_panel_y,
(float)osc_panel_width,
(float)osc_panel_height
},
"");
GuiPanel((Rectangle){(float)osc_panel_x, (float)osc_panel_y,
(float)osc_panel_width, (float)osc_panel_height},
"");
const float slider_padding = 50.f;
const float el_spacing = 5.f;
Rectangle el_rect = {
.x = (float)osc_panel_x + slider_padding + 30,
.y = (float)osc_panel_y + 10,
.width = (float)osc_panel_width - (slider_padding * 2),
.height = 25.f
};
Rectangle el_rect = {.x = (float)osc_panel_x + slider_padding + 30,
.y = (float)osc_panel_y + 10,
.width =
(float)osc_panel_width - (slider_padding * 2),
.height = 25.f};
// Volume slider
float decibels = (20.f * log10f(osc->GetVolume()));
char amp_slider_label[32];
sprintf(amp_slider_label, "%.1f dB", decibels);
decibels = GuiSlider(el_rect,
amp_slider_label,
"",
decibels,
-60.0f,
0.0f
);
ui_osc->volume = powf(10.f, decibels * (1.f/20.f));
decibels =
GuiSlider(el_rect, amp_slider_label, "", decibels, -60.0f, 0.0f);
ui_osc->volume = powf(10.f, decibels * (1.f / 20.f));
osc->SetVolume(ui_osc->volume);
el_rect.y += el_rect.height + el_spacing;
// Defer shape drop-down box.
ui_osc->shape_dropdown_rect = el_rect;
el_rect.y += el_rect.height + el_spacing;
@@ -142,49 +125,49 @@ void Renderer::DrawOscillatorsPanels(const std::vector<Oscillator*>& oscillators
if (is_delete_button_pressed)
{
memmove(
synth->ui_oscillator + ui_osc_i,
synth->ui_oscillator + ui_osc_i + 1,
(synth->ui_oscillator_count - ui_osc_i) * sizeof(UiOscillator)
synth->ui_oscillator + ui_osc_i,
synth->ui_oscillator + ui_osc_i + 1,
(synth->ui_oscillator_count - ui_osc_i) *
sizeof(UiOscillator)
);
synth->ui_oscillator_count -= 1;
}
*/
}
}
void Renderer::DrawMainPanel(const Rectangle& panel_bounds)
{
void Renderer::DrawMainPanel(const Rectangle& panel_bounds) {
bool is_shape_dropdown_open = false;
int shape_index = 0;
GuiPanel(panel_bounds, "");
}
void Renderer::DrawAddOscillatorButton(Synth & synth, SynthGuiState & synthGui, Rectangle panel_bounds)
{
bool click_add_oscillator = GuiButton((Rectangle){
panel_bounds.x + 10,
panel_bounds.y + 10,
panel_bounds.width - 20,
25.f
}, "Add Oscillator");
if (click_add_oscillator)
{
void Renderer::DrawAddOscillatorButton(Synth& synth, SynthGuiState& synthGui,
Rectangle panel_bounds) {
//clang-format off
bool click_add_oscillator =
GuiButton((Rectangle){panel_bounds.x + 10, panel_bounds.y + 10,
panel_bounds.width - 20, 25.f},
"Add Oscillator");
//clang-format on
if (click_add_oscillator) {
synth.AddOscillator();
Oscillator* osc = synth.GetOscillators().back();
OscillatorGuiState* ui = new OscillatorGuiState {
.freq = osc->GetFreq(),
.waveshape = osc->GetType(),
.volume = osc->GetVolume()
};
OscillatorGuiState* ui =
new OscillatorGuiState{.freq = osc->GetFreq(),
.waveshape = osc->GetType(),
.volume = osc->GetVolume()};
synthGui.oscillators.push_back(ui);
}
}
}
void Renderer::DrawUi(Synth & synth, SynthGuiState & synthGui)
{
Rectangle panel_bounds = {.x = 0, .y = 0, .width = OSCILLATOR_PANEL_WIDTH, .height = WINDOW_HEIGHT };
void Renderer::DrawUi(Synth& synth, SynthGuiState& synthGui) {
Rectangle panel_bounds = {.x = 0,
.y = 0,
.width = OSCILLATOR_PANEL_WIDTH,
.height = WINDOW_HEIGHT};
DrawMainPanel(panel_bounds);
DrawAddOscillatorButton(synth, synthGui, panel_bounds);
// Draw Oscillators

View File

@@ -1,39 +1,32 @@
#include "Synth.h"
#include "Settings.h"
#include "KeyBoard.h"
#include "OscillatorType.h"
#include "Settings.h"
Synth::Synth(/* args */)
{
AddOscillator();
}
Synth::Synth(/* args */) { AddOscillator(); }
Synth::~Synth()
{
}
Synth::~Synth() {}
std::vector<float> & Synth::get_note(int semitone, float beats)
{
std::vector<float>& Synth::get_note(int semitone, float beats) {
float hz = KeyBoard::GetHzBySemitone(semitone);
float duration = beats * BEAT_DURATION;
// will change after oscillator starts to be more autonomous
for (Oscillator* osc : m_oscillators)
{
for (Oscillator* osc : m_oscillators) {
osc->SetFreq(hz);
}
return m_adder.SumOscillators(m_oscillators, duration); //todo: add other pipeline steps (e.g ADSR, Filters, FX);
// todo: add other pipeline steps (e.g ADSR, Filters, FX);
return m_adder.SumOscillators(m_oscillators, duration);
}
void Synth::ProduceNoteSound(Note input)
{
void Synth::ProduceNoteSound(Note input) {
float length = 1.f / input.length;
int semitone_shift = KeyBoard::GetSemitoneShift(input.name);
m_out_signal = get_note(semitone_shift, length);
}
void Synth::AddOscillator()
{
m_oscillators.push_back(new Oscillator(OscillatorType::Sine, 440.f, VOLUME));
void Synth::AddOscillator() {
m_oscillators.push_back(
new Oscillator(OscillatorType::Sine, 440.f, VOLUME));
}