💿🐜 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.

388 lines
12 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.local.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 + 2 + 3 + 4 + 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_TEXCOORD_LOCATION, *vbo, 2, vertex_attribute_type::float_32, vertex_stride, sizeof(float) * offset);
  161. offset += 2;
  162. vao->bind_attribute(VERTEX_NORMAL_LOCATION, *vbo, 3, vertex_attribute_type::float_32, vertex_stride, sizeof(float) * offset);
  163. offset += 3;
  164. vao->bind_attribute(VERTEX_TANGENT_LOCATION, *vbo, 4, vertex_attribute_type::float_32, vertex_stride, sizeof(float) * offset);
  165. offset += 4;
  166. vao->bind_attribute(VERTEX_BARYCENTRIC_LOCATION, *vbo, 3, vertex_attribute_type::float_32, vertex_stride, sizeof(float) * offset);
  167. offset += 3;
  168. // Create model group
  169. model_group* model_group = terrain_model->add_group("terrain");
  170. model_group->set_material(resource_manager->load<material>("grassland-terrain.mtl"));
  171. model_group->set_drawing_mode(drawing_mode::triangles);
  172. model_group->set_start_index(0);
  173. model_group->set_index_count(terrain_mesh->get_faces().size() * 3);
  174. return terrain_model;
  175. }
  176. void terrain_system::project_terrain_mesh(mesh* terrain_mesh, const terrain_component& component)
  177. {
  178. float offset_x = (float)component.x * patch_size;
  179. float offset_z = (float)component.z * patch_size;
  180. for (mesh::vertex* vertex: terrain_mesh->get_vertices())
  181. {
  182. int pixel_x = (vertex->position[0] + offset_x + heightmap_size * 0.5f) / heightmap_size * (float)(heightmap->get_width() - 1);
  183. int pixel_y = (vertex->position[2] + offset_z + heightmap_size * 0.5f) / heightmap_size * (float)(heightmap->get_height() - 1);
  184. pixel_x = std::max<int>(0, std::min<int>(heightmap->get_width() - 1, pixel_x));
  185. pixel_y = std::max<int>(0, std::min<int>(heightmap->get_height() - 1, pixel_y));
  186. int pixel_index = (pixel_y * heightmap->get_width() + pixel_x) * heightmap->get_channels();
  187. const unsigned char* pixel = static_cast<const unsigned char*>(heightmap->get_pixels()) + pixel_index;
  188. float elevation = (static_cast<float>(*pixel) / 255.0f - 0.5) * heightmap_scale;
  189. vertex->position[1] = elevation;
  190. }
  191. }
  192. void terrain_system::update_terrain_model(model* terrain_model, mesh* terrain_mesh)
  193. {
  194. const std::vector<mesh::face*>& faces = terrain_mesh->get_faces();
  195. const std::vector<mesh::vertex*>& vertices = terrain_mesh->get_vertices();
  196. aabb<float> bounds = calculate_bounds(*terrain_mesh);
  197. float bounds_width = bounds.max_point.x - bounds.min_point.x;
  198. float bounds_height = bounds.max_point.y - bounds.min_point.y;
  199. float bounds_depth = bounds.max_point.z - bounds.min_point.z;
  200. static const float3 barycentric_coords[3] =
  201. {
  202. float3{1, 0, 0},
  203. float3{0, 1, 0},
  204. float3{0, 0, 1}
  205. };
  206. int triangle_count = faces.size();
  207. int vertex_count = triangle_count * 3;
  208. int vertex_size = 3 + 2 + 3 + 4 + 3;
  209. // Allocate vertex data
  210. float* vertex_data = new float[vertex_size * vertex_count];
  211. // Allocate and calculate face normals
  212. float3* face_normals = new float3[faces.size()];
  213. calculate_face_normals(face_normals, *terrain_mesh);
  214. // Allocate and calculate vertex normals
  215. float3* vertex_normals = new float3[vertices.size()];
  216. for (std::size_t i = 0; i < vertices.size(); ++i)
  217. {
  218. const mesh::vertex* vertex = vertices[i];
  219. float3 n = {0, 0, 0};
  220. mesh::edge* start = vertex->edge;
  221. mesh::edge* edge = start;
  222. do
  223. {
  224. if (edge->face)
  225. {
  226. n += face_normals[edge->face->index];
  227. }
  228. edge = edge->previous->symmetric;
  229. }
  230. while (edge != start);
  231. n = math::normalize(n);
  232. vertex_normals[i] = n;
  233. }
  234. // Allocate and generate vertex texture coordinates
  235. float2* vertex_texcoords = new float2[vertices.size()];
  236. for (std::size_t i = 0; i < vertices.size(); ++i)
  237. {
  238. const mesh::vertex* vertex = vertices[i];
  239. vertex_texcoords[i].x = (vertex->position.x - bounds.min_point.x) / bounds_width;
  240. vertex_texcoords[i].y = (vertex->position.z - bounds.min_point.z) / bounds_depth;
  241. }
  242. // Allocate and calculate vertex tangents
  243. float4* vertex_tangents = new float4[vertices.size()];
  244. calculate_vertex_tangents(vertex_tangents, vertex_texcoords, vertex_normals, *terrain_mesh);
  245. // Generate vertex data
  246. float* v = vertex_data;
  247. for (int i = 0; i < triangle_count; ++i)
  248. {
  249. const mesh::face* triangle = faces[i];
  250. const mesh::vertex* a = triangle->edge->vertex;
  251. const mesh::vertex* b = triangle->edge->next->vertex;
  252. const mesh::vertex* c = triangle->edge->previous->vertex;
  253. const mesh::vertex* abc[] = {a, b, c};
  254. for (int j = 0; j < 3; ++j)
  255. {
  256. const mesh::vertex* vertex = abc[j];
  257. const float3& position = vertex->position;
  258. const float2& texcoord = vertex_texcoords[vertex->index];
  259. const float3& normal = vertex_normals[vertex->index];
  260. const float4& tangent = vertex_tangents[vertex->index];
  261. const float3& barycentric = barycentric_coords[j];
  262. *(v++) = position.x;
  263. *(v++) = position.y;
  264. *(v++) = position.z;
  265. *(v++) = texcoord.x;
  266. *(v++) = texcoord.y;
  267. *(v++) = normal.x;
  268. *(v++) = normal.y;
  269. *(v++) = normal.z;
  270. *(v++) = tangent.x;
  271. *(v++) = tangent.y;
  272. *(v++) = tangent.z;
  273. *(v++) = tangent.w;
  274. *(v++) = barycentric.x;
  275. *(v++) = barycentric.y;
  276. *(v++) = barycentric.z;
  277. }
  278. }
  279. // Update bounds
  280. terrain_model->set_bounds(bounds);
  281. // Update VBO
  282. terrain_model->get_vertex_buffer()->update(0, vertex_count * vertex_size * sizeof(float), vertex_data);
  283. // Free vertex data
  284. delete[] face_normals;
  285. delete[] vertex_normals;
  286. delete[] vertex_texcoords;
  287. delete[] vertex_tangents;
  288. delete[] vertex_data;
  289. }
  290. void terrain_system::on_terrain_construct(entt::registry& registry, entt::entity entity, terrain_component& component)
  291. {
  292. mesh* terrain_mesh = generate_terrain_mesh(patch_size, component.subdivisions);
  293. model* terrain_model = generate_terrain_model(terrain_mesh);
  294. project_terrain_mesh(terrain_mesh, component);
  295. update_terrain_model(terrain_model, terrain_mesh);
  296. // Assign the entity a collision component with the terrain mesh
  297. collision_component collision;
  298. collision.mesh = terrain_mesh;
  299. collision.bounds = calculate_bounds(*terrain_mesh);
  300. collision.mesh_accelerator.build(*collision.mesh);
  301. registry.assign_or_replace<collision_component>(entity, collision);
  302. // Assign the entity a model component with the terrain model
  303. model_component model;
  304. model.model = terrain_model;
  305. model.instance_count = 0;
  306. model.layers = 1;
  307. registry.assign_or_replace<model_component>(entity, model);
  308. // Assign the entity a transform component
  309. transform_component transform;
  310. transform.local = math::identity_transform<float>;
  311. transform.local.translation = float3{(float)component.x * patch_size, 0.0f, (float)component.z * patch_size};
  312. transform.warp = true;
  313. registry.assign_or_replace<transform_component>(entity, transform);
  314. }
  315. void terrain_system::on_terrain_destroy(entt::registry& registry, entt::entity entity)
  316. {
  317. /*
  318. if (auto it = terrain_map.find(entity); it != terrain_map.end())
  319. {
  320. delete std::get<0>(it->second);
  321. delete std::get<1>(it->second);
  322. terrain_map.erase(it);
  323. }
  324. */
  325. }