Ejemplo n.º 1
0
def copy_images(dest_dir):
	if dest_dir[-1] != sys.sep:
		dest_dir += sys.sep
	
	# Get unique image names
	uniqueImages = {}
	for matname, mat, image in MTL_DICT.itervalues(): # Only use image name
		# Get Texface images
		if image:
			uniqueImages[image] = image # Should use sets here. wait until Python 2.4 is default.
		
		# Get MTex images
		if mat:
			for mtex in mat.getTextures():
				if mtex and mtex.tex.type == Blender.Texture.Types.IMAGE:
					image_tex = mtex.tex.image
					if image_tex:
						try:
							uniqueImages[image_tex] = image_tex
						except:
							pass
	
	# Now copy images
	copyCount = 0
	
	for bImage in uniqueImages.itervalues():
		image_path = sys.expandpath(bImage.filename)
		if sys.exists(image_path):
			# Make a name for the target path.
			dest_image_path = dest_dir + image_path.split('\\')[-1].split('/')[-1]
			if not sys.exists(dest_image_path): # Image isnt alredy there
				print '\tCopying "%s" > "%s"' % (image_path, dest_image_path)
				copy_file(image_path, dest_image_path)
				copyCount+=1
	print '\tCopied %d images' % copyCount
Ejemplo n.º 2
0
def copy_images(dest_dir):
	if dest_dir[-1] != sys.sep:
		dest_dir += sys.sep
	
	# Get unique image names
	uniqueImages = {}
	for matname, mat, image in MTL_DICT.itervalues(): # Only use image name
		# Get Texface images
		if image:
			uniqueImages[image] = image # Should use sets here. wait until Python 2.4 is default.
		
		# Get MTex images
		if mat:
			for mtex in mat.getTextures():
				if mtex and mtex.tex.type == Blender.Texture.Types.IMAGE:
					image_tex = mtex.tex.image
					if image_tex:
						try:
							uniqueImages[image_tex] = image_tex
						except:
							pass
	
	# Now copy images
	copyCount = 0
	
	for bImage in uniqueImages.itervalues():
		image_path = sys.expandpath(bImage.filename)
		if sys.exists(image_path):
			# Make a name for the target path.
			dest_image_path = dest_dir + image_path.split('\\')[-1].split('/')[-1]
			if not sys.exists(dest_image_path): # Image isnt alredy there
				print '\tCopying "%s" > "%s"' % (image_path, dest_image_path)
				copy_file(image_path, dest_image_path)
				copyCount+=1
	print '\tCopied %d images' % copyCount
Ejemplo n.º 3
0
def Warning_SaveOver(path):
    '''Returns - True to save, False dont save'''
    if sys.exists(sys.expandpath(path)):
        ret = Draw.PupMenu('Save over%t|' + path)
        if ret == -1:
            return False

    return True
Ejemplo n.º 4
0
def Warning_SaveOver(path):
	'''Returns - True to save, False dont save'''
	if sys.exists(sys.expandpath(path)):
		ret= Draw.PupMenu('Save over%t|' + path)
		if ret == -1:
			return False
	
	return True
Ejemplo n.º 5
0
 def writeHeader(self):
     bfile = sys.expandpath(Blender.Get('filename'))
     self.file.write("#VRML V2.0 utf8\n\n")
     self.file.write("# This file was authored with Blender " \
         "(http://www.blender.org/)\n")
     self.file.write("# Blender version %s\n" % Blender.Get('version'))
     self.file.write("# Blender file %s\n" % sys.basename(bfile))
     self.file.write("# Exported using VRML97 exporter " \
         "v1.55 (2006/01/17)\n\n")
Ejemplo n.º 6
0
	def writeHeader(self):
		bfile = sys.expandpath(Blender.Get('filename'))
		self.file.write("#VRML V2.0 utf8\n\n")
		self.file.write("# This file was authored with Blender " \
						"(http://www.blender.org/)\n")
		self.file.write("# Blender version %s\n" % Blender.Get('version'))
		self.file.write("# Blender file %s\n" % sys.basename(bfile))
		self.file.write("# Exported using VRML97 exporter " \
						"v1.55 (2006/01/17)\n\n")
Ejemplo n.º 7
0
def Error_NoDir(path):
    '''True if dirs missing, False if dirs there
	
	Use simply by doing...
	if Error_NoDir(path): return
	'''
    if not sys.exists(sys.expandpath(path)):
        Draw.PupMenu("Error%t|Path does not exist: " + path)
        return True
    return False
Ejemplo n.º 8
0
def Error_NoFile(path):
    '''True if file missing, False if files there
	
	Use simply by doing...
	if Error_NoFile(path): return
	'''
    if not sys.exists(sys.expandpath(path)):
        Draw.PupMenu("Error%t|Can't open file: " + path)
        return True
    return False
Ejemplo n.º 9
0
def Error_NoDir(path):
	'''True if dirs missing, False if dirs there
	
	Use simply by doing...
	if Error_NoDir(path): return
	'''
	if not sys.exists(sys.expandpath(path)):
		Draw.PupMenu("Error%t|Path does not exist: " + path)
		return True
	return False
Ejemplo n.º 10
0
def Error_NoFile(path):
	'''True if file missing, False if files there
	
	Use simply by doing...
	if Error_NoFile(path): return
	'''
	if not sys.exists(sys.expandpath(path)):
		Draw.PupMenu("Error%t|Can't open file: " + path)
		return True
	return False
	def export_texture(self, texture, material):
		image = texture.getImage()
			
		image_path = sys.expandpath(image.filename)
		dest_path = self.texture_dir + image_path.split('\\')[-1].split('/')[-1]
		
		texture_id = texture.getName()
		if material.getName() == texture_id:
			texture_id += "Texture"
		
		self.out.write("\t\t<texture id=\""+ texture_id +"\" src=\"images"+os.sep+os.path.basename(image.getFilename())+"\" />\n")
		self.out.write("\t\t<material_layer texture=\"#"+ texture_id +"\" mapinput=\"UV1\" mapto=\"M_COLOR\" />\n")
		
		if sys.exists(image_path) and not sys.exists(dest_path):
			copy_file(image_path, dest_path)
