src/gl/vertexprogram.cpp

Sun, 29 Aug 2021 20:39:55 +0300

author
Teemu Piippo <teemu@hecknology.net>
date
Sun, 29 Aug 2021 20:39:55 +0300
changeset 125
f127982d3412
parent 120
8c9fff699241
child 172
50f055543ff6
permissions
-rw-r--r--

Move tools under Document instead of MainWindow

#include "vertexprogram.h"
#include "document.h"

static const char vertexShaderSource[] = R"(
#version 330 core
const int FRAGSTYLE_Normal = 0;
const int FRAGSTYLE_Id = 1;
layout (location = 0) in vec3 in_position;
layout (location = 1) in vec3 in_color;
uniform mat4 view;
uniform mat4 projection;
uniform mat4 model;
smooth out vec3 ex_color;

void main()
{
	gl_Position = projection * view * model * vec4(in_position, 1.0);
	ex_color = in_color;
}
)";

static const char fragmentShaderSource[] = R"(
#version 330 core

out vec4 color;
smooth in vec3 ex_color;

void main(void)
{
	color = vec4(ex_color, 1);
}
)";

static constexpr glm::vec3 o = {0, 0, 0};
static constexpr glm::vec3 c1 = {1, -1, 1};
static constexpr glm::vec3 c2 = {1, -1, -1};
static constexpr glm::vec3 c3 = {-1, -1, -1};
static constexpr glm::vec3 c4 = {-1, -1, 1};

static constexpr glm::vec3 markerGeometry[] = {
	o, c1, c2,
	o, c2, c3,
	o, c3, c4,
	o, c4, c1,
};

VertexProgram::VertexProgram(QObject *parent) :
	AbstractBasicShaderProgram{parent}
{
}

const char *VertexProgram::vertexShaderSource() const
{
	return ::vertexShaderSource;
}

const char *VertexProgram::fragmentShaderSource() const
{
	return ::fragmentShaderSource;
}

const void *VertexProgram::vertexData() const
{
	return this->data.data();
}

int VertexProgram::vertexSize() const
{
	return sizeof(Vertex);
}

int VertexProgram::vertexCount() const
{
	return this->data.size();
}

void VertexProgram::setupVertexArrays()
{
	for (int i : {0, 1})
	{
		this->program->enableAttributeArray(i);
	}
	const int stride = this->vertexSize();
	this->program->setAttributeBuffer(0, GL_FLOAT, offsetof(Vertex, position), 3, stride);
	this->program->setAttributeBuffer(1, GL_FLOAT, offsetof(Vertex, color), 3, stride);
}

GLenum VertexProgram::drawMode() const
{
	return GL_TRIANGLES;
}

QOpenGLBuffer::UsagePattern VertexProgram::usagePattern() const
{
	return QOpenGLBuffer::DynamicDraw;
}

void VertexProgram::setFragmentStyle(const FragmentStyle newFragmentStyle)
{
	this->fragmentStyle = newFragmentStyle;
}

void VertexProgram::build(const Document *document)
{
	constexpr glm::vec3 color = {0.0, 1.0, 1.0};
	this->data.clear();
	document->applyToVertices([&](const glm::vec3&, const VertexMap::VertexInfo& info)
	{
		reserveMore(this->data, ::countof(::markerGeometry));
		for (const glm::vec3& point : ::markerGeometry)
		{
			const glm::vec3 transformed = info.transform * glm::vec4{point, 1};
			this->data.push_back({transformed, color});
		}
	});
	this->buffer.bind();
	this->buffer.allocate(this->vertexData(), this->vertexCount() * this->vertexSize());
	this->buffer.release();
}

mercurial