示例#1
0
	def endDocument(self):
		"""
			Invoked when mesh processing is done. Used for realizing
			the mesh from collected vertex/faces and texturizing info.
		"""
		# report
		print("Finished loading file, constructing mesh...")
		Blender.Window.DrawProgressBar(0.9, "Building mesh...")
		# build object
		meshtools.create_mesh(self.verts, self.faces, self.objName, self.faceuvs, self.uvs)
		print("Done, object built")
		# load corresponding images and set texture
		Blender.Window.DrawProgressBar(0.95, "Loading/Applying Texture...")
		colorTex, specTex = None, None
		# convert images into textures
		if self.colorTexture:
			colTexFName		= FindTexture(self.path, self.colorTexture)
			if colTexFName != None:
				colorImg		= Image.Load(colTexFName)
				colorTex		= Texture.New(self.objName + ".col.tx")
				colorTex.type	= Texture.Types.IMAGE
				colorTex.image	= colorImg
		if self.specTexture:
			specTexFName	= FindTexture(self.path, self.specTexture)
			if specTexFName != None:
				specImg			= Image.Load(specTexFName)
				specTex			= Texture.New(self.objName + ".spe.tx")
				specTex.type	= Texture.Types.IMAGE
				specTex.image	= specImg
		# make material with them and all other previously collected data
		mat = Material.New(self.objName + ".mat")
		mat.mode		|= Material.Modes.TEXFACE | Material.Modes.SHADOW | Material.Modes.TRACEABLE | Material.Modes.ZTRANSP
		mat.specTransp	= 1.0
		if self.alpha	: mat.alpha		= self.alpha
		if self.rgbCol	: mat.rgbCol	= self.rgbCol
		if self.amb		: mat.amb		= self.amb
		if self.emit	: mat.emit		= self.emit
		if self.spec	: mat.spec		= self.spec
		if self.specCol	: mat.specCol	= self.specCol
		if colorTex:
			mat.setTexture(0, colorTex, Texture.TexCo.UV, Texture.MapTo.COL)
		if specTex:
			mat.setTexture(1, specTex, Texture.TexCo.UV, Texture.MapTo.SPEC)
		# apply to mesh
		obj = Object.Get(self.objName)
		mesh = obj.data
		# mesh.mode = NMesh.Modes.NOVNORMALSFLIP
		# uncomment the following if you want models automatically sub-surfaced
		"""for currFace in mesh.faces:
			currFace.smooth = 1
		mesh.setSubDivLevels([1,2])
		mesh.setMode("SubSurf", "TwoSided")"""
		mesh.setMode("TwoSided")
		mesh.addMaterial(mat)
		mesh.update(1)
		# Done, notify user
		Blender.Window.DrawProgressBar(1.0, "Done.")
示例#2
0
    def addRegion(self, xoff, yoff, width, height):
        mesh = self.obj.getData(mesh=True)
        panelimage = mesh.faces[0].image
        name = 'PanelRegion'
        for img in Image.get():
            # try to re-use existing deleted panel region
            if img.size == [
                    width, height
            ] and img.source == Image.Sources.GENERATED and img.filename == name and not self.isRegion(
                    img):
                break
        else:
            img = Image.New(name, width, height, 24)
        for y in range(height):
            for x in range(width):
                rgba = panelimage.getPixelI(xoff + x, yoff + y)
                if not rgba[3]:
                    img.setPixelI(x, y,
                                  (102, 102, 255, 255))  # hilite transparent
                else:
                    img.setPixelI(x, y, rgba[:3] + [255])
        img.pack()

        for n in range(1, PanelRegionHandler.REGIONCOUNT + 1):
            if mesh.faces[n].image == panelimage:
                mesh.faces[n].image = img
                self.obj.addProperty('x%d' % n, xoff)
                self.obj.addProperty('y%d' % n, yoff)
                (width, height) = img.size
                (pwidth, pheight) = panelimage.size
                xoff = float(xoff) / pwidth
                yoff = float(yoff) / pheight
                xscale = float(pwidth) / width
                yscale = float(pheight) / height
                # Assign UV mappings from panel image
                for obj in Scene.GetCurrent().objects:
                    if obj != self.obj and obj.getType() == "Mesh":
                        mesh2 = obj.getData(mesh=True)
                        if mesh2.faceUV:
                            for face in mesh2.faces:
                                if face.image == panelimage:
                                    uv = []
                                    for v in face.uv:
                                        x = (v.x - xoff) * xscale
                                        y = (v.y - yoff) * yscale
                                        if not -UV.LIMIT <= x <= 1 + UV.LIMIT or not -UV.LIMIT <= y <= 1 + UV.LIMIT:
                                            break
                                        uv.append(
                                            Vector(min(max(x, 0), 1),
                                                   min(max(y, 0), 1)))
                                    else:
                                        face.uv = uv
                                        face.image = img
                            mesh2.update()
                break
        return img
