aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/old/vlib/stbi/stbi.v
blob: da72dca2207d1889cc9e554549aef1b695fda123 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.

module stbi

#flag -I @VEXEROOT/thirdparty/stb_image
#include "stb_image.h"
#flag @VEXEROOT/thirdparty/stb_image/stbi.o

pub struct Image {
pub mut:
	width       int
	height      int
	nr_channels int
	ok          bool
	data        voidptr
	ext         string
}

fn C.stbi_load(filename &char, x &int, y &int, channels_in_file &int, desired_channels int) &byte

fn C.stbi_load_from_file(f voidptr, x &int, y &int, channels_in_file &int, desired_channels int) &byte

fn C.stbi_load_from_memory(buffer &byte, len int, x &int, y &int, channels_in_file &int, desired_channels int) &byte

fn C.stbi_image_free(retval_from_stbi_load &byte)

fn C.stbi_set_flip_vertically_on_load(should_flip int)

fn init() {
	set_flip_vertically_on_load(false)
}

pub fn load(path string) ?Image {
	ext := path.all_after_last('.')
	mut res := Image{
		ok: true
		ext: ext
		data: 0
	}
	// flag := if ext == 'png' { C.STBI_rgb_alpha } else { 0 }
	desired_channels := if ext == 'png' { 4 } else { 0 }
	res.data = C.stbi_load(&char(path.str), &res.width, &res.height, &res.nr_channels,
		desired_channels)
	if desired_channels == 4 && res.nr_channels == 3 {
		// Fix an alpha png bug
		res.nr_channels = 4
	}
	if isnil(res.data) {
		return error('stbi image failed to load from "$path"')
	}
	return res
}

pub fn load_from_memory(buf &byte, bufsize int) ?Image {
	mut res := Image{
		ok: true
		data: 0
	}
	flag := C.STBI_rgb_alpha
	res.data = C.stbi_load_from_memory(buf, bufsize, &res.width, &res.height, &res.nr_channels,
		flag)
	if isnil(res.data) {
		return error('stbi image failed to load from memory')
	}
	return res
}

pub fn (img &Image) free() {
	C.stbi_image_free(img.data)
}

/*
pub fn (img Image) tex_image_2d() {
	mut rgb_flag := C.GL_RGB
	if img.ext == 'png' {
		rgb_flag = C.GL_RGBA
	}
	C.glTexImage2D(C.GL_TEXTURE_2D, 0, rgb_flag, img.width, img.height, 0,
		rgb_flag, C.GL_UNSIGNED_BYTE,	img.data)
}
*/

pub fn set_flip_vertically_on_load(val bool) {
	C.stbi_set_flip_vertically_on_load(val)
}