Mesh.h 2.0 KB

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