Ejemplo n.º 12
0
	def __init__(self, filename):
		# find where the directory path ends
		# (both un*x and win accounted for)
		self.path, simpleFile	= os.path.split(sys.expandpath(filename))
		self.objName			= os.path.splitext(simpleFile)[0]
		# material values (to be checked later)
		self.faces				= []
		self.verts				= []
		self.uvs				= []
		self.faceuvs			= []
		self.alpha				=\
		self.rgbCol	 			=\
		self.amb				=\
		self.emit				=\
		self.colorTexture		=\
		self.specTexture		=\
		self.spec				=\
		self.specCol			= None
		# finally, start chronometer
		sys.time()
Ejemplo n.º 13
0
	tmpPath = stripFile(filePath) + stripPath(imageFileName)
	if sys.exists(tmpPath):
		if VERBOSE: print '\t\tFile found in path (1)"%s".' % tmpPath
		return imageLoad(tmpPath)
	
	
	# os needed if we go any further.
	if not os:
		if VERBOSE: print '\t\tCreating a placeholder with a face path: "%s".' % imagePath
		return imageLoad(imagePath) # Will jus treturn a placeholder.
	
	
	# We have os.
	# GATHER PATHS.
	paths = {} # Store possible paths we may use, dict for no doubles.
	tmpPath = addSlash(sys.expandpath('//')) # Blenders path
	if sys.exists(tmpPath):
		if VERBOSE: print '\t\tSearching in %s' % tmpPath
		paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading 
		paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list.
		paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext
	else:
		if VERBOSE: print '\tNo Path: "%s"' % tmpPath
	
	tmpPath = imageFilePath
	if sys.exists(tmpPath):
		if VERBOSE: print '\t\tSearching in %s' % tmpPath
		paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading 
		paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list.
		paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext
	else:
Ejemplo n.º 14
0
def imageFromObjectsOrtho(objects,
                          path,
                          width,
                          height,
                          smooth,
                          alpha=True,
                          camera_matrix=None,
                          format=Render.PNG):
    '''
	Takes any number of objects and renders them on the z axis, between x:y-0 and x:y-1
	Usefull for making images from a mesh without per pixel operations
	- objects must be alredy placed
	- smooth, anti alias True/False
	- path renders to a PNG image
	- alpha weather to render background as alpha
	
	returns the blender image
	'''
    ext = '.' + extFromFormat(format)
    print ext
    # remove an extension if its alredy there
    if path.lower().endswith(ext):
        path = path[:-4]

    path_expand = sys.expandpath(path) + ext

    print path_expand, 'path'

    # Touch the path
    try:
        f = open(path_expand, 'w')
        f.close()
    except:
        raise 'Error, could not write to path:' + path_expand

    # RENDER THE FACES.
    scn = Scene.GetCurrent()
    render_scn = Scene.New()
    render_scn.makeCurrent()
    render_scn.Layers |= (1 << 20) - 1  # all layers enabled

    # Add objects into the current scene
    for ob in objects:
        render_scn.link(ob)

    render_context = render_scn.getRenderingContext()
    render_context.setRenderPath(
        '')  # so we can ignore any existing path and save to the abs path.

    render_context.imageSizeX(width)
    render_context.imageSizeY(height)

    if smooth:
        render_context.enableOversampling(True)
        render_context.setOversamplingLevel(16)
    else:
        render_context.enableOversampling(False)

    render_context.setRenderWinSize(100)
    render_context.setImageType(format)
    render_context.enableExtensions(True)
    #render_context.enableSky() # No alpha needed.
    if alpha:
        render_context.alphaMode = 1
        render_context.enableRGBAColor()
    else:
        render_context.alphaMode = 0
        render_context.enableRGBColor()

    render_context.displayMode = 0  # fullscreen

    # New camera and object
    render_cam_data = Camera.New('ortho')
    render_cam_ob = Object.New('Camera')
    render_cam_ob.link(render_cam_data)
    render_scn.link(render_cam_ob)
    render_scn.objects.camera = render_cam_ob

    render_cam_data.type = 'ortho'

    # Position the camera
    if camera_matrix:
        render_cam_ob.setMatrix(camera_matrix)
        # We need to take into account the matrix scaling when setting the size
        # so we get the image bounds defined by the matrix
        # first get the x and y factors from the matrix.
        # To render the correct dimensions we must use the aspy and aspy to force the matrix scale to
        # override the aspect enforced by the width and weight.
        cent = Vector() * camera_matrix
        xvec = Vector(1, 0, 0) * camera_matrix
        yvec = Vector(0, 1, 0) * camera_matrix
        # zvec= Vector(0,0,1) * camera_matrix
        xlen = (cent - xvec).length  # half height of the image
        ylen = (cent - yvec).length  # half width of the image
        # zlen = (cent-zvec).length # dist to place the camera? - just use the loc for now.

        # less then 1.0 portrate, 1.0 or more is portrate
        asp_cam_mat = xlen / ylen  # divide by zero? - possible but scripters fault.
        asp_image_res = float(width) / height
        #print 'asp quad', asp_cam_mat, 'asp_image', asp_image_res
        #print 'xylen', xlen, ylen, 'w/h', width, height
        # Setup the aspect

        if asp_cam_mat > asp_image_res:
            # camera is wider then image res.
            # to make the image wider, reduce the aspy
            asp_diff = asp_image_res / asp_cam_mat
            min_asp = asp_diff * 200
            #print 'X', min_asp

        elif asp_cam_mat < asp_image_res:  # asp_cam_mat < asp_image_res
            # camera is narrower then image res
            # to make the image narrower, reduce the aspx
            asp_diff = asp_cam_mat / asp_image_res
            min_asp = asp_diff * 200
            #print 'Y', min_asp
        else:
            min_asp = 200

        # set the camera size
        if xlen > ylen:
            if asp_cam_mat > asp_image_res:
                render_context.aspectX = 200  # get the greatest range possible
                render_context.aspectY = min_asp  # get the greatest range possible
            else:
                render_context.aspectY = 200  # get the greatest range possible
                render_context.aspectX = min_asp  # get the greatest range possible
            #print "xlen bigger"
            render_cam_data.scale = xlen * 2
        elif xlen < ylen:  # ylen is bigger
            if asp_cam_mat > asp_image_res:
                render_context.aspectX = 200  # get the greatest range possible
                render_context.aspectY = min_asp  # get the greatest range possible
            else:
                render_context.aspectY = 200  # get the greatest range possible
                render_context.aspectX = min_asp  # get the greatest range possible
            #print "ylen bigger"
            render_cam_data.scale = ylen * 2
        else:
            # asppect 1:1
            #print 'NOLEN Bigger'
            render_cam_data.scale = xlen * 2

        #print xlen, ylen, 'xlen, ylen'

    else:
        if width > height:
            min_asp = int((float(height) / width) * 200)
            render_context.aspectX = min_asp
            render_context.aspectY = 200
        else:
            min_asp = int((float(width) / height) * 200)
            render_context.aspectX = 200
            render_context.aspectY = min_asp

        render_cam_data.scale = 1.0
        render_cam_ob.LocZ = 1.0
        render_cam_ob.LocX = 0.5
        render_cam_ob.LocY = 0.5

    Blender.Window.RedrawAll()

    render_context.render()
    render_context.saveRenderedImage(path)
    Render.CloseRenderWindow()
    #if not B.sys.exists(PREF_IMAGE_PATH_EXPAND):
    #	raise 'Error!!!'

    scn.makeCurrent()
    Scene.Unlink(render_scn)

    # NOW APPLY THE SAVED IMAGE TO THE FACES!
    #print PREF_IMAGE_PATH_EXPAND
    try:
        target_image = Image.Load(path_expand)
        return target_image
    except:
        raise 'Error: Could not render or load the image at path "%s"' % path_expand
        return
