Skip to content

Commit

Permalink
Merge pull request #50 from ArnavMehta3000/main
Browse files Browse the repository at this point in the history
Added Model loading + RHICompat rule
  • Loading branch information
ArnavMehta3000 authored Aug 27, 2024
2 parents 78a108a + f6bba66 commit 2432a34
Showing 24 changed files with 190,073 additions and 99 deletions.
88 changes: 88 additions & 0 deletions Core/Graphics/Mesh.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#include "Mesh.h"
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>

namespace CGL::Graphics
{
CGL_DEFINE_LOG_CATEGORY(Mesh);

bool Mesh::LoadOBJ(const std::string& file)
{
namespace obj = tinyobj;

obj::ObjReader reader;

if (!reader.ParseFromFile(file))
{
if (!reader.Error().empty())
{
CGL_LOG(Mesh, Error, "Failed to parse OBJ file: {}", reader.Error());
}
return false;
}

if (!reader.Warning().empty())
{
CGL_LOG(Mesh, Warn, "Failed to parse OBJ file: {}", reader.Warning());
}

auto& attrib = reader.GetAttrib();
auto& shapes = reader.GetShapes();

// Clear any existing SubMeshes
SubMeshes.clear();

// Each shape corresponds to a mesh
for (const auto& shape : shapes)
{
SubMesh subMesh;

// Loop over faces(polygon)
size_t index_offset = 0;
for (size_t f = 0; f < shape.mesh.num_face_vertices.size(); f++)
{
size_t fv = shape.mesh.num_face_vertices[f];

// Loop over vertices in the face
for (size_t v = 0; v < fv; v++)
{
// Access to vertex index
tinyobj::index_t idx = shape.mesh.indices[index_offset + v];

// Vertex coordinates
tinyobj::real_t vx = attrib.vertices[3 * idx.vertex_index + 0];
tinyobj::real_t vy = attrib.vertices[3 * idx.vertex_index + 1];
tinyobj::real_t vz = attrib.vertices[3 * idx.vertex_index + 2];
subMesh.m_vertices.push_back(SM::Vector3(vx, vy, vz));

// Normals (if present)
if (idx.normal_index >= 0)
{
tinyobj::real_t nx = attrib.normals[3 * idx.normal_index + 0];
tinyobj::real_t ny = attrib.normals[3 * idx.normal_index + 1];
tinyobj::real_t nz = attrib.normals[3 * idx.normal_index + 2];
subMesh.m_normals.push_back(SM::Vector3(nx, ny, nz));
}

// Texture coordinates (if present)
if (idx.texcoord_index >= 0)
{
tinyobj::real_t tx = attrib.texcoords[2 * idx.texcoord_index + 0];
tinyobj::real_t ty = attrib.texcoords[2 * idx.texcoord_index + 1];
subMesh.m_uvs.push_back(SM::Vector2(tx, ty));
}

// Save index (used in drawing the elements)
subMesh.m_indices.push_back(static_cast<u32>(index_offset + v));
}
index_offset += fv;
}

// Add the processed submesh to the mesh
SubMeshes.push_back(subMesh);
}

CGL_LOG(Mesh, Info, "Successfully loaded OBJ file: {}", file);
return true;
}
}
51 changes: 51 additions & 0 deletions Core/Graphics/Mesh.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#pragma once
#include <Core/Common.h>
#include <Core/Logging/Log.h>
#include <Core/Math/Math.h>
#include <Core/Graphics/Buffer.h>

namespace CGL::Graphics
{
CGL_DECLARE_LOG_CATEGORY(Mesh);

struct MeshData
{
VertexBuffer VertexBuffer;
IndexBuffer IndexBuffer;
};


class SubMesh
{
friend class Mesh;
public:
SubMesh() = default;
~SubMesh() = default;

inline const std::vector<SM::Vector3>& GetVertices() const { return m_vertices; }
inline const std::vector<SM::Vector3>& GetNormals() const { return m_normals; }
inline const std::vector<SM::Vector2>& GetUVs() const { return m_uvs; }
inline const std::vector<u32>& GetIndices() const { return m_indices; }
inline MeshData& GetMeshData() { return m_meshData; }

private:
MeshData m_meshData;
std::vector<u32> m_indices;
std::vector<SM::Vector3> m_vertices;
std::vector<SM::Vector3> m_normals;
std::vector<SM::Vector2> m_uvs;
};


class Mesh
{
public:
Mesh() = default;
~Mesh() = default;

bool LoadOBJ(const std::string& file);

public:
std::vector<SubMesh> SubMeshes;
};
}
7 changes: 5 additions & 2 deletions Core/Graphics/RHI/D3D11/D3D11Renderer.cpp
Original file line number Diff line number Diff line change
@@ -78,9 +78,11 @@ namespace CGL::Graphics
assert(impl && impl->GetContext());

