resource_importer_obj.cpp 17 KB

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