Model.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. #include "Model.h"
  2. #include "stb_image.h"
  3. #include <iostream>
  4. #include <fstream>
  5. #include <string>
  6. #include <algorithm>
  7. #include <cmath>
  8. #include <cstring>
  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. try
  131. {
  132. for (Face &face : t->faces)
  133. {
  134. for (auto &vertex : face.vertices)
  135. {
  136. if(vertex.texcoord < texcoords.size()){
  137. t->VertexArray.push_back(Vertex(vertices[vertex.position].x, vertices[vertex.position].y, vertices[vertex.position].z,
  138. normals[vertex.normal].x, normals[vertex.normal].y, normals[vertex.normal].z,
  139. texcoords[vertex.texcoord].x, texcoords[vertex.texcoord].y));
  140. }else{
  141. t->VertexArray.push_back(Vertex(vertices[vertex.position].x, vertices[vertex.position].y, vertices[vertex.position].z,
  142. normals[vertex.normal].x, normals[vertex.normal].y, normals[vertex.normal].z,
  143. 0,0));
  144. }
  145. }
  146. }
  147. }catch (std::exception& e)
  148. {
  149. std::cerr << "Exception catched : " << e.what() << std::endl;
  150. }
  151. }
  152. void Model::draw()
  153. {
  154. glEnableClientState(GL_VERTEX_ARRAY);
  155. glEnableClientState(GL_NORMAL_ARRAY);
  156. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  157. for (auto &g : groups)
  158. {
  159. if (materials[g->materialIndex]->hasTexture)
  160. {
  161. glEnable(GL_TEXTURE_2D);
  162. materials[g->materialIndex]->texture->bind();
  163. }
  164. else
  165. {
  166. glDisable(GL_TEXTURE_2D);
  167. float color[4] = { 1, 0, 0, 1 };
  168. if (materials[g->materialIndex]->hasDiffuse)
  169. {
  170. memcpy(color, materials[g->materialIndex]->diffuseColor.v, 3 * sizeof(float));
  171. glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);
  172. }
  173. else if (materials[g->materialIndex]->hasAmbient)
  174. {
  175. memcpy(color, materials[g->materialIndex]->ambientColor.v, 3 * sizeof(float));
  176. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);
  177. }
  178. else if (materials[g->materialIndex]->hasSpecular)
  179. {
  180. memcpy(color, materials[g->materialIndex]->specularColor.v, 3 * sizeof(float));
  181. glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, color);
  182. }
  183. }
  184. glVertexPointer(3, GL_FLOAT, sizeof(Vertex), ((float*)g->VertexArray.data()) + 0);
  185. glNormalPointer(GL_FLOAT, sizeof(Vertex), ((float*)g->VertexArray.data()) + 3);
  186. glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), ((float*)g->VertexArray.data()) + 6);
  187. glDrawArrays(GL_TRIANGLES, 0, g->VertexArray.size());
  188. }
  189. glDisableClientState(GL_VERTEX_ARRAY);
  190. glDisableClientState(GL_NORMAL_ARRAY);
  191. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  192. }
  193. void Model::loadMaterialFile(std::string fileName, std::string dirName)
  194. {
  195. std::ifstream pFile(fileName.c_str());
  196. if (!pFile.is_open())
  197. {
  198. std::cout << "Could not open file " << fileName << std::endl;
  199. return;
  200. }
  201. MaterialInfo* currentMaterial = NULL;
  202. while (!pFile.eof())
  203. {
  204. std::string line;
  205. std::getline(pFile, line);
  206. line = replace(line, "\t", " ");
  207. while (line.find(" ") != std::string::npos)
  208. line = replace(line, " ", " ");
  209. if (line == "")
  210. continue;
  211. if (line[0] == ' ')
  212. line = line.substr(1);
  213. if (line == "")
  214. continue;
  215. if (line[line.length() - 1] == ' ')
  216. line = line.substr(0, line.length() - 1);
  217. if (line == "")
  218. continue;
  219. if (line[0] == '#')
  220. continue;
  221. std::vector<std::string> params = split(line, " ");
  222. params[0] = toLower(params[0]);
  223. if (params[0] == "newmtl")
  224. {
  225. if (currentMaterial != NULL)
  226. {
  227. materials.push_back(currentMaterial);
  228. }
  229. currentMaterial = new MaterialInfo();
  230. currentMaterial->name = params[1];
  231. }
  232. else if (params[0] == "map_kd")
  233. {
  234. currentMaterial->hasTexture = true;
  235. currentMaterial->texture = new Texture(dirName + "/" + params[1]);
  236. }
  237. else if (params[0] == "kd")
  238. {
  239. currentMaterial->hasDiffuse = true;
  240. currentMaterial->diffuseColor = Vec3f(atof(params[1].c_str()), atof(params[2].c_str()), atof(params[3].c_str()));
  241. }
  242. else if (params[0] == "ka")
  243. {
  244. currentMaterial->hasAmbient = true;
  245. currentMaterial->ambientColor = Vec3f(atof(params[1].c_str()), atof(params[2].c_str()), atof(params[3].c_str()));
  246. }
  247. else if (params[0] == "ks")
  248. {
  249. currentMaterial->hasSpecular = true;
  250. currentMaterial->specularColor = Vec3f(atof(params[1].c_str()), atof(params[2].c_str()), atof(params[3].c_str()));
  251. }
  252. else
  253. std::cout << "Didn't parse " << params[0] << " in material file" << std::endl;
  254. }
  255. if (currentMaterial != NULL)
  256. materials.push_back(currentMaterial);
  257. }
  258. Model::MaterialInfo::MaterialInfo()
  259. {
  260. hasTexture = false;
  261. }
  262. Model::Texture::Texture(const std::string & fileName)
  263. {
  264. int width, height, bpp;
  265. stbi_set_flip_vertically_on_load(true);
  266. unsigned char* imgData = stbi_load(fileName.c_str(), &width, &height, &bpp, 4);
  267. glGenTextures(1, &index);
  268. glBindTexture(GL_TEXTURE_2D, index);
  269. glTexImage2D(GL_TEXTURE_2D,
  270. 0, //level
  271. GL_RGBA, //internal format
  272. width, //width
  273. height, //height
  274. 0, //border
  275. GL_RGBA, //data format
  276. GL_UNSIGNED_BYTE, //data type
  277. imgData); //data
  278. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  279. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  280. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  281. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  282. stbi_image_free(imgData);
  283. }
  284. void Model::Texture::bind()
  285. {
  286. glBindTexture(GL_TEXTURE_2D, index);
  287. }
  288. std::string replace(std::string str, std::string toReplace, std::string replacement)
  289. {
  290. size_t index = 0;
  291. while (true)
  292. {
  293. index = str.find(toReplace, index);
  294. if (index == std::string::npos)
  295. break;
  296. str.replace(index, toReplace.length(), replacement);
  297. ++index;
  298. }
  299. return str;
  300. }
  301. std::vector<std::string> split(std::string str, std::string sep)
  302. {
  303. std::vector<std::string> ret;
  304. size_t index;
  305. while (true)
  306. {
  307. index = str.find(sep);
  308. if (index == std::string::npos)
  309. break;
  310. ret.push_back(str.substr(0, index));
  311. str = str.substr(index + 1);
  312. }
  313. ret.push_back(str);
  314. return ret;
  315. }
  316. inline std::string toLower(std::string data)
  317. {
  318. std::transform(data.begin(), data.end(), data.begin(), ::tolower);
  319. return data;
  320. }
  321. std::map<std::string, std::pair<Model*, int>> Model::cache;
  322. Model* Model::load(const std::string &fileName)
  323. {
  324. if (cache.find(fileName) == cache.end())
  325. cache[fileName] = std::pair<Model*, int>(new Model(fileName), 0);
  326. cache[fileName].second++;
  327. return cache[fileName].first;
  328. }
  329. void Model::unload(Model* model)
  330. {
  331. for (auto m : cache)
  332. {
  333. if (m.second.first == model)
  334. {
  335. m.second.second--;
  336. if (m.second.second == 0)
  337. {
  338. delete m.second.first;
  339. cache.erase(cache.find(m.first));
  340. break;
  341. }
  342. }
  343. }
  344. }
  345. Model::~Model(void)
  346. {
  347. }