Ejemplo n.º 15
0
def edit_extern(image=None):

    if not image:
        image = Image.GetCurrent()

    if not image:  # Image is None
        Draw.PupMenu('ERROR: You must select an active Image.')
        return
    if image.packed:
        Draw.PupMenu('ERROR: Image is packed, unpack before editing.')
        return

    imageFileName = sys.expandpath(image.filename)

    if not sys.exists(imageFileName):
        Draw.PupMenu('ERROR: Image path does not exist.')
        return

    pupblock = [imageFileName.split('/')[-1].split('\\')[-1]]

    new_text = False
    try:
        appstring = Registry.GetKey('ExternalImageEditor', True)
        appstring = appstring['path']

        # for ZanQdo if he removed the path from the textbox totaly. ;) - Cam
        if not appstring or appstring.find('%f') == -1:
            new_text = True
    except:
        new_text = True

    if new_text:
        pupblock.append('first time, set path.')
        if platform == 'win32':
            appstring = 'start "" /B "%f"'
        elif platform == 'darwin':
            appstring = 'open "%f"'
        else:
            appstring = 'gimp-remote "%f"'

    appstring_but = Draw.Create(appstring)
    save_default_but = Draw.Create(0)

    pupblock.append(
        ('editor: ', appstring_but, 0, 48,
         'Path to application, %f will be replaced with the image path.'))
    pupblock.append(('Set Default', save_default_but,
                     'Store this path in the blender registry.'))

    # Only configure if Shift is held,
    if Blender.Window.GetKeyQualifiers() & Blender.Window.Qual.SHIFT:
        if not Draw.PupBlock('External Image Editor...', pupblock):
            return

    appstring = appstring_but.val
    save_default = save_default_but.val

    if save_default:
        Registry.SetKey('ExternalImageEditor', {'path': appstring}, True)

    if appstring.find('%f') == -1:
        Draw.PupMenu(
            'ERROR: The comment you entered did not contain the filename ("%f")'
        )
        return

    # -------------------------------

    appstring = appstring.replace('%f', imageFileName)
    print '\tediting image with command "%s"' % appstring
    os.system(appstring)
