World.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "World.h"
  2. #include <GL/freeglut.h>
  3. #include "Entity.h"
  4. #include "LevelObject.h"
  5. #include "json.h"
  6. #include <fstream>
  7. #include <iostream>
  8. World::World() : player(Player::getInstance())
  9. {
  10. std::ifstream file("worlds/world1.json");
  11. if(!file.is_open())
  12. std::cout<<"Uhoh, can't open file\n";
  13. json::Value v = json::readJson(file);
  14. file.close();
  15. heightmap = new HeightMap(v["world"]["heightmap"].asString());
  16. heightmap->SetTexture(v["world"]["texture"].asString());
  17. player.position.x = v["player"]["startposition"][0];
  18. player.position.y = v["player"]["startposition"][1];
  19. player.position.z = v["player"]["startposition"][2];
  20. for (auto object : v["objects"])
  21. {
  22. bool hasCollision = true;
  23. if (!object["collide"].isNull())
  24. hasCollision = object["collide"].asBool();
  25. Vec3f rotation(0, 0, 0);
  26. if(!object["rot"].isNull())
  27. rotation = Vec3f(object["rot"][0], object["rot"][1], object["rot"][2]);
  28. float scale = 1;
  29. if (!object["scale"].isNull())
  30. scale = object["scale"].asFloat();
  31. Vec3f position(object["pos"][0], object["pos"][1], object["pos"][2]);
  32. entities.push_back(new LevelObject(object["file"], position, rotation, scale, hasCollision));
  33. }
  34. }
  35. World::~World()
  36. {
  37. }
  38. void World::draw()
  39. {
  40. player.setCamera();
  41. float lightPosition[4] = { 0, 2, 1, 0 };
  42. glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
  43. float lightAmbient[4] = { 0.5, 0.5, 0.5, 1 };
  44. glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
  45. glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
  46. heightmap->Draw();
  47. for (auto e : entities)
  48. e->draw();
  49. }
  50. void World::update(float elapsedTime)
  51. {
  52. for (auto e : entities)
  53. e->update(elapsedTime);
  54. }
  55. bool World::isPlayerPositionValid()
  56. {
  57. for (auto e : entities)
  58. {
  59. if (e->canCollide && e->inObject(player.position))
  60. return false;
  61. }
  62. return true;
  63. }