summaryrefslogtreecommitdiff
path: root/gfx/models/texture.cpp
blob: 645920f67ef7b89e4cd95ba9bec6a78e363cd127 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "texture.h"
#include "glArrays.h"
#include <GL/glew.h>
#include <cache.h>
#include <fcntl.h>
#include <gfx/image.h>
#include <glm/geometric.hpp>
#include <resource.h>
#include <stb/stb_image.h>

Cache<Texture, std::filesystem::path> Texture::cachedTexture;

Texture::Texture(const std::filesystem::path & fileName) :
	Texture {Image {Resource::mapPath(fileName).c_str(), STBI_rgb_alpha}}
{
}

Texture::Texture(const Image & tex) :
	Texture {static_cast<GLsizei>(tex.width), static_cast<GLsizei>(tex.height), tex.data.data()}
{
}

Texture::Texture(GLsizei width, GLsizei height, const void * data)
{
	glBindTexture(GL_TEXTURE_2D, m_texture);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
}

void
Texture::bind(GLenum unit) const
{
	glActiveTexture(unit);
	glBindTexture(GL_TEXTURE_2D, m_texture);
}

void
Texture::save(const glTexture & texture, GLenum format, const glm::ivec2 & size, unsigned short channels,
		const char * path, short tgaFormat)
{
	using PixelData = std::vector<unsigned char>;
	PixelData buffer(static_cast<size_t>(size.x * size.y * channels));
	glGetTextureImage(texture, 0, format, GL_UNSIGNED_BYTE, static_cast<GLsizei>(buffer.size()), buffer.data());

	auto out = open(path, O_WRONLY | O_CREAT, 0660);
	const short TGAhead[] = {0, tgaFormat, 0, 0, 0, 0, static_cast<short>(size.x), static_cast<short>(size.y),
			static_cast<short>(8 * channels)};
	std::ignore = write(out, &TGAhead, sizeof(TGAhead));
	std::ignore = write(out, buffer.data(), buffer.size());
	std::ignore = ftruncate(out, static_cast<off_t>(buffer.size() + sizeof(TGAhead)));
	close(out);
}

void
Texture::save(const glTexture & texture, const glm::ivec2 & size, const char * path)
{
	save(texture, GL_BGR, size, 3, path, 2);
}

void
Texture::saveDepth(const glTexture & texture, const glm::ivec2 & size, const char * path)
{
	save(texture, GL_DEPTH_COMPONENT, size, 1, path, 3);
}