| 1 | /**************************************************************************/ |
| 2 | /* resource_importer_obj.cpp */ |
| 3 | /**************************************************************************/ |
| 4 | /* This file is part of: */ |
| 5 | /* GODOT ENGINE */ |
| 6 | /* https://godotengine.org */ |
| 7 | /**************************************************************************/ |
| 8 | /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ |
| 9 | /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ |
| 10 | /* */ |
| 11 | /* Permission is hereby granted, free of charge, to any person obtaining */ |
| 12 | /* a copy of this software and associated documentation files (the */ |
| 13 | /* "Software"), to deal in the Software without restriction, including */ |
| 14 | /* without limitation the rights to use, copy, modify, merge, publish, */ |
| 15 | /* distribute, sublicense, and/or sell copies of the Software, and to */ |
| 16 | /* permit persons to whom the Software is furnished to do so, subject to */ |
| 17 | /* the following conditions: */ |
| 18 | /* */ |
| 19 | /* The above copyright notice and this permission notice shall be */ |
| 20 | /* included in all copies or substantial portions of the Software. */ |
| 21 | /* */ |
| 22 | /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ |
| 23 | /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ |
| 24 | /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ |
| 25 | /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ |
| 26 | /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ |
| 27 | /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ |
| 28 | /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ |
| 29 | /**************************************************************************/ |
| 30 | |
| 31 | #include "resource_importer_obj.h" |
| 32 | |
| 33 | #include "core/io/file_access.h" |
| 34 | #include "core/io/resource_saver.h" |
| 35 | #include "scene/3d/importer_mesh_instance_3d.h" |
| 36 | #include "scene/3d/node_3d.h" |
| 37 | #include "scene/resources/3d/importer_mesh.h" |
| 38 | #include "scene/resources/mesh.h" |
| 39 | #include "scene/resources/surface_tool.h" |
| 40 | |
| 41 | static Error _parse_material_library(const String &p_path, HashMap<String, Ref<StandardMaterial3D>> &material_map, List<String> *r_missing_deps) { |
| 42 | Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); |
| 43 | ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Couldn't open MTL file '%s', it may not exist or not be readable.", p_path)); |
| 44 | |
| 45 | Ref<StandardMaterial3D> current; |
| 46 | String current_name; |
| 47 | String base_path = p_path.get_base_dir(); |
| 48 | while (true) { |
| 49 | String l = f->get_line().strip_edges(); |
| 50 | |
| 51 | if (l.begins_with("newmtl ")) { |
| 52 | // Start of a new material. |
| 53 | current_name = l.replace("newmtl", "").strip_edges(); |
| 54 | current.instantiate(); |
| 55 | current->set_name(current_name); |
| 56 | material_map[current_name] = current; |
| 57 | } else if (l.begins_with("Ka ")) { |
| 58 | // Ambient color. |
| 59 | WARN_PRINT("OBJ: Ambient light for material '" + current_name + "' is ignored in PBR"); |
| 60 | |
| 61 | } else if (l.begins_with("Kd ")) { |
| 62 | // Diffuse color. |
| 63 | ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT); |
| 64 | Vector<String> v = l.split(" ", false); |
| 65 | ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA); |
| 66 | Color c = current->get_albedo(); |
| 67 | c.r = v[1].to_float(); |
| 68 | c.g = v[2].to_float(); |
| 69 | c.b = v[3].to_float(); |
| 70 | current->set_albedo(c); |
| 71 | } else if (l.begins_with("Ks ")) { |
| 72 | // Specular color. |
| 73 | ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT); |
| 74 | Vector<String> v = l.split(" ", false); |
| 75 | ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA); |
| 76 | float r = v[1].to_float(); |
| 77 | float g = v[2].to_float(); |
| 78 | float b = v[3].to_float(); |
| 79 | float metalness = MAX(r, MAX(g, b)); |
| 80 | current->set_metallic(metalness); |
| 81 | } else if (l.begins_with("Ns ")) { |
| 82 | // Specular exponent. |
| 83 | ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT); |
| 84 | Vector<String> v = l.split(" ", false); |
| 85 | ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA); |
| 86 | float s = v[1].to_float(); |
| 87 | current->set_metallic((1000.0 - s) / 1000.0); |
| 88 | } else if (l.begins_with("d ")) { |
| 89 | // Dissolve (1.0 is fully opaque, 0.0 is completely transparent). |
| 90 | ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT); |
| 91 | Vector<String> v = l.split(" ", false); |
| 92 | ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA); |
| 93 | float d = v[1].to_float(); |
| 94 | Color c = current->get_albedo(); |
| 95 | c.a = d; |
| 96 | current->set_albedo(c); |
| 97 | if (c.a < 0.99) { |
| 98 | current->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); |
| 99 | } |
| 100 | } else if (l.begins_with("Tr ")) { |
| 101 | // Transparency (1.0 is completely transparent, 0.0 is fully opaque). |
| 102 | ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT); |
| 103 | Vector<String> v = l.split(" ", false); |
| 104 | ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA); |
| 105 | float d = v[1].to_float(); |
| 106 | Color c = current->get_albedo(); |
| 107 | c.a = 1.0 - d; |
| 108 | current->set_albedo(c); |
| 109 | if (c.a < 0.99) { |
| 110 | current->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); |
| 111 | } |
| 112 | |
| 113 | } else if (l.begins_with("map_Ka ")) { |
| 114 | // Ambient texture map. |
| 115 | WARN_PRINT("OBJ: Ambient light texture for material '" + current_name + "' is ignored in PBR"); |
| 116 | |
| 117 | } else if (l.begins_with("map_Kd ")) { |
| 118 | // Diffuse texture map. |
| 119 | ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT); |
| 120 | |
| 121 | String p = l.replace("map_Kd", "").replace_char('\\', '/').strip_edges(); |
| 122 | String path; |
| 123 | if (p.is_absolute_path()) { |
| 124 | path = p; |
| 125 | } else { |
| 126 | path = base_path.path_join(p); |
| 127 | } |
| 128 | |
| 129 | Ref<Texture2D> texture = ResourceLoader::load(path); |
| 130 | |
| 131 | if (texture.is_valid()) { |
| 132 | current->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, texture); |
| 133 | } else if (r_missing_deps) { |
| 134 | r_missing_deps->push_back(path); |
| 135 | } |
| 136 | |
| 137 | } else if (l.begins_with("map_Ks ")) { |
| 138 | // Specular color texture map. |
| 139 | ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT); |
| 140 | |
| 141 | String p = l.replace("map_Ks", "").replace_char('\\', '/').strip_edges(); |
| 142 | String path; |
| 143 | if (p.is_absolute_path()) { |
| 144 | path = p; |
| 145 | } else { |
| 146 | path = base_path.path_join(p); |
| 147 | } |
| 148 | |
| 149 | Ref<Texture2D> texture = ResourceLoader::load(path); |
| 150 | |
| 151 | if (texture.is_valid()) { |
| 152 | current->set_texture(StandardMaterial3D::TEXTURE_METALLIC, texture); |
| 153 | } else if (r_missing_deps) { |
| 154 | r_missing_deps->push_back(path); |
| 155 | } |
| 156 | |
| 157 | } else if (l.begins_with("map_Ns ")) { |
| 158 | // Specular exponent texture map. |
| 159 | ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT); |
| 160 | |
| 161 | String p = l.replace("map_Ns", "").replace_char('\\', '/').strip_edges(); |
| 162 | String path; |
| 163 | if (p.is_absolute_path()) { |
| 164 | path = p; |
| 165 | } else { |
| 166 | path = base_path.path_join(p); |
| 167 | } |
| 168 | |
| 169 | Ref<Texture2D> texture = ResourceLoader::load(path); |
| 170 | |
| 171 | if (texture.is_valid()) { |
| 172 | current->set_texture(StandardMaterial3D::TEXTURE_ROUGHNESS, texture); |
| 173 | } else if (r_missing_deps) { |
| 174 | r_missing_deps->push_back(path); |
| 175 | } |
| 176 | } else if (l.begins_with("map_bump ") || l.begins_with("map_Bump ")) { |
| 177 | // Bump texture map. |
| 178 | ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT); |
| 179 | |
| 180 | l = l.begins_with("map_bump ") ? l.trim_prefix("map_bump ") : l.trim_prefix("map_Bump "); |
| 181 | l = l.strip_edges(); |
| 182 | |
| 183 | // Read path and optional bump multiplier. |
| 184 | String p; |
| 185 | float bm = 1.0; |
| 186 | int bm_pos = l.find("-bm "); |
| 187 | if (bm_pos >= 0) { |
| 188 | int bm_start = bm_pos + 4; |
| 189 | int bm_end = l.find_char(' ', bm_start); |
| 190 | if (bm_end >= 0) { |
| 191 | bm = l.substr(bm_start, bm_end - bm_start).to_float(); |
| 192 | p = l.substr(bm_end + 1); |
| 193 | } else { // Bump multiplier ends at end of line. |
| 194 | bm = l.substr(bm_start).to_float(); |
| 195 | p = l.substr(0, bm_pos); |
| 196 | } |
| 197 | } else { |
| 198 | p = l; |
| 199 | } |
| 200 | |
| 201 | String path = base_path.path_join(p.replace_char('\\', '/').strip_edges()); |
| 202 | |
| 203 | Ref<Texture2D> texture = ResourceLoader::load(path); |
| 204 | |
| 205 | if (texture.is_valid()) { |
| 206 | current->set_feature(StandardMaterial3D::FEATURE_NORMAL_MAPPING, true); |
| 207 | current->set_texture(StandardMaterial3D::TEXTURE_NORMAL, texture); |
| 208 | current->set_normal_scale(bm); |
| 209 | } else if (r_missing_deps) { |
| 210 | r_missing_deps->push_back(path); |
| 211 | } |
| 212 | } else if (f->eof_reached()) { |
| 213 | break; |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | return OK; |
| 218 | } |
| 219 | |
| 220 | static Error _parse_obj(const String &p_path, List<Ref<ImporterMesh>> &r_meshes, bool p_single_mesh, bool p_generate_tangents, bool p_generate_lods, bool p_generate_shadow_mesh, bool p_generate_lightmap_uv2, float p_generate_lightmap_uv2_texel_size, const PackedByteArray &p_src_lightmap_cache, Vector3 p_scale_mesh, Vector3 p_offset_mesh, bool p_disable_compression, Vector<Vector<uint8_t>> &r_lightmap_caches, List<String> *r_missing_deps) { |
| 221 | Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); |
| 222 | ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Couldn't open OBJ file '%s', it may not exist or not be readable.", p_path)); |
| 223 | |
| 224 | // Avoid trying to load/interpret potential build artifacts from Visual Studio (e.g. when compiling native plugins inside the project tree). |
| 225 | // This should only match if it's indeed a COFF file header. |
| 226 | // https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#machine-types |
| 227 | const int first_bytes = f->get_16(); |
| 228 | static const Vector<int> coff_header_machines{ |
| 229 | 0x0, // IMAGE_FILE_MACHINE_UNKNOWN |
| 230 | 0x8664, // IMAGE_FILE_MACHINE_AMD64 |
| 231 | 0x1c0, // IMAGE_FILE_MACHINE_ARM |
| 232 | 0x14c, // IMAGE_FILE_MACHINE_I386 |
| 233 | 0x200, // IMAGE_FILE_MACHINE_IA64 |
| 234 | }; |
| 235 | ERR_FAIL_COND_V_MSG(coff_header_machines.has(first_bytes), ERR_FILE_CORRUPT, vformat("Couldn't read OBJ file '%s', it seems to be binary, corrupted, or empty.", p_path)); |
| 236 | f->seek(0); |
| 237 | |
| 238 | Ref<ImporterMesh> mesh; |
| 239 | mesh.instantiate(); |
| 240 | |
| 241 | bool generate_tangents = p_generate_tangents; |
| 242 | Vector3 scale_mesh = p_scale_mesh; |
| 243 | Vector3 offset_mesh = p_offset_mesh; |
| 244 | |
| 245 | Vector<Vector3> vertices; |
| 246 | Vector<Vector3> normals; |
| 247 | Vector<Vector2> uvs; |
| 248 | Vector<Color> colors; |
| 249 | const String default_name = "Mesh"; |
| 250 | String name = default_name; |
| 251 | |
| 252 | HashMap<String, HashMap<String, Ref<StandardMaterial3D>>> material_map; |
| 253 | |
| 254 | Ref<SurfaceTool> surf_tool = memnew(SurfaceTool); |
| 255 | surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES); |
| 256 | |
| 257 | String current_material_library; |
| 258 | String current_material; |
| 259 | String current_group; |
| 260 | uint32_t smooth_group = 0; |
| 261 | bool smoothing = true; |
| 262 | const uint32_t no_smoothing_smooth_group = (uint32_t)-1; |
| 263 | |
| 264 | bool uses_uvs = false; |
| 265 | |
| 266 | while (true) { |
| 267 | String l = f->get_line().strip_edges(); |
| 268 | while (l.length() && l[l.length() - 1] == '\\') { |
| 269 | String add = f->get_line().strip_edges(); |
| 270 | l += add; |
| 271 | if (add.is_empty()) { |
| 272 | break; |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | if (l.begins_with("v ")) { |
| 277 | //vertex |
| 278 | Vector<String> v = l.split(" ", false); |
| 279 | ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT); |
| 280 | Vector3 vtx; |
| 281 | vtx.x = v[1].to_float() * scale_mesh.x + offset_mesh.x; |
| 282 | vtx.y = v[2].to_float() * scale_mesh.y + offset_mesh.y; |
| 283 | vtx.z = v[3].to_float() * scale_mesh.z + offset_mesh.z; |
| 284 | vertices.push_back(vtx); |
| 285 | //vertex color |
| 286 | if (v.size() >= 7) { |
| 287 | while (colors.size() < vertices.size() - 1) { |
| 288 | colors.push_back(Color(1.0, 1.0, 1.0)); |
| 289 | } |
| 290 | Color c; |
| 291 | c.r = v[4].to_float(); |
| 292 | c.g = v[5].to_float(); |
| 293 | c.b = v[6].to_float(); |
| 294 | colors.push_back(c); |
| 295 | } else if (!colors.is_empty()) { |
| 296 | colors.push_back(Color(1.0, 1.0, 1.0)); |
| 297 | } |
| 298 | } else if (l.begins_with("vt ")) { |
| 299 | //uv |
| 300 | Vector<String> v = l.split(" ", false); |
| 301 | ERR_FAIL_COND_V(v.size() < 3, ERR_FILE_CORRUPT); |
| 302 | Vector2 uv; |
| 303 | uv.x = v[1].to_float(); |
| 304 | uv.y = 1.0 - v[2].to_float(); |
| 305 | uvs.push_back(uv); |
| 306 | } else if (l.begins_with("vn ")) { |
| 307 | //normal |
| 308 | Vector<String> v = l.split(" ", false); |
| 309 | ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT); |
| 310 | Vector3 nrm; |
| 311 | nrm.x = v[1].to_float(); |
| 312 | nrm.y = v[2].to_float(); |
| 313 | nrm.z = v[3].to_float(); |
| 314 | normals.push_back(nrm); |
| 315 | } else if (l.begins_with("f ")) { |
| 316 | //vertex |
| 317 | |
| 318 | Vector<String> v = l.split(" ", false); |
| 319 | ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT); |
| 320 | |
| 321 | //not very fast, could be sped up |
| 322 | |
| 323 | Vector<String> face[3]; |
| 324 | face[0] = v[1].split("/"); |
| 325 | face[1] = v[2].split("/"); |
| 326 | ERR_FAIL_COND_V(face[0].is_empty(), ERR_FILE_CORRUPT); |
| 327 | |
| 328 | ERR_FAIL_COND_V(face[0].size() != face[1].size(), ERR_FILE_CORRUPT); |
| 329 | for (int i = 2; i < v.size() - 1; i++) { |
| 330 | face[2] = v[i + 1].split("/"); |
| 331 | |
| 332 | ERR_FAIL_COND_V(face[0].size() != face[2].size(), ERR_FILE_CORRUPT); |
| 333 | for (int j = 0; j < 3; j++) { |
| 334 | int idx = j; |
| 335 | |
| 336 | if (idx < 2) { |
| 337 | idx = 1 ^ idx; |
| 338 | } |
| 339 | |
| 340 | // Check UVs before faces as we may need to generate dummy tangents if there are no UVs. |
| 341 | if (face[idx].size() >= 2 && !face[idx][1].is_empty()) { |
| 342 | int uv = face[idx][1].to_int() - 1; |
| 343 | if (uv < 0) { |
| 344 | uv += uvs.size() + 1; |
| 345 | } |
| 346 | ERR_FAIL_INDEX_V(uv, uvs.size(), ERR_FILE_CORRUPT); |
| 347 | surf_tool->set_uv(uvs[uv]); |
| 348 | uses_uvs = true; |
| 349 | } |
| 350 | |
| 351 | if (face[idx].size() == 3) { |
| 352 | int norm = face[idx][2].to_int() - 1; |
| 353 | if (norm < 0) { |
| 354 | norm += normals.size() + 1; |
| 355 | } |
| 356 | ERR_FAIL_INDEX_V(norm, normals.size(), ERR_FILE_CORRUPT); |
| 357 | surf_tool->set_normal(normals[norm]); |
| 358 | if (generate_tangents && !uses_uvs) { |
| 359 | // We can't generate tangents without UVs, so create dummy tangents. |
| 360 | Vector3 tan = Vector3(normals[norm].z, -normals[norm].x, normals[norm].y).cross(normals[norm].normalized()).normalized(); |
| 361 | surf_tool->set_tangent(Plane(tan.x, tan.y, tan.z, 1.0)); |
| 362 | } |
| 363 | } else { |
| 364 | // No normals, use a dummy tangent since normals and tangents will be generated. |
| 365 | if (generate_tangents && !uses_uvs) { |
| 366 | // We can't generate tangents without UVs, so create dummy tangents. |
| 367 | surf_tool->set_tangent(Plane(1.0, 0.0, 0.0, 1.0)); |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | int vtx = face[idx][0].to_int() - 1; |
| 372 | if (vtx < 0) { |
| 373 | vtx += vertices.size() + 1; |
| 374 | } |
| 375 | ERR_FAIL_INDEX_V(vtx, vertices.size(), ERR_FILE_CORRUPT); |
| 376 | |
| 377 | Vector3 vertex = vertices[vtx]; |
| 378 | if (!colors.is_empty()) { |
| 379 | surf_tool->set_color(colors[vtx]); |
| 380 | } |
| 381 | surf_tool->set_smooth_group(smoothing ? smooth_group : no_smoothing_smooth_group); |
| 382 | surf_tool->add_vertex(vertex); |
| 383 | } |
| 384 | |
| 385 | face[1] = face[2]; |
| 386 | } |
| 387 | } else if (l.begins_with("s ")) { //smoothing |
| 388 | String what = l.substr(2).strip_edges(); |
| 389 | bool do_smooth; |
| 390 | if (what == "off") { |
| 391 | do_smooth = false; |
| 392 | } else { |
| 393 | do_smooth = true; |
| 394 | } |
| 395 | if (do_smooth != smoothing) { |
| 396 | smoothing = do_smooth; |
| 397 | if (smoothing) { |
| 398 | smooth_group++; |
| 399 | } |
| 400 | } |
| 401 | } else if (/*l.begins_with("g ") ||*/ l.begins_with("usemtl ") || (l.begins_with("o ") || f->eof_reached())) { //commit group to mesh |
| 402 | uint64_t mesh_flags = RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES; |
| 403 | |
| 404 | if (p_disable_compression) { |
| 405 | mesh_flags = 0; |
| 406 | } else { |
| 407 | bool is_mesh_2d = true; |
| 408 | |
| 409 | // Disable compression if all z equals 0 (the mesh is 2D). |
| 410 | for (int i = 0; i < vertices.size(); i++) { |
| 411 | if (!Math::is_zero_approx(vertices[i].z)) { |
| 412 | is_mesh_2d = false; |
| 413 | break; |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | if (is_mesh_2d) { |
| 418 | mesh_flags = 0; |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | //groups are too annoying |
| 423 | if (surf_tool->get_vertex_array().size()) { |
| 424 | //another group going on, commit it |
| 425 | if (normals.is_empty()) { |
| 426 | surf_tool->generate_normals(); |
| 427 | } |
| 428 | |
| 429 | if (generate_tangents && uses_uvs) { |
| 430 | surf_tool->generate_tangents(); |
| 431 | } |
| 432 | |
| 433 | surf_tool->index(); |
| 434 | |
| 435 | print_verbose("OBJ: Current material library " + current_material_library + " has " + itos(material_map.has(current_material_library))); |
| 436 | print_verbose("OBJ: Current material " + current_material + " has " + itos(material_map.has(current_material_library) && material_map[current_material_library].has(current_material))); |
| 437 | Ref<StandardMaterial3D> material; |
| 438 | if (material_map.has(current_material_library) && material_map[current_material_library].has(current_material)) { |
| 439 | material = material_map[current_material_library][current_material]; |
| 440 | if (!colors.is_empty()) { |
| 441 | material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); |
| 442 | } |
| 443 | surf_tool->set_material(material); |
| 444 | } |
| 445 | |
| 446 | Array array = surf_tool->commit_to_arrays(); |
| 447 | |
| 448 | if (mesh_flags & RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES && generate_tangents && uses_uvs) { |
| 449 | // Compression is enabled, so let's validate that the normals and generated tangents are correct. |
| 450 | Vector<Vector3> norms = array[Mesh::ARRAY_NORMAL]; |
| 451 | Vector<float> tangents = array[Mesh::ARRAY_TANGENT]; |
| 452 | ERR_FAIL_COND_V(tangents.is_empty(), ERR_FILE_CORRUPT); |
| 453 | for (int vert = 0; vert < norms.size(); vert++) { |
| 454 | Vector3 tan = Vector3(tangents[vert * 4 + 0], tangents[vert * 4 + 1], tangents[vert * 4 + 2]); |
| 455 | if (std::abs(tan.dot(norms[vert])) > 0.0001) { |
| 456 | // Tangent is not perpendicular to the normal, so we can't use compression. |
| 457 | mesh_flags &= ~RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES; |
| 458 | } |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES, array, TypedArray<Array>(), Dictionary(), material, name, mesh_flags); |
| 463 | |
| 464 | print_verbose("OBJ: Added surface :" + mesh->get_surface_name(mesh->get_surface_count() - 1)); |
| 465 | |
| 466 | if (!current_material.is_empty()) { |
| 467 | if (mesh->get_surface_count() >= 1) { |
| 468 | mesh->set_surface_name(mesh->get_surface_count() - 1, current_material.get_basename()); |
| 469 | } |
| 470 | } else if (!current_group.is_empty()) { |
| 471 | if (mesh->get_surface_count() >= 1) { |
| 472 | mesh->set_surface_name(mesh->get_surface_count() - 1, current_group); |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | surf_tool->clear(); |
| 477 | surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES); |
| 478 | uses_uvs = false; |
| 479 | } |
| 480 | |
| 481 | if (l.begins_with("o ") || f->eof_reached()) { |
| 482 | if (!p_single_mesh) { |
| 483 | if (mesh->get_surface_count() > 0) { |
| 484 | mesh->set_name(name); |
| 485 | r_meshes.push_back(mesh); |
| 486 | mesh.instantiate(); |
| 487 | } |
| 488 | name = default_name; |
| 489 | current_group = ""; |
| 490 | current_material = ""; |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | if (f->eof_reached()) { |
| 495 | break; |
| 496 | } |
| 497 | |
| 498 | if (l.begins_with("o ")) { |
| 499 | name = l.substr(2).strip_edges(); |
| 500 | } |
| 501 | |
| 502 | if (l.begins_with("usemtl ")) { |
| 503 | current_material = l.replace("usemtl", "").strip_edges(); |
| 504 | } |
| 505 | |
| 506 | if (l.begins_with("g ")) { |
| 507 | current_group = l.substr(2).strip_edges(); |
| 508 | } |
| 509 | |
| 510 | } else if (l.begins_with("mtllib ")) { //parse material |
| 511 | |
| 512 | current_material_library = l.replace("mtllib", "").strip_edges(); |
| 513 | if (!material_map.has(current_material_library)) { |
| 514 | HashMap<String, Ref<StandardMaterial3D>> lib; |
| 515 | String lib_path = current_material_library; |
| 516 | if (lib_path.is_relative_path()) { |
| 517 | lib_path = p_path.get_base_dir().path_join(current_material_library); |
| 518 | } |
| 519 | Error err = _parse_material_library(lib_path, lib, r_missing_deps); |
| 520 | if (err == OK) { |
| 521 | material_map[current_material_library] = lib; |
| 522 | } |
| 523 | } |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | if (p_generate_lightmap_uv2) { |
| 528 | Vector<uint8_t> lightmap_cache; |
| 529 | mesh->lightmap_unwrap_cached(Transform3D(), p_generate_lightmap_uv2_texel_size, p_src_lightmap_cache, lightmap_cache); |
| 530 | |
| 531 | if (!lightmap_cache.is_empty()) { |
| 532 | if (r_lightmap_caches.is_empty()) { |
| 533 | r_lightmap_caches.push_back(lightmap_cache); |
| 534 | } else { |
| 535 | // MD5 is stored at the beginning of the cache data. |
| 536 | const String new_md5 = String::md5(lightmap_cache.ptr()); |
| 537 | |
| 538 | for (int i = 0; i < r_lightmap_caches.size(); i++) { |
| 539 | const String md5 = String::md5(r_lightmap_caches[i].ptr()); |
| 540 | if (new_md5 < md5) { |
| 541 | r_lightmap_caches.insert(i, lightmap_cache); |
| 542 | break; |
| 543 | } |
| 544 | |
| 545 | if (new_md5 == md5) { |
| 546 | break; |
| 547 | } |
| 548 | } |
| 549 | } |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | if (p_generate_lods) { |
| 554 | // Use normal merge/split angles that match the defaults used for 3D scene importing. |
| 555 | mesh->generate_lods(60.0f, {}); |
| 556 | } |
| 557 | |
| 558 | if (p_generate_shadow_mesh) { |
| 559 | mesh->create_shadow_mesh(); |
| 560 | } |
| 561 | |
| 562 | mesh->optimize_indices(); |
| 563 | |
| 564 | if (p_single_mesh && mesh->get_surface_count() > 0) { |
| 565 | r_meshes.push_back(mesh); |
| 566 | } |
| 567 | |
| 568 | return OK; |
| 569 | } |
| 570 | |
| 571 | Node *EditorOBJImporter::import_scene(const String &p_path, uint32_t p_flags, const HashMap<StringName, Variant> &p_options, List<String> *r_missing_deps, Error *r_err) { |
| 572 | List<Ref<ImporterMesh>> meshes; |
| 573 | |
| 574 | // LOD, shadow mesh and lightmap UV2 generation are handled by ResourceImporterScene in this case, |
| 575 | // so disable it within the OBJ mesh import. |
| 576 | Vector<Vector<uint8_t>> mesh_lightmap_caches; |
| 577 | Error err = _parse_obj(p_path, meshes, false, p_flags & IMPORT_GENERATE_TANGENT_ARRAYS, false, false, false, 0.2, PackedByteArray(), Vector3(1, 1, 1), Vector3(0, 0, 0), p_flags & IMPORT_FORCE_DISABLE_MESH_COMPRESSION, mesh_lightmap_caches, r_missing_deps); |
| 578 | |
| 579 | if (err != OK) { |
| 580 | if (r_err) { |
| 581 | *r_err = err; |
| 582 | } |
| 583 | return nullptr; |
| 584 | } |
| 585 | |
| 586 | Node3D *scene = memnew(Node3D); |
| 587 | |
| 588 | for (Ref<ImporterMesh> m : meshes) { |
| 589 | ImporterMeshInstance3D *mi = memnew(ImporterMeshInstance3D); |
| 590 | mi->set_mesh(m); |
| 591 | mi->set_name(m->get_name()); |
| 592 | scene->add_child(mi, true); |
| 593 | mi->set_owner(scene); |
| 594 | } |
| 595 | |
| 596 | if (r_err) { |
| 597 | *r_err = OK; |
| 598 | } |
| 599 | |
| 600 | return scene; |
| 601 | } |
| 602 | |
| 603 | void EditorOBJImporter::get_extensions(List<String> *r_extensions) const { |
| 604 | r_extensions->push_back("obj"); |
| 605 | } |
| 606 | |
| 607 | //////////////////////////////////////////////////// |
| 608 | |
| 609 | String ResourceImporterOBJ::get_importer_name() const { |
| 610 | return "wavefront_obj"; |
| 611 | } |
| 612 | |
| 613 | String ResourceImporterOBJ::get_visible_name() const { |
| 614 | return "OBJ as Mesh"; |
| 615 | } |
| 616 | |
| 617 | void ResourceImporterOBJ::get_recognized_extensions(List<String> *p_extensions) const { |
| 618 | p_extensions->push_back("obj"); |
| 619 | } |
| 620 | |
| 621 | String ResourceImporterOBJ::get_save_extension() const { |
| 622 | return "mesh"; |
| 623 | } |
| 624 | |
| 625 | String ResourceImporterOBJ::get_resource_type() const { |
| 626 | return "Mesh"; |
| 627 | } |
| 628 | |
| 629 | int ResourceImporterOBJ::get_format_version() const { |
| 630 | return 1; |
| 631 | } |
| 632 | |
| 633 | int ResourceImporterOBJ::get_preset_count() const { |
| 634 | return 0; |
| 635 | } |
| 636 | |
| 637 | String ResourceImporterOBJ::get_preset_name(int p_idx) const { |
| 638 | return ""; |
| 639 | } |
| 640 | |
| 641 | void ResourceImporterOBJ::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const { |
| 642 | r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_tangents"), true)); |
| 643 | r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_lods"), true)); |
| 644 | r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_shadow_mesh"), true)); |
| 645 | r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_lightmap_uv2", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false)); |
| 646 | r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "generate_lightmap_uv2_texel_size", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 0.2)); |
| 647 | r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "scale_mesh"), Vector3(1, 1, 1))); |
| 648 | r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "offset_mesh"), Vector3(0, 0, 0))); |
| 649 | r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "force_disable_mesh_compression"), false)); |
| 650 | } |
| 651 | |
| 652 | bool ResourceImporterOBJ::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const { |
| 653 | if (p_option == "generate_lightmap_uv2_texel_size" && !p_options["generate_lightmap_uv2"]) { |
| 654 | // Only display the lightmap texel size import option when lightmap UV2 generation is enabled. |
| 655 | return false; |
| 656 | } |
| 657 | |
| 658 | return true; |
| 659 | } |
| 660 | |
| 661 | Error ResourceImporterOBJ::import(ResourceUID::ID p_source_id, const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) { |
| 662 | List<Ref<ImporterMesh>> meshes; |
| 663 | |
| 664 | Vector<uint8_t> src_lightmap_cache; |
| 665 | Vector<Vector<uint8_t>> mesh_lightmap_caches; |
| 666 | |
| 667 | Error err; |
| 668 | { |
| 669 | src_lightmap_cache = FileAccess::get_file_as_bytes(p_source_file + ".unwrap_cache", &err); |
| 670 | if (err != OK) { |
| 671 | src_lightmap_cache.clear(); |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | err = _parse_obj(p_source_file, meshes, true, p_options["generate_tangents"], p_options["generate_lods"], p_options["generate_shadow_mesh"], p_options["generate_lightmap_uv2"], p_options["generate_lightmap_uv2_texel_size"], src_lightmap_cache, p_options["scale_mesh"], p_options["offset_mesh"], p_options["force_disable_mesh_compression"], mesh_lightmap_caches, nullptr); |
| 676 | |
| 677 | if (mesh_lightmap_caches.size()) { |
| 678 | Ref<FileAccess> f = FileAccess::open(p_source_file + ".unwrap_cache", FileAccess::WRITE); |
| 679 | if (f.is_valid()) { |
| 680 | f->store_32(mesh_lightmap_caches.size()); |
| 681 | for (int i = 0; i < mesh_lightmap_caches.size(); i++) { |
| 682 | String md5 = String::md5(mesh_lightmap_caches[i].ptr()); |
| 683 | f->store_buffer(mesh_lightmap_caches[i].ptr(), mesh_lightmap_caches[i].size()); |
| 684 | } |
| 685 | } |
| 686 | } |
| 687 | err = OK; |
| 688 | |
| 689 | ERR_FAIL_COND_V(err != OK, err); |
| 690 | ERR_FAIL_COND_V(meshes.size() != 1, ERR_BUG); |
| 691 | |
| 692 | String save_path = p_save_path + ".mesh"; |
| 693 | |
| 694 | err = ResourceSaver::save(meshes.front()->get()->get_mesh(), save_path); |
| 695 | |
| 696 | ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save Mesh to file '" + save_path + "'."); |
| 697 | |
| 698 | r_gen_files->push_back(save_path); |
| 699 | |
| 700 | return OK; |
| 701 | } |