initial commit
[ld37_one_room] / src / material.cc
1 #include <algorithm>
2 #include <string.h>
3 #include "opengl.h"
4 #include "material.h"
5 #include "sdr.h"
6 #include "app.h"
7
8 Material::Material()
9         : diffuse(1.0f, 1.0f, 1.0f)
10 {
11         shininess = 0.0f;
12         alpha = 1.0f;
13         memset(stdtex, 0, sizeof stdtex);
14 }
15
16 void Material::setup() const
17 {
18         float kd[] = {diffuse.x, diffuse.y, diffuse.z, alpha};
19         float ks[] = {specular.x, specular.y, specular.z, 1.0f};
20
21         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, kd);
22         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, ks);
23         glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
24
25         int ntex = std::min((int)textures.size(), 8);   // TODO: use max texture units
26         for(int i=0; i<ntex; i++) {
27                 bind_texture(textures[i], i);
28         }
29
30         /*
31         if(stdtex[MTL_TEX_LIGHTMAP]) {
32                 bind_program(stdtex[MTL_TEX_DIFFUSE] ? sdr_ltmap : sdr_ltmap_notex);
33         }
34         */
35 }
36
37 void Material::add_texture(Texture *tex, int type)
38 {
39         if(std::find(textures.begin(), textures.end(), tex) == textures.end()) {
40                 textures.push_back(tex);
41         }
42
43         if(type != MTL_TEX_UNKNOWN) {
44                 stdtex[type] = tex;
45         }
46 }
47
48 void Material::remove_texture(Texture *tex)
49 {
50         std::vector<Texture*>::iterator it = std::find(textures.begin(), textures.end(), tex);
51         if(it != textures.end()) {
52                 textures.erase(it);
53         }
54
55         for(int i=0; i<NUM_MTL_TEXTURES; i++) {
56                 if(stdtex[i] == tex) {
57                         stdtex[i] = 0;
58                 }
59         }
60 }
61
62 int mtl_parse_type(const char *str)
63 {
64         if(strcmp(str, "diffuse") == 0) {
65                 return MTL_TEX_DIFFUSE;
66         } else if(strcmp(str, "specular") == 0) {
67                 return MTL_TEX_SPECULAR;
68         } else if(strcmp(str, "normalmap") == 0) {
69                 return MTL_TEX_NORMALMAP;
70         } else if(strcmp(str, "lightmap") == 0) {
71                 return MTL_TEX_LIGHTMAP;
72         } else if(strcmp(str, "envmap") == 0) {
73                 return MTL_TEX_ENVMAP;
74         }
75         return MTL_TEX_UNKNOWN;
76 }
77
78 const char *mtl_type_string(int type)
79 {
80         switch(type) {
81         case MTL_TEX_DIFFUSE:
82                 return "diffuse";
83         case MTL_TEX_SPECULAR:
84                 return "specular";
85         case MTL_TEX_NORMALMAP:
86                 return "normalmap";
87         case MTL_TEX_LIGHTMAP:
88                 return "lightmap";
89         case MTL_TEX_ENVMAP:
90                 return "envmap";
91         default:
92                 break;
93         }
94         return "unknown";
95 }