summaryrefslogtreecommitdiff
path: root/prge_texture.c
blob: cce3374c57d526b13c37760ca79bc290b05b57cc (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
Texture load_texture(Arena *arena, char *filename, B32 gamma_correction)
{
	U8		*data;

	S32		nchannels;
	GLenum		internal_format;
	GLenum		data_format;

	Texture		texture;

	Arena		*temparena;

	char		*cfilename;
	Str8		str;

	Assert(arena);

	MemoryZeroStruct(&texture);

	temparena = arena_alloc(0);

	cfilename = str8tocstr(arena, filename);

	stbi_set_flip_vertically_on_load(1);
	data = stbi_load(cfilename, &texture.width, &texture.height, &nchannels, 0);

	if (!data) {
		str = str8pushf(temparena, "[ERROR] : Texture : %s : Failed to load\n", cfilename);
		goto end;
	}

	switch (nchannels) {
	case 1:
		texture.type = TextureType_R;
		internal_format = data_format = GL_RED;
		break;
	case 3:
		texture.type = TextureType_RGB;
		internal_format = (gamma_correction) ? GL_SRGB : GL_RGB;
		data_format = GL_RGB;
		break;
	case 4:
		texture.type = TextureType_RGBA;
		internal_format = (gamma_correction) ? GL_SRGB_ALPHA : GL_RGBA;
		data_format = GL_RGBA;
		break;
	default:
		str = str8pushf(temparena, "[ERROR] : Texture : %s : Unsupported type\n", cfilename);
		goto end;
	}

	glGenTextures(1, &texture.id);
	glBindTexture(GL_TEXTURE_2D, texture.id);
	glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0, data_format, GL_UNSIGNED_BYTE, data);
	glGenerateMipmap(GL_TEXTURE_2D);
	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_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glBindTexture(GL_TEXTURE_2D, 0);

	str = str8pushf(temparena, "[INFO] : Texture : %s : Loaded successfully\n", cfilename);

end:
	str8print(str);
	stbi_image_free(data);
	arena_release(temparena);
	return texture;
}