示例#3
0
文件: utils.py 项目: Zildj1an/bui
def load_image(root_dir, file_name):
    file_path = find_file_path(root_dir, file_name)
    
    if file_path:
        return Image.Load(file_path)
    
    try:
        return Image.Get(file_name)
    except:
        pass
示例#4
0
def dodialog(newname):
    global newimage, newsize, offsets, rows, cols

    try:
        newimage = Image.Load(newname)
        newsize = newimage.getSize()
    except:
        Draw.PupMenu("Can't read image %s" % newname)
        return

    if newsize[0] == oldsize[0] and newsize[1] == oldsize[1]:
        # same size, just replace
        doapply(0, 0)
        return
    elif newsize[0] < oldsize[0] or newsize[1] < oldsize[1]:
        Draw.PupMenu("The new image must be larger than the old image")
        return
    else:
        if newsize[0] % oldsize[0] == 0:
            xoffs = range(0, newsize[0], oldsize[0])
        else:
            xoffs = [0, newsize[0] - oldsize[0]]
        if newsize[1] % oldsize[1] == 0:
            yoffs = range(newsize[1] - oldsize[1], -oldsize[1], -oldsize[1])
        else:
            yoffs = [newsize[1] - oldsize[1], 0]
        for i in yoffs:
            for j in xoffs:
                offsets.append((j, i))
        cols = len(xoffs)
        rows = len(yoffs)
        Draw.Register(gui, event, bevent)
示例#5
0
def draw():
    global as_package_name
    global fileButton, expFileName
    global engine_menu, engine_name
    global EVENT_NOEVENT, EVENT_DRAW, EVENT_EXIT, EVENT_EXPORT
    global export_all
    expFileName = ""
    ########## Titles
    glClear(GL_COLOR_BUFFER_BIT)
    glRasterPos2i(40, 240)

    logoImage = Image.Load(Get('scriptsdir') + sys.sep + 'AS3Export.png')
    Draw.Image(logoImage, 40, 155)

    as_package_name = Draw.String("Package name: ", EVENT_NOEVENT, 40, 130,
                                  250, 20, as_package_name.val, 300)
    engine_name = "Away3D%x1|Away3D 2.1.0%x5|Away3D 2.2.0%x6|Papervision3D%x2|Papervision3D 2.0%x3|Sandy 3.0%x4"
    engine_menu = Draw.Menu(engine_name, EVENT_NOEVENT, 40, 100, 200, 20,
                            engine_menu.val, "Choose your engine")

    fileButton = Draw.String('File location: ', EVENT_NOEVENT, 40, 70, 250, 20,
                             fileButton.val, 255)
    Draw.PushButton('...', EVENT_BROWSEFILE, 300, 70, 30, 20, 'browse file')
    export_all = Draw.Toggle('Export ALL scene objects', EVENT_NOEVENT, 40, 45,
                             200, 20, 0)
    ######### Draw and Exit Buttons
    Draw.Button("Export", EVENT_EXPORT, 40, 20, 80, 18)
    Draw.Button("Exit", EVENT_EXIT, 140, 20, 80, 18)
示例#6
0
def createImage(fn):
    try:
        img = Image.Load(fn)
    except:
        return (None)

    return (img)
示例#7
0
    def _pil_im_to_blender_disk(self, im):
        im, ext = get_image_extension(im)

        temporary_image = TempFile(ext)
        self.temporary_images.append(temporary_image)

        im.save(temporary_image.path)

        ret_im = Image.Load(temporary_image.path)

        return ret_im
示例#8
0
  def bitmap(file, words, data):
    global filename
    imagefname=os.path.dirname(filename) + '\\' + words[1]+'.tga'
    try:
      image=Image.Get(imagefname)
    except NameError:
      try:
	image=Image.Load(imagefname)
      except IOError:
        print '**************ERROR********************'
        print 'file : ' + filename
        print 'texture : ' + words[1]+'.tga unknown in directory : '
        print os.path.dirname(filename)
        print 'check if the bitmap exists with an other extension => translate in tga format'
        print 'or move it in the directory of the .mdl model'
        print 'null.tga could be used instead of the current one'
        print '**************ERROR********************'
        imagefname=os.path.dirname(filename) + '\\null.tga'
        image=Image.Load(imagefname)
        pass
    data['nwnprops'].write('%s.texture=%s\n'%(data['object'].name, words[1]))
    data['texture']=image