Ejemplo n.º 16
0
def comprehensiveImageLoad(
    imagePath, filePath, PLACE_HOLDER=True, RECURSIVE=True, VERBOSE=False, CONVERT_CALLBACK=None
):
    """
	imagePath: The image filename
		If a path precedes it, this will be searched as well.
		
	filePath: is the directory where the image may be located - any file at teh end will be ignored.
	
	PLACE_HOLDER: if True a new place holder image will be created.
		this is usefull so later you can relink the image to its original data.
	
	VERBOSE: If True debug info will be printed.
	
	RECURSIVE: If True, directories will be recursivly searched.
		Be carefull with this if you have files in your root directory because it may take a long time.
	
	CASE_INSENSITIVE: for non win32 systems, find the correct case for the file.
	
	CONVERT_CALLBACK: a function that takes an existing path and returns a new one.
		Use this when loading image formats blender may not support, the CONVERT_CALLBACK
		can take the path for a GIF (for example), convert it to a PNG and return the PNG's path.
		For formats blender can read, simply return the path that is given.
	"""

    # VERBOSE = True

    if VERBOSE:
        print "img:", imagePath, "file:", filePath

    if os == None and CASE_INSENSITIVE:
        CASE_INSENSITIVE = True

        # When we have the file load it with this. try/except niceness.

    def imageLoad(path):
        # if path.endswith('\\') or path.endswith('/'):
        # 	raise 'INVALID PATH'

        if CONVERT_CALLBACK:
            path = CONVERT_CALLBACK(path)

        try:
            img = bpy.data.images.new(filename=path)
            if VERBOSE:
                print '\t\tImage loaded "%s"' % path
            return img
        except:
            if VERBOSE:
                if sys.exists(path):
                    print '\t\tImage failed loading "%s", mabe its not a format blender can read.' % (path)
                else:
                    print '\t\tImage not found, making a place holder "%s"' % (path)
            if PLACE_HOLDER:
                img = bpy.data.images.new(stripPath(path), 4, 4)
                img.filename = path
                return img  # blank image
            else:
                return None

                # Image formats blender can read

    IMAGE_EXT = [
        "jpg",
        "jpeg",
        "png",
        "tga",
        "bmp",
        "rgb",
        "sgi",
        "bw",
        "iff",
        "lbm",  # Blender Internal
        "gif",
        "psd",
        "tif",
        "tiff",
        "pct",
        "pict",
        "pntg",
        "qtif",
    ]  # Quacktime, worth a try.

    imageFileName = stripPath(imagePath)  # image path only
    imageFileName_lower = imageFileName.lower()  # image path only

    if VERBOSE:
        print '\tSearchingExisting Images for "%s"' % imagePath
    for i in bpy.data.images:
        if stripPath(i.filename.lower()) == imageFileName_lower:
            if VERBOSE:
                print "\t\tUsing existing image."
            return i

    if VERBOSE:
        print '\tAttempting to load "%s"' % imagePath
    if sys.exists(imagePath):
        if VERBOSE:
            print '\t\tFile found where expected "%s".' % imagePath
        return imageLoad(imagePath)

    imageFileName_noext = stripExt(imageFileName)  # With no extension.
    imageFileName_noext_lower = stripExt(imageFileName_lower)  # With no extension.
    imageFilePath = stripFile(imagePath)

    # Remove relative path from image path
    if imageFilePath.startswith("./") or imageFilePath.startswith(".\\"):
        imageFilePath = imageFilePath[2:]

        # Attempt to load from obj path.
    tmpPath = stripFile(filePath) + stripPath(imageFileName)
    if sys.exists(tmpPath):
        if VERBOSE:
            print '\t\tFile found in path (1)"%s".' % tmpPath
        return imageLoad(tmpPath)

        # os needed if we go any further.
    if not os:
        if VERBOSE:
            print '\t\tCreating a placeholder with a face path: "%s".' % imagePath
        return imageLoad(imagePath)  # Will jus treturn a placeholder.

        # We have os.
        # GATHER PATHS.
    paths = {}  # Store possible paths we may use, dict for no doubles.
    tmpPath = addSlash(sys.expandpath("//"))  # Blenders path
    if sys.exists(tmpPath):
        if VERBOSE:
            print "\t\tSearching in %s" % tmpPath
        paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
        paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]])  # Lower case list.
        paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]])  # Lower case no ext
    else:
        if VERBOSE:
            print '\tNo Path: "%s"' % tmpPath

    tmpPath = imageFilePath
    if sys.exists(tmpPath):
        if VERBOSE:
            print "\t\tSearching in %s" % tmpPath
        paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
        paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]])  # Lower case list.
        paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]])  # Lower case no ext
    else:
        if VERBOSE:
            print '\tNo Path: "%s"' % tmpPath

    tmpPath = stripFile(filePath)
    if sys.exists(tmpPath):
        if VERBOSE:
            print "\t\tSearching in %s" % tmpPath
        paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
        paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]])  # Lower case list.
        paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]])  # Lower case no ext
    else:
        if VERBOSE:
            print '\tNo Path: "%s"' % tmpPath

    tmpPath = addSlash(bpy.config.textureDir)
    if tmpPath and sys.exists(tmpPath):
        if VERBOSE:
            print "\t\tSearching in %s" % tmpPath
        paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
        paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]])  # Lower case list.
        paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]])  # Lower case no ext
    else:
        if VERBOSE:
            print '\tNo Path: "%s"' % tmpPath

        # Add path if relative image patrh was given.
    tmp_paths = paths.keys()
    for k in tmp_paths:
        tmpPath = k + imageFilePath
        if sys.exists(tmpPath):
            paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
            paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]])  # Lower case list.
            paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]])  # Lower case no ext
        else:
            if VERBOSE:
                print '\tNo Path: "%s"' % tmpPath
            # DONE
            #
    for path, files in paths.iteritems():
        if sys.exists(path + imageFileName):
            if VERBOSE:
                print '\tFound image at path: "%s" file" "%s"' % (path, imageFileName)
            return imageLoad(path + imageFileName)

            # If the files not there then well do a case insensitive seek.
        filesOrigCase = files[0]
        filesLower = files[1]
        filesLowerNoExt = files[2]

        # We are going to try in index the file directly, if its not there just keep on

        index = None
        try:
            # Is it just a case mismatch?
            index = filesLower.index(imageFileName_lower)
        except:
            try:
                # Have the extensions changed?
                index = filesLowerNoExt.index(imageFileName_noext_lower)

                ext = getExt(filesLower[index])  # Get the extension of the file that matches all but ext.

                # Check that the ext is useable eg- not a 3ds file :)
                if ext.lower() not in IMAGE_EXT:
                    index = None

            except:
                index = None

        if index != None:
            tmpPath = path + filesOrigCase[index]
            img = imageLoad(tmpPath)
            if img != None:
                if VERBOSE:
                    print '\t\tImage Found "%s"' % tmpPath
                return img

    if RECURSIVE:
        # IMAGE NOT FOUND IN ANY OF THE DIRS!, DO A RECURSIVE SEARCH.
        if VERBOSE:
            print "\t\tImage Not Found in any of the dirs, doing a recusrive search"
        for path in paths.iterkeys():
            # Were not going to use files
            if path == "/" or len(path) == 3 and path[1:] == ":\\":
                continue

                # print path , 'ASS'

                # ------------------
                # finds the file starting at the root.
                # 	def findImage(findRoot, imagePath):
                # W---------------

                # ROOT, DIRS, FILES
            pathWalk = os.walk(path)
            pathList = [True]

            matchList = []  # Store a list of (match, size), choose the biggest.
            while True:
                try:
                    pathList = pathWalk.next()
                except:
                    break

                for file in pathList[2]:
                    file_lower = file.lower()
                    # FOUND A MATCH
                    if (file_lower == imageFileName_lower) or (
                        stripExt(file_lower) == imageFileName_noext_lower and getExt(file_lower) in IMAGE_EXT
                    ):
                        name = pathList[0] + sys.sep + file
                        size = os.path.getsize(name)
                        if VERBOSE:
                            print "\t\t\tfound:", name
                        matchList.append((name, size))

            if matchList:
                # Sort by file size
                matchList.sort(lambda A, B: cmp(B[1], A[1]))

                if VERBOSE:
                    print '\t\tFound "%s"' % matchList[0][0]

                # Loop through all we have found
                img = None
                for match in matchList:
                    img = imageLoad(match[0])  # 0 - first, 0 - pathname
                    if img != None:
                        break
                return img

                # No go.
    if VERBOSE:
        print '\t\tImage Not Found after looking everywhere! "%s"' % imagePath
    return imageLoad(imagePath)  # Will jus treturn a placeholder.