auto renderTarget = impl->GetBackBuffer();
auto depthStencil = impl->GetDepthStencilView();
impl->GetContext()->RSSetViewports(1, &impl->GetViewport());
impl->GetContext()->OMSetRenderTargets(1, &renderTarget, nullptr);
impl->GetContext()->OMSetRenderTargets(1, &renderTarget, depthStencil);
impl->GetContext()->ClearRenderTargetView(renderTarget, m_clearColor.data());
impl->GetContext()->ClearDepthStencilView(depthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
}

void Renderer::EndFrame_D3D11()
@@ -386,7 +388,8 @@ namespace CGL::Graphics

void Renderer::SetConstantBufferData_D3D11(ID3D11Buffer* buffer, const void* data, size_t size)
{
assert(buffer && GetImpl() && GetImpl()->GetContext());
assert(buffer && "Invalid buffer");
assert(GetImpl() && GetImpl()->GetContext());

D3D11_MAPPED_SUBRESOURCE mappedResource;
if (SUCCEEDED(GetImpl()->GetContext()->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)))
20 changes: 20 additions & 0 deletions Core/Graphics/RHI/D3D11/D3D11RendererImpl.cpp
Original file line number Diff line number Diff line change
@@ -54,12 +54,32 @@ namespace CGL::Graphics

// Create render target view
DXCall(hr = m_device->CreateRenderTargetView(m_backBufferTexture.Get(), nullptr, &m_backBuffer));

// Create depth/stencil buffer
D3D11_TEXTURE2D_DESC depthStencilDesc{};

depthStencilDesc.Width = width;
depthStencilDesc.Height = height;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilDesc.SampleDesc.Count = 1;
depthStencilDesc.SampleDesc.Quality = 0;
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.MiscFlags = 0;

m_device->CreateTexture2D(&depthStencilDesc, NULL, &m_depthStencilTexture);
m_device->CreateDepthStencilView(m_depthStencilTexture.Get(), NULL, &m_depthStencilView);
}

void Graphics::D3D11RendererImpl::ReleaseSizeDependentResources()
{
m_backBufferTexture.Reset();
m_backBuffer.Reset();
m_depthStencilTexture.Reset();
m_depthStencilView.Reset();
}

void D3D11RendererImpl::Init()
3 changes: 3 additions & 0 deletions Core/Graphics/RHI/D3D11/D3D11RendererImpl.h
Original file line number Diff line number Diff line change
@@ -21,6 +21,7 @@ namespace CGL::Graphics
inline IDXGISwapChain* GetSwapChain() const { return m_swapChain.Get(); }
inline ID3D11RenderTargetView* GetBackBuffer() const { return m_backBuffer.Get(); }
inline ID3D11Texture2D* GetBackBufferTexture() const { return m_backBufferTexture.Get(); }
inline ID3D11DepthStencilView* GetDepthStencilView() const { return m_depthStencilView.Get(); }
inline const D3D11_VIEWPORT& GetViewport() const { return m_viewport; }

private:
@@ -39,5 +40,7 @@ namespace CGL::Graphics
ComPtr<IDXGISwapChain> m_swapChain;
ComPtr<ID3D11RenderTargetView> m_backBuffer;
ComPtr<ID3D11Texture2D> m_backBufferTexture;
ComPtr<ID3D11DepthStencilView> m_depthStencilView;
ComPtr<ID3D11Texture2D> m_depthStencilTexture;
};
}
2 changes: 1 addition & 1 deletion Core/Graphics/Renderer.h
Original file line number Diff line number Diff line change
@@ -54,7 +54,7 @@ namespace CGL::Graphics

template <typename T> void CreateContantBuffer(const BufferSource& source, ConstantBuffer<T>& outBuffer);
template <typename T> void SetConstantBufferData(const ConstantBuffer<T>& buffer, const T& data);
template <typename T> void SetContantBuffer(ShaderType shaderType, u32 startSlot, const ConstantBuffer<T>& buffer);
template <typename T> void SetConstantBuffer(ShaderType shaderType, u32 startSlot, const ConstantBuffer<T>& buffer);

void Draw(u32 vertexCount, u32 startVertex = 0);
void DrawIndexed(u32 indexCount, u32 startIndex = 0, u32 baseVertex = 0);
2 changes: 1 addition & 1 deletion Core/Graphics/Renderer.inl
Original file line number Diff line number Diff line change
@@ -22,7 +22,7 @@ namespace CGL::Graphics
#endif
}
template <typename T>
void Renderer::SetContantBuffer(ShaderType shaderType, u32 startSlot, const ConstantBuffer<T>& buffer)
void Renderer::SetConstantBuffer(ShaderType shaderType, u32 startSlot, const ConstantBuffer<T>& buffer)
{
#if defined(CGL_RHI_DX11)
SetContantBuffer_D3D11(shaderType, startSlot, buffer.Buffer);
7 changes: 7 additions & 0 deletions Core/Graphics/Types.h
Original file line number Diff line number Diff line change
@@ -162,5 +162,12 @@ namespace CGL::Graphics
SM::Vector4 Color;
SM::Vector2 Texture;
};

