62 lines
2.4 KiB
C++
62 lines
2.4 KiB
C++
#include "Mesh.h"
|
|
#include "Log.h"
|
|
|
|
#define TINYGLTF_IMPLEMENTATION
|
|
#define STB_IMAGE_IMPLEMENTATION
|
|
#define STB_IMAGE_WRITE_IMPLEMENTATION
|
|
#include "../dependency/tinygltf/tiny_gltf.h"
|
|
|
|
namespace Game
|
|
{
|
|
void LoadMesh(Model& mesh)
|
|
{
|
|
mesh.VertLayout.begin()
|
|
.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
|
|
.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
|
|
.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
|
|
.end();
|
|
|
|
tinygltf::Model model;
|
|
tinygltf::TinyGLTF loader;
|
|
std::string warn;
|
|
std::string err;
|
|
bool loadSuccess = loader.LoadASCIIFromFile(&model, &err, &warn, "models/cube.gltf");
|
|
|
|
if (!warn.empty()) Log("WARN: %s", warn.c_str());
|
|
if (!err.empty()) Log("ERR: %s", err.c_str());
|
|
if (!loadSuccess) Log("Model load failed!");
|
|
|
|
tinygltf::Primitive primitive = model.meshes[0].primitives[0];
|
|
{
|
|
tinygltf::Accessor accessor = model.accessors.at(primitive.indices);
|
|
tinygltf::BufferView bufferView = model.bufferViews.at(accessor.bufferView);
|
|
tinygltf::Buffer buffer = model.buffers[bufferView.buffer];
|
|
const bgfx::Memory* ibMem = bgfx::alloc(bufferView.byteLength);
|
|
bx::memCopy(ibMem->data, &buffer.data.at(bufferView.byteOffset), bufferView.byteLength);
|
|
mesh.IndexBuffer = bgfx::createIndexBuffer(ibMem);
|
|
}
|
|
{
|
|
tinygltf::Accessor posAccessor = model.accessors.at(primitive.attributes.at("POSITION"));
|
|
tinygltf::Accessor uvAccessor = model.accessors.at(primitive.attributes.at("TEXCOORD_0"));
|
|
tinygltf::BufferView posBufferView = model.bufferViews[posAccessor.bufferView];
|
|
tinygltf::BufferView uvBufferView = model.bufferViews[uvAccessor.bufferView];
|
|
int posStride = posAccessor.ByteStride(posBufferView);
|
|
int uvStride = uvAccessor.ByteStride(uvBufferView);
|
|
tinygltf::Buffer posBuffer = model.buffers[posBufferView.buffer];
|
|
tinygltf::Buffer uvBuffer = model.buffers[uvBufferView.buffer];
|
|
|
|
uint32_t vertexCount = posBufferView.byteLength / posStride;
|
|
const bgfx::Memory* vbMem = bgfx::alloc(vertexCount * sizeof(PosColorVertex));
|
|
|
|
for (uint32_t i = 0; i < vertexCount; ++i)
|
|
{
|
|
PosColorVertex& v = *reinterpret_cast<PosColorVertex*>(vbMem->data + i * sizeof(PosColorVertex));
|
|
bx::memCopy(&v.x, &posBuffer.data.at(posBufferView.byteOffset + i * posStride), posStride);
|
|
v.abgr = 0;
|
|
bx::memCopy(&v.uv_x, &uvBuffer.data.at(uvBufferView.byteOffset + i * uvStride), uvStride);
|
|
}
|
|
mesh.VertexBuffer = bgfx::createVertexBuffer(vbMem, mesh.VertLayout);
|
|
}
|
|
}
|
|
}
|