Ejemplo n.º 17
0
def edit_extern(image=None):
	
	if not image:
		image = Image.GetCurrent()
	
	if not image: # Image is None
		Draw.PupMenu('ERROR: Please select active Image.')
		return
	if image.packed:
		Draw.PupMenu('ERROR: Image is packed, unpack before editing.')
		return
	
	imageFileName = sys.expandpath( image.filename )
	
	if not sys.exists(imageFileName):
		Draw.PupMenu('ERROR: Image path does not exist.')
		return
	
	pupblock = [imageFileName.split('/')[-1].split('\\')[-1]]
	
	new_text= False
	try:
		appstring = Registry.GetKey('ExternalImageEditor', True)
		appstring = appstring['path']
		
		# for ZanQdo if he removed the path from the textbox totaly. ;) - Cam
		if not appstring or appstring.find('%f')==-1:
			new_text= True
	except:
		new_text= True
	
	if new_text:
		pupblock.append('first time, set path.')
		if platform == 'win32':
			# Example of path to popular image editor... ;-)
			# appstring = '"C:\\Program Files\\Adobe\\Photoshop CS\\photoshop.exe" "%f"'
			# Have to add "cmd /c" to make sure we're using Windows shell.
			appstring = 'cmd /c start "" /B "%f"'
		elif platform == 'darwin':
			appstring = 'open "%f"'
		else:
			appstring = 'gimp %f'
	
	appstring_but = Draw.Create(appstring)
	save_default_but = Draw.Create(0)
	
	pupblock.append(('editor: ', appstring_but, 0, 99, 'Path to application, %f will be replaced with the image path.'))
	pupblock.append(('Set Default', save_default_but, 'Store this path in the blender registry.'))
	
	# Only configure if Shift is held,
	if Blender.Window.GetKeyQualifiers() & Blender.Window.Qual.SHIFT:
		if not Draw.PupBlock('External Image Editor...', pupblock):
			return
	
	appstring = appstring_but.val
	save_default= save_default_but.val
	
	if save_default:
		Registry.SetKey('ExternalImageEditor', {'path':appstring}, True)
	
	if appstring.find('%f') == -1:
		Draw.PupMenu('ERROR: No filename specified! ("%f")')
		return
	
	# -------------------------------
	
	os_run(appstring, imageFileName)
