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