texture.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include "texture.h"
  2. #include "lua.h"
  3. #include <glplatform/glplatform-glcore.h>
  4. static int texture_gc(lua_State *L)
  5. {
  6. struct texture *t = lua_touserdata(L, -1);
  7. glDeleteTextures(1, &t->texid);
  8. return 0;
  9. }
  10. void ltexture_create(lua_State *L, GdkPixbuf *pbuf)
  11. {
  12. GLuint texid;
  13. glGenTextures(1, &texid);
  14. glBindTexture(GL_TEXTURE_2D, texid);
  15. int width = gdk_pixbuf_get_width(pbuf);
  16. int height = gdk_pixbuf_get_height(pbuf);
  17. int n_chan = gdk_pixbuf_get_n_channels(pbuf);
  18. glPixelStorei(GL_UNPACK_ROW_LENGTH, gdk_pixbuf_get_rowstride(pbuf)/ n_chan);
  19. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  20. glTexImage2D(GL_TEXTURE_2D,
  21. 0, /* level */
  22. n_chan > 3 ? GL_RGBA : GL_RGB,
  23. width,
  24. height,
  25. 0, /* border */
  26. n_chan > 3 ? GL_RGBA : GL_RGB,
  27. GL_UNSIGNED_BYTE,
  28. gdk_pixbuf_get_pixels(pbuf));
  29. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  30. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  31. glGenerateMipmap(GL_TEXTURE_2D);
  32. struct texture *t = lua_newuserdata(L, sizeof(struct texture));
  33. t->texid = texid;
  34. lua_newtable(L);
  35. lua_pushcfunction(L, texture_gc);
  36. lua_setfield(L, -2, "__gc");
  37. lua_setmetatable(L, -2);
  38. }