/*
    QGLView
    Copyright (C) 2012  Ivan Pelipenko peri4ko@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "rope_system.h"
#include "qglview.h"


RopeSystem::RopeSystem(): GLObjectBase(), fbo(2, false, GL_RGBA16F, GL_TEXTURE_1D) {
	tex[0] = tex[1] = tex[2] = 0;
}


RopeSystem::~RopeSystem() {
}


void RopeSystem::init() {
	pos.clear();
	for (int i = 0; i < 1024; ++i)
		pos << (i - 512) / 51.2f << 0.f << 20.f << 0.1f;
	deleteGLTexture(tex[0]);
	deleteGLTexture(tex[1]);
	deleteGLTexture(tex[2]);
	glGenTextures(3, tex);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_1D, tex[0]);
	glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA16F, 1024, 0, GL_RGBA, GL_FLOAT, pos.constData());
	glBindTexture(GL_TEXTURE_1D, tex[1]);
	glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA16F, 1024, 0, GL_RGBA, GL_FLOAT, pos.constData());
	glBindTexture(GL_TEXTURE_1D, tex[2]);
	glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA16F, 1024, 0, GL_RGBA, GL_FLOAT, pos.constData());
}


void RopeSystem::draw(QGLShaderProgram * prog, bool simplest) {
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_1D, tex[0]);
	glGetTexImage(GL_TEXTURE_1D, 0, GL_RGBA, GL_FLOAT, pos.data());
	glColor3f(1.f, 1.f, 1.f);
	glBegin(GL_LINE_STRIP);
	int ind = 0;
	for (int i = 0; i < 1024; ++i) {
		ind = i * 4;
		glVertex3f(pos[ind], pos[ind + 1], pos[ind + 2]);
	}
	glEnd();
	/*((QGLView * )view_)->shader_rope->bind();
	((QGLView * )view_)->shader_rope->setUniformValue("t0", 0);
	((QGLView * )view_)->shader_rope->setUniformValue("dt", 1.f / 1024.f);
	((QGLView * )view_)->shader_rope->release();*/
}
