dl
dl_model_loader.h
浏览该文件的文档.
1
16#pragma once
17
18#define TINYOBJLOADER_IMPLEMENTATION
19#include <tiny_obj_loader.h>
20#define TINYGLTF_IMPLEMENTATION
21#include <tiny_gltf.h>
22
23#include "io/dl_json.h"
24
25namespace dl
26{
27 struct equal_idx
28 {
29 bool operator()(const tinyobj::index_t& a, const tinyobj::index_t& b) const
30 {
31 return a.vertex_index == b.vertex_index
32 && a.texcoord_index == b.texcoord_index
33 && a.normal_index == b.normal_index;
34 }
35 };
36
37 struct hash_idx
38 {
39 size_t operator()(const tinyobj::index_t& a) const
40 {
41 return ((a.vertex_index
42 ^ a.texcoord_index << 1) >> 1)
43 ^ (a.normal_index << 1);
44 }
45 };
46
47 inline float ShininessToRoughness(float Ypoint)
48 {
49 float a = -1;
50 float b = 2;
51
52 float c;
53 c = (Ypoint / 100) - 1;
54
55 float D;
56 D = b * b - (4 * a * c);
57
58 float x1;
59 x1 = (-b + sqrt(D)) / (2 * a);
60
61 return x1;
62 }
63
65{
66public:
67 std::vector<ModelObject*> Load(std::string_view path_name, std::string_view res_name)
68 {
69 std::string ext = File::GetExtension(path_name);
70 if (ext == "obj")
71 return _load_obj(path_name);
72 else if (ext == "glb")
73 return _load_gltf(path_name, true);
74 else if (ext == "gltf")
75 return _load_gltf(path_name, false);
76 log_err("不支持的模型格式:{}", path_name);
77 return {};
78 }
79private:
80 std::vector<ModelObject*> _load_obj(std::string_view path_name)
81 {
82 std::string str_path = std::string{ path_name };
83 std::string str_base = String::EraseFilename(path_name);
84
85 const char* filename = str_path.c_str();
86 const char* basepath = str_base.c_str();
87 bool triangulate = true;
88
89 log_info("开始加载obj文件:{},{}", filename, basepath);
90
91 tinyobj::attrib_t attrib; // 所有的数据放在这里
92 std::vector<tinyobj::shape_t> shapes;// 子模型
93 std::vector<tinyobj::material_t> materials;
94
95 std::string warn;
96 std::string err;
97
98 bool b_read = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filename,
99 basepath, triangulate);
100
101 // 打印错误
102 if (!warn.empty())
103 log_warn("{}", warn);
104
105 if (!err.empty())
106 log_warn("{}", err);
107
108 if (!b_read)
109 {
110 log_err("读取obj文件失败:{}", path_name);
111 return {};
112 }
113 log_info("顶点数:{}", attrib.vertices.size() / 3);
114 log_info("法线数:{}", attrib.normals.size() / 3);
115 log_info("UV数:{}", attrib.texcoords.size() / 2);
116 log_info("子模型数:{}", shapes.size());
117 log_info("材质数:{}", materials.size());
118
119 // 读取配置
120 bool is_axis_up_z = false;
121 {
122 Json::DisableLog l;
123 json j = Json::Parse(String::ReplaceExtension(path_name, "json"));
124 if (!j.is_null())
125 {
126 std::string str;
127 if (Json::Get(j, "axis_up", str))
128 {
129 if (str == "z")
130 is_axis_up_z = true;
131 }
132 }
133 }
134
135 // obj只有一个ModelObject
136 std::vector<ModelObject*> ret;
137 ModelObject* model_object = new ModelObject;
138 std::vector<Vertex>& mo_vertices = model_object->_allVertex;
139 std::vector<uint32_t>& mo_indices = model_object->_allIndex;
140 std::vector<ModelObjectMaterial>& mo_material = model_object->_allMaterial;
141 ret.push_back(model_object);
142
143 //------------------获取材质-------------------
144 mo_material.resize(materials.size());
145 for (size_t i = 0; i < materials.size(); ++i)
146 {
147 tinyobj::material_t m = materials[i];
148 log_info("材质:{},{}", i, m.name);
149
150 ModelObjectMaterial& material = mo_material[i];
151 material._materialName = m.name;
152
153 material._material._diffuseAlbedo = { m.diffuse[0], m.diffuse[1], m.diffuse[2], 1.0f };
154 material._material._fresnelR0 = { m.specular[0], m.specular[1], m.specular[2] };
155 material._material._roughness = ShininessToRoughness(m.shininess);
156
157 if (!m.diffuse_texname.empty())
158 material._pathTexDiffuse = str_base + m.diffuse_texname;
159 if (!m.normal_texname.empty())// 注意这里凹凸贴图(bump_texname)更常见
160 material._pathTexNormal = str_base + m.normal_texname;
161 }
162
163 //------------------获取模型-------------------
164 // 按 材质 放入面的顶点
165 std::vector<std::vector<tinyobj::index_t>> all_sub;
166 all_sub.resize(1 + materials.size());// 0为默认
167
168 for (size_t i = 0; i < shapes.size(); i++)
169 {// 每一个子shape
170 tinyobj::shape_t& shape = shapes[i];
171 size_t num_index = shape.mesh.indices.size();
172 size_t num_face = shape.mesh.num_face_vertices.size();
173 log_info("读取子模型:{},{}", i, shape.name);
174 log_info("索引数:{};面数:{}", num_index, num_face);
175
176 //当前mesh下标(每个面递增3)
177 size_t index_offset = 0;
178 //每一个面
179 for (size_t j = 0; j < num_face; ++j)
180 {
181 int index_mat = shape.mesh.material_ids[j];//每个面的材质
182 std::vector<tinyobj::index_t>& sub_idx = all_sub[1 + index_mat];
183 sub_idx.push_back(shape.mesh.indices[index_offset + 0]);
184 if (!is_axis_up_z)
185 {
186 sub_idx.push_back(shape.mesh.indices[index_offset + 1]);
187 sub_idx.push_back(shape.mesh.indices[index_offset + 2]);
188 }
189 else
190 {
191 sub_idx.push_back(shape.mesh.indices[index_offset + 2]);
192 sub_idx.push_back(shape.mesh.indices[index_offset + 1]);
193 }
194 index_offset += 3;
195 }
196 }
197 //生成子模型,并填入顶点
198 std::unordered_map<tinyobj::index_t, size_t, hash_idx, equal_idx>
199 uniqueVertices;//避免重复插入顶点
200 size_t i = 0;
201 size_t j = 0;
202 for (std::vector<tinyobj::index_t>& sub_idx : all_sub)
203 {
204 ModelObjectSub sub;
205 sub._range._offsetIndex = i;
206 sub._range._countTriangle = sub_idx.size() / 3;
207 sub._indexMaterial = j - 1;
208 ++j;
209 model_object->_allSub.push_back(sub);
210
211 for (tinyobj::index_t& idx : sub_idx)
212 {
213 auto iter = uniqueVertices.find(idx);
214 if (iter == uniqueVertices.end())
215 {
216 Vertex v;
217 //v
218 v._pos[0] = attrib.vertices[idx.vertex_index * 3 + 0];
219 if (!is_axis_up_z)
220 {
221 v._pos[1] = attrib.vertices[idx.vertex_index * 3 + 1];
222 v._pos[2] = attrib.vertices[idx.vertex_index * 3 + 2];
223 }
224 else
225 {
226 v._pos[1] = attrib.vertices[idx.vertex_index * 3 + 2];
227 v._pos[2] = attrib.vertices[idx.vertex_index * 3 + 1];
228 }
229
230 // vt
231 v._uv[0] = attrib.texcoords[idx.texcoord_index * 2 + 0];
232 v._uv[1] = attrib.texcoords[idx.texcoord_index * 2 + 1];
233 v._uv[1] = 1.0f - v._uv[1];
234
235 uniqueVertices[idx] = mo_vertices.size();
236 mo_indices.push_back((uint32_t)mo_vertices.size());
237 mo_vertices.push_back(v);
238 }
239 else
240 {
241 mo_indices.push_back((uint32_t)iter->second);
242 }
243 ++i;
244 }
245 }
246 log_msg("解析obj模型完成:v{},i{}", mo_vertices.size(), mo_indices.size());
247 return ret;
248 }
249 std::vector<ModelObject*> _load_gltf(std::string_view path_name, bool is_glb)
250 {
251 tinygltf::Model model;
252 tinygltf::TinyGLTF loader;
253 std::string err;
254 std::string warn;
255
256 bool ret;
257 if(is_glb)
258 ret = loader.LoadBinaryFromFile(&model, &err, &warn, std::string{ path_name });
259 else
260 ret = loader.LoadASCIIFromFile(&model, &err, &warn, std::string{ path_name });
261
262
263 if (!warn.empty())
264 log_warn("{}", warn);
265
266 if (!err.empty())
267 log_err("{}", err);
268
269 if (!ret)
270 {
271 log_err("解析gltf格式失败:{}", err);
272 return {};
273 }
274
275
276 return {};
277 }
278};
279
281
282}
std::vector< ModelObject * > Load(std::string_view path_name, std::string_view res_name)
json格式相关
nlohmann::json json
Definition: dl_json.h:19
#define log_warn(...)
Definition: dl_log.h:242
#define log_msg(...)
Definition: dl_log.h:240
#define log_info(...)
Definition: dl_log.h:239
#define log_err(...)
Definition: dl_log.h:243
std::string GetExtension(std::string_view path_name, bool has_dot=false)
返回文件后缀
json Parse(std::string_view path_name)
从 文件 构建json对象
bool Get(const json &j, const std::string &name, T &t)
从json返回值,不存在则返回false,打印日志
Definition: dl_json.h:54
Definition: dl_array2.h:18
ModelLoader * g_modelLoader
float ShininessToRoughness(float Ypoint)
bool operator()(const tinyobj::index_t &a, const tinyobj::index_t &b) const
size_t operator()(const tinyobj::index_t &a) const