283 lines
7.4 KiB
C++
283 lines
7.4 KiB
C++
/**
|
||
* @file dl_model_loader.ixx
|
||
* @brief 模型加载器
|
||
*
|
||
*
|
||
* @version 1.0
|
||
* @author lveyou
|
||
* @date 22-09-02
|
||
*
|
||
* @note 由于Assimp库过于庞大,我们只在windows平台使用动态链接库
|
||
* @note Assimp默认为右手坐标系(+X 指向右侧,+Y 指向上方,+Z 指向屏幕外朝向观看者)
|
||
* @note 逆时针顶点绕序为正面
|
||
* @note 行优先矩阵
|
||
* @note 以上为旧注释,将来只支持gltf
|
||
*/
|
||
#pragma once
|
||
|
||
#define TINYOBJLOADER_IMPLEMENTATION
|
||
#include <tiny_obj_loader.h>
|
||
#define TINYGLTF_IMPLEMENTATION
|
||
#include <tiny_gltf.h>
|
||
|
||
#include "io/dl_json.h"
|
||
|
||
namespace dl
|
||
{
|
||
struct equal_idx
|
||
{
|
||
bool operator()(const tinyobj::index_t& a, const tinyobj::index_t& b) const
|
||
{
|
||
return a.vertex_index == b.vertex_index
|
||
&& a.texcoord_index == b.texcoord_index
|
||
&& a.normal_index == b.normal_index;
|
||
}
|
||
};
|
||
|
||
struct hash_idx
|
||
{
|
||
size_t operator()(const tinyobj::index_t& a) const
|
||
{
|
||
return ((a.vertex_index
|
||
^ a.texcoord_index << 1) >> 1)
|
||
^ (a.normal_index << 1);
|
||
}
|
||
};
|
||
|
||
inline float ShininessToRoughness(float Ypoint)
|
||
{
|
||
float a = -1;
|
||
float b = 2;
|
||
|
||
float c;
|
||
c = (Ypoint / 100) - 1;
|
||
|
||
float D;
|
||
D = b * b - (4 * a * c);
|
||
|
||
float x1;
|
||
x1 = (-b + sqrt(D)) / (2 * a);
|
||
|
||
return x1;
|
||
}
|
||
|
||
class ModelLoader
|
||
{
|
||
public:
|
||
std::vector<ModelObject*> Load(std::string_view path_name, std::string_view res_name)
|
||
{
|
||
std::string ext = File::GetExtension(path_name);
|
||
if (ext == "obj")
|
||
return _load_obj(path_name);
|
||
else if (ext == "glb")
|
||
return _load_gltf(path_name, true);
|
||
else if (ext == "gltf")
|
||
return _load_gltf(path_name, false);
|
||
log_err("不支持的模型格式:{}", path_name);
|
||
return {};
|
||
}
|
||
private:
|
||
std::vector<ModelObject*> _load_obj(std::string_view path_name)
|
||
{
|
||
std::string str_path = std::string{ path_name };
|
||
std::string str_base = String::EraseFilename(path_name);
|
||
|
||
const char* filename = str_path.c_str();
|
||
const char* basepath = str_base.c_str();
|
||
bool triangulate = true;
|
||
|
||
log_info("开始加载obj文件:{},{}", filename, basepath);
|
||
|
||
tinyobj::attrib_t attrib; // 所有的数据放在这里
|
||
std::vector<tinyobj::shape_t> shapes;// 子模型
|
||
std::vector<tinyobj::material_t> materials;
|
||
|
||
std::string warn;
|
||
std::string err;
|
||
|
||
bool b_read = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filename,
|
||
basepath, triangulate);
|
||
|
||
// 打印错误
|
||
if (!warn.empty())
|
||
log_warn("{}", warn);
|
||
|
||
if (!err.empty())
|
||
log_warn("{}", err);
|
||
|
||
if (!b_read)
|
||
{
|
||
log_err("读取obj文件失败:{}", path_name);
|
||
return {};
|
||
}
|
||
log_info("顶点数:{}", attrib.vertices.size() / 3);
|
||
log_info("法线数:{}", attrib.normals.size() / 3);
|
||
log_info("UV数:{}", attrib.texcoords.size() / 2);
|
||
log_info("子模型数:{}", shapes.size());
|
||
log_info("材质数:{}", materials.size());
|
||
|
||
// 读取配置
|
||
bool is_axis_up_z = false;
|
||
{
|
||
Json::DisableLog l;
|
||
json j = Json::Parse(String::ReplaceExtension(path_name, "json"));
|
||
if (!j.is_null())
|
||
{
|
||
std::string str;
|
||
if (Json::Get(j, "axis_up", str))
|
||
{
|
||
if (str == "z")
|
||
is_axis_up_z = true;
|
||
}
|
||
}
|
||
}
|
||
|
||
// obj只有一个ModelObject
|
||
std::vector<ModelObject*> ret;
|
||
ModelObject* model_object = new ModelObject;
|
||
std::vector<Vertex>& mo_vertices = model_object->_allVertex;
|
||
std::vector<uint32_t>& mo_indices = model_object->_allIndex;
|
||
std::vector<ModelObjectMaterial>& mo_material = model_object->_allMaterial;
|
||
ret.push_back(model_object);
|
||
|
||
//------------------获取材质-------------------
|
||
mo_material.resize(materials.size());
|
||
for (size_t i = 0; i < materials.size(); ++i)
|
||
{
|
||
tinyobj::material_t m = materials[i];
|
||
log_info("材质:{},{}", i, m.name);
|
||
|
||
ModelObjectMaterial& material = mo_material[i];
|
||
material._materialName = m.name;
|
||
|
||
material._material._diffuseAlbedo = { m.diffuse[0], m.diffuse[1], m.diffuse[2], 1.0f };
|
||
material._material._fresnelR0 = { m.specular[0], m.specular[1], m.specular[2] };
|
||
material._material._roughness = ShininessToRoughness(m.shininess);
|
||
|
||
if (!m.diffuse_texname.empty())
|
||
material._pathTexDiffuse = str_base + m.diffuse_texname;
|
||
if (!m.normal_texname.empty())// 注意这里凹凸贴图(bump_texname)更常见
|
||
material._pathTexNormal = str_base + m.normal_texname;
|
||
}
|
||
|
||
//------------------获取模型-------------------
|
||
// 按 材质 放入面的顶点
|
||
std::vector<std::vector<tinyobj::index_t>> all_sub;
|
||
all_sub.resize(1 + materials.size());// 0为默认
|
||
|
||
for (size_t i = 0; i < shapes.size(); i++)
|
||
{// 每一个子shape
|
||
tinyobj::shape_t& shape = shapes[i];
|
||
size_t num_index = shape.mesh.indices.size();
|
||
size_t num_face = shape.mesh.num_face_vertices.size();
|
||
log_info("读取子模型:{},{}", i, shape.name);
|
||
log_info("索引数:{};面数:{}", num_index, num_face);
|
||
|
||
//当前mesh下标(每个面递增3)
|
||
size_t index_offset = 0;
|
||
//每一个面
|
||
for (size_t j = 0; j < num_face; ++j)
|
||
{
|
||
int index_mat = shape.mesh.material_ids[j];//每个面的材质
|
||
std::vector<tinyobj::index_t>& sub_idx = all_sub[1 + index_mat];
|
||
sub_idx.push_back(shape.mesh.indices[index_offset + 0]);
|
||
if (!is_axis_up_z)
|
||
{
|
||
sub_idx.push_back(shape.mesh.indices[index_offset + 1]);
|
||
sub_idx.push_back(shape.mesh.indices[index_offset + 2]);
|
||
}
|
||
else
|
||
{
|
||
sub_idx.push_back(shape.mesh.indices[index_offset + 2]);
|
||
sub_idx.push_back(shape.mesh.indices[index_offset + 1]);
|
||
}
|
||
index_offset += 3;
|
||
}
|
||
}
|
||
//生成子模型,并填入顶点
|
||
std::unordered_map<tinyobj::index_t, size_t, hash_idx, equal_idx>
|
||
uniqueVertices;//避免重复插入顶点
|
||
size_t i = 0;
|
||
size_t j = 0;
|
||
for (std::vector<tinyobj::index_t>& sub_idx : all_sub)
|
||
{
|
||
ModelObjectSub sub;
|
||
sub._range._offsetIndex = i;
|
||
sub._range._countTriangle = sub_idx.size() / 3;
|
||
sub._indexMaterial = j - 1;
|
||
++j;
|
||
model_object->_allSub.push_back(sub);
|
||
|
||
for (tinyobj::index_t& idx : sub_idx)
|
||
{
|
||
auto iter = uniqueVertices.find(idx);
|
||
if (iter == uniqueVertices.end())
|
||
{
|
||
Vertex v;
|
||
//v
|
||
v._pos[0] = attrib.vertices[idx.vertex_index * 3 + 0];
|
||
if (!is_axis_up_z)
|
||
{
|
||
v._pos[1] = attrib.vertices[idx.vertex_index * 3 + 1];
|
||
v._pos[2] = attrib.vertices[idx.vertex_index * 3 + 2];
|
||
}
|
||
else
|
||
{
|
||
v._pos[1] = attrib.vertices[idx.vertex_index * 3 + 2];
|
||
v._pos[2] = attrib.vertices[idx.vertex_index * 3 + 1];
|
||
}
|
||
|
||
// vt
|
||
v._uv[0] = attrib.texcoords[idx.texcoord_index * 2 + 0];
|
||
v._uv[1] = attrib.texcoords[idx.texcoord_index * 2 + 1];
|
||
v._uv[1] = 1.0f - v._uv[1];
|
||
|
||
uniqueVertices[idx] = mo_vertices.size();
|
||
mo_indices.push_back((uint32_t)mo_vertices.size());
|
||
mo_vertices.push_back(v);
|
||
}
|
||
else
|
||
{
|
||
mo_indices.push_back((uint32_t)iter->second);
|
||
}
|
||
++i;
|
||
}
|
||
}
|
||
log_msg("解析obj模型完成:v{},i{}", mo_vertices.size(), mo_indices.size());
|
||
return ret;
|
||
}
|
||
std::vector<ModelObject*> _load_gltf(std::string_view path_name, bool is_glb)
|
||
{
|
||
tinygltf::Model model;
|
||
tinygltf::TinyGLTF loader;
|
||
std::string err;
|
||
std::string warn;
|
||
|
||
bool ret;
|
||
if(is_glb)
|
||
ret = loader.LoadBinaryFromFile(&model, &err, &warn, std::string{ path_name });
|
||
else
|
||
ret = loader.LoadASCIIFromFile(&model, &err, &warn, std::string{ path_name });
|
||
|
||
|
||
if (!warn.empty())
|
||
log_warn("{}", warn);
|
||
|
||
if (!err.empty())
|
||
log_err("{}", err);
|
||
|
||
if (!ret)
|
||
{
|
||
log_err("解析gltf格式失败:{}", err);
|
||
return {};
|
||
}
|
||
|
||
|
||
return {};
|
||
}
|
||
};
|
||
|
||
ModelLoader* g_modelLoader;
|
||
|
||
}
|