Debian Codegraph @

dokidoki-support/lua_stb_image.c

raw symbols SCIP
1 #include <lua.h>
2 #include <lauxlib.h>
3 #include <lualib.h>
4
5 #define STBI_NO_WRITE
6 #define STBI_NO_HDR
7 #include "stb_image.c"
8
9 static int check_req_comp(lua_State *L, int index)
10 {
11 int req_comp = luaL_optint(L, 2, 0);
12 luaL_argcheck(L, 0 <= req_comp && req_comp <= 4, 2,
13 "invalid requested component count");
14 return req_comp;
15 }
16
17 static int return_image(lua_State *L, unsigned char * image, int x, int y,
18 int comp, int req_comp)
19 {
20 if(req_comp == 0) req_comp = comp;
21
22 if(image)
23 {
24 lua_pushlstring(L, (char *)image, x * y * req_comp);
25 lua_pushinteger(L, x);
26 lua_pushinteger(L, y);
27 lua_pushinteger(L, comp);
28 stbi_image_free(image);
29 return 4;
30 }
31 else
32 {
33 lua_pushnil(L);
34 lua_pushstring(L, stbi_failure_reason());
35 return 2;
36 }
37 }
38
39 static int stb_image_load(lua_State *L)
40 {
41 const char * filename = luaL_checkstring(L, 1);
42 int req_comp = check_req_comp(L, 2);
43
44 int x, y, comp;
45 unsigned char * image = stbi_load(filename, &x, &y, &comp, req_comp);
46
47 return return_image(L, image, x, y, comp, req_comp);
48 }
49
50 static int stb_image_load_from_string(lua_State *L)
51 {
52 size_t source_len;
53 const char * source = luaL_checklstring(L, 1, &source_len);
54 int req_comp = check_req_comp(L, 2);
55
56 int x, y, comp;
57 unsigned char * image = stbi_load_from_memory(
58 (unsigned char *)source, source_len, &x, &y, &comp, req_comp);
59
60 return return_image(L, image, x, y, comp, req_comp);
61 }
62
63 static const luaL_Reg stb_image_lib[] =
64 {
65 {"load", stb_image_load},
66 {"load_from_string", stb_image_load_from_string},
67 {NULL, NULL}
68 };
69
70 int luaopen_stb_image(lua_State *L)
71 {
72 lua_newtable(L);
73 luaL_register(L, NULL, stb_image_lib);
74 return 1;
75 }