示例#9
0
 def make_image(self, root):
     fullpath = root + '/' + self.tex
     if not os.path.exists(fullpath):
         fullpath = fullpath[:-3] + 'dds'
     if not os.path.exists(fullpath):
         fullpath = fullpath[:-3] + 'png'
     print "Will load image %s" % fullpath
     img = Image.Load(fullpath)
     mat = Material.New(self.name)
     tex = Texture.New(self.name)
     tex.setImage(img)
     mat.setTexture(0, tex)
     self.material = mat
示例#10
0
    def addRegion(self, xoff, yoff, width, height):
        mesh=self.obj.getData(mesh=True)
        panelimage=mesh.faces[0].image
        name='PanelRegion'
        for img in Image.get():
            # try to re-use existing deleted panel region
            if img.size==[width,height] and img.source==Image.Sources.GENERATED and img.filename==name and not self.isRegion(img):
                break
        else:
            img=Image.New(name, width, height, 24)
        for y in range(height):
            for x in range(width):
                rgba=panelimage.getPixelI(xoff+x,yoff+y)
                if not rgba[3]:
                    img.setPixelI(x,y, (102,102,255,255))	# hilite transparent
                else:
                    img.setPixelI(x,y, rgba[:3]+[255])
        img.pack()

        for n in range(1,PanelRegionHandler.REGIONCOUNT+1):
            if mesh.faces[n].image==panelimage:
                mesh.faces[n].image=img
                self.obj.addProperty('x%d' % n, xoff)
                self.obj.addProperty('y%d' % n, yoff)
                (width,height)=img.size
                (pwidth,pheight)=panelimage.size
                xoff=float(xoff)/pwidth
                yoff=float(yoff)/pheight
                xscale=float(pwidth)/width
                yscale=float(pheight)/height
                # Assign UV mappings from panel image
                for obj in Scene.GetCurrent().objects:
                    if obj!=self.obj and obj.getType()=="Mesh":
                        mesh2 = obj.getData(mesh=True)
                        if mesh2.faceUV:
                            for face in mesh2.faces:
                                if face.image==panelimage:
                                    uv=[]
                                    for v in face.uv:
                                        x=(v.x-xoff)*xscale
                                        y=(v.y-yoff)*yscale
                                        if not -UV.LIMIT<=x<=1+UV.LIMIT or not -UV.LIMIT<=y<=1+UV.LIMIT:
                                            break
                                        uv.append(Vector(min(max(x,0),1), min(max(y,0),1)))
                                    else:
                                        face.uv=uv
                                        face.image=img
                            mesh2.update()
                break
        return img
示例#11
0
def findTex(basefile, texture, subdirs):
    texdir = basefile
    for l in range(PanelRegionHandler.REGIONCOUNT + 1):
        q = texdir[:-1].rfind(Blender.sys.dirsep)
        if q == -1:
            return
        texdir = texdir[:q + 1]

        for subdir in subdirs:
            # Handle empty subdir
            if subdir:
                sd = subdir + Blender.sys.dirsep
            for extension in ['.dds', '.DDS', '.png', '.PNG', '.bmp', '.BMP']:
                try:
                    return Image.Load(texdir + sd + texture + extension)
                except IOError:
                    pass
    return None
示例#12
0
	def texture(self, faces):
		tex = ""
		for f in faces:
			if f.image:
				tex = f.image.name
				break
		if tex:
			image = Image.Get(tex)
			texfname = image.filename
			if SET_TEX_DIR:
				texfname = bsys.basename(texfname)
				if TEX_DIR:
					texfname = bsys.join(TEX_DIR, texfname)
			buf = 'texture "%s"\n' % texfname
			xrep = image.xrep
			yrep = image.yrep
			buf += 'texrep %s %s\n' % (xrep, yrep)
			self.file.write(buf)
