💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

350 lines
11 KiB

  1. /*
  2. * Copyright (C) 2020 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "terrain-system.hpp"
  20. #include "game/components/model-component.hpp"
  21. #include "game/components/collision-component.hpp"
  22. #include "game/components/transform-component.hpp"
  23. #include "renderer/model.hpp"
  24. #include "geometry/mesh.hpp"
  25. #include "geometry/mesh-functions.hpp"
  26. #include "renderer/vertex-attributes.hpp"
  27. #include "rasterizer/vertex-attribute-type.hpp"
  28. #include "rasterizer/drawing-mode.hpp"
  29. #include "rasterizer/vertex-buffer.hpp"
  30. #include "resources/resource-manager.hpp"
  31. #include "resources/image.hpp"
  32. #include "utility/fundamental-types.hpp"
  33. #include <limits>
  34. using namespace ecs;
  35. terrain_system::terrain_system(entt::registry& registry, ::resource_manager* resource_manager):
  36. entity_system(registry),
  37. resource_manager(resource_manager)
  38. {
  39. registry.on_construct<terrain_component>().connect<&terrain_system::on_terrain_construct>(this);
  40. registry.on_destroy<terrain_component>().connect<&terrain_system::on_terrain_destroy>(this);
  41. heightmap = resource_manager->load<image>("grassland-heightmap.png");
  42. heightmap_size = 2000.0f;
  43. heightmap_scale = 150.0f;
  44. }
  45. terrain_system::~terrain_system()
  46. {}
  47. void terrain_system::update(double t, double dt)
  48. {
  49. registry.view<terrain_component, transform_component>().each(
  50. [this](auto entity, auto& terrain, auto& transform)
  51. {
  52. transform.transform.translation = float3{(float)terrain.x * patch_size, 0.0f, (float)terrain.z * patch_size};
  53. transform.warp = true;
  54. });
  55. }
  56. void terrain_system::set_patch_size(float size)
  57. {
  58. patch_size = size;
  59. }
  60. mesh* terrain_system::generate_terrain_mesh(float size, int subdivisions)
  61. {
  62. // Allocate terrain mesh
  63. mesh* terrain_mesh = new mesh();
  64. // Determine vertex count and placement
  65. int columns = static_cast<int>(std::pow(2, subdivisions));
  66. int rows = columns;
  67. int vertex_count = (columns + 1) * (rows + 1);
  68. float vertex_increment = size / static_cast<float>(columns);
  69. float radius = size * 0.5f;
  70. // Generate mesh vertices
  71. float3 position = {0.0f, 0.0f, -radius};
  72. for (int i = 0; i <= rows; ++i)
  73. {
  74. position[0] = -radius;
  75. for (int j = 0; j <= columns; ++j)
  76. {
  77. terrain_mesh->add_vertex(position);
  78. position[0] += vertex_increment;
  79. }
  80. position[2] += vertex_increment;
  81. }
  82. // Function to eliminate duplicate edges
  83. std::map<std::array<std::size_t, 2>, mesh::edge*> edge_map;
  84. auto add_or_find_edge = [&](mesh::vertex* start, mesh::vertex* end) -> mesh::edge*
  85. {
  86. mesh::edge* edge;
  87. if (auto it = edge_map.find({start->index, end->index}); it != edge_map.end())
  88. {
  89. edge = it->second;
  90. }
  91. else
  92. {
  93. edge = terrain_mesh->add_edge(start, end);
  94. edge_map[{start->index, end->index}] = edge;
  95. edge_map[{end->index, start->index}] = edge->symmetric;
  96. }
  97. return edge;
  98. };
  99. const std::vector<mesh::vertex*>& vertices = terrain_mesh->get_vertices();
  100. for (int i = 0; i < rows; ++i)
  101. {
  102. for (int j = 0; j < columns; ++j)
  103. {
  104. mesh::vertex* a = vertices[i * (columns + 1) + j];
  105. mesh::vertex* b = vertices[(i + 1) * (columns + 1) + j];
  106. mesh::vertex* c = vertices[i * (columns + 1) + j + 1];
  107. mesh::vertex* d = vertices[(i + 1) * (columns + 1) + j + 1];
  108. // +---+---+
  109. // | \ | / |
  110. // |---+---|
  111. // | / | \ |
  112. // +---+---+
  113. if ((j % 2) == (i % 2))
  114. {
  115. mesh::edge* ab = add_or_find_edge(a, b);
  116. mesh::edge* bd = add_or_find_edge(b, d);
  117. mesh::edge* da = add_or_find_edge(d, a);
  118. mesh::edge* ca = add_or_find_edge(c, a);
  119. mesh::edge* ad = da->symmetric;
  120. mesh::edge* dc = add_or_find_edge(d, c);
  121. // a---c
  122. // | \ |
  123. // b---d
  124. terrain_mesh->add_face({ab, bd, da});
  125. terrain_mesh->add_face({ca, ad, dc});
  126. }
  127. else
  128. {
  129. mesh::edge* ab = add_or_find_edge(a, b);
  130. mesh::edge* bc = add_or_find_edge(b, c);
  131. mesh::edge* ca = add_or_find_edge(c, a);
  132. mesh::edge* cb = bc->symmetric;
  133. mesh::edge* bd = add_or_find_edge(b, d);
  134. mesh::edge* dc = add_or_find_edge(d, c);
  135. // a---c
  136. // | / |
  137. // b---d
  138. terrain_mesh->add_face({ab, bc, ca});
  139. terrain_mesh->add_face({cb, bd, dc});
  140. }
  141. }
  142. }
  143. return terrain_mesh;
  144. }
  145. model* terrain_system::generate_terrain_model(mesh* terrain_mesh)
  146. {
  147. // Allocate model
  148. model* terrain_model = new model();
  149. // Get model's VAO and VBO
  150. vertex_buffer* vbo = terrain_model->get_vertex_buffer();
  151. vertex_array* vao = terrain_model->get_vertex_array();
  152. // Resize VBO
  153. int vertex_size = 3 + 3 + 3;
  154. int vertex_stride = vertex_size * sizeof(float);
  155. vbo->resize(terrain_mesh->get_faces().size() * 3 * vertex_stride, nullptr);
  156. // Bind vertex attributes
  157. std::size_t offset = 0;
  158. vao->bind_attribute(VERTEX_POSITION_LOCATION, *vbo, 3, vertex_attribute_type::float_32, vertex_stride, 0);
  159. offset += 3;
  160. vao->bind_attribute(VERTEX_NORMAL_LOCATION, *vbo, 3, vertex_attribute_type::float_32, vertex_stride, sizeof(float) * offset);
  161. offset += 3;
  162. vao->bind_attribute(VERTEX_BARYCENTRIC_LOCATION, *vbo, 3, vertex_attribute_type::float_32, vertex_stride, sizeof(float) * offset);
  163. offset += 3;
  164. // Create model group
  165. model_group* model_group = terrain_model->add_group("terrain");
  166. model_group->set_material(resource_manager->load<material>("grassland-terrain.mtl"));
  167. model_group->set_drawing_mode(drawing_mode::triangles);
  168. model_group->set_start_index(0);
  169. model_group->set_index_count(terrain_mesh->get_faces().size() * 3);
  170. return terrain_model;
  171. }
  172. void terrain_system::project_terrain_mesh(mesh* terrain_mesh, const terrain_component& component)
  173. {
  174. float offset_x = (float)component.x * patch_size;
  175. float offset_z = (float)component.z * patch_size;
  176. for (mesh::vertex* vertex: terrain_mesh->get_vertices())
  177. {
  178. int pixel_x = (vertex->position[0] + offset_x + heightmap_size * 0.5f) / heightmap_size * (float)(heightmap->get_width() - 1);
  179. int pixel_y = (vertex->position[2] + offset_z + heightmap_size * 0.5f) / heightmap_size * (float)(heightmap->get_height() - 1);
  180. pixel_x = std::max<int>(0, std::min<int>(heightmap->get_width() - 1, pixel_x));
  181. pixel_y = std::max<int>(0, std::min<int>(heightmap->get_height() - 1, pixel_y));
  182. int pixel_index = (pixel_y * heightmap->get_width() + pixel_x) * heightmap->get_channels();
  183. const unsigned char* pixel = static_cast<const unsigned char*>(heightmap->get_pixels()) + pixel_index;
  184. float elevation = (static_cast<float>(*pixel) / 255.0f - 0.5) * heightmap_scale;
  185. vertex->position[1] = elevation;
  186. }
  187. }
  188. void terrain_system::update_terrain_model(model* terrain_model, mesh* terrain_mesh)
  189. {
  190. aabb<float> bounds =
  191. {
  192. {std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()},
  193. {-std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity()}
  194. };
  195. static const float3 barycentric_coords[3] =
  196. {
  197. float3{1, 0, 0},
  198. float3{0, 1, 0},
  199. float3{0, 0, 1}
  200. };
  201. int triangle_count = terrain_mesh->get_faces().size();
  202. int vertex_count = triangle_count * 3;
  203. int vertex_size = 3 + 3 + 3;
  204. // Allocate vertex data
  205. float* vertex_data = new float[vertex_size * vertex_count];
  206. // Allocate face normals
  207. float* face_normals = new float[terrain_mesh->get_faces().size() * 3];
  208. calculate_face_normals(face_normals, *terrain_mesh);
  209. // Generate vertex data
  210. float* v = vertex_data;
  211. const std::vector<mesh::face*>& faces = terrain_mesh->get_faces();
  212. for (int i = 0; i < triangle_count; ++i)
  213. {
  214. const mesh::face* triangle = faces[i];
  215. const mesh::vertex* a = triangle->edge->vertex;
  216. const mesh::vertex* b = triangle->edge->next->vertex;
  217. const mesh::vertex* c = triangle->edge->previous->vertex;
  218. const mesh::vertex* abc[] = {a, b, c};
  219. for (int j = 0; j < 3; ++j)
  220. {
  221. const mesh::vertex* vertex = abc[j];
  222. float3 n = {0, 0, 0};
  223. mesh::edge* start = vertex->edge;
  224. mesh::edge* edge = start;
  225. do
  226. {
  227. if (edge->face)
  228. {
  229. n += reinterpret_cast<const float3&>(face_normals[edge->face->index * 3]);
  230. }
  231. edge = edge->previous->symmetric;
  232. }
  233. while (edge != start);
  234. n = math::normalize(n);
  235. *(v++) = vertex->position[0];
  236. *(v++) = vertex->position[1];
  237. *(v++) = vertex->position[2];
  238. *(v++) = n[0];
  239. *(v++) = n[1];
  240. *(v++) = n[2];
  241. *(v++) = barycentric_coords[j][0];
  242. *(v++) = barycentric_coords[j][1];
  243. *(v++) = barycentric_coords[j][2];
  244. // Add position to bounds
  245. for (int i = 0; i < 3; ++i)
  246. {
  247. bounds.min_point[i] = std::min<float>(bounds.min_point[i], vertex->position[i]);
  248. bounds.max_point[i] = std::max<float>(bounds.max_point[i], vertex->position[i]);
  249. }
  250. }
  251. }
  252. // Update bounds
  253. terrain_model->set_bounds(bounds);
  254. // Update VBO
  255. terrain_model->get_vertex_buffer()->update(0, vertex_count * vertex_size * sizeof(float), vertex_data);
  256. // Free vertex data
  257. delete[] face_normals;
  258. delete[] vertex_data;
  259. }
  260. void terrain_system::on_terrain_construct(entt::registry& registry, entt::entity entity, terrain_component& component)
  261. {
  262. mesh* terrain_mesh = generate_terrain_mesh(patch_size, component.subdivisions);
  263. model* terrain_model = generate_terrain_model(terrain_mesh);
  264. project_terrain_mesh(terrain_mesh, component);
  265. update_terrain_model(terrain_model, terrain_mesh);
  266. // Assign the entity a collision component with the terrain mesh
  267. collision_component collision;
  268. collision.mesh = terrain_mesh;
  269. collision.bounds = calculate_bounds(*terrain_mesh);
  270. collision.mesh_accelerator.build(*collision.mesh);
  271. registry.assign_or_replace<collision_component>(entity, collision);
  272. // Assign the entity a model component with the terrain model
  273. model_component model;
  274. model.model = terrain_model;
  275. model.instance_count = 0;
  276. model.layers = 1;
  277. registry.assign_or_replace<model_component>(entity, model);
  278. // Assign the entity a transform component
  279. transform_component transform;
  280. transform.transform = math::identity_transform<float>;
  281. transform.transform.translation = float3{(float)component.x * patch_size, 0.0f, (float)component.z * patch_size};
  282. transform.warp = true;
  283. registry.assign_or_replace<transform_component>(entity, transform);
  284. }
  285. void terrain_system::on_terrain_destroy(entt::registry& registry, entt::entity entity)
  286. {
  287. /*
  288. if (auto it = terrain_map.find(entity); it != terrain_map.end())
  289. {
  290. delete std::get<0>(it->second);
  291. delete std::get<1>(it->second);
  292. terrain_map.erase(it);
  293. }
  294. */
  295. }