[Bf-extensions-cvs] SVN commit: /data/svn/bf-extensions [1259] trunk/py/scripts/addons/ io_convert_image_to_scene_gimp.py: GIMPImagetoScene: Moving to addons.

Daniel Salazar zanqdo at gmail.com
Thu Dec 9 17:46:25 CET 2010


Revision: 1259
          http://projects.blender.org/plugins/scmsvn/viewcvs.php?view=rev&root=bf-extensions&revision=1259
Author:   zanqdo
Date:     2010-12-09 17:46:25 +0100 (Thu, 09 Dec 2010)

Log Message:
-----------
GIMPImagetoScene: Moving to addons. Docs here (for now). Still some
discussion over naming conventions

http://wiki.blender.org/index.php/Extensions:2.5/Py/Scripts/File_I-O/GIMPImageToScene

Added Paths:
-----------
    trunk/py/scripts/addons/io_convert_image_to_scene_gimp.py

Added: trunk/py/scripts/addons/io_convert_image_to_scene_gimp.py
===================================================================
--- trunk/py/scripts/addons/io_convert_image_to_scene_gimp.py	                        (rev 0)
+++ trunk/py/scripts/addons/io_convert_image_to_scene_gimp.py	2010-12-09 16:46:25 UTC (rev 1259)
@@ -0,0 +1,662 @@
+# ##### 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": "Convert GIMP Image to Scene (.xcf, .xjt)",
+	"author": "Daniel Salazar (ZanQdo)",
+	"version": (2,0,0),
+	"blender": (2, 5, 5),
+	"api": 33419,
+	"location": "File > Import > GIMP Image to Scene(.xcf, .xjt)",
+	"description": "Imports GIMP multilayer image files into 3D Layers",
+	"warning": "XCF import requires xcftools installed",
+	"wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/"\
+		"Scripts/File_I-O/GIMPImageToScene",
+	"tracker_url": "http://projects.blender.org/tracker/index.php?"\
+		"func=detail&aid=25136&group_id=153&atid=469",
+	"category": "Import/Export"}
+
+"""
+This script imports GIMP layered image files into 3D Scenes (.xcf, .xjt)
+"""
+
+def main(File, Path, LayerViewers, MixerViewers, LayerOffset,\
+	LayerScale, OpacityMode, PremulAlpha, ShadelessMats,\
+	SetCamera, SetupCompo, GroupUntagged, Ext):
+	
+	#-------------------------------------------------
+	
+	#Folder = '['+File.rstrip(Ext)+']'+'_images/'
+	Folder = 'images_'+'['+File.rstrip(Ext)+']/'
+	
+	if bpy.data.is_dirty:
+		PathSaveRaw = Path+Folder
+		PathSave = PathSaveRaw.replace(' ', '\ ')
+		try: os.mkdir(PathSaveRaw)
+		except: pass
+	else:
+		PathSave = bpy.data.filepath
+		RSlash = PathSave.rfind('/')
+		PathSaveRaw = PathSave[:RSlash+1]+Folder
+		PathSave = PathSaveRaw.replace(' ', '\ ')
+		try: os.mkdir(PathSaveRaw)
+		except: pass
+		PathSaveRaw = bpy.path.relpath(PathSaveRaw)+'/'
+	
+	PathRaw = Path
+	Path = Path.replace(' ', '\ ')
+	if Ext == '.xjt':
+		ExtSave = '.jpg'
+		#-------------------------------------------------
+		# EXTRACT XJT
+		import tarfile
+		
+		IMG = tarfile.open ('%s%s' % (PathRaw, File))
+		PRP = IMG.extractfile('PRP')
+		
+		Members = IMG.getmembers()
+		
+		for Member in Members:
+			Name = Member.name
+			if Name.startswith('l') and Name.endswith('.jpg'):
+				IMG.extract(Name, path=PathSaveRaw)
+		
+		#-------------------------------------------------
+		# INFO XJT
+		IMGs = []
+		for Line in PRP.readlines():
+			Line = str(Line)
+			
+			if Line.startswith("b'GIMP_XJ_IMAGE"):
+				for Segment in Line.split():
+					if Segment.startswith('w/h:'):
+						ResX, ResY = map (int, Segment[4:].split(','))
+			if Line.startswith("b'L") or Line.startswith("b'l"):
+				
+				if Line.startswith("b'L"): HasAlpha = True
+				else: HasAlpha = False
+				
+				md = None
+				op = 1
+				ox, oy = 0,0
+				
+				for Segment in Line.split():
+					
+					if Segment.startswith("b'"):
+						imageFile = 'l' + Segment[3:] + '.jpg'
+						imageFileAlpha ='la'+Segment[3:]+'.jpg'
+						
+						# Get Widht and Height from images
+						data = open(PathSaveRaw+imageFile, "rb").read()
+						
+						hexList = []
+						for ch in data:
+							byt = "%02X" % ch
+							hexList.append(byt)
+						
+						for k in range(len(hexList)-1):
+							if hexList[k] == 'FF' and (hexList[k+1] == 'C0' or hexList[k+1] == 'C2'):
+								ow = int(hexList[k+7],16)*256 + int(hexList[k+8],16)
+								oh = int(hexList[k+5],16)*256 + int(hexList[k+6],16)
+					
+					elif Segment.startswith('md:'): # mode
+						md = Segment[3:]
+						
+					elif Segment.startswith('op:'): # opacity
+						op = float(Segment[3:])*.01
+					
+					elif Segment.startswith('o:'): # origin
+						ox, oy = map(int, Segment[2:].split(','))
+					
+					elif Segment.startswith('n:'): # name
+						n = Segment[3:-4]
+						OpenBracket = n.find ('[')
+						CloseBracket = n.find (']')
+						
+						if OpenBracket != -1 and CloseBracket != -1:
+							RenderLayer = n[OpenBracket+1:CloseBracket]
+							NameShort = n[:OpenBracket]
+							
+						else:
+							RenderLayer = n
+							NameShort = n
+						
+						os.rename(PathSaveRaw+imageFile, PathSaveRaw+NameShort+'.jpg')
+						if HasAlpha: os.rename(PathSaveRaw+imageFileAlpha, PathSaveRaw+NameShort+'_A'+'.jpg')
+						
+				IMGs.append({'LayerMode':md, 'LayerOpacity':op,\
+							'LayerName':n, 'LayerNameShort':NameShort,\
+							'RenderLayer':RenderLayer, 'LayerCoords':[ow, oh, ox, oy], 'HasAlpha':HasAlpha})
+	
+	else: # Ext == '.xcf':
+		ExtSave = '.png'
+		#-------------------------------------------------
+		# CONFIG
+		XCFInfo = 'xcfinfo'
+		XCF2PNG = 'xcf2png'
+		#-------------------------------------------------
+		# INFO XCF
+		
+		CMD = '%s %s%s' % (XCFInfo, Path, File)
+		
+		Info = os.popen(CMD)
+		
+		IMGs = []
+		for Line in Info.readlines():
+			if Line.startswith ('+'):
+				
+				Line = Line.split(' ', 4)
+				
+				RenderLayer = Line[4]
+				
+				OpenBracket = RenderLayer.find ('[')
+				CloseBracket = RenderLayer.find (']')
+				
+				if OpenBracket != -1 and CloseBracket != -1:
+					RenderLayer = RenderLayer[OpenBracket+1:CloseBracket]
+					NameShort = Line[4][:OpenBracket]
+				else:
+					NameShort = Line[4].rstrip()
+					if GroupUntagged:
+						RenderLayer = '__Undefined__'
+					else:
+						RenderLayer = NameShort
+				
+				LineThree = Line[3]
+				Slash = LineThree.find('/')
+				if Slash == -1:
+					Mode = LineThree
+					Opacity = 1
+				else:
+					Mode = LineThree[:Slash]
+					Opacity = float(LineThree[Slash+1:LineThree.find('%')])*.01
+				
+				IMGs.append ({\
+					'LayerMode':Mode,\
+					'LayerOpacity':Opacity,\
+					'LayerName':Line[4].rstrip(),\
+					'LayerNameShort':NameShort,\
+					'LayerCoords':list(map(int, Line[1].replace('x', ' ').replace('+', ' +').replace('-', ' -').split())),\
+					'RenderLayer':RenderLayer,\
+					'HasAlpha':True,\
+					})
+			elif Line.startswith('Version'):
+				ResX, ResY = map (int, Line.split()[2].split('x'))
+		
+		#-------------------------------------------------
+		# EXTRACT XCF
+		if OpacityMode == 'BAKE':
+			Opacity = ''
+		else:
+			Opacity = ' --percent 100'
+		for Layer in IMGs:
+			CMD = '%s -C %s%s -o %s%s.png "%s"%s' %\
+			(XCF2PNG, Path, File, PathSave, Layer['LayerName'].replace(' ', '_'), Layer['LayerName'], Opacity)
+			os.system(CMD)
+	
+	#-------------------------------------------------
+	Scene = bpy.context.scene
+	#-------------------------------------------------
+	# CAMERA
+	
+	if SetCamera:
+		bpy.ops.object.camera_add(location=(0, 0, 10))
+		
+		Camera = bpy.context.active_object.data
+		
+		Camera.type = 'ORTHO'
+		Camera.ortho_scale = ResX * .01
+	
+	#-------------------------------------------------
+	# RENDER SETTINGS
+	
+	Render = Scene.render
+	
+	if SetCamera:
+		Render.resolution_x = ResX
+		Render.resolution_y = ResY
+		Render.resolution_percentage = 100
+	if PremulAlpha: Render.alpha_mode = 'PREMUL'
+	
+	#-------------------------------------------------
+	# 3D VIEW SETTINGS
+	
+	Scene.game_settings.material_mode = 'GLSL'
+	
+	Areas = bpy.context.screen.areas
+	
+	for Area in Areas:
+		if Area.type == 'VIEW_3D':
+			Area.active_space.viewport_shade = 'TEXTURED'
+			Area.active_space.show_textured_solid = True
+			Area.active_space.show_floor = False
+	
+	#-------------------------------------------------
+	# 3D LAYERS
+	
+	def Make3DLayer (Name, NameShort, Z, Coords, RenderLayer, LayerMode, LayerOpacity, HasAlpha):
+		
+		# RenderLayer
+		
+		if SetupCompo:
+			if not bpy.context.scene.render.layers.get(RenderLayer):
+				
+				bpy.ops.scene.render_layer_add()
+				
+				LayerActive = bpy.context.scene.render.layers.active
+				LayerActive.name = RenderLayer
+				LayerActive.use_pass_vector = True
+				LayerActive.use_sky = False
+				LayerActive.use_edge_enhance = False
+				LayerActive.use_strand = False
+				LayerActive.use_halo = False
+				
+				global LayerNum
+				for i in range (0,20):
+					if not i == LayerNum:
+						LayerActive.layers[i] = False
+				
+				bpy.context.scene.layers[LayerNum] = True
+				
+				LayerFlags[RenderLayer] = bpy.context.scene.render.layers.active.layers
+				
+				LayerList.append([RenderLayer, LayerMode, LayerOpacity])
+				
+				LayerNum += 1
+		
+		# Object
+		bpy.ops.mesh.primitive_plane_add(\
+		view_align=False,\
+		enter_editmode=False,\
+		rotation=(0, 0, pi))
+		
+		bpy.ops.object.rotation_apply()
+		
+		Active = bpy.context.active_object
+		
+		if SetupCompo:
+			Active.layers = LayerFlags[RenderLayer]
+		
+		Active.location = (\
+			(float(Coords[2])-(ResX*0.5))*LayerScale,\
+			(-float(Coords[3])+(ResY*0.5))*LayerScale, Z)
+		
+		for Vert in Active.data.vertices:
+			Vert.co[0] += 1
+			Vert.co[1] += -1
+			
+		Active.dimensions = float(Coords[0])*LayerScale, float(Coords[1])*LayerScale, 0
+		
+		bpy.ops.object.scale_apply()
+		
+		bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='MEDIAN')
+		
+		Active.show_wire = True
+		
+		Active.name = NameShort
+		bpy.ops.mesh.uv_texture_add()
+		
+		# Material
+		
+		'''if bpy.data.materials.get(NameShort):
+			Mat = bpy.data.materials[NameShort]
+			if not Active.material_slots:
+				bpy.ops.object.material_slot_add()
+			Active.material_slots[0].material = Mat
+		else:'''
+		
+		Mat = bpy.data.materials.new(NameShort)
+		Mat.diffuse_color = (1,1,1)
+		Mat.use_raytrace = False
+		Mat.use_shadows = False
+		Mat.use_cast_buffer_shadows = False
+		Mat.use_cast_approximate = False
+		if HasAlpha:
+			Mat.use_transparency = True
+			if OpacityMode == 'MAT': Mat.alpha = LayerOpacity
+			else: Mat.alpha = 0
+		if ShadelessMats: Mat.use_shadeless = True
+		
+		if Ext == '.xcf':
+			# Color & Alpha PNG
+			Tex = bpy.data.textures.new(NameShort, 'IMAGE')
+			Tex.extension = 'CLIP'
+			Tex.use_preview_alpha = True
+			
+			Img = bpy.data.images.new(NameShort)
+			Img.source = 'FILE'

@@ Diff output truncated at 10240 characters. @@



More information about the Bf-extensions-cvs mailing list