示例#13
0
def createMat(texname, path=""):
    filename = "texture/" + texname.replace('\\', '/')

    ffn = "%s%s" % (path, filename)

    #dn = filename.decode('utf-8')

    #print filename
    #print dn

    # texture
    texture = Texture.New(texname)
    texture.setType('Image')
    # texture.uvlayer = texname

    img = createImage(ffn)
    if (img == None):
        print "Can't find file %s" % ffn
        nfn = "%s%s" % (path, getFile(filename))
        img = createImage(nfn)
    if (img == None):
        print "Can't find file %s. You're on your own..." % nfn
        img = Image.New(getFile(ffn), 10, 10, 1)

    #try:
    #  img = Image.Load(ffn);
    #  #img = Image.Load(dn);
    #except:
    #  print ("Can't find texture %s. You'll have to assign it on your own" % ffn)
    #  img = Image.New(ffn, 10, 10, 1)

    texture.image = img

    mat = Material.New(texname)
    mat.setTexture(3, texture, Blender.Texture.TexCo.UV)

    # TODO: Optimize this
    for m in mat.getTextures():
        if (m != None):
            m.uvlayer = texname

    return (mat)
示例#14
0
    def execute(self, input_image_path, blender_object):
        im = Image.Load(input_image_path)

        im_width, im_height = im.getSize()
        im_size_ratio = im_width / im_height

        tex_width = blender_object.texface.width
        tex_height = blender_object.texface.height
        tex_size_ratio = tex_width / tex_height

        ob = Object.Get(blender_object.name).getParent()
        if tex_size_ratio > im_size_ratio:
            # scale width
            scaling_ratio = im_size_ratio / tex_size_ratio
            ob.SizeY *= scaling_ratio
        else:
            # scale height
            scaling_ratio = tex_size_ratio / im_size_ratio
            ob.SizeZ *= scaling_ratio

        return im
示例#15
0
def loadTGARAW(fileName):
    """
	Loads a RAW TGA image from a file.  On success, the method
	returns: (image, imagebuffer).  On failure, the method
	returns None.
	
	@param filename: Name of the RAW TGA file to load.
	
	@return: (image, imagebuffer) 2-tuple on success, or None
	         on failure.
	"""

    # create the image and allocate the image buffer using
    #  Blender's own methods
    image = Image.Load(fileName)
    #ibuf = BGL.Buffer(BGL.GL_BYTE, (image.size[1], image.size[0], 4))

    ## read in the file
    #infile = open(fileName, 'rb')
    #array = map(ord, infile.read())
    #infile.close()

    ## check the validity of the file and offset the data
    ##  array to the start of the image data
    #if array[2] is not 2:
    #	menuError('Can only load RAW TGA images.')
    #	return None
    #array = array[(18+array[0]):]

    # read the array into the image buffer
    #index = 0
    #for y in range(0, image.size[1]):
    #	for x in range(0, image.size[0]):
    #		ibuf[y][x][2] = array[index]
    #		ibuf[y][x][1] = array[index+1]
    #		ibuf[y][x][0] = array[index+2]
    #		index += 3

    # return the (image, imagebuffer) tuple
    return (image, )
示例#16
0
def setTex(ob):
    scn = Scene.GetCurrent()  # link object to current scene
    #ob = scn.objects.get('myObj')
    mat = Material.New('myMat')
    mat.rgbCol = [0.9, 0.9, 0.9]

    footex = Texture.New('footex')
    footex.setType('Image')
    img = Image.Load('/tmp/t-XXXXXXXX.tga')
    footex.image = img
    #mat.tex.type = Texture.Types.IMAGE

    mat.setTexture(0, footex)
    for potential_ob in scn.objects:
        if potential_ob.name == 'myObj':
            ob = potential_ob
            break
    ob.setMaterials([mat])
    ob.colbits = 1
    print 'I did what you asked me to!'
    for ob in scn.objects:
        print ob.name
示例#17
0
def gettexture(name, dirname, filename):
    (filename,ext)=splitext(basename(filename).lower())
    img=None
    for d in [dirname, normpath(join(dirname, pardir, 'texture'))]:
        for e in ['.png', '.psd', '.jpg', '.jpeg', '.tga', '.bmp', '.dds',ext]:
            try:
                img=Image.Load(join(d,filename+e))
                img.getSize()	# force attempt to load image
                break
            except:
                pass
        else:
            continue

    # Re-use existing
    for tex in Texture.Get():
        if tex.name.startswith(name) and tex.type==Texture.Types.IMAGE and tex.image==img:
            return tex

    tex=Texture.New(name)
    tex.type=Texture.Types.IMAGE
    if img: tex.image=img

    return tex
示例#18
0
 def execute(self, input_image_path, blender_object):
     return Image.Load(input_image_path)
