Texture.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "rendering/Texture.h"
  2. #include "io/ImageReader.h"
  3. Texture::Texture()
  4. : format(TextureFormat::unknown()), texture(0), maxMipMaps(0) {
  5. }
  6. Texture::~Texture() {
  7. GL::deleteTexture(texture);
  8. }
  9. void Texture::init(const TextureFormat& format, int maxMipMaps) {
  10. if(texture != 0) {
  11. return;
  12. }
  13. Texture::format = format;
  14. Texture::maxMipMaps = maxMipMaps;
  15. texture = GL::genTexture();
  16. setNearestFilter();
  17. setRepeatWrap();
  18. }
  19. void Texture::setNearestFilter() {
  20. bind();
  21. if(maxMipMaps > 0) {
  22. GL::setMipMapNearFilter2D();
  23. } else {
  24. GL::setNearFilter2D();
  25. }
  26. }
  27. void Texture::setLinearFilter() {
  28. bind();
  29. if(maxMipMaps > 0) {
  30. GL::setMipMapLinearFilter2D();
  31. } else {
  32. GL::setLinearFilter2D();
  33. }
  34. }
  35. void Texture::setRepeatWrap() {
  36. bind();
  37. GL::setRepeatWrap2D();
  38. }
  39. void Texture::setClampWrap() {
  40. bind();
  41. GL::setClampWrap2D();
  42. }
  43. void Texture::setData(int width, int height, const void* data) {
  44. bind();
  45. GL::texImage2D(format.format, width, height, data);
  46. if(maxMipMaps > 0) {
  47. GL::generateMipmap2D(maxMipMaps);
  48. }
  49. }
  50. void Texture::bind() const {
  51. GL::bindTexture2D(texture);
  52. }
  53. void Texture::bindTo(int index) const {
  54. GL::activeTexture(index);
  55. bind();
  56. }
  57. Error Texture::load(const char* path, int maxMipMaps) {
  58. ImageReader::Image image;
  59. Error error = ImageReader::load(image, path);
  60. if(error.has()) {
  61. return error;
  62. }
  63. if(image.channels < 1 || image.channels > 4) {
  64. Error error = {"'"};
  65. error.message.append(path)
  66. .append("' has unsupported number of channels: ")
  67. .append(image.channels);
  68. return error;
  69. } else if(image.bitdepth != 8) {
  70. Error error = {"bit depth of '"};
  71. error.message.append(path).append("' is not 8");
  72. return error;
  73. }
  74. init(TextureFormat::color8(image.channels), maxMipMaps);
  75. setData(image.width, image.height, image.data);
  76. return {};
  77. }