/*
    QGL FramebufferMipmap
    Ivan Pelipenko peri4ko@yandex.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser 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 Lesser General Public License for more details.

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

#include "glframebuffer_mipmap.h"

#include <QOpenGLExtraFunctions>
#include <QTime>


FramebufferMipmap::FramebufferMipmap(const Framebuffer & fb, int index_from_, int levels): src_fb(fb) {
	index_from = index_from_;
	for (int i = 0; i < levels; ++i)
		fbo << new Framebuffer(fb.f, 1, false, fb.color_formats[index_from]);
}


FramebufferMipmap::~FramebufferMipmap() {}


void FramebufferMipmap::setIndexFrom(int index) {
	index_from = index;
}


void FramebufferMipmap::resize() {
	QSize sz = src_fb.size();
	for (int i = 0; i < fbo.size(); ++i) {
		sz /= 2;
		fbo[i]->resize(sz.width(), sz.height());
	}
}


void FramebufferMipmap::create() {
	if (fbo.isEmpty()) return;
	src_fb.blit(index_from, fbo[0]->id(), 0, src_fb.rect(), fbo[0]->rect(), GL_COLOR_BUFFER_BIT, GL_LINEAR);
	for (int i = 0; i < fbo.size() - 1; ++i)
		fbo[i]->blit(0, fbo[i + 1]->id(), 0, fbo[i]->rect(), fbo[i + 1]->rect(), GL_COLOR_BUFFER_BIT, GL_LINEAR);
}


void FramebufferMipmap::reinit() {
	for (auto * f: fbo)
		f->reinit();
}
