From 3a2267df7f14641667ce498bd73fbffb6d5a8512 Mon Sep 17 00:00:00 2001
From: Brendon Murphy <meta.androcto1@gmail.com>
Date: Fri, 5 Nov 2010 22:15:04 +0000
Subject: [PATCH] added to trunk/py/scripts/addons/io_coat3D this is the App
 Link Script which links 3d Coat & Blender for Texture & Model interchange.
 Wiki page to be written.

---
 io_coat3D/__init__.py | 221 +++++++++++++++++++
 io_coat3D/coat.py     | 500 ++++++++++++++++++++++++++++++++++++++++++
 io_coat3D/tex.py      | 383 ++++++++++++++++++++++++++++++++
 3 files changed, 1104 insertions(+)
 create mode 100644 io_coat3D/__init__.py
 create mode 100644 io_coat3D/coat.py
 create mode 100644 io_coat3D/tex.py

diff --git a/io_coat3D/__init__.py b/io_coat3D/__init__.py
new file mode 100644
index 000000000..c99f47c79
--- /dev/null
+++ b/io_coat3D/__init__.py
@@ -0,0 +1,221 @@
+# ##### BEGIN GPL LICENSE BLOCK #####
+#
+#  This program is free software; you can redistribute it and/or
+#  modify it under the terms of the GNU General Public License
+#  as published by the Free Software Foundation; either version 2
+#  of the License, or (at your option) any later version.
+#
+#  This program is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with this program; if not, write to the Free Software Foundation,
+#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# ##### END GPL LICENSE BLOCK #####
+
+bl_addon_info = {
+    "name": "3D-Coat Applink",
+    "author": "Kalle-Samuli Riihikoski (haikalle)",
+    "version": (1,61),
+    "blender": (2, 5, 4),
+    "api": 31667,
+    "location": "Scene -> 3D-Coat Applink",
+    "description": "Transfer data between 3D-Coat/Blender",
+    "warning": "",
+    "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/' \
+        'Scripts/",
+    "tracker_url": "https://projects.blender.org/tracker/?"\
+        "func=detail&atid=467&aid=24446&group_id=153",
+    "category": "Import/Export"}
+
+
+
+#if "bpy" in locals(): Don't know if this is important
+#    reload(render)
+#    reload(ui)
+
+#else:
+import bpy
+from bpy.props import *
+from io_coat3D import coat
+from io_coat3D import tex
+
+def register():
+
+	bpy.coat3D = dict()
+	bpy.coat3D['active_coat'] = ''
+	bpy.coat3D['status'] = 0
+	bpy.coat3D['kuva'] = 1
+    
+	class coat3D(bpy.types.IDPropertyGroup):
+		pass
+		
+	bpy.types.Object.coat3D= PointerProperty(
+		name= "Applink Variables",
+		type=  coat3D,
+		description= "Applink variables"
+	)
+
+	coat3D.objpath = StringProperty(
+		name="Object_Path",
+		default= ""
+	)
+
+	coat3D.coatpath = StringProperty(
+		name="Coat_Path",
+		default= ""
+	)
+
+
+	class coat3D(bpy.types.IDPropertyGroup):
+		pass
+
+	bpy.types.Scene.coat3D= PointerProperty(
+		name= "Applink Variables",
+		type=  coat3D,
+		description= "Applink variables"
+	)
+
+	coat3D.objectdir = StringProperty(
+		name="ObjectPath",
+		subtype="FILE_PATH",
+		default= ""
+	)
+
+	coat3D.exchangedir = StringProperty(
+		name="FilePath",
+		subtype="DIR_PATH",
+		default= ""
+	)
+
+	coat3D.wasactive = StringProperty(
+		name="Pass active object",
+		default= ""
+	)
+
+	coat3D.export_on = BoolProperty(
+		name="Export_On",
+		description="Add Modifiers and export.",
+		default= False
+	)
+
+	coat3D.smooth_on = BoolProperty(
+		name="Auto Smooth",
+		description="Add Modifiers and export.",
+		default= True
+	)
+
+	coat3D.exportfile = BoolProperty(
+		name="No Import File",
+		description="Add Modifiers and export.",
+		default= False
+	)
+
+	coat3D.importmod = BoolProperty(
+		name="Remove Modifiers",
+		description="Import and add modifiers.",
+		default= True
+	)
+
+	coat3D.exportmod = BoolProperty(
+		name="Modifiers",
+		description="Export modifiers.",
+		default= False
+	)
+
+	coat3D.export_pos = BoolProperty(
+		name="Remember Position",
+		description="Remember position.",
+		default= True
+	)
+
+	coat3D.importtextures = BoolProperty(
+		name="Bring Textures",
+		description="Import Textures.",
+		default= True
+	)
+
+	coat3D.exportover = BoolProperty(
+		name="Export Obj",
+		description="Import Textures.",
+		default= False
+	)
+
+	coat3D.importmesh = BoolProperty(
+		name="Mesh",
+		description="Import Mesh.",
+		default= True
+	)
+
+	#copy location
+
+	coat3D.cursor = FloatVectorProperty(
+		name="Cursor",
+		description="Location.",
+		subtype="XYZ",
+		default=(0.0, 0.0, 0.0)
+	)
+
+	coat3D.loca = FloatVectorProperty(
+		name="location",
+		description="Location.",
+		subtype="XYZ",
+		default=(0.0, 0.0, 0.0)
+	)
+
+	coat3D.rota = FloatVectorProperty(
+		name="location",
+		description="Location.",
+		subtype="EULER",
+		default=(0.0, 0.0, 0.0)
+	)
+
+	coat3D.scal = FloatVectorProperty(
+		name="location",
+		description="Location.",
+		subtype="XYZ",
+		default=(0.0, 0.0, 0.0)
+	)
+
+	coat3D.dime = FloatVectorProperty(
+		name="dimension",
+		description="Dimension.",
+		subtype="XYZ",
+		default=(0.0, 0.0, 0.0)
+	)
+
+	coat3D.type = EnumProperty( name= "Export Type",
+	description= "Diffrent Export Types.",
+	items=(
+		("ppp",   "Per-Pixel Painting", ""),
+		("mv",   "Microvertex Painting", ""),
+		("ptex",   "Ptex Painting", ""),
+		("uv",   "UV-Mapping", ""),
+		("ref",  "Reference Mesh", ""),
+		("retopo",  "Retopo mesh as new layer", ""),
+		("vox",  "Mesh As Voxel Object", ""),
+		("alpha",  "Mesh As New Pen Alpha", ""),
+		("prim",  "Mesh As Voxel Primitive", ""),
+		("autopo",  "Mesh for Auto-retopology", ""),
+	),
+	default= "ppp"
+	)
+
+
+def unregister():
+	import bpy
+
+	del bpy.types.Object.coat3D
+	del bpy.types.Scene.coat3D
+	del bpy.coat3D
+	
+
+
+if __name__ == "__main__":
+	register()
+
+
+
diff --git a/io_coat3D/coat.py b/io_coat3D/coat.py
new file mode 100644
index 000000000..14593e6e7
--- /dev/null
+++ b/io_coat3D/coat.py
@@ -0,0 +1,500 @@
+# scene_blend_info.py Copyright (C) 2010, Mariano Hidalgo
+#
+# Show Information About the Blend.
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+# ***** END GPL LICENCE BLOCK *****
+
+bl_addon_info = {
+	"name": "Coat Applink",
+	"author": "Kalle-Samuli Riihikoski (haikalle)",
+	"version": (1,6),
+	"blender": (2, 5, 4),
+	"api": 31965,
+	"location": "Properties space > Scene tab > 3D-Coat Applink",
+	"description": "Show information about the .blend",
+	"warning": "",
+	"wiki_url": 'http://wiki.blender.org/index.php/Extensions:2.5/Py/' \
+	    'Scripts/System/Blend Info',
+	"tracker_url": "https://projects.blender.org/tracker/index.php?" \
+	    "func=detail&aid=22102&group_id=153&atid=469",
+	"category": "System"}
+
+import bpy
+from bpy.props import *
+from io_coat3D import tex
+import os
+import linecache
+
+bpy.coat3D = dict()
+bpy.coat3D['active_coat'] = ''
+bpy.coat3D['status'] = 0
+bpy.coat3D['kuva'] = 1
+
+#bpy.context.user_preferences.filepaths.use_relative_paths = False
+
+class ObjectButtonsPanel():
+	bl_space_type = 'PROPERTIES'
+	bl_region_type = 'WINDOW'
+	bl_context = "object"
+
+class SCENE_PT_Borgleader(ObjectButtonsPanel,bpy.types.Panel):
+	bl_label = "3D-Coat Applink"
+	bl_space_type = "PROPERTIES"
+	bl_region_type = "WINDOW"
+	bl_context = "scene"
+
+	def draw(self, context):
+		layout = self.layout
+		scene = context.scene
+		me = context.scene.objects
+		mat_list = []
+		import_no = 0
+		coat = bpy.coat3D
+		coat3D = bpy.context.scene.coat3D
+
+		if(coat['kuva'] == 1):
+                        bpy.context.scene.game_settings.material_mode = 'GLSL'
+                        coat['kuva'] = 0
+                
+		
+		if(os.path.isdir(coat3D.exchangedir)):
+			foldder = coat3D.exchangedir
+			if(foldder.rfind('Exchange') >= 0):
+				coat3D.exchangedir = foldder
+				coat['status'] = 1
+			else:
+				coat['status'] = 0
+		else:
+			coat['status'] = 0
+		#Here you add your GUI 
+		row = layout.row()
+		row.prop(coat3D,"type",text = "")
+		row = layout.row()
+		colL = row.column()
+		colR = row.column()
+		if(context.selected_objects):
+			if(context.selected_objects[0].type == 'MESH'):
+				colL.active = True
+			else:
+				colL.active = False
+		else:
+			colL.active = False
+		colL.operator("exportbutton", text="Export")
+		colL.label(text="Export Settings:")
+
+		colL.prop(coat3D,"exportover")
+		if(coat3D.exportover):
+			colL.prop(coat3D,"exportmod")
+		colL.prop(coat3D,"exportfile")
+		colL.prop(coat3D,"export_pos")
+		
+		
+		if(bpy.context.active_object):
+			colR.active = True
+		else:
+			colR.active = False
+		    
+		colR.operator("importbutton", text="Import")
+		colR.label(text="Import Settings:")
+		colR.prop(coat3D,"importmesh")
+		colR.prop(coat3D,"importmod")
+		colR.prop(coat3D,"smooth_on")
+		colR.prop(coat3D,"importtextures")
+		row = layout.row()
+		colL = row.column()
+		colM = row.column()
+		colR = row.column()
+		colL.operator("deltex",text="Del Tex")
+		if(bpy.context.active_object):
+			colM.active = True
+			if(bpy.context.active_object.coat3D.coatpath and os.path.isfile(bpy.context.active_object.coat3D.coatpath)):
+				colR.active = True
+				if(coat['active_coat'] == bpy.context.active_object.coat3D.coatpath):
+					colR.operator("load3b", text="Active 3b")
+				else:
+					colR.operator("load3b", text="Load 3b")
+			else:
+				colR.active = False
+				colR.operator("no3b",text="No 3b")
+		else:
+			colM.active = False
+			colR.active = False
+			colR.operator("no3b",text="")
+		colM.operator("pickname",text="Object name")
+		row = layout.row()
+		row.label(text="Object Path:")
+		row = layout.row()
+		row.prop(coat3D,"objectdir",text="")
+		if(bpy.context.active_object):
+			if(bpy.context.active_object.name != coat3D.wasactive):
+				coat3D.wasactive = bpy.context.active_object.name
+				if(bpy.context.active_object.coat3D.objpath):
+					coat3D.objectdir = bpy.context.active_object.coat3D.objpath
+			else:
+				bpy.context.active_object.coat3D.objpath = coat3D.objectdir
+					
+		row = layout.row()
+		
+		if(coat['status'] == 1):
+			row.label(text="Exchange Folder: connected")
+			Blender_folder = ("%s%sBlender"%(coat3D.exchangedir,os.sep))
+			Blender_export = Blender_folder
+			Blender_export += ('%sexport.txt'%(os.sep))
+
+			if(not(os.path.isdir(Blender_folder))):
+				os.makedirs(Blender_folder)
+				Blender_folder = os.path.join(Blender_folder,"run.txt")
+				file = open(Blender_folder, "w")
+				file.close()
+				
+			if(os.path.isfile(Blender_export)):
+				obj_path =''
+				obj_pathh = open(Blender_export)
+				for line in obj_pathh:
+					obj_path = line
+					break
+				obj_pathh.close()
+				print("%s"%obj_path)
+				export = obj_path
+				mod_time = os.path.getmtime(obj_path)
+				mtl_list = obj_path.replace('.obj','.mtl')
+				if(os.path.isfile(mtl_list)):
+					os.remove(mtl_list)
+
+				for palikka in bpy.context.scene.objects:
+					if(palikka.type == 'MESH'):
+						if(palikka.coat3D.objpath == export):
+							import_no = 1
+							target = palikka
+							break
+
+				if(import_no):
+					new_obj = palikka
+					import_no = 0
+				else:
+					bpy.ops.import_scene.obj(filepath=obj_path)
+					new_obj = scene.objects[0]
+				os.remove(Blender_export)
+				
+				bpy.context.scene.objects.active = new_obj
+				bpy.context.active_object.coat3D.objpath = obj_path
+
+				if(coat3D.smooth_on):
+					bpy.ops.object.shade_smooth()
+				else:
+					bpy.ops.object.shade_flat()
+
+				Blender_tex = ("%s%stextures.txt"%(coat3D.exchangedir,os.sep))
+				mat_list.append(new_obj.material_slots[0].material)
+				tex.gettex(mat_list, new_obj, scene,export)
+				
+
+				
+				
+			
+		if(coat['status'] == 0):
+			row.label(text="Exchange Folder: not connected")
+		row = layout.row()
+		row.prop(coat3D,"exchangedir",text="")
+		row = layout.row()
+		row.label(text="Author: haikalle@gmail.com")
+
+
+class SCENE_OT_export(bpy.types.Operator):
+	bl_idname = "exportbutton"
+	bl_label = "Export your custom property"
+	bl_description = "Export your custom property"
+
+    
+	def invoke(self, context, event):
+		checkname = ''
+		coat3D = bpy.context.scene.coat3D
+		scene = context.scene
+		coat3D.export_on = False
+		activeobj = bpy.context.active_object.name
+		obj = scene.objects[activeobj]
+
+		importfile = coat3D.exchangedir
+		texturefile = coat3D.exchangedir
+		importfile += ('%simport.txt'%(os.sep))
+		texturefile += ('%stextures.txt'%(os.sep))
+		if(os.path.isfile(texturefile)):
+				os.remove(texturefile)
+		
+		checkname = coat3D.objectdir
+		
+		if(coat3D.objectdir[-4:] != '.obj'):
+			checkname += ('%s.obj'%(activeobj))
+
+		if(not(os.path.isfile(checkname)) or coat3D.exportover):
+                        if(coat3D.export_pos):
+
+                                bpy.ops.export_scene.obj(filepath=checkname,use_selection=True,
+                                use_modifiers=coat3D.exportmod,use_blen_objects=False, group_by_material= True,
+                                use_materials = False,keep_vertex_order = True)
+
+                                coat3D.export_on = True
+                        else:
+                                coat3D.loca = obj.location
+                                coat3D.rota = obj.rotation_euler
+                                coat3D.scal = obj.scale
+                                obj.location = (0,0,0)
+                                obj.rotation_euler = (0,0,0)
+                                obj.scale = (1,1,1)
+
+                                bpy.ops.export_scene.obj(filepath=checkname,use_selection=True,
+                                use_modifiers=coat3D.exportmod,use_blen_objects=False, group_by_material= True,
+                                use_materials = False,keep_vertex_order = True)
+
+                                obj.location = coat3D.loca
+                                obj.rotation_euler = coat3D.rota
+                                obj.scale = coat3D.scal
+                                coat3D.export_on = True
+                                
+			
+	
+		if(coat3D.exportfile == False):
+			file = open(importfile, "w")
+			file.write("%s"%(checkname))
+			file.write("\n%s"%(checkname))
+			file.write("\n[%s]"%(coat3D.type))
+			file.close()
+		coat3D.objectdir = checkname
+		bpy.context.active_object.coat3D.objpath = coat3D.objectdir
+
+		return('FINISHED')
+
+
+class SCENE_OT_import(bpy.types.Operator):
+	bl_idname = "importbutton"
+	bl_label = "import your custom property"
+	bl_description = "import your custom property"
+    
+	def invoke(self, context, event):
+		scene = context.scene
+		coat3D = bpy.context.scene.coat3D
+		coat = bpy.coat3D
+		activeobj = bpy.context.active_object.name
+		mat_list = []
+		scene.objects[activeobj].select = True
+		objekti = scene.objects[activeobj]
+		coat3D.loca = objekti.location
+		coat3D.rota = objekti.rotation_euler
+
+		exportfile = coat3D.exchangedir
+		exportfile += ('%sexport.txt'%(os.sep))
+		if(os.path.isfile(exportfile)):
+			export_file = open(exportfile)
+			for line in export_file:
+				if line.rfind('.3b'):
+					objekti.coat3D.coatpath = line
+					coat['active_coat'] = line
+			export_file.close()
+			os.remove(exportfile)
+			
+			
+		   
+
+		if(objekti.material_slots):
+			for obj_mat in objekti.material_slots:
+				mat_list.append(obj_mat.material)
+			act_mat_index = objekti.active_material_index
+
+
+		if(coat3D.importmesh and os.path.isfile(coat3D.objectdir)):
+			mtl = coat3D.objectdir
+			mtl = mtl.replace('.obj','.mtl')
+			if(os.path.isfile(mtl)):
+				os.remove(mtl)
+
+			
+			bpy.ops.import_scene.obj(filepath=coat3D.objectdir)
+			obj_proxy = scene.objects[0]
+			proxy_mat = obj_proxy.material_slots[0].material
+			obj_proxy.data.materials.pop(0)
+			proxy_mat.user_clear()
+			bpy.data.materials.remove(proxy_mat)
+			bpy.ops.object.select_all(action='TOGGLE')
+			if(coat3D.export_pos):
+				scene.objects.active = objekti
+				objekti.select = True
+				coat3D.cursor = bpy.context.scene.cursor_location
+				bpy.context.scene.cursor_location = (0.0,0.0,0.0)
+				bpy.ops.object.origin_set(type='ORIGIN_CURSOR', center='MEDIAN')
+
+				scene.objects.active = obj_proxy
+				
+				obj_data = objekti.data.id_data
+				objekti.data = obj_proxy.data.id_data
+
+				if(coat3D.export_on):
+					objekti.scale = (1,1,1)
+					objekti.rotation_euler = (0,0,0)
+					
+				if(bpy.data.meshes[obj_data.name].users == 0):
+					bpy.data.meshes.remove(obj_data)
+					objekti.data.id_data.name = obj_data.name
+
+				bpy.ops.object.select_all(action='TOGGLE')
+
+				obj_proxy.select = True
+				bpy.ops.object.delete()
+				objekti.select = True
+				bpy.context.scene.objects.active = objekti
+				if(coat3D.export_on):
+					bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='MEDIAN')
+					coat3D.export_on = False
+
+				else:
+					objekti.location = coat3D.loca
+					objekti.rotation_euler = coat3D.rota
+					bpy.ops.object.origin_set(type='GEOMETRY_ORIGIN', center='MEDIAN')
+			else:
+				scene.objects.active = obj_proxy
+
+				obj_data = objekti.data.id_data
+				objekti.data = obj_proxy.data.id_data
+				if(bpy.data.meshes[obj_data.name].users == 0):
+					bpy.data.meshes.remove(obj_data)
+					objekti.data.id_data.name = obj_data.name
+
+				obj_proxy.select = True
+				bpy.ops.object.delete()
+				objekti.select = True
+				bpy.context.scene.objects.active = objekti
+				
+				
+	
+			if(coat3D.smooth_on):
+				bpy.ops.object.shade_smooth()
+			else:
+				bpy.ops.object.shade_flat()
+				
+		if(coat3D.importmesh and not(os.path.isfile(coat3D.objectdir))):
+			coat3D.importmesh = False
+
+		if(mat_list and coat3D.importmesh):
+			for mat_one in mat_list:
+				objekti.data.materials.append(mat_one)
+			objekti.active_material_index = act_mat_index
+			
+		if(mat_list):
+			for obj_mate in objekti.material_slots:
+				for tex_slot in obj_mate.material.texture_slots:
+					if(hasattr(tex_slot,'texture')):
+						if(tex_slot.texture.type == 'IMAGE'):
+                                                        tex_slot.texture.image.reload()
+                                                        
+
+		if(coat3D.importmod):
+			mod_list = []
+			for mod_index in objekti.modifiers:
+				objekti.modifiers.remove(mod_index)
+                
+		
+				
+		if(coat3D.importtextures):
+                        export = ''
+                        tex.gettex(mat_list,objekti,scene,export)
+		
+		return('FINISHED')
+
+class SCENE_OT_load3b(bpy.types.Operator):
+	bl_idname = "load3b"
+	bl_label = "Loads 3b linked into object"
+	bl_description = "Loads 3b linked into object"
+
+    
+	def invoke(self, context, event):
+		checkname = ''
+		coat3D = bpy.context.scene.coat3D
+		scene = context.scene
+		importfile = coat3D.exchangedir
+		importfile += ('%simport.txt'%(os.sep))
+		
+		coat_path = bpy.context.active_object.coat3D.coatpath
+		
+		file = open(importfile, "w")
+		file.write("%s"%(coat_path))
+		file.write("\n%s"%(coat_path))
+		file.write("\n[3B]")
+		file.close()
+
+		
+		coat['active_coat'] = coat_path
+
+
+		return('FINISHED')
+
+class SCENE_OT_no3b(bpy.types.Operator):
+	bl_idname = "no3b"
+	bl_label = "Loads 3b linked into object"
+	bl_description = "Loads 3b linked into object"
+
+    
+	def invoke(self, context, event):
+		scene = context.scene
+	
+		return('FINISHED')
+
+class SCENE_OT_pickname(bpy.types.Operator):
+	bl_idname = "pickname"
+	bl_label = "Picks Object's name into path"
+	bl_description = "Loads 3b linked into object"
+
+    
+	def invoke(self, context, event):
+		coat3D = bpy.context.scene.coat3D
+		scene = context.scene
+		new_name = tex.stripFile(coat3D.objectdir)
+		new_name += ("%s.obj"%(bpy.context.active_object.name))
+		coat3D.objectdir = new_name
+	
+		return('FINISHED')
+
+class SCENE_OT_deltex(bpy.types.Operator):
+	bl_idname = "deltex"
+	bl_label = "Picks Object's name into path"
+	bl_description = "Loads 3b linked into object"
+
+    
+	def invoke(self, context, event):
+		coat3D = bpy.context.scene.coat3D
+		scene = context.scene
+		nimi = tex.objname(coat3D.objectdir)
+		osoite = tex.stripFile(coat3D.objectdir)
+		just_nimi = tex.justname(nimi)
+		just_nimi += '_'
+
+		files = os.listdir(osoite)
+		for i in files:
+			if(i.rfind(just_nimi) >= 0):
+			    del_osoite = osoite + i
+			    os.remove(del_osoite)
+	
+		return('FINISHED')
+
+def register():
+	pass
+
+def unregister():
+	pass
+
+if __name__ == "__main__":
+	register()
diff --git a/io_coat3D/tex.py b/io_coat3D/tex.py
new file mode 100644
index 000000000..db74d1dcb
--- /dev/null
+++ b/io_coat3D/tex.py
@@ -0,0 +1,383 @@
+import bpy
+import os
+import filecmp
+
+
+def objname(path):
+
+	path2 = os.path.dirname(path) + os.sep
+	print("kalle:%s"%path2)
+	pituus = len(path2)
+	nimi = path[pituus:]
+
+	return nimi
+
+def justname(name):
+	monesko = name.rfind('.')
+	justname = name[:monesko]
+	return justname
+
+def setgallery():
+	newname =''
+	tex_name =[]
+	index_tex = 0
+	for tt in bpy.data.textures:
+		tex_name.append(tt.name)
+	return tex_name
+
+def find_index(objekti):
+        luku = 0
+        for tex in objekti.active_material.texture_slots:
+                if(not(hasattr(tex,'texture'))):
+                        break
+                luku = luku +1
+                
+
+        return luku
+
+def gettex(mat_list, objekti, scene,export):
+
+	coat3D = bpy.context.scene.coat3D
+	
+	if(bpy.context.scene.render.engine == 'VRAY_RENDER' or bpy.context.scene.render.engine == 'VRAY_RENDER_PREVIEW'):
+		vray = True
+	else:
+		vray = False
+    
+        
+	
+	take_color = 0;
+	take_spec = 0;
+	take_normal = 0;
+	take_disp = 0;
+	
+	bring_color = 1;
+	bring_spec = 1;
+	bring_normal = 1;
+	bring_disp = 1;
+
+	texcoat = {}
+	texcoat['color'] = []
+	texcoat['specular'] = []
+	texcoat['nmap'] = []
+	texcoat['disp'] = []
+	texu = []
+
+	if(export):
+		objekti.coat3D.objpath = export
+		nimi = objname(export)
+		osoite = os.path.dirname(export) + os.sep
+		for mate in objekti.material_slots:
+			for tex_slot in mate.material.texture_slots:
+				if(hasattr(tex_slot,'texture')):
+					if(tex_slot.texture.type == 'IMAGE'):
+                                                tex_slot.texture.image.reload()
+	else:
+		nimi = objname(coat3D.objectdir)
+		osoite = os.path.dirname(coat3D.objectdir) + os.sep
+	just_nimi = justname(nimi)
+	just_nimi += '_'
+	just_nimi_len = len(just_nimi)
+		
+	
+	if(len(objekti.material_slots) != 0):
+		for obj_tex in objekti.active_material.texture_slots:
+			if(hasattr(obj_tex,'texture')):
+				if(obj_tex.texture):
+					if(obj_tex.use_map_color_diffuse):
+						bring_color = 0;
+					if(obj_tex.use_map_specular):
+						bring_spec = 0;
+					if(obj_tex.use_map_normal):
+						bring_normal = 0;
+					if(obj_tex.use_map_displacement):
+						bring_disp = 0;
+				
+	files = os.listdir(osoite)
+	for i in files:
+		tui = i[:just_nimi_len]
+		if(tui == just_nimi):
+		    texu.append(i)
+		    
+	for yy in texu:
+		minimi = (yy.rfind('_'))+1
+		maksimi = (yy.rfind('.'))
+		tex_name = yy[minimi:maksimi]
+		koko = ''
+		koko += osoite
+		koko += yy
+		texcoat[tex_name].append(koko)
+		#date = os.path.getmtime(texcoat[tex_name][0])
+
+	if((texcoat['color'] or texcoat['nmap'] or texcoat['disp'] or texcoat['specular']) and (len(objekti.material_slots)) == 0):
+		new_mat = ("%s_Material"%(objekti.name))
+		bpy.data.materials.new(new_mat)
+		ki = bpy.data.materials[new_mat]
+		objekti.data.materials.append(ki)
+		
+		
+			
+	if(bring_color == 1 and texcoat['color']):
+		name_tex ='Color_'
+		num = []
+
+		index = find_index(objekti)
+		
+
+		tex = bpy.ops.Texture
+		objekti.active_material.texture_slots.create(index)
+		total_mat = len(objekti.active_material.texture_slots.items())
+		useold = ''
+		
+		for seekco in bpy.data.textures:
+			if((seekco.name[:6] == 'Color_') and (seekco.users_material == ())):
+				useold = seekco
+
+		
+
+
+		if(useold == ''):
+
+			tex_name = setgallery()
+
+			for num_tex in tex_name:
+				if(num_tex[:6] == 'Color_'):
+					num.append(num_tex)
+			luku_tex = len(num)
+			name_tex = ('Color_%s'%(luku_tex))
+
+			bpy.ops.image.new(name=name_tex)
+			bpy.data.images[name_tex].filepath = texcoat['color'][0]
+			bpy.data.images[name_tex].source = 'FILE'
+		    
+
+			bpy.data.textures.new(name_tex,type='IMAGE')
+			objekti.active_material.texture_slots[index].texture = bpy.data.textures[name_tex]
+			objekti.active_material.texture_slots[index].texture.image = bpy.data.images[name_tex]
+		
+			if(objekti.data.uv_textures.active):
+				objekti.active_material.texture_slots[index].texture_coords = 'UV'
+				objekti.active_material.texture_slots[index].uv_layer = objekti.data.uv_textures.active.name
+
+			objekti.active_material.texture_slots[index].texture.image.reload()
+			
+
+		elif(useold != ''):
+			
+			objekti.active_material.texture_slots[index].texture = useold
+			objekti.active_material.texture_slots[index].texture.image.filepath = texcoat['color'][0]
+			if(objekti.data.uv_textures.active):
+				objekti.active_material.texture_slots[index].texture_coords = 'UV'
+				objekti.active_material.texture_slots[index].uv_layer = objekti.data.uv_textures.active.name
+	
+	if(bring_normal == 1 and texcoat['nmap']):
+		name_tex ='Normal_'
+		num = []
+		
+		index = find_index(objekti)
+		
+
+		tex = bpy.ops.Texture
+		objekti.active_material.texture_slots.create(index)
+		total_mat = len(objekti.active_material.texture_slots.items())
+		useold = ''
+		
+		for seekco in bpy.data.textures:
+			if((seekco.name[:7] == 'Normal_') and (seekco.users_material == ())):
+				useold = seekco
+
+		
+
+		if(useold == ''):
+
+			tex_name = setgallery()
+
+			for num_tex in tex_name:
+				if(num_tex[:7] == 'Normal_'):
+					num.append(num_tex)
+			luku_tex = len(num)
+			name_tex = ('Normal_%s'%(luku_tex))
+
+			bpy.ops.image.new(name=name_tex)
+			bpy.data.images[name_tex].filepath = texcoat['nmap'][0]
+			bpy.data.images[name_tex].source = 'FILE'
+		    
+
+			bpy.data.textures.new(name_tex,type='IMAGE')
+			objekti.active_material.texture_slots[index].texture = bpy.data.textures[name_tex]
+			objekti.active_material.texture_slots[index].texture.image = bpy.data.images[name_tex]
+		
+			if(objekti.data.uv_textures.active):
+				objekti.active_material.texture_slots[index].texture_coords = 'UV'
+				objekti.active_material.texture_slots[index].uv_layer = objekti.data.uv_textures.active.name
+			objekti.active_material.texture_slots[index].use_map_color_diffuse = False
+			objekti.active_material.texture_slots[index].use_map_normal = True
+
+			objekti.active_material.texture_slots[index].texture.image.reload()
+			if(vray):
+				bpy.data.textures[name_tex].vray_slot.BRDFBump.map_type = 'TANGENT'
+
+			else:
+				bpy.data.textures[name_tex].use_normal_map = True
+				bpy.data.textures[name_tex].normal_space = 'TANGENT'
+			
+
+		elif(useold != ''):
+			
+			objekti.active_material.texture_slots[index].texture = useold
+			objekti.active_material.texture_slots[index].texture.image.filepath = texcoat['nmap'][0]
+			if(objekti.data.uv_textures.active):
+				objekti.active_material.texture_slots[index].texture_coords = 'UV'
+				objekti.active_material.texture_slots[index].uv_layer = objekti.data.uv_textures.active.name
+			objekti.active_material.texture_slots[index].use_map_color_diffuse = False
+			objekti.active_material.texture_slots[index].use_map_normal = True
+
+	
+						
+	if(bring_spec == 1 and texcoat['specular']):
+		name_tex ='Specular_'
+		num = []
+
+		index = find_index(objekti)
+		
+
+		tex = bpy.ops.Texture
+		objekti.active_material.texture_slots.create(index)
+		total_mat = len(objekti.active_material.texture_slots.items())
+		useold = ''
+		
+		for seekco in bpy.data.textures:
+			if((seekco.name[:9] == 'Specular_') and (seekco.users_material == ())):
+				useold = seekco
+
+		
+
+
+		if(useold == ''):
+
+			tex_name = setgallery()
+
+			for num_tex in tex_name:
+				if(num_tex[:9] == 'Specular_'):
+					num.append(num_tex)
+			luku_tex = len(num)
+			name_tex = ('Specular_%s'%(luku_tex))
+
+			bpy.ops.image.new(name=name_tex)
+			bpy.data.images[name_tex].filepath = texcoat['specular'][0]
+			bpy.data.images[name_tex].source = 'FILE'
+		    
+
+			bpy.data.textures.new(name_tex,type='IMAGE')
+			objekti.active_material.texture_slots[index].texture = bpy.data.textures[name_tex]
+			objekti.active_material.texture_slots[index].texture.image = bpy.data.images[name_tex]
+		
+			if(objekti.data.uv_textures.active):
+				objekti.active_material.texture_slots[index].texture_coords = 'UV'
+				objekti.active_material.texture_slots[index].uv_layer = objekti.data.uv_textures.active.name
+			objekti.active_material.texture_slots[index].use_map_color_diffuse = False
+			objekti.active_material.texture_slots[index].use_map_specular = True
+
+			objekti.active_material.texture_slots[index].texture.image.reload()
+			
+
+		elif(useold != ''):
+			
+			objekti.active_material.texture_slots[index].texture = useold
+			objekti.active_material.texture_slots[index].texture.image.filepath = texcoat['specular'][0]
+			if(objekti.data.uv_textures.active):
+				objekti.active_material.texture_slots[index].texture_coords = 'UV'
+				objekti.active_material.texture_slots[index].uv_layer = objekti.data.uv_textures.active.name
+			objekti.active_material.texture_slots[index].use_map_color_diffuse = False
+			objekti.active_material.texture_slots[index].use_map_specular = True
+
+	if(bring_disp == 1 and texcoat['disp']):
+		name_tex ='Displacement_'
+		num = []
+
+		index = find_index(objekti)
+		
+
+		tex = bpy.ops.Texture
+		objekti.active_material.texture_slots.create(index)
+		total_mat = len(objekti.active_material.texture_slots.items())
+		useold = ''
+		
+		for seekco in bpy.data.textures:
+			if((seekco.name[:13] == 'Displacement_') and (seekco.users_material == ())):
+				useold = seekco
+
+		
+
+
+		if(useold == ''):
+
+			tex_name = setgallery()
+
+			for num_tex in tex_name:
+				if(num_tex[:13] == 'Displacement_'):
+					num.append(num_tex)
+			luku_tex = len(num)
+			name_tex = ('Displacement_%s'%(luku_tex))
+
+			bpy.ops.image.new(name=name_tex)
+			bpy.data.images[name_tex].filepath = texcoat['disp'][0]
+			bpy.data.images[name_tex].source = 'FILE'
+		    
+
+			bpy.data.textures.new(name_tex,type='IMAGE')
+			objekti.active_material.texture_slots[index].texture = bpy.data.textures[name_tex]
+			objekti.active_material.texture_slots[index].texture.image = bpy.data.images[name_tex]
+		
+			if(objekti.data.uv_textures.active):
+				objekti.active_material.texture_slots[index].texture_coords = 'UV'
+				objekti.active_material.texture_slots[index].uv_layer = objekti.data.uv_textures.active.name
+			objekti.active_material.texture_slots[index].use_map_color_diffuse = False
+			objekti.active_material.texture_slots[index].use_map_displacement = True
+
+			objekti.active_material.texture_slots[index].texture.image.reload()
+			
+
+		elif(useold != ''):
+			
+			objekti.active_material.texture_slots[index].texture = useold
+			objekti.active_material.texture_slots[index].texture.image.filepath = texcoat['disp'][0]
+			if(objekti.data.uv_textures.active):
+				objekti.active_material.texture_slots[index].texture_coords = 'UV'
+				objekti.active_material.texture_slots[index].uv_layer = objekti.data.uv_textures.active.name
+			objekti.active_material.texture_slots[index].use_map_color_diffuse = False
+			objekti.active_material.texture_slots[index].use_map_displacement = True
+
+		if(vray):
+			objekti.active_material.texture_slots[index].texture.use_interpolation = False
+			objekti.active_material.texture_slots[index].displacement_factor = 0.05
+			
+
+		else:
+			disp_modi = ''
+			for seek_modi in objekti.modifiers:
+				if(seek_modi.type == 'DISPLACE'):
+					disp_modi = seek_modi
+					break
+			if(disp_modi):
+				disp_modi.texture = objekti.active_material.texture_slots[index].texture
+				if(objekti.data.uv_textures.active):
+					disp_modi.texture_coords = 'UV'
+					disp_modi.uv_layer = objekti.data.uv_textures.active.name
+			else:
+				objekti.modifiers.new('Displace',type='DISPLACE')
+				objekti.modifiers['Displace'].texture = objekti.active_material.texture_slots[index].texture
+				if(objekti.data.uv_textures.active):
+					objekti.modifiers['Displace'].texture_coords = 'UV'
+					objekti.modifiers['Displace'].uv_layer = objekti.data.uv_textures.active.name
+	
+
+
+
+
+
+
+    
+	return('FINISHED')
+
+	
-- 
GitLab