[Bf-blender-cvs] SVN commit: /data/svn/bf-blender [20143] trunk/blender/release/scripts/ image_2d_cutout.py: 2D Cutout Image Importer

Campbell Barton ideasman42 at gmail.com
Mon May 11 07:35:32 CEST 2009


Revision: 20143
          http://projects.blender.org/plugins/scmsvn/viewcvs.php?view=rev&root=bf-blender&revision=20143
Author:   campbellbarton
Date:     2009-05-11 07:35:32 +0200 (Mon, 11 May 2009)

Log Message:
-----------
2D Cutout Image Importer
from Kevin Morgan (forTe)

imports images as quads in the 3D view

made some changes
- images that fail to import give an error popup rather then a script error
- extension input is only shown for batch directory importing
- extension comparison is now case insensitive
- importing images from "/" failed, (bug in Blender.sys.dirname), use os.path.dirname since os is needed for batch import in other places.
- disable Esc for quitting because escaping from the file selector would quit the script too.

Added Paths:
-----------
    trunk/blender/release/scripts/image_2d_cutout.py

Added: trunk/blender/release/scripts/image_2d_cutout.py
===================================================================
--- trunk/blender/release/scripts/image_2d_cutout.py	                        (rev 0)
+++ trunk/blender/release/scripts/image_2d_cutout.py	2009-05-11 05:35:32 UTC (rev 20143)
@@ -0,0 +1,559 @@
+#!BPY
+
+"""
+Name: '2D Cutout Image Importer'
+Blender: 249
+Group: 'Image'
+Tooltip: 'Batch UV Map images to Planes'
+"""
+
+__author__ = "Kevin Morgan (forTe)"
+__url__ = ("Home page, http://gamulabs.freepgs.com")
+__version__ = "1.2.1"
+__bpydoc__ = """\
+This Script will take an image and
+UV map it to a plane sharing the same width to height ratio as the image.
+Import options allow for the image to be a still or sequence type image
+<br><br>
+Imports can be single images or whole directories of images depending on the chosen
+option.
+"""
+
+####################################################
+#Copyright (C) 2008: Kevin Morgan
+####################################################
+#-------------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 3 of the License, or
+#(at your option) any later version.
+#
+#This program is distributed in the hopes 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, see <http://www.gnu.org/licenses>.
+####################################################
+####################################################
+#V1.0
+#Basic Functionality
+#Published June 28, 2007
+####################################################
+#V1.1
+#Added Support for enabling viewport transparency
+#Added more options to the UI for materials
+#Added Proportionality code (Pixels per unit)
+#Added GPL License Block
+#Published June 29, 2007
+####################################################
+#V1.2
+#Added Support for Copying Existing Materials
+#Import Images as Sequences
+#Refreshed GUI - now with more clutter :(
+#Miscellaneous and Housekeeping
+#Published June 16, 2008
+####################################################
+#V1.2.1
+#Added Extend Texture Mode option at request of a user
+#Published September 24, 2008
+####################################################
+
+import Blender
+from Blender import BGL, Draw, Image, Mesh, Material, Texture, Window
+from Blender.Mathutils import *
+import bpy
+
+# Global Constants
+DIR = 0
+SINGLE = 1
+CUROFFS = 0
+
+# GUI CONSTANTS
+NO_EVT = 0
+SINGLE_IMG = 1
+DIRECTORY_IMG = 2
+CLR_PATH = 3
+CHG_EXT = 4
+EXIT = 5
+DO_SCRIPT = 6
+
+VERSIONSTRING = '1.2.1'
+
+# Note the two parameter dicts could be combined, I just, liked them seperate...
+# GUI Buttons Dict
+GUIPARAMS = {
+	'Path': Draw.Create(''),
+	'ImageExt': Draw.Create(''),
+	'Seq': Draw.Create(0),
+	'PackImage': Draw.Create(0),
+	'PPU': Draw.Create(50),
+	'VPTransp': Draw.Create(1),
+	'XOff': Draw.Create(0.0),
+	'YOff': Draw.Create(0.0),
+	'ZOff': Draw.Create(0.0),
+	'CopyMat': Draw.Create(0),
+	'MatId': Draw.Create(0),
+	'MatCol': Draw.Create(1.0, 0.0, 0.0),
+	'Ref': Draw.Create(0.8),
+	'Spec': Draw.Create(0.5),
+	'Hard': Draw.Create(50),
+	'Alpha': Draw.Create(1.0),
+	'ZTransp': Draw.Create(1),
+	'Shadeless': Draw.Create(0),
+	'TexChan': Draw.Create(1),
+	'MPTCol': Draw.Create(1),
+	'MPTAlpha': Draw.Create(1),
+	'UseAlpha': Draw.Create(1),
+	'CalcAlpha': Draw.Create(0),
+	'ExtendMode': Draw.Create(0),
+	'AutoRefresh': Draw.Create(0),
+	'Cyclic': Draw.Create(0),
+	'Frames': Draw.Create(100),
+	'Offs': Draw.Create(0),
+	'StartFr': Draw.Create(1),
+	'RedrawImp': Draw.Create(0)
+}
+
+# Script Execution Paramaters
+PARAMS = {
+	'ImagePaths': [], 									# Path to images to import
+	'ImportType': SINGLE, 							# Import a Directory or a Single Image?
+	'ImageProp': Image.Sources.STILL, 	# What sources for the image, still or sequence
+	'PackImage': 0,											# Pack the Image(s)?
+	'PPU': 20, 													# Pixels Per Blender Unit
+	'MakeTransp': 1, 										# Make face transparent in viewport
+	
+	'NewMat': 1, 												# If true make a new material, otherwise duplicate an existing one, replacing appropriate attributes
+	'MaterialId': 0,										# ID to take from the Materials list upon copy
+	'Materials': None,									# Materials in Scene
+	'MatProps': {'Col': [1.0, 0.0, 0.0], 'Shadeless': 1, 'Ref': 0.5, 'Spec': 0.5, 'Hard': 200, 'Alpha': 1.0, 'ZTransp': 1},
+	
+	'TexProps': {'UseAlpha': 1, 'CalcAlpha': 0, 'ExtendMode': 0}, # Texture Properties
+	'TexChannel': 0, 										# Texture Channel
+	'TexMapTo': {'Col': 1, 'Alpha': 1}, # Map to Col and/or Alpha
+	'SeqProps': {'AutoRefresh': 0, 'Cyclic': 0, 'Frames': 100, 'Offs': 0, 'StartFr': 1},
+	'ObOffset': Vector(1, 0, 0) 				# Offset by this vector upon creation for multifile import
+}
+
+# Get the Active Scene, of course
+scn = bpy.data.scenes.active
+
+##########################################
+# MAIN SCRIPT FUNCTIONS
+##########################################
+
+def imgImport(imgPath):
+	global CUROFFS, PARAMS
+	######################################
+	# Load the image
+	######################################
+	try:
+		img = Image.Load(imgPath)
+		imgDimensions = img.getSize() # do this to ensure the data is available
+	except:
+		Blender.Draw.PupMenu('Error%t|Unsupported image format for "'+ imgPath.split('\\')[-1].split('/')[-1] +'"')
+		return		
+	
+	if PARAMS['PackImage']:
+		img.pack()
+	name = Blender.sys.makename(imgPath, strip = 1)
+	
+	######################################
+	# Construct the mesh
+	######################################
+	
+	me = Mesh.New(name)
+	
+	# Calculate Dimensions from Image Size
+	dim = [float(i)/PARAMS['PPU'] for i in imgDimensions]
+	v = [[dim[0], dim[1], 0], [-dim[0], dim[1], 0], [-dim[0], -dim[1], 0], [dim[0], -dim[1], 0]]
+	me.verts.extend(v)
+	me.faces.extend([0, 1, 2, 3])
+	
+	me.faces[0].image = img
+	me.faces[0].uv = [Vector(1.0, 1.0), Vector(0.0, 1.0), Vector(0.0, 0.0), Vector(1.0, 0.0)]
+	
+	if PARAMS['MakeTransp']:
+		me.faces[0].transp = Mesh.FaceTranspModes.ALPHA
+	
+	######################################
+	# Modify the Material
+	######################################
+	
+	mat = None
+	if not PARAMS['NewMat']:
+		mat = PARAMS['Materials'][PARAMS['MaterialId']].__copy__()
+		mat.setName(name)
+	else:
+		mat = Material.New(name)
+		properties = PARAMS['MatProps']
+		mat.setRGBCol(properties['Col'])
+		mat.setRef(properties['Ref'])
+		mat.setSpec(properties['Spec'])
+		mat.setHardness(properties['Hard'])
+		mat.setAlpha(properties['Alpha'])
+		
+		if properties['Shadeless']:
+			mat.mode |= Material.Modes.SHADELESS
+		if properties['ZTransp']:
+			mat.mode |= Material.Modes.ZTRANSP
+	
+	properties = PARAMS['TexProps']
+		
+	tex = Texture.New(name)
+	tex.setType('Image')
+	tex.setImage(img)
+	if properties['UseAlpha']:
+		tex.useAlpha = Texture.ImageFlags.USEALPHA
+			
+	if properties['CalcAlpha']:
+		tex.calcAlpha = Texture.ImageFlags.CALCALPHA
+		
+	if properties['ExtendMode']:
+		tex.setExtend('Extend')
+		
+	if PARAMS['ImageProp'] == Image.Sources.SEQUENCE:
+		properties = PARAMS['SeqProps']
+		
+		img.source = PARAMS['ImageProp'] # Needs to be done here, otherwise an error with earlier getSize()
+		
+		tex.animStart = properties['StartFr']
+		tex.animOffset = properties['Offs']
+		tex.animFrames = properties['Frames']
+		tex.autoRefresh = properties['AutoRefresh']
+		tex.cyclic = properties['Cyclic']
+			
+	texMapSetters = Texture.TexCo.UV
+	
+	# PARAMS['TexMapTo']['Col'] (and alpha) will either be 0 or 1 because its from a toggle, otherwise this line doesn't work
+	texChanSetters = Texture.MapTo.COL * PARAMS['TexMapTo']['Col'] | Texture.MapTo.ALPHA * PARAMS['TexMapTo']['Alpha']
+	
+	mat.setTexture(PARAMS['TexChannel'], tex, texMapSetters, texChanSetters)
+	me.materials += [mat]
+	
+	######################################
+	# Object Construction
+	######################################
+	
+	ob = scn.objects.new(me, name)
+	p = Vector(ob.getLocation()) # Should be the origin, but just to be safe, get it
+	ob.setLocation((CUROFFS * PARAMS['ObOffset']) + p)
+		
+	return
+
+def translateParams():
+	# Translates (or assigns for the most part) GUI values to those that can be read by the
+	# Import Function
+	
+	global GUIPARAMS, PARAMS
+	
+	if GUIPARAMS['Seq'].val and PARAMS['ImportType'] != DIR:
+		PARAMS['ImageProp'] = Image.Sources.SEQUENCE
+	
+	PARAMS['PackImage'] = GUIPARAMS['PackImage'].val
+	PARAMS['PPU'] = GUIPARAMS['PPU'].val
+	PARAMS['MakeTransp'] = GUIPARAMS['VPTransp'].val
+	PARAMS['ObOffset'] = Vector(GUIPARAMS['XOff'].val, GUIPARAMS['YOff'].val, GUIPARAMS['ZOff'].val)
+	
+	PARAMS['NewMat'] = not GUIPARAMS['CopyMat'].val
+	PARAMS['MaterialId'] = GUIPARAMS['MatId'].val
+	PARAMS['MatProps']['Col'] = list(GUIPARAMS['MatCol'].val)
+	PARAMS['MatProps']['Ref'] = GUIPARAMS['Ref'].val
+	PARAMS['MatProps']['Spec'] = GUIPARAMS['Spec'].val
+	PARAMS['MatProps']['Hard'] = GUIPARAMS['Hard'].val
+	PARAMS['MatProps']['Alpha'] = GUIPARAMS['Alpha'].val
+	PARAMS['MatProps']['ZTransp'] = GUIPARAMS['ZTransp'].val
+	PARAMS['MatProps']['Shadeless'] = GUIPARAMS['Shadeless'].val
+	
+	PARAMS['TexChannel'] = GUIPARAMS['TexChan'].val - 1 #Channels are 0-9, but GUI shows 1-10
+	PARAMS['TexProps']['UseAlpha'] = GUIPARAMS['UseAlpha'].val
+	PARAMS['TexProps']['CalcAlpha'] = GUIPARAMS['CalcAlpha'].val
+	PARAMS['TexProps']['ExtendMode'] = GUIPARAMS['ExtendMode'].val
+	PARAMS['TexMapTo']['Col'] = GUIPARAMS['MPTCol'].val
+	PARAMS['TexMapTo']['Alpha'] = GUIPARAMS['MPTAlpha'].val
+	
+	PARAMS['SeqProps']['AutoRefresh'] = GUIPARAMS['AutoRefresh'].val
+	PARAMS['SeqProps']['Cyclic'] = GUIPARAMS['Cyclic'].val
+	PARAMS['SeqProps']['Frames'] = GUIPARAMS['Frames'].val
+	PARAMS['SeqProps']['Offs'] = GUIPARAMS['Offs'].val
+	PARAMS['SeqProps']['StartFr'] = GUIPARAMS['StartFr'].val
+	return
+	
+def doScript():
+	# Main script Function
+	# Consists of choosing between 2 loops, one with a redraw, one without, see comments for why
+	
+	global CUROFFS
+	
+	translateParams()
+	
+	total = len(PARAMS['ImagePaths'])
+	broken = 0
+	
+	if GUIPARAMS['RedrawImp'].val: # Reduces the need to compare on every go through the loop
+		for i, path in enumerate(PARAMS['ImagePaths']):

@@ Diff output truncated at 10240 characters. @@




More information about the Bf-blender-cvs mailing list