示例#19
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)
示例#20
0
def LoadImage(filename):
    image = Image.Load(filename)
    print "Image from", image.getFilename(),
    print "loaded to obj", image.getName()
    MakeMesh(image)
示例#21
0
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
示例#22
0
#
# Copyright (c) 2007 Jonathan Harris
#
# This code is licensed under version 2 of the GNU General Public License.
# http://www.gnu.org/licenses/gpl-2.0.html
#
# See ReadMe-XPlane2Blender.html for usage.
#

from Blender import Draw, Image, Window
from math import log

from XPlaneUtils import PanelRegionHandler

image = Image.GetCurrent()  # may be None
h = PanelRegionHandler()

opts = []
if not image:
    pass
elif h.isRegion(image):
    opts.append('Delete this region%x1')
    opts.append('Reload all regions%x3')
elif h.isPanel(image):
    if h.countRegions() < PanelRegionHandler.REGIONCOUNT:
        opts.append('Create new region...%x2')
    else:
        opts.append(
            'Can\'t create new region - already using maximum of %d regions%%x0'
            % PanelRegionHandler.REGIONCOUNT)
	def ParseMesh( self, szMeshName ):
		print "\tfound Mesh", szMeshName
		self.FindNextCharacter( '{' )
		nHierarchyLevel = 1

		aLineTokens = self.TokeniseLine()
		aVertices = self.ParseVec3Array( int( aLineTokens[ 0 ]))
		aLineTokens = self.TokeniseLine()
		aFaces = self.ParseFaceArray( int( aLineTokens[ 0 ]))
		aMaterialList = []

		while self.m_uLineIndex < self.m_uLineCount:
			uBaseLine = self.m_uLineIndex
			aLineTokens = self.TokeniseLine()
			strToken = aLineTokens[ 0 ].lower()

			if "material" == strToken:
				aMaterialList.append( self.ParseMaterial() )

			elif "meshmateriallist" == strToken:
				nHierarchyLevel += 1
				self.FindNextCharacter( '{' )
				aLineTokens = self.TokeniseLine()
				uMaterialCount = int( aLineTokens[ 0 ])
				aLineTokens = self.TokeniseLine()
				aMaterialFaces = self.ParseIntArray( int( aLineTokens[ 0 ]))

				print "\tMaterial Count =", uMaterialCount, "Material Faces =", len( aMaterialFaces )

			elif "meshnormals" == strToken:
				self.FindBracePair()

#				nHierarchyLevel += 1
#				self.FindNextCharacter( '{' )
#				aLineTokens = self.TokeniseLine()
#				aNormals = self.ParseVec3Array( int( aLineTokens[ 0 ]))
#				aLineTokens = self.TokeniseLine()
#				aNormalFaces = self.ParseFaceArray( int( aLineTokens[ 0 ]))
#				print "\tNormal count =", len( aNormals ), "Normal Faces =", len( aNormalFaces )

			elif "meshtexturecoords" == strToken:
				nHierarchyLevel += 1
				self.FindNextCharacter( '{' )
				aLineTokens = self.TokeniseLine()
				aTexCoords = self.ParseVec2Array( int( aLineTokens[ 0 ]))

			elif "skinweights" == strToken:
				self.ParseSkinWeights()

			elif "xskinmeshheader" == strToken:
				self.ParseXSkinMeshHeader()

			elif -1 != string.find( self.m_aLines[ uBaseLine ], '}' ):
				nHierarchyLevel -= 1

				if 0 == nHierarchyLevel:
					print "End Mesh"
					break
			else:
				print "Unexpected Mesh Token '", strToken, "' on line", self.m_uLineIndex
				break

		print "Vertex count =", len( aVertices ), "Face Count =", len( aFaces ), "Tex Coord count =", len( aTexCoords )
		meshCurrent = NMesh.GetRaw()

		for vertex in aVertices:
			v3Vertex = Blender.Mathutils.Vector( vertex ) * self.matrix
			meshCurrent.verts.append( NMesh.Vert( v3Vertex[ 0 ], v3Vertex[ 2 ], v3Vertex[ 1 ]))

