From c07f1b9a9420f28078d77aebc749000f677346ce Mon Sep 17 00:00:00 2001
From: Bastien Montagne <montagne29@wanadoo.fr>
Date: Sun, 15 Jul 2012 14:23:58 +0000
Subject: [PATCH] Fix for [#32102] Saving obj extends the material name by
 texture name

Changed how mtl_mat names are generated, so that we can still be sure to always have a unique mtl_name for each key (mat_name, tex_name), yet avoiding to add tex name to mat when not needed.
---
 io_scene_obj/export_obj.py | 23 +++++++++++++++++++----
 1 file changed, 19 insertions(+), 4 deletions(-)

diff --git a/io_scene_obj/export_obj.py b/io_scene_obj/export_obj.py
index 8a3978ca8..c5fe57af3 100644
--- a/io_scene_obj/export_obj.py
+++ b/io_scene_obj/export_obj.py
@@ -291,6 +291,10 @@ def write_file(filepath, objects, scene,
     # A Dict of Materials
     # (material.name, image.name):matname_imagename # matname_imagename has gaps removed.
     mtl_dict = {}
+    # Used to reduce the usage of matname_texname materials, which can become annoying in case of
+    # repeated exports/imports, yet keeping unique mat names per keys!
+    # mtl_name: (material.name, image.name)
+    mtl_rev_dict = {}
 
     copy_set = set()
 
@@ -505,10 +509,21 @@ def write_file(filepath, objects, scene,
                             # converting any spaces to underscores with name_compat.
 
                             # If none image dont bother adding it to the name
-                            if key[1] is None:
-                                mat_data = mtl_dict[key] = ("%s" % name_compat(key[0])), materials[f_mat], f_image
-                            else:
-                                mat_data = mtl_dict[key] = ("%s_%s" % (name_compat(key[0]), name_compat(key[1]))), materials[f_mat], f_image
+                            # Try to avoid as much as possible adding texname (or other things)
+                            # to the mtl name (see [#32102])...
+                            mtl_name = "%s" % name_compat(key[0])
+                            if mtl_rev_dict.get(mtl_name, None) not in {key, None}:
+                                if key[1] is None:
+                                    tmp_ext = "_NONE"
+                                else:
+                                    tmp_ext = "_%s" % name_compat(key[1])
+                                i = 0
+                                while mtl_rev_dict.get(mtl_name + tmp_ext, None) not in {key, None}:
+                                    i += 1
+                                    tmp_ext = "_%3d" % i
+                                mtl_name += tmp_ext
+                            mat_data = mtl_dict[key] = mtl_name, materials[f_mat], f_image
+                            mtl_rev_dict[mtl_name] = key
 
                         if EXPORT_GROUP_BY_MAT:
                             fw("g %s_%s_%s\n" % (name_compat(ob.name), name_compat(ob.data.name), mat_data[0]))  # can be mat_image or (null)
-- 
GitLab