Ejemplo n.º 18
0
def imageFromObjectsOrtho(objects, path, width, height, smooth, alpha= True, camera_matrix= None, format=Render.PNG):
	'''
	Takes any number of objects and renders them on the z axis, between x:y-0 and x:y-1
	Usefull for making images from a mesh without per pixel operations
	- objects must be alredy placed
	- smooth, anti alias True/False
	- path renders to a PNG image
	- alpha weather to render background as alpha
	
	returns the blender image
	'''
	ext = '.' + extFromFormat(format)
	print ext
	# remove an extension if its alredy there
	if path.lower().endswith(ext):
		path= path[:-4] 
	
	path_expand= sys.expandpath(path) + ext
	
	print path_expand, 'path'
	
	# Touch the path
	try:
		f= open(path_expand, 'w')
		f.close()
	except:
		raise 'Error, could not write to path:' + path_expand
	
	
	# RENDER THE FACES.
	scn= Scene.GetCurrent()
	render_scn= Scene.New()
	render_scn.makeCurrent()
	render_scn.Layers |= (1<<20)-1 # all layers enabled
	 
	# Add objects into the current scene
	for ob in objects:
		render_scn.link(ob)
	
	render_context= render_scn.getRenderingContext()
	render_context.setRenderPath('') # so we can ignore any existing path and save to the abs path.
	
	
	render_context.imageSizeX(width)
	render_context.imageSizeY(height)
	
	if smooth:
		render_context.enableOversampling(True) 
		render_context.setOversamplingLevel(16)
	else:
		render_context.enableOversampling(False) 
	
	render_context.setRenderWinSize(100)
	render_context.setImageType(format)
	render_context.enableExtensions(True) 
	#render_context.enableSky() # No alpha needed.
	if alpha:
		render_context.alphaMode= 1
		render_context.enableRGBAColor()
	else:
		render_context.alphaMode= 0
		render_context.enableRGBColor()
	
	render_context.displayMode= 0 # fullscreen
	
	# New camera and object
	render_cam_data= Camera.New('ortho')
	render_cam_ob= Object.New('Camera')
	render_cam_ob.link(render_cam_data)
	render_scn.link(render_cam_ob)
	render_scn.objects.camera = render_cam_ob
	
	render_cam_data.type= 'ortho'
	
	
	
	# Position the camera
	if camera_matrix:
		render_cam_ob.setMatrix(camera_matrix)
		# We need to take into account the matrix scaling when setting the size
		# so we get the image bounds defined by the matrix
		# first get the x and y factors from the matrix.
		# To render the correct dimensions we must use the aspy and aspy to force the matrix scale to
		# override the aspect enforced by the width and weight.
		cent= Vector() * camera_matrix
		xvec= Vector(1,0,0) * camera_matrix
		yvec= Vector(0,1,0) * camera_matrix
		# zvec= Vector(0,0,1) * camera_matrix
		xlen = (cent-xvec).length # half height of the image
		ylen = (cent-yvec).length # half width of the image
		# zlen = (cent-zvec).length # dist to place the camera? - just use the loc for now.
		
		
		# less then 1.0 portrate, 1.0 or more is portrate
		asp_cam_mat= xlen/ylen # divide by zero? - possible but scripters fault.
		asp_image_res= float(width)/height
		#print 'asp quad', asp_cam_mat, 'asp_image', asp_image_res
		#print 'xylen', xlen, ylen, 'w/h', width, height
		# Setup the aspect
		
		if asp_cam_mat > asp_image_res:
			# camera is wider then image res.
			# to make the image wider, reduce the aspy
			asp_diff= asp_image_res/asp_cam_mat
			min_asp= asp_diff * 200
			#print 'X', min_asp
			
		elif asp_cam_mat < asp_image_res: # asp_cam_mat < asp_image_res
			# camera is narrower then image res
			# to make the image narrower, reduce the aspx
			asp_diff= asp_cam_mat/asp_image_res
			min_asp= asp_diff * 200
			#print 'Y', min_asp
		else:
			min_asp= 200
		
		# set the camera size
		if xlen > ylen:
			if asp_cam_mat > asp_image_res:
				render_context.aspectX= 200 # get the greatest range possible
				render_context.aspectY= min_asp # get the greatest range possible
			else:
				render_context.aspectY= 200 # get the greatest range possible
				render_context.aspectX= min_asp # get the greatest range possible
			#print "xlen bigger"
			render_cam_data.scale= xlen * 2
		elif xlen < ylen:# ylen is bigger
			if asp_cam_mat > asp_image_res:
				render_context.aspectX= 200 # get the greatest range possible
				render_context.aspectY= min_asp # get the greatest range possible
			else:
				render_context.aspectY= 200 # get the greatest range possible
				render_context.aspectX= min_asp # get the greatest range possible
			#print "ylen bigger"
			render_cam_data.scale= ylen *2 
		else:
			# asppect 1:1
			#print 'NOLEN Bigger'
			render_cam_data.scale= xlen * 2

		#print xlen, ylen, 'xlen, ylen'
		
	else:
		if width > height:
			min_asp = int((float(height) / width) * 200)
			render_context.aspectX= min_asp
			render_context.aspectY= 200
		else:
			min_asp = int((float(width) / height) * 200)
			render_context.aspectX= 200
			render_context.aspectY= min_asp
		
		
		render_cam_data.scale= 1.0
		render_cam_ob.LocZ= 1.0
		render_cam_ob.LocX= 0.5
		render_cam_ob.LocY= 0.5
	
	Blender.Window.RedrawAll()
	
	render_context.render()
	render_context.saveRenderedImage(path)
	Render.CloseRenderWindow()
	#if not B.sys.exists(PREF_IMAGE_PATH_EXPAND):
	#	raise 'Error!!!'
	
	scn.makeCurrent()
	Scene.Unlink(render_scn)
	
	# NOW APPLY THE SAVED IMAGE TO THE FACES!
	#print PREF_IMAGE_PATH_EXPAND
	try:
		target_image= Image.Load(path_expand)
		return target_image
	except:
		raise 'Error: Could not render or load the image at path "%s"' % path_expand
		return
Ejemplo n.º 19
0
	tmpPath = stripFile(filePath) + stripPath(imageFileName)
	if sys.exists(tmpPath):
		if VERBOSE: print '\t\tFile found in path (1)"%s".' % tmpPath
		return imageLoad(tmpPath)
	
	
	# os needed if we go any further.
	if not os:
		if VERBOSE: print '\t\tCreating a placeholder with a face path: "%s".' % imagePath
		return imageLoad(imagePath) # Will jus treturn a placeholder.
	
	
	# We have os.
	# GATHER PATHS.
	paths = {} # Store possible paths we may use, dict for no doubles.
	tmpPath = addSlash(sys.expandpath('//')) # Blenders path
	if sys.exists(tmpPath):
		if VERBOSE: print '\t\tSearching in %s' % tmpPath
		paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading 
		paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list.
		paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext
	else:
		if VERBOSE: print '\tNo Path: "%s"' % tmpPath
	
	tmpPath = imageFilePath
	if sys.exists(tmpPath):
		if VERBOSE: print '\t\tSearching in %s' % tmpPath
		paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading 
		paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list.
		paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext
	else:
Ejemplo n.º 20
0
def comprehensiveImageLoad(imagePath,
                           filePath,
                           PLACE_HOLDER=True,
                           RECURSIVE=True,
                           VERBOSE=False,
                           CONVERT_CALLBACK=None):
    '''
	imagePath: The image filename
		If a path precedes it, this will be searched as well.
		
	filePath: is the directory where the image may be located - any file at teh end will be ignored.
	
	PLACE_HOLDER: if True a new place holder image will be created.
		this is usefull so later you can relink the image to its original data.
	
	VERBOSE: If True debug info will be printed.
	
	RECURSIVE: If True, directories will be recursivly searched.
		Be carefull with this if you have files in your root directory because it may take a long time.
	
	CASE_INSENSITIVE: for non win32 systems, find the correct case for the file.
	
	CONVERT_CALLBACK: a function that takes an existing path and returns a new one.
		Use this when loading image formats blender may not support, the CONVERT_CALLBACK
		can take the path for a GIF (for example), convert it to a PNG and return the PNG's path.
		For formats blender can read, simply return the path that is given.
	'''

    # VERBOSE = True

    if VERBOSE: print 'img:', imagePath, 'file:', filePath
    CASE_INSENSITIVE = True
    if os == None and CASE_INSENSITIVE:
        CASE_INSENSITIVE = True

    # When we have the file load it with this. try/except niceness.
    def imageLoad(path):
        #if path.endswith('\\') or path.endswith('/'):
        #	raise 'INVALID PATH'

        if CONVERT_CALLBACK:
            path = CONVERT_CALLBACK(path)

        try:
            img = bpy.data.images.new(filename=path)
            if VERBOSE: print '\t\tImage loaded "%s"' % path
            return img
        except:
            if VERBOSE:
                if sys.exists(path):
                    print '\t\tImage failed loading "%s", mabe its not a format blender can read.' % (
                        path)
                else:
                    print '\t\tImage not found, making a place holder "%s"' % (
                        path)
            if PLACE_HOLDER:
                img = bpy.data.images.new(stripPath(path), 4, 4)
                img.filename = path
                return img  #blank image
            else:
                return None

    # Image formats blender can read
    IMAGE_EXT = [
        'jpg',
        'jpeg',
        'png',
        'tga',
        'bmp',
        'rgb',
        'sgi',
        'bw',
        'iff',
        'lbm',  # Blender Internal
        'gif',
        'psd',
        'tif',
        'tiff',
        'pct',
        'pict',
        'pntg',
        'qtif'
    ]  # Quacktime, worth a try.

    imageFileName = stripPath(imagePath)  # image path only
    imageFileName_lower = imageFileName.lower()  # image path only

    if VERBOSE: print '\tSearchingExisting Images for "%s"' % imagePath
    for i in bpy.data.images:
        if stripPath(i.filename.lower()) == imageFileName_lower:
            if VERBOSE: print '\t\tUsing existing image.'
            return i

    if VERBOSE: print '\tAttempting to load "%s"' % imagePath
    if sys.exists(imagePath):
        if VERBOSE: print '\t\tFile found where expected "%s".' % imagePath
        return imageLoad(imagePath)

    imageFileName_noext = stripExt(imageFileName)  # With no extension.
    imageFileName_noext_lower = stripExt(
        imageFileName_lower)  # With no extension.
    imageFilePath = stripFile(imagePath)

    # Remove relative path from image path
    if imageFilePath.startswith('./') or imageFilePath.startswith('.\\'):
        imageFilePath = imageFilePath[2:]

    # Attempt to load from obj path.
    tmpPath = stripFile(filePath) + stripPath(imageFileName)
    if sys.exists(tmpPath):
        if VERBOSE: print '\t\tFile found in path (1)"%s".' % tmpPath
        return imageLoad(tmpPath)

    # os needed if we go any further.
    if not os:
        if VERBOSE:
            print '\t\tCreating a placeholder with a face path: "%s".' % imagePath
        return imageLoad(imagePath)  # Will jus treturn a placeholder.

    # We have os.
    # GATHER PATHS.
    paths = {}  # Store possible paths we may use, dict for no doubles.
    tmpPath = addSlash(sys.expandpath('//'))  # Blenders path
    if sys.exists(tmpPath):
        if VERBOSE: print '\t\tSearching in %s' % tmpPath
        paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
        paths[tmpPath].append([f.lower()
                               for f in paths[tmpPath][0]])  # Lower case list.
        paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]
                               ])  # Lower case no ext
    else:
        if VERBOSE: print '\tNo Path: "%s"' % tmpPath

    tmpPath = imageFilePath
    if sys.exists(tmpPath):
        if VERBOSE: print '\t\tSearching in %s' % tmpPath
        paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
        paths[tmpPath].append([f.lower()
                               for f in paths[tmpPath][0]])  # Lower case list.
        paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]
                               ])  # Lower case no ext
    else:
        if VERBOSE: print '\tNo Path: "%s"' % tmpPath

    tmpPath = stripFile(filePath)
    if sys.exists(tmpPath):
        if VERBOSE: print '\t\tSearching in %s' % tmpPath
        paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
        paths[tmpPath].append([f.lower()
                               for f in paths[tmpPath][0]])  # Lower case list.
        paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]
                               ])  # Lower case no ext
    else:
        if VERBOSE: print '\tNo Path: "%s"' % tmpPath

    tmpPath = addSlash(bpy.config.textureDir)
    if tmpPath and sys.exists(tmpPath):
        if VERBOSE: print '\t\tSearching in %s' % tmpPath
        paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
        paths[tmpPath].append([f.lower()
                               for f in paths[tmpPath][0]])  # Lower case list.
        paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]
                               ])  # Lower case no ext
    else:
        if VERBOSE: print '\tNo Path: "%s"' % tmpPath

    # Add path if relative image patrh was given.
    tmp_paths = paths.keys()
    for k in tmp_paths:
        tmpPath = k + imageFilePath
        if sys.exists(tmpPath):
            paths[tmpPath] = [os.listdir(tmpPath)]  # Orig name for loading
            paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]
                                   ])  # Lower case list.
            paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]
                                   ])  # Lower case no ext
        else:
            if VERBOSE: print '\tNo Path: "%s"' % tmpPath
    # DONE
    #
    for path, files in paths.iteritems():
        if sys.exists(path + imageFileName):
            if VERBOSE:
                print '\tFound image at path: "%s" file" "%s"' % (
                    path, imageFileName)
            return imageLoad(path + imageFileName)

        # If the files not there then well do a case insensitive seek.
        filesOrigCase = files[0]
        filesLower = files[1]
        filesLowerNoExt = files[2]

        # We are going to try in index the file directly, if its not there just keep on

        index = None
        try:
            # Is it just a case mismatch?
            index = filesLower.index(imageFileName_lower)
        except:
            try:
                # Have the extensions changed?
                index = filesLowerNoExt.index(imageFileName_noext_lower)

                ext = getExt(
                    filesLower[index]
                )  # Get the extension of the file that matches all but ext.

                # Check that the ext is useable eg- not a 3ds file :)
                if ext.lower() not in IMAGE_EXT:
                    index = None

            except:
                index = None

        if index != None:
            tmpPath = path + filesOrigCase[index]
            img = imageLoad(tmpPath)
            if img != None:
                if VERBOSE: print '\t\tImage Found "%s"' % tmpPath
                return img

    if RECURSIVE:
        # IMAGE NOT FOUND IN ANY OF THE DIRS!, DO A RECURSIVE SEARCH.
        if VERBOSE:
            print '\t\tImage Not Found in any of the dirs, doing a recusrive search'
        for path in paths.iterkeys():
            # Were not going to use files
            if path == '/' or len(path) == 3 and path[1:] == ':\\':
                continue

            # print path , 'ASS'

            #------------------
            # finds the file starting at the root.
            #	def findImage(findRoot, imagePath):
            #W---------------

            # ROOT, DIRS, FILES
            pathWalk = os.walk(path)
            pathList = [True]

            matchList = [
            ]  # Store a list of (match, size), choose the biggest.
            while True:
                try:
                    pathList = pathWalk.next()
                except:
                    break

                for file in pathList[2]:
                    file_lower = file.lower()
                    # FOUND A MATCH
                    if (file_lower == imageFileName_lower) or\
                    (stripExt(file_lower) == imageFileName_noext_lower and getExt(file_lower) in IMAGE_EXT):
                        name = pathList[0] + sys.sep + file
                        size = os.path.getsize(name)
                        if VERBOSE: print '\t\t\tfound:', name
                        matchList.append((name, size))

            if matchList:
                # Sort by file size
                matchList.sort(lambda A, B: cmp(B[1], A[1]))

                if VERBOSE: print '\t\tFound "%s"' % matchList[0][0]

                # Loop through all we have found
                img = None
                for match in matchList:
                    img = imageLoad(match[0])  # 0 - first, 0 - pathname
                    if img != None:
                        break
                return img

    # No go.
    if VERBOSE:
        print '\t\tImage Not Found after looking everywhere! "%s"' % imagePath
    return imageLoad(imagePath)  # Will jus treturn a placeholder.