#		aMaterialList = []
#		material = Material.New( "Material_Test" )
#		material.rgbCol = [ float(words[0]), float(words[1]), float(words[2]) ]
#		material.setAlpha( float(words[3]) )
#		aMaterialList.append( material )
#		meshCurrent.setMaterials( aMaterialList )
#		meshCurrent.update()

		aImageList = []
		uFaceIndex = 0

		for material in aMaterialList:
			szFileName = self.szDirectoryName + '\\' + material[ 0 ]
			print "Loading Image " + szFileName
			aImageList.append( Image.Load( szFileName ))

		for face in aFaces:
			faceNew = NMesh.Face()
			faceNew.v.append( meshCurrent.verts[ face[ 0 ]])
			faceNew.uv.append( (aTexCoords[ face[ 0 ]][ 0 ], -aTexCoords[ face[ 0 ]][ 1 ]) )
			faceNew.v.append( meshCurrent.verts[ face[ 2 ]])
			faceNew.uv.append( (aTexCoords[ face[ 2 ]][ 0 ], -aTexCoords[ face[ 2 ]][ 1 ]) )
			faceNew.v.append( meshCurrent.verts[ face[ 1 ]])
			faceNew.uv.append( (aTexCoords[ face[ 1 ]][ 0 ], -aTexCoords[ face[ 1 ]][ 1 ]) )
			faceNew.image = aImageList[ aMaterialFaces[ uFaceIndex ]]
#			faceNew.materialIndex = uMaterialIndex
#			faceNew.smooth = 1
			meshCurrent.faces.append( faceNew )
			uFaceIndex += 1

		NMesh.PutRaw( meshCurrent, self.szModelName + "_" + str( self.uMeshIndex ), 1 )
		self.uMeshIndex += 1
		meshCurrent.update()
示例#24
0
stop = 0
showHelp = 0
guiPopup = 0

# initial button values
exportPath = Draw.Create(
    Get("filename")[0:Get("filename").rfind(".")] +
    ".i3d")  #creates a text box thing

#mouse x/y (just for fun)
#mouseX = 0
#mouseY = 0

logo = false
try:
    logo = Image.Load(Get("scriptsdir") + "/morc.png")
except:
    logo = false


def gui():
    global evtExport, evtPathChanged, evtBrows
    global exportPath
    global guiExport, guiBrows, guiExportSelection, guiExportNormals, guiExportTriangulated, guiAddObjExtension, guiAddMatExtension, guiLogo

    guiAddObjExtension = Draw.PushButton(
        "add obj script link", evtAddObjExtension, 10, 155, 150, 25,
        "add a text file for more i3d object properties and link it to the active object via script links"
    )
    guiAddMatExtension = Draw.PushButton(
        "add mat script link", evtAddMatExtension, 175, 155, 155, 25,
示例#25
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)
示例#26
0
    xoff /= float(newsize[0])
    yoff /= float(newsize[1])

    Draw.Exit()
    for ob in Scene.GetCurrent().objects:
        if ob.getType() == "Mesh":
            mesh = ob.getData()
            if mesh.hasFaceUV():
                for face in mesh.faces:
                    if face.mode & NMesh.FaceModes.TEX and face.image == oldimage:
                        for i in range(len(face.uv)):
                            (s, t) = face.uv[i]
                            face.uv[i] = (xoff + s * xscale, yoff + t * yscale)
                            face.image = newimage
                mesh.update()

    newimage.makeCurrent()
    Window.RedrawAll()


#---------------------------------------------------------------------------
oldimage = Image.GetCurrent()
if oldimage:
    try:
        oldsize = oldimage.getSize()
    except:
        Draw.PupMenu("Can't read image %s" % oldimage.name)
    else:
        #Window.ImageSelector(dodialog, 'Replace image', oldimage.filename)
        Window.FileSelector(dodialog, 'Replace image', oldimage.filename)
示例#27
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
示例#28
0
def DefaultImage():
    image = Image.GetCurrent()
    return image
示例#29
0
import Blender
from Blender import Image
from Blender import Draw, BGL

fn = "C:\\lux\\luxgui\\luxblend\\new_icons\\filter.png"

img = Image.Load(fn)
ofn = Blender.sys.makename(fn, '.txt')


def base64char(value):
    if value < 26: return chr(65 + value)
    if value < 52: return chr(97 - 26 + value)
    if value < 62: return chr(48 - 52 + value)
    if value == 62: return '+'
    return '/'


def base64value(char):
    if ord(char) in range(65, 91): return ord(char) - 65
    if ord(char) in range(97, 123): return ord(char) - 97 + 26
    if ord(char) in range(48, 58): return ord(char) - 48 + 52
    if char == '+': return 62
    return 63


s = ""
for y in range(16):
    for x in range(16):
        print x
        print y
