diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp index e4c683f2645..1a9dacfa0b8 100644 --- a/modules/gltf/gltf_document.cpp +++ b/modules/gltf/gltf_document.cpp @@ -2833,13 +2833,17 @@ Error GLTFDocument::_parse_meshes(Ref p_state) { Vector indices_vec4_mapping; if (p.has("indices")) { indices = _decode_accessor_as_ints(p_state, p["indices"], false); - const int is = indices.size(); + const int index_count = indices.size(); if (primitive == Mesh::PRIMITIVE_TRIANGLES) { + if (index_count % 3 != 0) { + ERR_PRINT("glTF import: Mesh " + itos(i) + " surface " + itos(j) + " in file " + p_state->filename + " is invalid. Indexed triangle meshes MUST have an index array with a size that is a multiple of 3, but got " + itos(index_count) + " indices."); + continue; + } // Swap around indices, convert ccw to cw for front face. int *w = indices.ptrw(); - for (int k = 0; k < is; k += 3) { + for (int k = 0; k < index_count; k += 3) { SWAP(w[k + 1], w[k + 2]); } } @@ -2848,7 +2852,7 @@ Error GLTFDocument::_parse_meshes(Ref p_state) { Vector used_indices; used_indices.resize_zeroed(orig_vertex_num); bool *used_w = used_indices.ptrw(); - for (int idx_i = 0; idx_i < is; idx_i++) { + for (int idx_i = 0; idx_i < index_count; idx_i++) { ERR_FAIL_INDEX_V(indices_w[idx_i], orig_vertex_num, ERR_INVALID_DATA); used_w[indices_w[idx_i]] = true; } @@ -3048,11 +3052,15 @@ Error GLTFDocument::_parse_meshes(Ref p_state) { // Generate indices because they need to be swapped for CW/CCW. const Vector &vertices = array[Mesh::ARRAY_VERTEX]; ERR_FAIL_COND_V(vertices.is_empty(), ERR_PARSE_ERROR); - const int vs = vertices.size(); - indices.resize(vs); + const int vertex_count = vertices.size(); + if (vertex_count % 3 != 0) { + ERR_PRINT("glTF import: Mesh " + itos(i) + " surface " + itos(j) + " in file " + p_state->filename + " is invalid. Non-indexed triangle meshes MUST have a vertex array with a size that is a multiple of 3, but got " + itos(vertex_count) + " vertices."); + continue; + } + indices.resize(vertex_count); { int *w = indices.ptrw(); - for (int k = 0; k < vs; k += 3) { + for (int k = 0; k < vertex_count; k += 3) { w[k] = k; w[k + 1] = k + 2; w[k + 2] = k + 1; diff --git a/scene/resources/3d/importer_mesh.cpp b/scene/resources/3d/importer_mesh.cpp index f912d2650da..6f7a597184d 100644 --- a/scene/resources/3d/importer_mesh.cpp +++ b/scene/resources/3d/importer_mesh.cpp @@ -307,6 +307,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli if (index_count == 0) { continue; //no lods if no indices } + ERR_FAIL_COND_MSG(index_count % 3 != 0, "ImporterMesh::generate_lods: Indexed triangle meshes MUST have an index array with a size that is a multiple of 3, but got " + itos(index_count) + " indices. Cannot generate LODs for this invalid mesh."); const Vector3 *vertices_ptr = vertices.ptr(); const int *indices_ptr = indices.ptr();