Model.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. #include "Model.h"
  2. #define STB_IMAGE_IMPLEMENTATION
  3. #include "stb_image.h"
  4. #include <iostream>
  5. #include <fstream>
  6. #include <string>
  7. #include <algorithm>
  8. #include <cmath>
  9. //Prototypes
  10. std::vector<std::string> split(std::string str, std::string sep);
  11. std::string replace(std::string str, std::string toReplace, std::string replacement);
  12. std::string toLower(std::string data);
  13. Model::Model(std::string fileName)
  14. {
  15. std::string dirName = fileName;
  16. if (dirName.rfind("/") != std::string::npos)
  17. dirName = dirName.substr(0, dirName.rfind("/"));
  18. if (dirName.rfind("\\") != std::string::npos)
  19. dirName = dirName.substr(0, dirName.rfind("\\"));
  20. if (fileName == dirName)
  21. dirName = "";
  22. std::ifstream pFile(fileName.c_str());
  23. if (!pFile.is_open())
  24. {
  25. std::cout << "Could not open file " << fileName << std::endl;
  26. return;
  27. }
  28. ObjGroup* currentGroup = new ObjGroup();
  29. currentGroup->materialIndex = -1;
  30. while (!pFile.eof())
  31. {
  32. std::string line;
  33. std::getline(pFile, line);
  34. line = replace(line, "\t", " ");
  35. while (line.find(" ") != std::string::npos)
  36. line = replace(line, " ", " ");
  37. if (line == "")
  38. continue;
  39. if (line[0] == ' ')
  40. line = line.substr(1);
  41. if (line == "")
  42. continue;
  43. if (line[line.length() - 1] == ' ')
  44. line = line.substr(0, line.length() - 1);
  45. if (line == "")
  46. continue;
  47. if (line[0] == '#')
  48. continue;
  49. std::vector<std::string> params = split(line, " ");
  50. params[0] = toLower(params[0]);
  51. if (params[0] == "v")
  52. vertices.push_back(Vec3f((float)atof(params[1].c_str()), (float)atof(params[2].c_str()), (float)atof(params[3].c_str())));
  53. else if (params[0] == "vn")
  54. normals.push_back(Vec3f((float)atof(params[1].c_str()), (float)atof(params[2].c_str()), (float)atof(params[3].c_str())));
  55. else if (params[0] == "vt")
  56. texcoords.push_back(Vec2f((float)atof(params[1].c_str()), (float)atof(params[2].c_str())));
  57. else if (params[0] == "f")
  58. {
  59. for (size_t ii = 4; ii <= params.size(); ii++)
  60. {
  61. Face face;
  62. for (size_t i = ii - 3; i < ii; i++) //magische forlus om van quads triangles te maken ;)
  63. {
  64. VertexIndex vertex;
  65. std::vector<std::string> indices = split(params[i == (ii - 3) ? 1 : i], "/");
  66. if (indices.size() >= 1) //er is een positie
  67. vertex.position = atoi(indices[0].c_str()) - 1;
  68. if (indices.size() == 2) //alleen texture
  69. vertex.texcoord = atoi(indices[1].c_str()) - 1;
  70. if (indices.size() == 3) //v/t/n of v//n
  71. {
  72. if (indices[1] != "")
  73. vertex.texcoord = atoi(indices[1].c_str()) - 1;
  74. vertex.normal = atoi(indices[2].c_str()) - 1;
  75. }
  76. face.vertices.push_back(vertex);
  77. }
  78. currentGroup->faces.push_back(face);
  79. }
  80. }
  81. else if (params[0] == "s")
  82. {//smoothing
  83. }
  84. else if (params[0] == "mtllib")
  85. {
  86. loadMaterialFile(dirName + "/" + params[1], dirName);
  87. }
  88. else if (params[0] == "usemtl")
  89. {
  90. if (currentGroup->faces.size() != 0)
  91. groups.push_back(currentGroup);
  92. currentGroup = new ObjGroup();
  93. currentGroup->materialIndex = -1;
  94. for (size_t i = 0; i < materials.size(); i++)
  95. {
  96. MaterialInfo* info = materials[i];
  97. if (info->name == params[1])
  98. {
  99. currentGroup->materialIndex = i;
  100. break;
  101. }
  102. }
  103. if (currentGroup->materialIndex == -1)
  104. std::cout << "Could not find material name " << params[1] << std::endl;
  105. }
  106. }
  107. groups.push_back(currentGroup);
  108. minVertex = vertices[0];
  109. maxVertex = vertices[0];
  110. for (auto v : vertices)
  111. {
  112. for (int i = 0; i < 3; i++)
  113. {
  114. minVertex[i] = fmin(minVertex[i], v[i]);
  115. maxVertex[i] = fmax(maxVertex[i], v[i]);
  116. }
  117. }
  118. center = (minVertex + maxVertex) / 2.0f;
  119. radius = 0;
  120. for (auto v : vertices)
  121. radius = fmax(radius, (center.x - v.x) * (center.x - v.x) + (center.z - v.z) * (center.z - v.z));
  122. radius = sqrt(radius);
  123. for (ObjGroup *group : groups)
  124. {
  125. Optimise(group);
  126. }
  127. }
  128. void Model::Optimise(ObjGroup *t)
  129. {
  130. for (Face &face : t->faces)
  131. {
  132. for (auto &vertex : face.vertices)
  133. {
  134. t->VertexArray.push_back(Vertex(vertices[vertex.position].x, vertices[vertex.position].y, vertices[vertex.position].z,
  135. normals[vertex.normal].x, normals[vertex.normal].y, normals[vertex.normal].z,
  136. texcoords[vertex.texcoord].x, texcoords[vertex.texcoord].y));
  137. }
  138. }
  139. }
  140. void Model::draw()
  141. {
  142. glEnableClientState(GL_VERTEX_ARRAY);
  143. glEnableClientState(GL_NORMAL_ARRAY);
  144. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  145. for (auto &g : groups)
  146. {
  147. if (materials[g->materialIndex]->hasTexture)
  148. {
  149. glEnable(GL_TEXTURE_2D);
  150. materials[g->materialIndex]->texture->bind();
  151. }
  152. else
  153. {
  154. glDisable(GL_TEXTURE_2D);
  155. float color[4] = { 1, 0, 0, 1 };
  156. if (materials[g->materialIndex]->hasDiffuse)
  157. {
  158. memcpy(color, materials[g->materialIndex]->diffuseColor.v, 3 * sizeof(float));
  159. glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);
  160. }
  161. else if (materials[g->materialIndex]->hasAmbient)
  162. {
  163. memcpy(color, materials[g->materialIndex]->ambientColor.v, 3 * sizeof(float));
  164. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);
  165. }
  166. else if (materials[g->materialIndex]->hasSpecular)
  167. {
  168. memcpy(color, materials[g->materialIndex]->specularColor.v, 3 * sizeof(float));
  169. glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, color);
  170. }
  171. }
  172. glVertexPointer(3, GL_FLOAT, sizeof(Vertex), ((float*)g->VertexArray.data()) + 0);
  173. glNormalPointer(GL_FLOAT, sizeof(Vertex), ((float*)g->VertexArray.data()) + 3);
  174. glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), ((float*)g->VertexArray.data()) + 6);
  175. glDrawArrays(GL_TRIANGLES, 0, g->VertexArray.size());
  176. }
  177. glDisableClientState(GL_VERTEX_ARRAY);
  178. glDisableClientState(GL_NORMAL_ARRAY);
  179. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  180. }
  181. void Model::loadMaterialFile(std::string fileName, std::string dirName)
  182. {
  183. std::ifstream pFile(fileName.c_str());
  184. if (!pFile.is_open())
  185. {
  186. std::cout << "Could not open file " << fileName << std::endl;
  187. return;
  188. }
  189. MaterialInfo* currentMaterial = NULL;
  190. while (!pFile.eof())
  191. {
  192. std::string line;
  193. std::getline(pFile, line);
  194. line = replace(line, "\t", " ");
  195. while (line.find(" ") != std::string::npos)
  196. line = replace(line, " ", " ");
  197. if (line == "")
  198. continue;
  199. if (line[0] == ' ')
  200. line = line.substr(1);
  201. if (line == "")
  202. continue;
  203. if (line[line.length() - 1] == ' ')
  204. line = line.substr(0, line.length() - 1);
  205. if (line == "")
  206. continue;
  207. if (line[0] == '#')
  208. continue;
  209. std::vector<std::string> params = split(line, " ");
  210. params[0] = toLower(params[0]);
  211. if (params[0] == "newmtl")
  212. {
  213. if (currentMaterial != NULL)
  214. {
  215. materials.push_back(currentMaterial);
  216. }
  217. currentMaterial = new MaterialInfo();
  218. currentMaterial->name = params[1];
  219. }
  220. else if (params[0] == "map_kd")
  221. {
  222. currentMaterial->hasTexture = true;
  223. currentMaterial->texture = new Texture(dirName + "/" + params[1]);
  224. }
  225. else if (params[0] == "kd")
  226. {
  227. currentMaterial->hasDiffuse = true;
  228. currentMaterial->diffuseColor = Vec3f(atof(params[1].c_str()), atof(params[2].c_str()), atof(params[3].c_str()));
  229. }
  230. else if (params[0] == "ka")
  231. {
  232. currentMaterial->hasAmbient = true;
  233. currentMaterial->ambientColor = Vec3f(atof(params[1].c_str()), atof(params[2].c_str()), atof(params[3].c_str()));
  234. }
  235. else if (params[0] == "ks")
  236. {
  237. currentMaterial->hasSpecular = true;
  238. currentMaterial->specularColor = Vec3f(atof(params[1].c_str()), atof(params[2].c_str()), atof(params[3].c_str()));
  239. }
  240. else
  241. std::cout << "Didn't parse " << params[0] << " in material file" << std::endl;
  242. }
  243. if (currentMaterial != NULL)
  244. materials.push_back(currentMaterial);
  245. }
  246. Model::MaterialInfo::MaterialInfo()
  247. {
  248. hasTexture = false;
  249. }
  250. Model::Texture::Texture(const std::string & fileName)
  251. {
  252. int width, height, bpp;
  253. stbi_set_flip_vertically_on_load(true);
  254. unsigned char* imgData = stbi_load(fileName.c_str(), &width, &height, &bpp, 4);
  255. glGenTextures(1, &index);
  256. glBindTexture(GL_TEXTURE_2D, index);
  257. glTexImage2D(GL_TEXTURE_2D,
  258. 0, //level
  259. GL_RGBA, //internal format
  260. width, //width
  261. height, //height
  262. 0, //border
  263. GL_RGBA, //data format
  264. GL_UNSIGNED_BYTE, //data type
  265. imgData); //data
  266. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  267. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  268. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  269. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  270. stbi_image_free(imgData);
  271. }
  272. void Model::Texture::bind()
  273. {
  274. glBindTexture(GL_TEXTURE_2D, index);
  275. }
  276. std::string replace(std::string str, std::string toReplace, std::string replacement)
  277. {
  278. size_t index = 0;
  279. while (true)
  280. {
  281. index = str.find(toReplace, index);
  282. if (index == std::string::npos)
  283. break;
  284. str.replace(index, toReplace.length(), replacement);
  285. ++index;
  286. }
  287. return str;
  288. }
  289. std::vector<std::string> split(std::string str, std::string sep)
  290. {
  291. std::vector<std::string> ret;
  292. size_t index;
  293. while (true)
  294. {
  295. index = str.find(sep);
  296. if (index == std::string::npos)
  297. break;
  298. ret.push_back(str.substr(0, index));
  299. str = str.substr(index + 1);
  300. }
  301. ret.push_back(str);
  302. return ret;
  303. }
  304. inline std::string toLower(std::string data)
  305. {
  306. std::transform(data.begin(), data.end(), data.begin(), ::tolower);
  307. return data;
  308. }
  309. std::map<std::string, std::pair<Model*, int>> Model::cache;
  310. Model* Model::load(const std::string &fileName)
  311. {
  312. if (cache.find(fileName) == cache.end())
  313. cache[fileName] = std::pair<Model*, int>(new Model(fileName), 0);
  314. cache[fileName].second++;
  315. return cache[fileName].first;
  316. }
  317. void Model::unload(Model* model)
  318. {
  319. for (auto m : cache)
  320. {
  321. if (m.second.first == model)
  322. {
  323. m.second.second--;
  324. if (m.second.second == 0)
  325. {
  326. delete m.second.first;
  327. cache.erase(cache.find(m.first));
  328. }
  329. }
  330. }
  331. }
  332. Model::~Model(void)
  333. {
  334. for (auto m : cache)
  335. {
  336. delete m.second.first;
  337. }
  338. }