struct PositionNormalTexture
{
SM::Vector4 Position;
SM::Vector3 Normal;
SM::Vector2 Texture;
};
}
}
2 changes: 1 addition & 1 deletion Core/xmake.lua
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ target("VisualizerCore")
set_kind("static")
set_group("CrossVL")

add_packages("libsdl", "directxmath")
add_packages("libsdl", "directxmath", "tinyobjloader")
set_options("rhi")

add_includedirs("..")
26 changes: 3 additions & 23 deletions Samples/BlankApp/xmake.lua
Original file line number Diff line number Diff line change
@@ -7,39 +7,19 @@ target("BlankApp")
set_kind("binary")
set_group("Samples")

add_packages("libsdl", "directxmath")
add_rules("RHICompat")
add_packages("libsdl", "directxmath", "tinyobjloader")

add_includedirs("..", "$(projectdir)")
add_files("**.cpp")
add_headerfiles("**.h", { install = false })

add_deps("VisualizerCore")

-- Throw errors if trying to build using RHI for an unsupported platform
on_config(function (target)
if is_plat("macosx", "linux") then
if has_config("rhi") then
local rhi = string.upper(get_config("rhi"))
if rhi == "DX11" or rhi == "DX12" then
raise("Trying to build for " .. rhi .. " on an unsupported platform!")
end
end
end

if is_plat("windows", "linux") then
if has_config("rhi") then
local rhi = string.upper(get_config("rhi"))
if rhi == "METAL" then
raise("Trying to build for " .. rhi .. " on an unsupported platform!")
end
end
end
end)

if has_config("rhi") then
local rhi = string.upper(get_config("rhi"))
add_links("VisualizerCore" .. "_" .. rhi)

if rhi == "OPENGL" then
add_packages("glew")
if is_plat("windows") then
26 changes: 3 additions & 23 deletions Samples/HelloTriangle/xmake.lua
Original file line number Diff line number Diff line change
@@ -6,36 +6,16 @@ target("HelloTriangle")
set_default(true)
set_kind("binary")
set_group("Samples")

add_packages("libsdl", "directxmath")

add_rules("RHICompat")
add_packages("libsdl", "directxmath", "tinyobjloader")

add_includedirs("..", "$(projectdir)")
add_files("**.cpp")
add_headerfiles("**.h", { install = false })

add_deps("VisualizerCore")

-- Throw errors if trying to build using RHI for an unsupported platform
on_config(function (target)
if is_plat("macosx", "linux") then
if has_config("rhi") then
local rhi = string.upper(get_config("rhi"))
if rhi == "DX11" or rhi == "DX12" then
raise("Trying to build for " .. rhi .. " on an unsupported platform!")
end
end
end

if is_plat("windows", "linux") then
if has_config("rhi") then
local rhi = string.upper(get_config("rhi"))
if rhi == "METAL" then
raise("Trying to build for " .. rhi .. " on an unsupported platform!")
end
end
end
end)

-- Add RHI specific rules
if has_config("rhi") then
local rhi = string.upper(get_config("rhi"))
18 changes: 18 additions & 0 deletions Samples/ModelLoading/Assets/DirectX/ModelLoadingPS.hlsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
struct PS_INPUT
{
float4 Position : SV_Position;
float3 Normal : NORMAL;
float3 Color : COLOR0;
};

struct PS_OUTPUT
{
float4 Color : SV_Target0;
};

PS_OUTPUT main(PS_INPUT input)
{
PS_OUTPUT output = (PS_OUTPUT)0;
output.Color = float4(input.Normal, 1.0);
return output;
}
35 changes: 35 additions & 0 deletions Samples/ModelLoading/Assets/DirectX/ModelLoadingVS.hlsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
cbuffer FrameData : register(b0)
{
matrix WorldMatrix;
matrix ViewMatrix;
matrix ProjMatrix;
};

struct VS_INPUT
{
float4 Position : POSITION;
float3 Normal : NORMAL;
float3 Color : COLOR0;
};

struct VS_OUTPUT
{
float4 Position : SV_Position;
float3 Normal : NORMAL;
float3 Color : COLOR0;
};

VS_OUTPUT main(VS_INPUT input)
{
VS_OUTPUT output = (VS_OUTPUT)0;

output.Position = input.Position;
output.Position = mul(output.Position, WorldMatrix);
output.Position = mul(output.Position, ViewMatrix);
output.Position = mul(output.Position, ProjMatrix);

output.Normal = input.Normal;
output.Color = input.Color;

return output;
}
Loading

0 comments on commit 2432a34

Please sign in to comment.