| 200 | } |
| 201 | |
| 202 | void PeriodicWave::generateBasicWaveform(OscillatorType shape) |
| 203 | { |
| 204 | unsigned fftSize = periodicWaveSize(); |
| 205 | unsigned halfSize = fftSize / 2; |
| 206 | |
| 207 | lab::AudioFloatArray real(halfSize); |
| 208 | lab::AudioFloatArray imag(halfSize); |
| 209 | float * realP = real.data(); |
| 210 | float * imagP = imag.data(); |
| 211 | |
| 212 | // Clear DC and Nyquist. |
| 213 | realP[0] = 0; |
| 214 | imagP[0] = 0; |
| 215 | |
| 216 | for (unsigned n = 1; n < halfSize; ++n) |
| 217 | { |
| 218 | float piFactor = 2 / (n * static_cast<float>(LAB_PI)); |
| 219 | |
| 220 | // All waveforms are odd functions with a positive slope at time 0. Hence the coefficients |
| 221 | // for cos() are always 0. |
| 222 | |
| 223 | // Fourier coefficients according to standard definition: |
| 224 | // b = 1/pi*integrate(f(x)*sin(n*x), x, -pi, pi) |
| 225 | // = 2/pi*integrate(f(x)*sin(n*x), x, 0, pi) |
| 226 | // since f(x) is an odd function. |
| 227 | |
| 228 | float b; // Coefficient for sin(). |
| 229 | |
| 230 | // Calculate Fourier coefficients depending on the shape. Note that the overall scaling |
| 231 | // (magnitude) of the waveforms is normalized in createBandLimitedTables(). |
| 232 | switch (shape) |
| 233 | { |
| 234 | case OscillatorType::SINE: |
| 235 | // Standard sine wave function. |
| 236 | b = (n == 1) ? 1.f : 0; |
| 237 | break; |
| 238 | case OscillatorType::SQUARE: |
| 239 | // Square-shaped waveform with the first half its maximum value and the second half its |
| 240 | // minimum value. |
| 241 | // |
| 242 | // See http://mathworld.wolfram.com/FourierSeriesSquareWave.html |
| 243 | // |
| 244 | // b[n] = 2/n/pi*(1-(-1)^n) |
| 245 | // = 4/n/pi for n odd and 0 otherwise. |
| 246 | // = 2*(2/(n*pi)) for n odd |
| 247 | b = (n & 1) ? 2 * piFactor : 0; |
| 248 | break; |
| 249 | case OscillatorType::SAWTOOTH: |
| 250 | // Sawtooth-shaped waveform with the first half ramping from zero to maximum and the |
| 251 | // second half from minimum to zero. |
| 252 | // |
| 253 | // b[n] = -2*(-1)^n/pi/n |
| 254 | // = (2/(n*pi))*(-1)^(n+1) |
| 255 | b = piFactor * ((n & 1) ? 1 : -1); |
| 256 | break; |
| 257 | case OscillatorType::TRIANGLE: |
| 258 | // Triangle-shaped waveform going from 0 at time 0 to 1 at time pi/2 and back to 0 at |
| 259 | // time pi. |