示例#30
0
    def texture(self, faces, mesh):
        uvlayer0 = ""
        uvlayer1 = ""
        uvlayer2 = ""
        uvlayer3 = ""

        uvlayers = mesh.getUVLayerNames()
        numlayer = len(uvlayers)
        if numlayer > 0:
            uvlayer0 = uvlayers[0]
        if numlayer > 1:
            uvlayer1 = uvlayers[1]
        if numlayer > 2:
            uvlayer2 = uvlayers[2]
        if numlayer > 3:
            uvlayer3 = uvlayers[3]

        mmat = mesh.materials
        tex = ""
        for f in faces:
            if f.image:
                tex = f.image.name
                break
        if tex:
            image = Image.Get(tex)
            texfname = image.filename
            if SET_TEX_DIR:
                texfname = bsys.basename(texfname)
                if TEX_DIR:
                    texfname = bsys.join(TEX_DIR, texfname)
            buf = 'texture "%s" base\n' % texfname
            #TODO support multi textures
            #lookup second texture value
            fmat = mmat[f.mat]
            tex1 = ""
            tex2 = ""
            mtextures = fmat.getTextures()
            for mtex in mtextures:
                if not (mtex == None):
                    if mtex.uvlayer == uvlayer1:
                        img1 = mtex.tex.getImage()
                        tex1 = img1.getFilename()
                        tex1 = bsys.basename(tex1)
                    if mtex.uvlayer == uvlayer2:
                        img2 = mtex.tex.getImage()
                        tex2 = img2.getFilename()
                        tex2 = bsys.basename(tex2)

            if tex1 != "":
                buf += 'texture "'
                buf += tex1
                buf += '" tiled\n'
            else:
                buf += 'texture empty_texture_no_mapping skids\n'

            if tex2 != "":
                buf += 'texture "'
                buf += tex2
                buf += '" tiled\n'
            else:
                buf += 'texture empty_texture_no_mapping skids\n'

            buf += 'texture empty_texture_no_mapping shad\n'

            xrep = image.xrep
            yrep = image.yrep
            #			buf += 'texrep %s %s\n' % (xrep, yrep)
            self.file.write(buf)
示例#31
0
                # black/white texture
                ir = a
                ig = a<<8
                ib = a<<16
                color = ir | ig | ib | 255<<24
            else:
                # colored texture
                # TODO: what todo with intensity here?
                g = g<<8
                b = b<<16
                color = r | g | b | 255<<24
                
            img[x,y] = color
    
    # render to file... yippieh
    image = Image.frombuffer("RGBA", (w,h), img, 'raw', "RGBA", 0, 1)
    image.save(imageName)

def mesh2XML(oname, mesh, matrix):
    vertices = {}
    normals = {}
    uvcos = {}
    faces = {}
    materialNames = []
    
    # remember used materials
    for material in mesh.materials:
        materialNames.append(material.name)

    if len(materialNames) == 0:
        print "WARNING: skipping mesh without material."
