Mesh.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #ifndef MESH_H
  2. #define MESH_H
  3. #include <string>
  4. #include <fstream>
  5. #include <sstream>
  6. #include <iostream>
  7. #include <vector>
  8. #include <stdexcept>
  9. #include <d3d11_1.h>
  10. #include <DirectXMath.h>
  11. using namespace DirectX;
  12. #include "SafeRelease.hpp"
  13. struct VERTEX {
  14. FLOAT X, Y, Z;
  15. XMFLOAT2 texcoord;
  16. };
  17. struct Texture {
  18. std::string type;
  19. std::string path;
  20. ID3D11ShaderResourceView *texture;
  21. void Release() {
  22. SafeRelease(texture);
  23. }
  24. };
  25. class Mesh {
  26. public:
  27. std::vector<VERTEX> vertices_;
  28. std::vector<UINT> indices_;
  29. std::vector<Texture> textures_;
  30. ID3D11Device *dev_;
  31. Mesh(ID3D11Device *dev, const std::vector<VERTEX>& vertices, const std::vector<UINT>& indices, const std::vector<Texture>& textures) :
  32. vertices_(vertices),
  33. indices_(indices),
  34. textures_(textures),
  35. dev_(dev),
  36. VertexBuffer_(nullptr),
  37. IndexBuffer_(nullptr) {
  38. this->setupMesh(this->dev_);
  39. }
  40. void Draw(ID3D11DeviceContext *devcon) {
  41. UINT stride = sizeof(VERTEX);
  42. UINT offset = 0;
  43. devcon->IASetVertexBuffers(0, 1, &VertexBuffer_, &stride, &offset);
  44. devcon->IASetIndexBuffer(IndexBuffer_, DXGI_FORMAT_R32_UINT, 0);
  45. devcon->PSSetShaderResources(0, 1, &textures_[0].texture);
  46. devcon->DrawIndexed(static_cast<UINT>(indices_.size()), 0, 0);
  47. }
  48. void Close() {
  49. SafeRelease(VertexBuffer_);
  50. SafeRelease(IndexBuffer_);
  51. }
  52. private:
  53. // Render data
  54. ID3D11Buffer *VertexBuffer_, *IndexBuffer_;
  55. // Functions
  56. // Initializes all the buffer objects/arrays
  57. void setupMesh(ID3D11Device *dev) {
  58. HRESULT hr;
  59. D3D11_BUFFER_DESC vbd;
  60. vbd.Usage = D3D11_USAGE_IMMUTABLE;
  61. vbd.ByteWidth = static_cast<UINT>(sizeof(VERTEX) * vertices_.size());
  62. vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  63. vbd.CPUAccessFlags = 0;
  64. vbd.MiscFlags = 0;
  65. D3D11_SUBRESOURCE_DATA initData;
  66. initData.pSysMem = &vertices_[0];
  67. hr = dev->CreateBuffer(&vbd, &initData, &VertexBuffer_);
  68. if (FAILED(hr)) {
  69. Close();
  70. throw std::runtime_error("Failed to create vertex buffer.");
  71. }
  72. D3D11_BUFFER_DESC ibd;
  73. ibd.Usage = D3D11_USAGE_IMMUTABLE;
  74. ibd.ByteWidth = static_cast<UINT>(sizeof(UINT) * indices_.size());
  75. ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
  76. ibd.CPUAccessFlags = 0;
  77. ibd.MiscFlags = 0;
  78. initData.pSysMem = &indices_[0];
  79. hr = dev->CreateBuffer(&ibd, &initData, &IndexBuffer_);
  80. if (FAILED(hr)) {
  81. Close();
  82. throw std::runtime_error("Failed to create index buffer.");
  83. }
  84. }
  85. };
  86. #endif