-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgltfLoader.cpp
More file actions
384 lines (325 loc) · 13.5 KB
/
gltfLoader.cpp
File metadata and controls
384 lines (325 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#include "gltfLoader.h"
#include "material.h"
#include "utils.h"
#include "stb_image.h"
void GltfLoader::load(const std::string& filepath) {
entt::entity gltfEntity = m_scene->addEntity();
tinygltf::Model model;
tinygltf::TinyGLTF loader;
std::string err;
std::string warn;
std::string extension = Utils::getFileExtension(filepath);
bool ret = false;
if (extension == "gltf")
ret = loader.LoadASCIIFromFile(&model, &err, &warn, filepath);
else if (extension == "glb")
ret = loader.LoadBinaryFromFile(&model, &err, &warn, filepath);
else
assert(false);
if (!warn.empty()) {
std::cout << "WARN: " << warn << std::endl;
}
if (!err.empty()) {
std::cerr << "ERR: " << err << std::endl;
}
if (!ret) {
return;
}
std::string baseDir = Utils::GetBaseDir(filepath);
for (auto& gltfTexture : model.textures)
{
const tinygltf::Image& gltfImage = model.images[gltfTexture.source];
unsigned char* pixelData;
TextureView textureView = nullptr;
if (!gltfImage.uri.empty()) {
std::smatch matches;
if (std::regex_search(gltfImage.uri, matches, base64Pattern)) {
//Base64
loadImageFromBase64(gltfImage.uri, &textureView);
}
else {
//Relative path
std::string texturePath = baseDir + "/" + gltfImage.uri;
Utils::loadImageFromPath(texturePath, &textureView);
}
}
//else if (!gltfImage.image.empty()) {
// //Load image from a vector of unsigned char
// loadImageFromVector(gltfImage.image, &textureView);
//}
else
{
//Buffer
loadImageFromBuffer(model, gltfImage, &textureView);
}
std::string imageId = generateTextureId(gltfImage.uri, baseDir, gltfTexture.source);
TextureManager().getInstance().add(imageId, textureView);
m_sourceToId[gltfTexture.source] = imageId;
}
for (const auto& sceneNodeIndex : model.scenes[model.defaultScene].nodes) {
entt::entity rootNode = m_scene->addEntity();
m_scene->addChild(gltfEntity, rootNode);
loadNode(model, model.nodes[sceneNodeIndex], rootNode, m_scene, sceneNodeIndex);
//scene.push_back(rootNode);
}
//return scene;
//return gltfEntity;
m_entity = gltfEntity;
};
void GltfLoader::unload()
{
for (auto& texId : m_sourceToId)
{
TextureManager().getInstance().remove(texId.second);
}
m_scene->removeEntity(m_entity);
}
// Base64 decoding function
std::string base64_decode(const std::string& in) {
std::string out;
std::vector<int> T(256, -1);
for (int i = 0; i < 64; i++) T["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;
int val = 0, valb = -8;
for (unsigned char c : in) {
if (T[c] == -1) break;
val = (val << 6) + T[c];
valb += 6;
if (valb >= 0) {
out.push_back(char((val >> valb) & 0xFF));
valb -= 8;
}
}
return out;
}
Texture GltfLoader::loadImageFromBase64(const std::string& base64, TextureView* pTextureView) {
int width, height, channels;
std::string base64Data = base64.substr(base64.find(",") + 1);
std::string decodedData = base64_decode(base64Data);
unsigned char* data = stbi_load_from_memory(reinterpret_cast<const stbi_uc*>(decodedData.data()), decodedData.size(), &width, &height, &channels, 4);
if (!data) {
std::cerr << "Failed to load image from Base64 data" << std::endl;
}
return Utils::loadTexture(data, width, height, channels, TextureFormat::RGBA8Unorm, pTextureView);
}
Texture GltfLoader::loadImageFromVector(const std::vector<unsigned char>& imageVector, TextureView* pTextureView) {
int width, height, channels;
unsigned char* data = stbi_load_from_memory(imageVector.data(), imageVector.size(), &width, &height, &channels, 4);
if (!data) {
std::cerr << "Failed to load image from vector data" << std::endl;
}
return Utils::loadTexture(data, width, height, channels, TextureFormat::RGBA8Unorm, pTextureView);
}
// Load image from GLTF buffer
Texture GltfLoader::loadImageFromBuffer(const tinygltf::Model& model, const tinygltf::Image& image, TextureView* pTextureView) {
int width, height, channels;
const tinygltf::BufferView& bufferView = model.bufferViews[image.bufferView];
const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer];
const unsigned char* dataBuffer = buffer.data.data() + bufferView.byteOffset;
size_t size = bufferView.byteLength;
unsigned char* data = stbi_load_from_memory(dataBuffer, size, &width, &height, &channels, 4);
if (!data) {
std::cerr << "Failed to load image from GLTF buffer" << std::endl;
}
return Utils::loadTexture(data, width, height, channels, TextureFormat::RGBA8Unorm, pTextureView);
}
std::string GltfLoader::generateTextureId(const std::string& uri, const std::string& baseDir, int source)
{
if (!uri.empty()) {
std::smatch matches;
if (std::regex_search(uri, matches, base64Pattern)) {
//Base64
return "image64_" + std::to_string(source);
}
else {
//Relative path
std::string texturePath = baseDir + "/" + uri;
return uri;
}
}
else
{
//Buffer
return "imageBuffer_" + std::to_string(source);
}
}
void GltfLoader::loadMesh(const tinygltf::Model& model, const tinygltf::Mesh& mesh, entt::entity parent, Issam::Scene* scene)
{
int primitiveIdx = 0;
for (const auto& primitive : mesh.primitives)
{
entt::entity entity = scene->addEntity();
scene->addChild(parent, entity);
std::vector<Vertex> vertices;
std::vector<uint16_t> indices;
// Process vertex attributes
const tinygltf::Accessor& posAccessor = model.accessors[primitive.attributes.find("POSITION")->second];
if (posAccessor.bufferView == -1) return;
const tinygltf::BufferView& posBufferView = model.bufferViews[posAccessor.bufferView];
const tinygltf::Buffer& posBuffer = model.buffers[posBufferView.buffer];
const tinygltf::Accessor* normAccessor = nullptr;
const tinygltf::BufferView* normBufferView = nullptr;
const tinygltf::Buffer* normBuffer = nullptr;
const tinygltf::Accessor* uvAccessor = nullptr;
const tinygltf::BufferView* uvBufferView = nullptr;
const tinygltf::Buffer* uvBuffer = nullptr;
const tinygltf::Accessor* tangentAccessor = nullptr;
const tinygltf::BufferView* tangentBufferView = nullptr;
const tinygltf::Buffer* tangentBuffer = nullptr;
if (primitive.attributes.find("NORMAL") != primitive.attributes.end()) {
normAccessor = &model.accessors[primitive.attributes.find("NORMAL")->second];
normBufferView = &model.bufferViews[normAccessor->bufferView];
normBuffer = &model.buffers[normBufferView->buffer];
}
if (primitive.attributes.find("TEXCOORD_0") != primitive.attributes.end()) {
uvAccessor = &model.accessors[primitive.attributes.find("TEXCOORD_0")->second];
uvBufferView = &model.bufferViews[uvAccessor->bufferView];
uvBuffer = &model.buffers[uvBufferView->buffer];
}
if (primitive.attributes.find("TANGENT") != primitive.attributes.end()) {
tangentAccessor = &model.accessors[primitive.attributes.find("TANGENT")->second];
tangentBufferView = &model.bufferViews[tangentAccessor->bufferView];
tangentBuffer = &model.buffers[tangentBufferView->buffer];
}
for (size_t i = 0; i < posAccessor.count; ++i) {
Vertex vertex = {};
size_t posIndex = i * posAccessor.ByteStride(posBufferView) + posAccessor.byteOffset + posBufferView.byteOffset;
vertex.position = glm::vec3(
*reinterpret_cast<const float*>(&posBuffer.data[posIndex + 0 * sizeof(float)]),
*reinterpret_cast<const float*>(&posBuffer.data[posIndex + 1 * sizeof(float)]),
*reinterpret_cast<const float*>(&posBuffer.data[posIndex + 2 * sizeof(float)]));
if (normAccessor) {
size_t normIndex = i * normAccessor->ByteStride(*normBufferView) + normAccessor->byteOffset + normBufferView->byteOffset;
vertex.normal = glm::vec3(
*reinterpret_cast<const float*>(&normBuffer->data[normIndex + 0 * sizeof(float)]),
*reinterpret_cast<const float*>(&normBuffer->data[normIndex + 1 * sizeof(float)]),
*reinterpret_cast<const float*>(&normBuffer->data[normIndex + 2 * sizeof(float)]));
}
if (uvAccessor) {
size_t uvIndex = i * uvAccessor->ByteStride(*uvBufferView) + uvAccessor->byteOffset + uvBufferView->byteOffset;
vertex.uv = glm::vec2(
*reinterpret_cast<const float*>(&uvBuffer->data[uvIndex + 0 * sizeof(float)]),
*reinterpret_cast<const float*>(&uvBuffer->data[uvIndex + 1 * sizeof(float)]));
}
if (tangentAccessor) {
size_t tangentIndex = i * tangentAccessor->ByteStride(*tangentBufferView) + tangentAccessor->byteOffset + tangentBufferView->byteOffset;
vertex.tangent = glm::vec3(
*reinterpret_cast<const float*>(&tangentBuffer->data[tangentIndex + 0 * sizeof(float)]),
*reinterpret_cast<const float*>(&tangentBuffer->data[tangentIndex + 1 * sizeof(float)]),
*reinterpret_cast<const float*>(&tangentBuffer->data[tangentIndex + 2 * sizeof(float)]));
}
vertices.push_back(vertex);
}
MeshPtr myMesh = std::make_shared<Mesh>();
myMesh->setVertices(vertices);
if (primitive.indices != -1)
{
// Process indices
const tinygltf::Accessor& indexAccessor = model.accessors[primitive.indices];
const tinygltf::BufferView& indexBufferView = model.bufferViews[indexAccessor.bufferView];
const tinygltf::Buffer& indexBuffer = model.buffers[indexBufferView.buffer];
for (size_t i = 0; i < indexAccessor.count; ++i) {
size_t index = i * indexAccessor.ByteStride(indexBufferView) + indexAccessor.byteOffset + indexBufferView.byteOffset;
uint32_t indexValue;
switch (indexAccessor.componentType) {
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
indexValue = *reinterpret_cast<const uint8_t*>(&indexBuffer.data[index]);
break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
indexValue = *reinterpret_cast<const uint16_t*>(&indexBuffer.data[index]);
break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
assert(false); //NOT SUPPORTED
indexValue = *reinterpret_cast<const uint32_t*>(&indexBuffer.data[index]);
break;
default:
throw std::runtime_error("Unsupported index component type");
}
indices.push_back(indexValue);
}
myMesh->setIndices(indices);
}
Issam::MeshRenderer meshRenderer;
meshRenderer.mesh = myMesh;
if (primitive.material != -1)
{
Material* material = new Material();
auto& gltfMaterial = model.materials[primitive.material];
auto& baseColorFactor = gltfMaterial.pbrMetallicRoughness.baseColorFactor;
material->setAttribute("baseColorFactor", glm::make_vec4(baseColorFactor.data()));
int baseColorTextureIndex = gltfMaterial.pbrMetallicRoughness.baseColorTexture.index;
if (baseColorTextureIndex >= 0 && baseColorTextureIndex < model.textures.size())
{
const tinygltf::Texture& gltfTexture = model.textures[baseColorTextureIndex];
// const tinygltf::Image& gltfImage = model.images[gltfTexture.source];
std::string id = m_sourceToId.find(gltfTexture.source)->second;
material->setAttribute("baseColorTexture", TextureManager::getInstance().get(id));
}
int metallicRoughnessIndex = gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture.index;
if (metallicRoughnessIndex >= 0 && metallicRoughnessIndex < model.textures.size())
{
const tinygltf::Texture& gltfTexture = model.textures[metallicRoughnessIndex];
//const tinygltf::Image& gltfImage = model.images[gltfTexture.source];
std::string id = m_sourceToId.find(gltfTexture.source)->second;
material->setAttribute("metallicRoughnessTexture", TextureManager::getInstance().get(id));
}
auto& metallicFactor = gltfMaterial.pbrMetallicRoughness.metallicFactor;
material->setAttribute("metallicFactor", (float)metallicFactor);
auto& roughnessFactor = gltfMaterial.pbrMetallicRoughness.roughnessFactor;
material->setAttribute("roughnessFactor", (float)roughnessFactor);
material->setAttribute("unlitMaterialModel", "colorFactor", glm::vec4(1.0, 0.5, 0.0, 1.0), 0);
material->setAttribute("unlitMaterialModel", "colorFactor", glm::vec4(0.0), 1);
meshRenderer.material = material;
Issam::Filters filters;
filters.add("pbr");
scene->addComponent<Issam::Filters>(entity, filters);
}
scene->addComponent<Issam::MeshRenderer>(entity, meshRenderer);
}
}
void GltfLoader::loadNode(const tinygltf::Model& model, const tinygltf::Node& gltfNode, entt::entity entity, Issam::Scene* scene, int idx) {
static int nodeId = 0;
std::string nodeName = gltfNode.name;
if (nodeName.empty())
nodeName = "node_" + std::to_string(idx);
scene->addComponent<Issam::Name>(entity, Issam::Name({ nodeName }));
const glm::vec3 T =
gltfNode.translation.empty()
? glm::vec3(0.0f)
: glm::vec3(
(float)(gltfNode.translation[0]),
(float)(gltfNode.translation[1]),
(float)(gltfNode.translation[2])
);
const glm::quat R =
gltfNode.rotation.empty()
? glm::quat()
: glm::quat(
(float)(gltfNode.rotation[3]),
(float)(gltfNode.rotation[0]),
(float)(gltfNode.rotation[1]),
(float)(gltfNode.rotation[2])
);
const glm::vec3 S =
gltfNode.scale.empty()
? glm::vec3(1.0f)
: glm::vec3(
(float)(gltfNode.scale[0]),
(float)(gltfNode.scale[1]),
(float)(gltfNode.scale[2])
);
//node->setTransform(glm::translate(glm::mat4(1.0), T) * glm::mat4_cast(R) * glm::scale(glm::mat4(1.0), S));
scene->setLocalTransform(entity, glm::translate(glm::mat4(1.0), T) * glm::mat4_cast(R) * glm::scale(glm::mat4(1.0), S));
if (!gltfNode.matrix.empty()) {
scene->setLocalTransform(entity, glm::make_mat4(gltfNode.matrix.data()));
//node->setTransform(glm::make_mat4(gltfNode.matrix.data()));
}
if (gltfNode.mesh >= 0) {
loadMesh(model, model.meshes[gltfNode.mesh], entity, scene);
}
for (int childIndex : gltfNode.children) {
entt::entity childEntity = scene->addEntity();
loadNode(model, model.nodes[childIndex], childEntity, scene, childIndex);
scene->addChild(entity, childEntity);
//node->children.push_back(childNode);
}
}