mesh.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include "buffer.h"
  3. #include <QOpenGLFunctions_3_3_Core>
  4. #include <array>
  5. #include <functional>
  6. #include <memory>
  7. #include <vector>
  8. namespace Render::GL {
  9. struct Vertex {
  10. std::array<float, 3> position{};
  11. std::array<float, 3> normal{};
  12. std::array<float, 2> tex_coord{};
  13. };
  14. class Mesh : protected QOpenGLFunctions_3_3_Core {
  15. public:
  16. Mesh(const std::vector<Vertex> &vertices,
  17. const std::vector<unsigned int> &indices);
  18. ~Mesh() override;
  19. void draw();
  20. void draw_instanced(std::size_t instance_count);
  21. auto bind_vao() -> bool { return prepare_draw("Mesh::bind_vao"); }
  22. void unbind_vao();
  23. void draw_instanced_raw(std::size_t instance_count);
  24. [[nodiscard]] auto get_vertices() const -> const std::vector<Vertex> & {
  25. return m_vertices;
  26. }
  27. [[nodiscard]] auto get_indices() const -> const std::vector<unsigned int> & {
  28. return m_indices;
  29. }
  30. [[nodiscard]] auto clone_with_filtered_indices(
  31. const std::function<bool(unsigned int, unsigned int, unsigned int,
  32. const std::vector<Vertex> &)> &predicate) const
  33. -> std::unique_ptr<Mesh> {
  34. if (!predicate) {
  35. return nullptr;
  36. }
  37. std::vector<unsigned int> filtered;
  38. filtered.reserve(m_indices.size());
  39. for (std::size_t i = 0; i + 2 < m_indices.size(); i += 3) {
  40. unsigned int a = m_indices[i];
  41. unsigned int b = m_indices[i + 1];
  42. unsigned int c = m_indices[i + 2];
  43. if (!predicate(a, b, c, m_vertices)) {
  44. filtered.push_back(a);
  45. filtered.push_back(b);
  46. filtered.push_back(c);
  47. }
  48. }
  49. if (filtered.empty()) {
  50. return nullptr;
  51. }
  52. return std::make_unique<Mesh>(m_vertices, filtered);
  53. }
  54. private:
  55. std::vector<Vertex> m_vertices;
  56. std::vector<unsigned int> m_indices;
  57. std::unique_ptr<VertexArray> m_vao;
  58. std::unique_ptr<Buffer> m_vbo;
  59. std::unique_ptr<Buffer> m_ebo;
  60. void setup_buffers();
  61. [[nodiscard]] auto prepare_draw(const char *caller_name) -> bool;
  62. };
  63. auto create_quad_mesh() -> std::unique_ptr<Mesh>;
  64. auto create_cube_mesh() -> std::unique_ptr<Mesh>;
  65. auto create_plane_mesh(float width, float height,
  66. int subdivisions = 1) -> std::unique_ptr<Mesh>;
  67. } // namespace Render::GL