resource_importer_obj.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. #include "resource_importer_obj.h"
  31. #include "core/io/resource_saver.h"
  32. #include "core/os/file_access.h"
  33. #include "scene/3d/mesh_instance.h"
  34. #include "scene/3d/spatial.h"
  35. #include "scene/resources/mesh.h"
  36. #include "scene/resources/surface_tool.h"
  37. uint32_t EditorOBJImporter::get_import_flags() const {
  38. return IMPORT_SCENE;
  39. }
  40. static Error _parse_material_library(const String &p_path, Map<String, Ref<Material3D>> &material_map, List<String> *r_missing_deps) {
  41. FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
  42. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Couldn't open MTL file '%s', it may not exist or not be readable.", p_path));
  43. Ref<SpatialMaterial> current;
  44. String current_name;
  45. String base_path = p_path.get_base_dir();
  46. while (true) {
  47. String l = f->get_line().strip_edges();
  48. if (l.begins_with("newmtl ")) {
  49. //vertex
  50. current_name = l.replace("newmtl", "").strip_edges();
  51. current.instance();
  52. current->set_name(current_name);
  53. material_map[current_name] = current;
  54. } else if (l.begins_with("Ka ")) {
  55. //uv
  56. WARN_PRINT("OBJ: Ambient light for material '" + current_name + "' is ignored in PBR");
  57. } else if (l.begins_with("Kd ")) {
  58. //normal
  59. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  60. Vector<String> v = l.split(" ", false);
  61. ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
  62. Color c = current->get_albedo();
  63. c.r = v[1].to_float();
  64. c.g = v[2].to_float();
  65. c.b = v[3].to_float();
  66. current->set_albedo(c);
  67. } else if (l.begins_with("Ks ")) {
  68. //normal
  69. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  70. Vector<String> v = l.split(" ", false);
  71. ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
  72. float r = v[1].to_float();
  73. float g = v[2].to_float();
  74. float b = v[3].to_float();
  75. float metalness = MAX(r, MAX(g, b));
  76. current->set_metallic(metalness);
  77. } else if (l.begins_with("Ns ")) {
  78. //normal
  79. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  80. Vector<String> v = l.split(" ", false);
  81. ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
  82. float s = v[1].to_float();
  83. current->set_metallic((1000.0 - s) / 1000.0);
  84. } else if (l.begins_with("d ")) {
  85. //normal
  86. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  87. Vector<String> v = l.split(" ", false);
  88. ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
  89. float d = v[1].to_float();
  90. Color c = current->get_albedo();
  91. c.a = d;
  92. current->set_albedo(c);
  93. if (c.a < 0.99) {
  94. current->set_feature(Material3D::FEATURE_TRANSPARENT, true);
  95. }
  96. } else if (l.begins_with("Tr ")) {
  97. //normal
  98. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  99. Vector<String> v = l.split(" ", false);
  100. ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
  101. float d = v[1].to_float();
  102. Color c = current->get_albedo();
  103. c.a = 1.0 - d;
  104. current->set_albedo(c);
  105. if (c.a < 0.99) {
  106. current->set_feature(Material3D::FEATURE_TRANSPARENT, true);
  107. }
  108. } else if (l.begins_with("map_Ka ")) {
  109. //uv
  110. WARN_PRINT("OBJ: Ambient light texture for material '" + current_name + "' is ignored in PBR");
  111. } else if (l.begins_with("map_Kd ")) {
  112. //normal
  113. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  114. String p = l.replace("map_Kd", "").replace("\\", "/").strip_edges();
  115. String path;
  116. if (p.is_abs_path()) {
  117. path = p;
  118. } else {
  119. path = base_path.plus_file(p);
  120. }
  121. Ref<Texture> texture = ResourceLoader::load(path);
  122. if (texture.is_valid()) {
  123. current->set_texture(Material3D::TEXTURE_ALBEDO, texture);
  124. } else if (r_missing_deps) {
  125. r_missing_deps->push_back(path);
  126. }
  127. } else if (l.begins_with("map_Ks ")) {
  128. //normal
  129. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  130. String p = l.replace("map_Ks", "").replace("\\", "/").strip_edges();
  131. String path;
  132. if (p.is_abs_path()) {
  133. path = p;
  134. } else {
  135. path = base_path.plus_file(p);
  136. }
  137. Ref<Texture> texture = ResourceLoader::load(path);
  138. if (texture.is_valid()) {
  139. current->set_texture(Material3D::TEXTURE_METALLIC, texture);
  140. } else if (r_missing_deps) {
  141. r_missing_deps->push_back(path);
  142. }
  143. } else if (l.begins_with("map_Ns ")) {
  144. //normal
  145. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  146. String p = l.replace("map_Ns", "").replace("\\", "/").strip_edges();
  147. String path;
  148. if (p.is_abs_path()) {
  149. path = p;
  150. } else {
  151. path = base_path.plus_file(p);
  152. }
  153. Ref<Texture> texture = ResourceLoader::load(path);
  154. if (texture.is_valid()) {
  155. current->set_texture(Material3D::TEXTURE_ROUGHNESS, texture);
  156. } else if (r_missing_deps) {
  157. r_missing_deps->push_back(path);
  158. }
  159. } else if (l.begins_with("map_bump ")) {
  160. //normal
  161. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  162. String p = l.replace("map_bump", "").replace("\\", "/").strip_edges();
  163. String path = base_path.plus_file(p);
  164. Ref<Texture> texture = ResourceLoader::load(path);
  165. if (texture.is_valid()) {
  166. current->set_feature(Material3D::FEATURE_NORMAL_MAPPING, true);
  167. current->set_texture(Material3D::TEXTURE_NORMAL, texture);
  168. } else if (r_missing_deps) {
  169. r_missing_deps->push_back(path);
  170. }
  171. } else if (f->eof_reached()) {
  172. break;
  173. }
  174. }
  175. return OK;
  176. }
  177. static Error _parse_obj(const String &p_path, List<Ref<Mesh>> &r_meshes, bool p_single_mesh, bool p_generate_tangents, int p_compress_flags, Vector3 p_scale_mesh, Vector3 p_offset_mesh, List<String> *r_missing_deps) {
  178. FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
  179. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Couldn't open OBJ file '%s', it may not exist or not be readable.", p_path));
  180. Ref<ArrayMesh> mesh;
  181. mesh.instance();
  182. bool generate_tangents = p_generate_tangents;
  183. Vector3 scale_mesh = p_scale_mesh;
  184. Vector3 offset_mesh = p_offset_mesh;
  185. Vector<Vector3> vertices;
  186. Vector<Vector3> normals;
  187. Vector<Vector2> uvs;
  188. Vector<Color> colors;
  189. String name;
  190. Map<String, Map<String, Ref<Material3D>>> material_map;
  191. Ref<SurfaceTool> surf_tool = memnew(SurfaceTool);
  192. surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
  193. String current_material_library;
  194. String current_material;
  195. String current_group;
  196. while (true) {
  197. String l = f->get_line().strip_edges();
  198. while (l.length() && l[l.length() - 1] == '\\') {
  199. String add = f->get_line().strip_edges();
  200. l += add;
  201. if (add == String()) {
  202. break;
  203. }
  204. }
  205. if (l.begins_with("v ")) {
  206. //vertex
  207. Vector<String> v = l.split(" ", false);
  208. ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
  209. Vector3 vtx;
  210. vtx.x = v[1].to_float() * scale_mesh.x + offset_mesh.x;
  211. vtx.y = v[2].to_float() * scale_mesh.y + offset_mesh.y;
  212. vtx.z = v[3].to_float() * scale_mesh.z + offset_mesh.z;
  213. vertices.push_back(vtx);
  214. //vertex colors
  215. if (v.size() >= 7) {
  216. while (colors.size() < vertices.size() - 1) {
  217. colors.push_back(Color(1.0, 1.0, 1.0));
  218. }
  219. Color c;
  220. c.r = v[4].to_float();
  221. c.g = v[5].to_float();
  222. c.b = v[6].to_float();
  223. colors.push_back(c);
  224. } else if (!colors.empty()) {
  225. colors.push_back(Color(1.0, 1.0, 1.0));
  226. }
  227. } else if (l.begins_with("vt ")) {
  228. //uv
  229. Vector<String> v = l.split(" ", false);
  230. ERR_FAIL_COND_V(v.size() < 3, ERR_FILE_CORRUPT);
  231. Vector2 uv;
  232. uv.x = v[1].to_float();
  233. uv.y = 1.0 - v[2].to_float();
  234. uvs.push_back(uv);
  235. } else if (l.begins_with("vn ")) {
  236. //normal
  237. Vector<String> v = l.split(" ", false);
  238. ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
  239. Vector3 nrm;
  240. nrm.x = v[1].to_float();
  241. nrm.y = v[2].to_float();
  242. nrm.z = v[3].to_float();
  243. normals.push_back(nrm);
  244. } else if (l.begins_with("f ")) {
  245. //vertex
  246. Vector<String> v = l.split(" ", false);
  247. ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
  248. //not very fast, could be sped up
  249. Vector<String> face[3];
  250. face[0] = v[1].split("/");
  251. face[1] = v[2].split("/");
  252. ERR_FAIL_COND_V(face[0].size() == 0, ERR_FILE_CORRUPT);
  253. ERR_FAIL_COND_V(face[0].size() != face[1].size(), ERR_FILE_CORRUPT);
  254. for (int i = 2; i < v.size() - 1; i++) {
  255. face[2] = v[i + 1].split("/");
  256. ERR_FAIL_COND_V(face[0].size() != face[2].size(), ERR_FILE_CORRUPT);
  257. for (int j = 0; j < 3; j++) {
  258. int idx = j;
  259. if (idx < 2) {
  260. idx = 1 ^ idx;
  261. }
  262. if (face[idx].size() == 3) {
  263. int norm = face[idx][2].to_int() - 1;
  264. if (norm < 0) {
  265. norm += normals.size() + 1;
  266. }
  267. ERR_FAIL_INDEX_V(norm, normals.size(), ERR_FILE_CORRUPT);
  268. surf_tool->add_normal(normals[norm]);
  269. }
  270. if (face[idx].size() >= 2 && face[idx][1] != String()) {
  271. int uv = face[idx][1].to_int() - 1;
  272. if (uv < 0) {
  273. uv += uvs.size() + 1;
  274. }
  275. ERR_FAIL_INDEX_V(uv, uvs.size(), ERR_FILE_CORRUPT);
  276. surf_tool->add_uv(uvs[uv]);
  277. }
  278. int vtx = face[idx][0].to_int() - 1;
  279. if (vtx < 0) {
  280. vtx += vertices.size() + 1;
  281. }
  282. ERR_FAIL_INDEX_V(vtx, vertices.size(), ERR_FILE_CORRUPT);
  283. Vector3 vertex = vertices[vtx];
  284. if (!colors.empty()) {
  285. surf_tool->add_color(colors[vtx]);
  286. }
  287. //if (weld_vertices)
  288. // vertex.snap(Vector3(weld_tolerance, weld_tolerance, weld_tolerance));
  289. surf_tool->add_vertex(vertex);
  290. }
  291. face[1] = face[2];
  292. }
  293. } else if (l.begins_with("s ")) { //smoothing
  294. String what = l.substr(2, l.length()).strip_edges();
  295. if (what == "off") {
  296. surf_tool->add_smooth_group(false);
  297. } else {
  298. surf_tool->add_smooth_group(true);
  299. }
  300. } else if (/*l.begins_with("g ") ||*/ l.begins_with("usemtl ") || (l.begins_with("o ") || f->eof_reached())) { //commit group to mesh
  301. //groups are too annoying
  302. if (surf_tool->get_vertex_array().size()) {
  303. //another group going on, commit it
  304. if (normals.size() == 0) {
  305. surf_tool->generate_normals();
  306. }
  307. if (generate_tangents && uvs.size()) {
  308. surf_tool->generate_tangents();
  309. }
  310. surf_tool->index();
  311. print_verbose("OBJ: Current material library " + current_material_library + " has " + itos(material_map.has(current_material_library)));
  312. print_verbose("OBJ: Current material " + current_material + " has " + itos(material_map.has(current_material_library) && material_map[current_material_library].has(current_material)));
  313. if (material_map.has(current_material_library) && material_map[current_material_library].has(current_material)) {
  314. Ref<Material3D> &material = material_map[current_material_library][current_material];
  315. if (!colors.empty()) {
  316. material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  317. }
  318. surf_tool->set_material(material);
  319. }
  320. mesh = surf_tool->commit(mesh, p_compress_flags);
  321. if (current_material != String()) {
  322. mesh->surface_set_name(mesh->get_surface_count() - 1, current_material.get_basename());
  323. } else if (current_group != String()) {
  324. mesh->surface_set_name(mesh->get_surface_count() - 1, current_group);
  325. }
  326. print_verbose("OBJ: Added surface :" + mesh->surface_get_name(mesh->get_surface_count() - 1));
  327. surf_tool->clear();
  328. surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
  329. }
  330. if (l.begins_with("o ") || f->eof_reached()) {
  331. if (!p_single_mesh) {
  332. mesh->set_name(name);
  333. r_meshes.push_back(mesh);
  334. mesh.instance();
  335. current_group = "";
  336. current_material = "";
  337. }
  338. }
  339. if (f->eof_reached()) {
  340. break;
  341. }
  342. if (l.begins_with("o ")) {
  343. name = l.substr(2, l.length()).strip_edges();
  344. }
  345. if (l.begins_with("usemtl ")) {
  346. current_material = l.replace("usemtl", "").strip_edges();
  347. }
  348. if (l.begins_with("g ")) {
  349. current_group = l.substr(2, l.length()).strip_edges();
  350. }
  351. } else if (l.begins_with("mtllib ")) { //parse material
  352. current_material_library = l.replace("mtllib", "").strip_edges();
  353. if (!material_map.has(current_material_library)) {
  354. Map<String, Ref<Material3D>> lib;
  355. String lib_path = current_material_library;
  356. if (lib_path.is_rel_path()) {
  357. lib_path = p_path.get_base_dir().plus_file(current_material_library);
  358. }
  359. Error err = _parse_material_library(lib_path, lib, r_missing_deps);
  360. if (err == OK) {
  361. material_map[current_material_library] = lib;
  362. }
  363. }
  364. }
  365. }
  366. if (p_single_mesh) {
  367. r_meshes.push_back(mesh);
  368. }
  369. return OK;
  370. }
  371. Node *EditorOBJImporter::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, uint32_t p_compress_flags, List<String> *r_missing_deps, Error *r_err) {
  372. List<Ref<Mesh>> meshes;
  373. Error err = _parse_obj(p_path, meshes, false, p_flags & IMPORT_GENERATE_TANGENT_ARRAYS, p_compress_flags, Vector3(1, 1, 1), Vector3(0, 0, 0), r_missing_deps);
  374. if (err != OK) {
  375. if (r_err) {
  376. *r_err = err;
  377. }
  378. return nullptr;
  379. }
  380. Spatial *scene = memnew(Spatial);
  381. for (List<Ref<Mesh>>::Element *E = meshes.front(); E; E = E->next()) {
  382. MeshInstance *mi = memnew(MeshInstance);
  383. mi->set_mesh(E->get());
  384. mi->set_name(E->get()->get_name());
  385. scene->add_child(mi);
  386. mi->set_owner(scene);
  387. }
  388. if (r_err) {
  389. *r_err = OK;
  390. }
  391. return scene;
  392. }
  393. Ref<Animation> EditorOBJImporter::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  394. return Ref<Animation>();
  395. }
  396. void EditorOBJImporter::get_extensions(List<String> *r_extensions) const {
  397. r_extensions->push_back("obj");
  398. }
  399. EditorOBJImporter::EditorOBJImporter() {
  400. }
  401. ////////////////////////////////////////////////////
  402. String ResourceImporterOBJ::get_importer_name() const {
  403. return "wavefront_obj";
  404. }
  405. String ResourceImporterOBJ::get_visible_name() const {
  406. return "OBJ As Mesh";
  407. }
  408. void ResourceImporterOBJ::get_recognized_extensions(List<String> *p_extensions) const {
  409. p_extensions->push_back("obj");
  410. }
  411. String ResourceImporterOBJ::get_save_extension() const {
  412. return "mesh";
  413. }
  414. String ResourceImporterOBJ::get_resource_type() const {
  415. return "Mesh";
  416. }
  417. int ResourceImporterOBJ::get_preset_count() const {
  418. return 0;
  419. }
  420. String ResourceImporterOBJ::get_preset_name(int p_idx) const {
  421. return "";
  422. }
  423. void ResourceImporterOBJ::get_import_options(List<ImportOption> *r_options, int p_preset) const {
  424. r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "scale_mesh"), Vector3(1, 1, 1)));
  425. r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "offset_mesh"), Vector3(0, 0, 0)));
  426. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "optimize_mesh_flags", PROPERTY_HINT_FLAGS, "Vertex,Normal,Tangent,Color,TexUV,TexUV2,Bones,Weights,Index"), VS::ARRAY_COMPRESS_DEFAULT >> VS::ARRAY_COMPRESS_BASE));
  427. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_tangents"), true));
  428. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "vertex_cache_optimization"), true));
  429. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "octahedral_compression"), true));
  430. }
  431. bool ResourceImporterOBJ::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
  432. return true;
  433. }
  434. Error ResourceImporterOBJ::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
  435. List<Ref<Mesh>> meshes;
  436. uint32_t compress_flags = int(p_options["optimize_mesh_flags"]) << VS::ARRAY_COMPRESS_BASE;
  437. if (bool(p_options["octahedral_compression"])) {
  438. compress_flags |= VS::ARRAY_FLAG_USE_OCTAHEDRAL_COMPRESSION;
  439. }
  440. if (bool(p_options["vertex_cache_optimization"])) {
  441. compress_flags |= VS::ARRAY_FLAG_USE_VERTEX_CACHE_OPTIMIZATION;
  442. }
  443. Error err = _parse_obj(p_source_file, meshes, true, p_options["generate_tangents"], compress_flags, p_options["scale_mesh"], p_options["offset_mesh"], nullptr);
  444. ERR_FAIL_COND_V(err != OK, err);
  445. ERR_FAIL_COND_V(meshes.size() != 1, ERR_BUG);
  446. String save_path = p_save_path + ".mesh";
  447. err = ResourceSaver::save(save_path, meshes.front()->get());
  448. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save Mesh to file '" + save_path + "'.");
  449. r_gen_files->push_back(save_path);
  450. return OK;
  451. }
  452. ResourceImporterOBJ::ResourceImporterOBJ() {
  453. }