Skip to content

Instantly share code, notes, and snippets.

@satoruhiga
Last active April 3, 2016 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satoruhiga/5169084 to your computer and use it in GitHub Desktop.
Save satoruhiga/5169084 to your computer and use it in GitHub Desktop.
Spectrum.h
#pragma once
#include "ofMain.h"
class Spectrum
{
public:
Spectrum() : buffer_size(100), x_scale(0.001) {}
void setBufferSize(int n)
{
buffer_size = n;
}
inline void update(const vector<float>& line)
{
update(&line[0], line.size());
}
void update(const float *ptr, size_t len)
{
buffer.push_front(vector<float>());
vector<float>& amp = buffer[0];
amp.resize(len);
for (int i = 0; i < len; i++)
{
float d = ofMap(i, 0, len, 0, 1);
d = d * d;
int index = d * (len - 1);
float sample = ptr[index] * (expf(i * x_scale) - 1);
max_sample = max(max_sample, fabs(sample));
amp[i] = sample;
}
if (buffer.size() > buffer_size)
{
buffer.pop_back();
}
// update mesh
ofMesh mesh;
for (int y = 0; y < buffer.size(); y++)
{
float yy = ofMap(y, 0, buffer.size(), 0, 1);
vector<float> &smp = buffer[y];
for (int x = 0; x < smp.size(); x++)
{
float xx = ofMap(x, 0, smp.size(), 0, 1);
mesh.addVertex(ofVec3f(xx, yy, smp[x] / max_sample));
}
}
for (int y = 0; y < buffer.size() - 1; y++)
{
for (int x = 0; x < len - 1; x++)
{
int index = y * len + x;
int idx0 = index;
int idx1 = index + 1;
int idx2 = index + len;
int idx3 = index + len + 1;
mesh.addTriangle(idx0, idx1, idx2);
mesh.addTriangle(idx1, idx3, idx2);
}
}
this->mesh = mesh;
}
void draw(float width = 100, float height = 100, float amp = 100)
{
glPushMatrix();
glScalef(width, height, amp);
for (int y = 0; y < buffer.size(); y++)
{
float yy = ofMap(y, 0, buffer.size(), 0, 1);
vector<float> &smp = buffer[y];
glBegin(GL_LINE_STRIP);
for (int x = 0; x < smp.size(); x++)
{
float xx = ofMap(x, 0, smp.size(), 0, 1);
glVertex3f(xx, yy, smp[x] / max_sample);
}
glEnd();
}
glPopMatrix();
}
ofMesh getMesh() { return mesh; }
void resetPeak()
{
max_sample = 0;
}
protected:
int buffer_size;
float max_sample;
float x_scale;
deque< vector<float> > buffer;
ofMesh mesh;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment