1 module ws.gl.texture; 2 3 import 4 ws.log, 5 ws.file.freeimage, 6 ws.string, 7 ws.gl.gl, 8 ws.gui.point, 9 ws.file.tga, 10 ws.exception, 11 ws.io; 12 13 __gshared: 14 15 class Texture { 16 17 private static Texture[string] textures; 18 19 uint id; 20 string path; 21 Point size; 22 23 void destroy(){ 24 glDeleteTextures(1, &id); 25 } 26 27 this(){} 28 29 this(uint id){ 30 this.id = id; 31 } 32 33 int bind(int where){ 34 glActiveTexture(GL_TEXTURE0 + where); 35 glBindTexture(GL_TEXTURE_2D, id); 36 return where; 37 } 38 39 static Texture load(string path){ 40 if(path in textures) 41 return textures[path]; 42 try { 43 //auto file = new TGA("materials/" ~ path); 44 auto file = new FIImage("materials/" ~ path); 45 auto t = new Texture; 46 t.path = path; 47 t.id = 0; 48 t.size = Point(cast(int)file.width, cast(int)file.height); 49 textures[path] = t; 50 if(file.width >= GL_MAX_TEXTURE_SIZE) 51 Log.warning("Image width too large (" ~ tostring(file.width) ~ " of " ~ tostring(GL_MAX_TEXTURE_SIZE) ~ "): " ~ path); 52 if(file.height >= GL_MAX_TEXTURE_SIZE) 53 Log.warning("Image height too large (" ~ tostring(file.height) ~ " of " ~ tostring(GL_MAX_TEXTURE_SIZE) ~ "): " ~ path); 54 glGenTextures(1, &t.id); 55 glBindTexture(GL_TEXTURE_2D, t.id); 56 glTexImage2D( 57 GL_TEXTURE_2D, 58 0, 59 cast(uint)(file.colors == 4 ? GL_RGBA : (file.colors == 3 ? GL_SRGB : 0x1909)), 60 cast(int)file.width, 61 cast(int)file.height, 62 0, 63 file.colors == 4 ? GL_RGBA : (file.colors == 3 ? GL_RGB : 0x1909), 64 GL_UNSIGNED_BYTE, 65 file.data.ptr 66 ); 67 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 68 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 69 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); 70 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST); 71 glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 72 glGenerateMipmap(GL_TEXTURE_2D); 73 float aniso = 0.0f; 74 glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &aniso); 75 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso); 76 return t; 77 }catch(Exception e) 78 exception("Failed to load texture \"" ~ path ~ "\"", e); 79 return null; 80 } 81 82 }