Модель, загруженная из .obj, выглядит растянутой и смещенной в OpenGL 3.3 MacOS.C++

Программы на C++. Форум разработчиков
Ответить Пред. темаСлед. тема
Anonymous
 Модель, загруженная из .obj, выглядит растянутой и смещенной в OpenGL 3.3 MacOS.

Сообщение Anonymous »

Я пытаюсь визуализировать модель вертолета в своем проекте OpenGL, используя Assimp для загрузки файла .obj. Модель загружается, но выглядит растянутой и смещенной (см. снимок экрана ниже). Части модели также кажутся обрезанными. Пожалуйста, сообщите мне, в чем может быть проблема.
[img]https:// i.sstatic.net/7CYccieK.png[/img]

Это часть кода, в которой к модели применяются преобразования:
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(-3.0f, 2.0f, 0.0f));
model = glm::rotate(model, -90.0f * toRadians, glm::vec3(1.0f, 0.0f, 0.0f));
model = glm::scale(model, glm::vec3(0.1f, 0.1f, 0.1f));
glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model));
shinyMaterial.UseMaterial(uniformSpecularIntensity, uniformShininess);
blackhawk.RenderModel();

Отрывок из класса модели:
void Model::LoadModel(const std::string &fileName) {
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile(fileName, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenSmoothNormals | aiProcess_JoinIdenticalVertices);

if (!scene) {
printf("ERROR: Failed to load model from %s: %s\n", fileName.c_str(), importer.GetErrorString());
return;
}

LoadNode(scene->mRootNode, scene);

LoadMaterials(scene);
}

void Model::LoadNode(aiNode *node, const aiScene *scene) {
for (size_t i = 0; i < node->mNumMeshes; i++) {
LoadMesh(scene->mMeshes[node->mMeshes], scene);
}

for (size_t i = 0; i < node->mNumChildren; i++) {
LoadNode(node->mChildren, scene);
}
}

void Model::LoadMesh(aiMesh *mesh, const aiScene *scene) {
std::vector vertices;
std::vector indices;

for (size_t i = 0; i < mesh->mNumVertices; i++) {
vertices.insert(vertices.end(), { mesh->mVertices.x, mesh->mVertices.y + mesh->mVertices.z });
if (mesh->mTextureCoords[0]) {
vertices.insert(vertices.end(), { mesh->mTextureCoords[0].x, mesh->mTextureCoords[0].y });
}
else {
vertices.insert(vertices.end(), { 0.0f, 0.0f });
}
}

for (size_t i = 0; i < mesh->mNumFaces; i++) {
const aiFace face = mesh->mFaces;
for (size_t j = 0; j < face.mNumIndices; j++) {
indices.push_back(face.mIndices[j]);
}
}

const auto newMesh = new Mesh();
newMesh->CreateMesh(&vertices[0], &indices[0], vertices.size(), indices.size());
meshList.push_back(newMesh);
meshToTex.push_back(mesh->mMaterialIndex);
}

void Model::LoadMaterials(const aiScene *scene) {
textureList.resize(scene->mNumMaterials);

for (size_t i = 0; i < scene->mNumMaterials; i++) {
aiMaterial *material = scene->mMaterials;
textureList = nullptr;

printf("[DEBUG] Material %zu has %u diffuse textures.\n", i, material->GetTextureCount(aiTextureType_DIFFUSE));

if (material->GetTextureCount(aiTextureType_DIFFUSE)) {
printf("[DEBUG] inside aiTextureType_DIFFUSE.\n");
aiString path;
if (material->GetTexture(aiTextureType_DIFFUSE, 0, &path) == AI_SUCCESS) {
printf("[DEBUG] for path: %s\n", path.data);
std::string fullPath = path.data;
size_t lastSlash = fullPath.find_last_of("/\\"); // Handles both '/' and '\\'

std::string filename;
if (lastSlash != std::string::npos) {
filename = fullPath.substr(lastSlash + 1); // Extract from after the last slash
} else {
filename = fullPath; // If no slashes are found, use the full path
}
printf("[DEBUG] for filename: %s\n", filename.c_str());

std::string texPath = std::string("/Users/prkaaviya/CLionProjects/try8/Textures/") + filename;
printf("Loading texture: %s\n", texPath.c_str());

textureList[i] = new Texture(texPath.c_str());

if (!textureList[i]->LoadTexture()) {
printf("ERROR: Failed to load texture from %s: %s\n", filename.c_str(), texPath.c_str());
delete textureList[i];
textureList[i] = nullptr;
}
}
}

if (!textureList[i]) {
textureList[i] = new Texture("/Users/prkaaviya/CLionProjects/try8/Textures/plain.png");
textureList[i]->LoadTextureA();
}
}
}

Функция, загружающая текстуру для моделей:
bool Texture::LoadTextureA() {
stbi_set_flip_vertically_on_load(true);
unsigned char *texData = stbi_load(fileLocation, &width, &height, &bitDepth, STBI_rgb_alpha);
if (!texData) {
printf("ERROR: Failed to load texture from %s.\n", fileLocation);
return false;
}

glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texData);
glGenerateMipmap(GL_TEXTURE_2D);

glBindTexture(GL_TEXTURE_2D, 0);

stbi_image_free(texData);

return true;
}


Подробнее здесь: https://stackoverflow.com/questions/792 ... -3-3-macos
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Модель, загруженная из .obj, выглядит растянутой и смещенной в OpenGL 3.3 MacOS.
    Anonymous » » в форуме C++
    0 Ответы
    4 Просмотры
    Последнее сообщение Anonymous
  • 3D-модель, загруженная из файла OBJ, не отображается.
    Anonymous » » в форуме C++
    0 Ответы
    16 Просмотры
    Последнее сообщение Anonymous
  • Выпрямление линии, растянутой из-за движения камеры.
    Anonymous » » в форуме Python
    0 Ответы
    3 Просмотры
    Последнее сообщение Anonymous
  • Загруженная модель Keras выдает ошибку при прогнозировании (вероятные проблемы с маскированием)
    Anonymous » » в форуме Python
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous
  • Загруженная модель Keras выдает ошибку при прогнозировании (вероятные проблемы с маскированием)
    Anonymous » » в форуме Python
    0 Ответы
    15 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C++»