#include "ObjImportUtil.h" #include "tiny_obj_loader.h" int ObjImportUtil::ObjVertex::Compare(const ObjVertex& Other) const { const float pp[] = { this->inPos.x, this->inPos.y, this->inPos.z, this->inColor.x, this->inColor.y, this->inColor.z, this->inTexCoord.x, this->inTexCoord.y, this->inNormal.x, this->inNormal.y, this->inNormal.z }; const float rr[] = { Other.inPos.x, Other.inPos.y, Other.inPos.z, Other.inColor.x, Other.inColor.y, Other.inColor.z, Other.inTexCoord.x, Other.inTexCoord.y, Other.inNormal.x, Other.inNormal.y, Other.inNormal.z }; for (int i = 0; i < std::size(pp); ++i) { auto k = pp[i] - rr[i]; if (abs(k) < 0.0001) continue; if (k > 0) return 1; else if (k < 0) return -1; } return 0; } ObjImportUtil::ObjImportedMeshData ObjImportUtil::LoadFromObjFile( const DKString& inPath , DKResourcePool& inDKResourcePool) { ObjImportedMeshData retData; DKObject objData = inDKResourcePool.LoadResourceData(inPath); if (objData && objData->Length() > 0) { DKLog("Loading %ls... (%lu bytes)\n" , (const wchar_t*)inPath , objData->Length()); DKTimer timer; timer.Reset(); retData.vertices.Reserve(100000); retData.indices.Reserve(100000); retData.vertexSize = sizeof(ObjImportUtil::ObjVertex); tinyobj::attrib_t attrib; std::vector shapes; shapes.reserve(1000000); std::vector materials; std::string err; if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &err, DKStringU8(inPath))) { throw std::runtime_error(err); } DKMap uniqueVertices; DKLog("Save to Container"); for (const auto& shape : shapes) { for (const auto& index : shape.mesh.indices) { ObjVertex vertex = {}; vertex.inPos = { attrib.vertices[3 * index.vertex_index + 0], attrib.vertices[3 * index.vertex_index + 1], attrib.vertices[3 * index.vertex_index + 2] }; if (attrib.texcoords.size()) { vertex.inTexCoord = { attrib.texcoords[2 * index.texcoord_index + 0], 1.0f - attrib.texcoords[2 * index.texcoord_index + 1] }; } vertex.inColor = { 1.0f, 1.0f, 1.0f }; if (attrib.normals.size()) { vertex.inNormal = { attrib.normals[3 * index.normal_index + 0], attrib.normals[3 * index.normal_index + 1], attrib.normals[3 * index.normal_index + 2] }; } if (uniqueVertices.Find(vertex) == nullptr) { uniqueVertices.Insert(vertex , static_cast(retData.vertices.Count())); retData.vertices.Add(vertex); } retData.indices.Add(uniqueVertices.Value(vertex)); retData.aabb.Expand(vertex.inPos); } } } return retData; }