示例#32
0
def makeTree():
    #INIZIO PROGRAMMA
    print "-------------------"
    global leafTexture, stemTexture
    global tronco, foglie
    n = baseResolutionButton.val
    #Creo Mesh del tronco
    tronco = NMesh.GetRaw("stemMesh")
    if (tronco == None): tronco = NMesh.GetRaw()
    tronco.verts = []
    tronco.faces = []

    #Creo Mesh delle foglie
    foglie = NMesh.GetRaw("leafMesh")
    if (foglie == None): foglie = NMesh.GetRaw()
    foglie.verts = []
    foglie.faces = []

    #Creo la base del tronco
    for i in range(0, n):
        x = baseFactorButton.val * cos(2 * pi * i / (n - 1))
        y = baseFactorButton.val * sin(2 * pi * i / (n - 1))
        z = 0
        v = NMesh.Vert(x, y, z)
        tronco.verts.append(v)
    #

    direction = Vector([0, 0, treeGrowSpeedButton.val, 1])
    traslTotal = TranslationMatrix(direction)
    rotTotal = RotationMatrix(0, 4, 'z')

    nTasselli = creaTronco(
        treeLengthButton.val, 0, initialMinBranchHeightButton.val,
        initialBranchFrequencyButton.val, direction, rotTotal, traslTotal,
        closureGrowFactorButton.val, 0,
        treeGrowSpeedButton.val * closureTreeGrowSpeedButton.val)

    progressMAX = nTasselli * 1.0
    #Drawing Faces TRONCO
    for j in range(0, nTasselli):
        #Al posto di 1000 mettere nTasselli/numeroRedraw (???Non so come trasformare in intero)
        if ((j % 1000) == 0):
            DrawProgressBar(j / progressMAX, "Drawing Trunc...")
        for i in range(0, n - 1):
            #print "faccia:"
            #print i
            #Evito di disegnare i punti collassati in [0,0,0] inseriti per accorgermi della giunzione
            if ((tronco.verts[(j + 1) * n + i + 1].co[0] == 0)
                    and (tronco.verts[(j + 1) * n + i + 1].co[1] == 0)
                    and (tronco.verts[(j + 1) * n + i + 1].co[2] == 0)):
                continue
            if ((tronco.verts[(j) * n + i + 1].co[0] == 0)
                    and (tronco.verts[(j) * n + i + 1].co[1] == 0)
                    and (tronco.verts[(j) * n + i + 1].co[2] == 0)):
                continue
            f = NMesh.Face()
            f.v.append(tronco.verts[j * n + i])
            f.v.append(tronco.verts[j * n + i + 1])
            f.v.append(tronco.verts[(j + 1) * n + i + 1])
            f.v.append(tronco.verts[(j + 1) * n + i])
            tronco.faces.append(f)
        #

    #Drawing Faces LEAF
    cont = 0
    numVert = 0
    numFace = 0
    f = NMesh.Face()
    nFoglie = len(foglie.verts) * 1.0
    actual_nFoglie = 0.0
    for vert in foglie.verts:
        #modificare anche qui come sopra
        if ((actual_nFoglie % 10000) == 0):
            DrawProgressBar(actual_nFoglie / nFoglie, "Drawing Leaf...")
        actual_nFoglie += 1
        numVert += 1
        #print "Aggiungo vertice"
        f.v.append(vert)
        cont += 1
        if (cont == 4):
            f.uv.append((0, 0))
            f.uv.append((1, 0))
            f.uv.append((1, 1))
            f.uv.append((0, 1))
            foglie.faces.append(f)
            f = NMesh.Face()
            #print "Stampo Faccia"
            #print numFace
            numFace += 1
            cont = 0
    #

    #Materiali, Texture, e update
    if ((not tronco.materials) and (not foglie.materials)):
        #Primo avvio: inserire materiali etcc..

        #Materiale e texture Foglia
        leafMat = Material.New("leafMaterial")
        leafMat.setAlpha(0)
        leafMat.setRGBCol([0, 0.3, 0])
        leafMat.setSpecCol([0, 0, 0])
        leafMat.mode |= Material.Modes.ZTRANSP

        leafTex = Texture.New("leafTexture")
        leafTex.setType("Image")
        image = Image.Load(defaultDirButton.val)
        leafTex.image = image
        leafTex.setImageFlags("MipMap", "UseAlpha")

        leafMat.setTexture(0, leafTex)

        leafMTexList = leafMat.getTextures()
        leafMTex = leafMTexList[0]
        leafMTex.texco = Texture.TexCo.UV
        leafMTex.mapto |= Texture.MapTo.ALPHA

        #Associo materiale
        foglie.materials.append(leafMat)

        #Materiale Tronco
        stemMat = Material.New("stemMaterial")
        stemMat.setSpecCol([0, 0, 0])

        stemTex = Texture.New("stemTexture")
        stemTex.setType("Image")

        image = Image.Load(defaultDirButtonStem.val)
        stemTex.image = image
        stemTex.setImageFlags("MipMap")

        stemMat.setTexture(0, stemTex)

        stemMTexList = stemMat.getTextures()
        stemMTex = stemMTexList[0]
        stemMTex.texco = Texture.TexCo.UV

        #Associo materiale
        tronco.materials.append(stemMat)

        NMesh.PutRaw(tronco, "stemMesh", 1)
        NMesh.PutRaw(foglie, "leafMesh", 1)

    else:
        #Neccessito solo di cambiare le immagini texture
        leafMat = foglie.materials[0]
        leafMTexList = leafMat.getTextures()
        leafMTex = leafMTexList[0]
        image = Image.Load(defaultDirButton.val)
        leafTex = leafMTex.tex
        leafTex.image = image

        stemMat = tronco.materials[0]
        stemMTexList = stemMat.getTextures()
        stemMTex = stemMTexList[0]
        image = Image.Load(defaultDirButtonStem.val)
        stemTex = stemMTex.tex
        stemTex.image = image

        tronco.update()
        foglie.update()

    DrawProgressBar(1.0, "Finished")