Ejemplo n.º 21
0
def edit_extern(image=None):
	
	if not image:
		image = Image.GetCurrent()
	
	if not image: # Image is None
		Draw.PupMenu('ERROR: Please select active Image.')
		return
	if image.packed:
		Draw.PupMenu('ERROR: Image is packed, unpack before editing.')
		return
	
	imageFileName = sys.expandpath( image.filename )
	
	if not sys.exists(imageFileName):
		Draw.PupMenu('ERROR: Image path does not exist.')
		return
	
	pupblock = [imageFileName.split('/')[-1].split('\\')[-1]]
	
	new_text= False
	try:
		appstring = Registry.GetKey('ExternalImageEditor', True)
		appstring = appstring['path']
		
		# for ZanQdo if he removed the path from the textbox totaly. ;) - Cam
		if not appstring or appstring.find('%f')==-1:
			new_text= True
	except:
		new_text= True
	
	if new_text:
		pupblock.append('first time, set path.')
		if platform == 'win32':
			# Example of path to popular image editor... ;-)
			# appstring = '"C:\\Program Files\\Adobe\\Photoshop CS\\photoshop.exe" "%f"'
			# Have to add "cmd /c" to make sure we're using Windows shell.
			appstring = 'cmd /c start "" /B "%f"'
		elif platform == 'darwin':
			appstring = 'open "%f"'
		else:
			appstring = 'gimp %f'
	
	appstring_but = Draw.Create(appstring)
	save_default_but = Draw.Create(0)
	
	pupblock.append(('editor: ', appstring_but, 0, 99, 'Path to application, %f will be replaced with the image path.'))
	pupblock.append(('Set Default', save_default_but, 'Store this path in the blender registry.'))
	
	# Only configure if Shift is held,
	if Blender.Window.GetKeyQualifiers() & Blender.Window.Qual.SHIFT:
		if not Draw.PupBlock('External Image Editor...', pupblock):
			return
	
	appstring = appstring_but.val
	save_default= save_default_but.val
	
	if save_default:
		Registry.SetKey('ExternalImageEditor', {'path':appstring}, True)
	
	if appstring.find('%f') == -1:
		Draw.PupMenu('ERROR: No filename specified! ("%f")')
		return
	
	# -------------------------------
	
	os_run(appstring, imageFileName)