示例#1
0
def material_to_blender(pglmat):
    """Create a blender material
	
	:Parameters:
	 - `pglmat` (pgl.Material)
	
	:Returns Type: bld.Material
	"""
    #creation
    if pglmat.isNamed():
        name = pglmat.name
    else:
        name = "pglmat%d" % pglmat.getId()

    mat = Material.New(name)

    #ambient
    col = pglmat.ambient
    mat.setRGBCol(col.red / 255., col.green / 255., col.blue / 255.)

    #specular
    col = pglmat.specular
    mat.setSpecCol(col.red / 255., col.green / 255., col.blue / 255.)

    #TODO other material properties

    #return
    return mat
示例#2
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.")
示例#3
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
示例#4
0
def getmaterial9(bgldir, m, matlist, t, texnames):
    (dr,dg,db,da,ar,ag,ab,aa,sr,sg,sb,sa,er,eg,eb,ea,sp)=matlist[m]
    texcount=0
    mat=Material.New()
    mat.rgbCol=[dr,dg,db]
    mat.alpha=da
    mat.specCol=[sr,sg,sb]
    mat.hard=int(sp+0.5)

    diffuse=night=reflect=light=None
    i=t
    for i in range(t,len(texnames)):
        if i==-1: break
        (cls, rgba, reserved, size, name)=texnames[i]
        if i>t and not cls&0xff00: break	# TEXTURE2_MASK
        if cls==1 or cls==6:		# TEXTURE_AIRCRAFT, TEXTURE_BUILDING
            diffuse=name
        elif cls==0x100:		# TEXTURE2_NIGHT
            night=name
        elif cls==0x200:		# TEXTURE2_REFLECT
            reflect=name
        elif cls==0x300 or cls==0x400:	# TEXTURE2_LIGHTMAP, TEXTURE2_LIGHTMAP_A
            light=name

    if diffuse:
        tex=gettexture('Diffuse', bgldir, diffuse)
        mat.setTexture(texcount, tex)
        mtex=mat.getTextures()[texcount]
        mtex.texco=Texture.TexCo.UV
        mtex.mapto=Texture.MapTo.COL
        if diffuse==reflect:
            mtex.mapto|=Texture.MapTo.REF
            mtex.mtRef=-1
        texcount+=1

    if night or light:
        if light:
            mat.setTexture(texcount, gettexture('Emissive', bgldir, light))
        else:
            mat.setTexture(texcount, gettexture('Emissive', bgldir, night))
        mtex=mat.getTextures()[texcount]
        mtex.texco=Texture.TexCo.UV
        mtex.mapto=Texture.MapTo.EMIT
        if light:
            mtex.blendmode=Texture.BlendModes.ADD
        else:	# default / FS2004 syle - night
            mtex.blendmode=Texture.BlendModes.MIX
        texcount+=1

    return mat
示例#5
0
def CreateBlenderMaterialFromNode(scene, materialNode, blenderScene):
    mat = Material.New(scene.GetNodeName(materialNode))

    # load the textures for this material
    childLink = scene.GetFirstChildLink(materialNode)
    while childLink != None:
        textureNode = scene.GetNodeFromLink(childLink)
        if scene.IsTextureNode(textureNode) == True:
            sourceTexture = pyScene.pyTexture(scene, textureNode)
            texture = g_textureMap[sourceTexture.GetId()]
            #mat.setTexture(0, texture)
            mat.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL)
        childLink = scene.GetNextChildLink(materialNode, childLink)

    return mat
示例#6
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)
示例#7
0
def AddGlobalMaterial(name, matindex):
    #=========================================

    index = 0
    found = 0
    matindex = 0
    MatList = Material.Get()
    limit = len(MatList)

    while index < limit:
        if MatList[index].name == name:
            matindex = index
            found = 1
            index = limit
        index = index + 1

    if found == 0:
        material = Material.New(name)
        matindex = index

    return matindex
示例#8
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
示例#9
0
import bpy
import Blender
from Blender import Material, Texture, Image
i = 0
for mesh in bpy.data.meshes:
    if not mesh.materials:
        i += 1
        print(mesh.materials)
        texture = Texture.New('Yoo0')
        texture.setType('Image')
        material = Material.New('mat' + str(i))
        material.setTexture(0, texture, Texture.TexCo.UV)
        mesh.materials += [material]
        print(mesh.materials[0].getTextures())
#	mesh.materials = []
#	if mesh.materials:
#		print(mesh.materials[0].getTextures()[0].tex)
示例#10
0
def buildParticles(grains,particles,q):
	import csv
	from Blender import Camera, Lamp, Material, Mesh, Object, Constraint
		
	scene = bpy.data.scenes.active
    ##############################################################
    # Get rid of all object from default scene
	print 'Removing objects in current scene'
	for ob in scene.objects:
		if ((cmp(ob.getName(),'Lamp')==0), (cmp(ob.getName(),'Cube')==0), (cmp(ob.getName(),'Camera')==0)):
			scene.objects.unlink(ob)
			print str(ob) + 'removed'
	print 'Adding new objects'
    ##############################################################
    # add mesh at origin to focus camera on
    #
	me = Mesh.Primitives.UVsphere(3,3,0)
	origin = scene.objects.new(me,'Origin')
    ##############################################################
    # add a camera and set it up
    #
	camdata = Camera.New('ortho')   # create new ortho camera data
#	camdata.scale = 25.0             # set scale value for ortho view
	cam = scene.objects.new(camdata)   # add a new camera object from the data
	scene.objects.camera = cam    # make this camera the active camera
    
    # This makes the camera follow the origin
	ob = Object.Get('Camera')
	const = ob.constraints.append(Constraint.Type.TRACKTO)
	const[Constraint.Settings.TARGET] = origin
	const.__setitem__(Constraint.Settings.TRACK, Constraint.Settings.TRACKNEGZ)
	const.__setitem__(Constraint.Settings.UP, Constraint.Settings.UPY)

    ##############################################################
    # add a lamp and set it up
    #
	lampdata = Lamp.New()
	lampdata.setEnergy(1.0)
#	lampdata.setType('Sun')
	lamp = scene.objects.new(lampdata)
	lamp.setLocation(10.0,-10.0,10.0)
	lamp.setEuler(0.0,0.0,0.0)
	##############################################################
    # get particle data
    #
	for pt in range(particles):
		me = Mesh.Primitives.UVsphere(q,q,grains[pt,0,3])   # create a new sphere of (segments,rings,diameter)
		ob = scene.objects.new(me,'Grain' + str(pt))        # add a new mesh-type object to the scene
		ob.setLocation (grains[pt,0,0], grains[pt,0,1], grains[pt,0,2])       # position the object in the scene
		# smooth the mesh
		faces = me.faces            # Get the faces.
		for f in faces:             # Loop through them.
			f.smooth = 1            # Smooth each face.
		# set the material
		mat = Material.New('Mat') # create a new Material called 'Mat'
		mat.rgbCol = [grains[pt,0,4], grains[pt,0,5], grains[pt,0,6]] # change the color of the sphere
		mat.setAlpha(0.8)                     # mat.alpha = 0.2 -- almost transparent
		mat.emit = 0.5                        # equivalent to mat.setEmit(0.8)
		mat.mode |= Material.Modes.ZTRANSP    # turn on Z-Buffer transparency
		mat.setAdd(1) 
		me.materials += [mat]
示例#11
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
示例#12
0
def PolyDataMapperToBlender(pmapper, me=None):
    global flags
    faces = []
    edges = []
    oldmats = None

    newmesh = 0
    if (me == None):
        me = Mesh.New()
        newmesh = 1
    else:
        if me.materials:
            oldmats = me.materials

        me.verts = None  # this kills the faces/edges tooo

    pmapper.Update()

    pdata = pmapper.GetInput()
    plut = pmapper.GetLookupTable()
    #print pdata.GetNumberOfCells()

    scalars = pdata.GetPointData().GetScalars()

    verts = []
    for i in range(pdata.GetNumberOfPoints()):
        point = pdata.GetPoint(i)
        verts.append([point[0], point[1], point[2]])

    me.verts.extend(verts)
    # I think we can free some memory by killing the reference
    # from vert to the list it points at (not sure though)
    verts = []

    colors = None

    if ((scalars != None) and (plut != None)):
        colors = []

        # Have to be a bit careful since VTK 5.0 changed the
        # prototype of vtkLookupTable.GetColor()
        try:
            # VTK 5.x
            scolor = [0, 0, 0]
            for i in range(scalars.GetNumberOfTuples()):
                plut.GetColor(scalars.GetTuple1(i), scolor)
                color = map(VTKToBlenderColor, scolor)
                alpha = int(plut.GetOpacity(scalars.GetTuple1(i)) * 255)
                colors.append([color[0], color[1], color[2], alpha])

        except:
            # VTK 4.x
            for i in range(scalars.GetNumberOfTuples()):
                color = map(VTKToBlenderColor, \
                   plut.GetColor(scalars.GetTuple1(i)))
                alpha = int(plut.GetOpacity(scalars.GetTuple1(i)) * 255)
                colors.append([color[0], color[1], color[2], alpha])

    skiptriangle = False
    for i in range(pdata.GetNumberOfCells()):

        cell = pdata.GetCell(i)

        #print i, pdata.GetCellType(i)

        # Do lines
        if pdata.GetCellType(i) == 3:

            n1 = cell.GetPointId(0)
            n2 = cell.GetPointId(1)

            BlenderAddEdge(me, edges, n1, n2)

        # Do poly lines
        if pdata.GetCellType(i) == 4:
            for j in range(cell.GetNumberOfPoints() - 1):

                n1 = cell.GetPointId(j)
                n2 = cell.GetPointId(j + 1)

                BlenderAddEdge(me, edges, n1, n2)

        # Do triangles
        if pdata.GetCellType(i) == 5:
            if skiptriangle == True:
                skiptriangle = False
            elif ((flags & TRIS_TO_QUADS)
                  and (i < pdata.GetNumberOfCells() - 1)
                  and (pdata.GetCellType(i + 1) == 5)):
                n1 = cell.GetPointId(0)
                n2 = cell.GetPointId(1)
                n3 = cell.GetPointId(2)
                nextcell = pdata.GetCell(i + 1)
                m1 = nextcell.GetPointId(0)
                m2 = nextcell.GetPointId(1)
                m3 = nextcell.GetPointId(2)

                if ((n2 == m3) and (n3 == m2)):
                    BlenderAddFace(me, faces, n1, n2, m1, n3)
                    skiptriangle = True
                else:
                    BlenderAddFace(me, faces, n1, n2, n3)

            else:
                n1 = cell.GetPointId(0)
                n2 = cell.GetPointId(1)
                n3 = cell.GetPointId(2)

                BlenderAddFace(me, faces, n1, n2, n3)

        # Do triangle strips
        if pdata.GetCellType(i) == 6:
            numpoints = cell.GetNumberOfPoints()
            if ((flags & TRIS_TO_QUADS) and (numpoints % 2 == 0)):
                for j in range(cell.GetNumberOfPoints() - 3):
                    if (j % 2 == 0):
                        n1 = cell.GetPointId(j)
                        n2 = cell.GetPointId(j + 1)
                        n3 = cell.GetPointId(j + 2)
                        n4 = cell.GetPointId(j + 3)

                        BlenderAddFace(me, faces, n1, n2, n4, n3)
            else:
                for j in range(cell.GetNumberOfPoints() - 2):
                    if (j % 2 == 0):
                        n1 = cell.GetPointId(j)
                        n2 = cell.GetPointId(j + 1)
                        n3 = cell.GetPointId(j + 2)
                    else:
                        n1 = cell.GetPointId(j)
                        n2 = cell.GetPointId(j + 2)
                        n3 = cell.GetPointId(j + 1)

                    BlenderAddFace(me, faces, n1, n2, n3)
        # Do polygon
        if pdata.GetCellType(i) == 7:
            # Add a vert at the center of the polygon,
            # and break into triangles
            x = 0.0
            y = 0.0
            z = 0.0
            scal = 0.0
            N = cell.GetNumberOfPoints()
            for j in range(N):
                point = pdata.GetPoint(cell.GetPointId(j))
                x = x + point[0]
                y = y + point[1]
                z = z + point[2]
                if (scalars != None):
                    scal = scal + scalars.GetTuple1(j)
            x = x / N
            y = y / N
            z = z / N
            scal = scal / N

            newidx = len(me.verts)
            me.verts.extend(x, y, z)

            if (scalars != None):
                try:
                    # VTK 5.x
                    scolor = [0, 0, 0]
                    plut.GetColor(scal, scolor)
                    color = map(VTKToBlenderColor, scolor)
                except:
                    color = map(VTKToBlenderColor, plut.GetColor(scal))
                alpha = int(plut.GetOpacity(scalars.GetTuple1(i)) * 255)

                colors.append([color[0], color[1], color[2], alpha])

            # Add triangles connecting polynomial sides to new vert
            for j in range(N):
                n1 = cell.GetPointId(j)
                n2 = cell.GetPointId((j + 1) % N)
                n3 = newidx
                BlenderAddFace(me, faces, n1, n2, n3)

        # Do pixel
        if pdata.GetCellType(i) == 8:
            n1 = cell.GetPointId(0)
            n2 = cell.GetPointId(1)
            n3 = cell.GetPointId(2)
            n4 = cell.GetPointId(3)

            BlenderAddFace(me, faces, n1, n2, n3, n4)
        # Do quad
        if pdata.GetCellType(i) == 9:
            n1 = cell.GetPointId(0)
            n2 = cell.GetPointId(1)
            n3 = cell.GetPointId(2)
            n4 = cell.GetPointId(3)

            BlenderAddFace(me, faces, n1, n2, n3, n4)

    if len(edges) > 0:
        me.edges.extend(edges)
    if len(faces) > 0:
        me.faces.extend(faces)

        if (flags & SMOOTH_FACES):
            for f in me.faces:
                f.smooth = 1

    # Some faces in me.faces may have been discarded from our
    # list, so best to compute the vertex colors after the faces
    # have been added to the mesh
    if (colors != None):
        me.vertexColors = 1
        for f in me.faces:
            f_col = []
            for v in f.v:
                f_col.append(colors[v.index])

            SetVColors(f.col, f_col)

    if not me.materials:
        if oldmats:
            me.materials = oldmats
        else:
            newmat = Material.New()
            if (colors != None):
                newmat.mode |= Material.Modes.VCOL_PAINT
            me.materials = [newmat]

    if (newmesh == 0):
        me.update()

    return me
示例#13
0
def getmaterialx(data, bgldir, texnames):

    (flags,flags2,diffuse,detail,bumpmap,specular,emissive,reflection,fresnel,dr,dg,db,da,sr,sg,sb,sa,sp,detailtile,bumptile,reflectionscale,precipoffset,bloomfloor,amb,unk,srcblend,dstblend,alphafunc,alphathreshold,alphamultiply)=unpack('<9I4f4ff4f2ffIIIff', data)
    if debug: print "%x %x %s" % (flags,flags2,(diffuse,detail,bumpmap,specular,emissive,reflection,fresnel,dr,dg,db,da,sr,sg,sb,sa,sp,detailtile,bumptile,reflectionscale,precipoffset,bloomfloor,amb,unk,srcblend,dstblend,alphafunc,alphathreshold,alphamultiply))

    texcount=0
    mat=Material.New()
    mat.rgbCol=[dr,dg,db]
    mat.alpha=da
    mat.specCol=[sr,sg,sb]
    mat.hard=int(sp+0.5)
    mat.amb=amb

    if flags&VERTICALNORM:
        mat.mode&=~Material.Modes.SHADELESS
    else:
        mat.mode|= Material.Modes.SHADELESS

    if flags&ZWRITEALPHA:
        mat.mode|= Material.Modes.ZTRANSP
    else:
        mat.mode&=~Material.Modes.ZTRANSP

    if flags&VOLUMESHADOW or not flags&NOSHADOW:
        mat.mode|= Material.Modes.SHADOWBUF
    else:
        mat.mode&=~Material.Modes.SHADOWBUF

    if flags&DIFFUSE:
        tex=gettexture('Diffuse', bgldir, texnames[diffuse])
        if srcblend==BLEND_SRCALPHA or flags&ENVINVDIFALPHA:
            tex.imageFlags|=Texture.ImageFlags.USEALPHA
        elif srcblend==BLEND_INVSRCALPHA:
            tex.imageFlags|=Texture.ImageFlags.USEALPHA
            tex.flags|=Texture.Flags.NEGALPHA
        mat.setTexture(texcount, tex)
        mtex=mat.getTextures()[texcount]
        mtex.texco=Texture.TexCo.UV
        mtex.mapto=Texture.MapTo.COL
        if dstblend==BLEND_SRCALPHA:
            mtex.mapto|=Texture.MapTo.ALPHA
            mtex.dvar=0.0
            mat.mode|= Material.Modes.ZTRANSP
        elif dstblend==BLEND_INVSRCALPHA:
            mtex.mapto|=Texture.MapTo.ALPHA
            mtex.mtAlpha=-1
            mtex.dvar=0.0
            mat.mode|= Material.Modes.ZTRANSP
        if flags&ENVINVDIFALPHA:
            mtex.mapto|=Texture.MapTo.REF
            mtex.mtRef=-1
        texcount+=1

    if flags&DETAIL:
        mat.setTexture(texcount, gettexture('Detail', bgldir, texnames[detail]))
        mtex=mat.getTextures()[texcount]
        mtex.texco=Texture.TexCo.UV
        mtex.mapto=Texture.MapTo.COL
        mtex.colfac=0.5
        mtex.size=(detailtile,detailtile,detailtile)
        texcount+=1

    if flags&BUMP:
        mat.setTexture(texcount, gettexture('BumpMap', bgldir, texnames[bumpmap]))
        mtex=mat.getTextures()[texcount]
        mtex.texco=Texture.TexCo.UV
        mtex.mapto=Texture.MapTo.NOR
        mtex.size=(bumptile,bumptile,bumptile)
        texcount+=1

    if flags&SPECULAR:
        tex=gettexture('Specular', bgldir, texnames[specular])
        tex.imageFlags|=Texture.ImageFlags.USEALPHA
        mat.setTexture(texcount, tex)
        mtex=mat.getTextures()[texcount]
        mtex.texco=Texture.TexCo.UV
        mtex.mapto=Texture.MapTo.CSP
        if flags&ENVSPECALPHA:
            mtex.mapto|=Texture.MapTo.REF
        texcount+=1
    if flags&ISSPECULAR:
        mat.spec=0.5
    else:
        mat.spec=0

    if flags&ENVMAP or flags&GLOBALENVMAP:
        if flags&ENVMAP:
            tex=gettexture('EnvMap', bgldir, texnames[reflection])
        else:
            try:
                tex=Texture.Get('DefaultEnvMap')
            except:
                tex=Texture.New('DefaultEnvMap')
        tex.type=Texture.Types.ENVMAP
        tex.stype=Texture.STypes.ENV_LOAD
        mat.setTexture(texcount, tex)
        mtex=mat.getTextures()[texcount]
        mtex.texco=Texture.TexCo.REFL
        mtex.mapto=Texture.MapTo.CMIR
        mtex.colfac=reflectionscale
        texcount+=1

    if flags&EMISSIVE:
        mat.setTexture(texcount, gettexture('Emissive', bgldir, texnames[emissive]))
        mtex=mat.getTextures()[texcount]
        mtex.texco=Texture.TexCo.UV
        mtex.mapto=Texture.MapTo.EMIT
        if flags2&EMADD or flags2&EMADDUSR or flags2&EMADDNOUSR:
            mtex.blendmode=Texture.BlendModes.ADD
        elif flags2&EMMUL or flags2&EMMULUSR:
            mtex.blendmode=Texture.BlendModes.MULTIPLY
        else:	# default / FS2004 syle
            mtex.blendmode=Texture.BlendModes.MIX
        texcount+=1

    return mat
示例#14
0
# I'm importing an .obj file. Applying a material and a texture and then exporting again. 
# I've come to importing the file and creating a new material etc but now I need to apply it to the 
# imported object. But how do I access the object functions for the imported object?


import Blender
from Blender import Scene, Object, Material
import import_obj

ob = import_obj.load_obj('/home/arnaud/Documents/z25/bodycount/scans/Arnaud/scan_faceFrnt_scl8_tst02.obj',CLAMP_SIZE=10.0)
print(ob)

mat = Material.New('gezichtMat')
mat.rgbCol = [0.8, 0.2, 0.2]
ob.setMaterials(mat)

Blender.Redraw()




# import_obj dosnt return 1 object. make a new scene for each import, then loop on its objects.
# also, set the materials for the mesh, not the object
# ob.getData(mesh=1).materials = [mymat]
示例#15
0
def PolyDataMapperToBlender(pmapper, me=None):

    newmesh = 0
    if (me == None):
        me = NMesh.GetRaw(
        )  #Este metodo es usado para crear un objeto "malla" en memoria. Este objeto es creado en Buffer
        newmesh = 1
    else:
        me.verts = []
        me.faces = []

    # vtkLookupTable es un objeto usado por los objetos de mapeado para mapear valores escalares en una especificacion de color rgba
    pmapper.Update()

    pdata = pmapper.GetInput()  #Especifica los datos de entrada a mapear
    plut = pmapper.GetLookupTable()  #
    #print pdata.GetNumberOfCells()

    scalars = pdata.GetPointData().GetScalars()

    for i in range(pdata.GetNumberOfPoints()):
        point = pdata.GetPoint(i)
        v = NMesh.Vert(point[0], point[1], point[2])
        me.verts.append(v)

    colors = None
    if ((scalars != None) and (plut != None)):
        colors = []
        for i in range(scalars.GetNumberOfTuples()):
            color = map(VTKToBlenderColor, plut.GetColor(scalars.GetTuple1(i)))
            colors.append(NMesh.Col(color[0], color[1], color[2]))

    for i in range(pdata.GetNumberOfCells()):
        cell = pdata.GetCell(i)
        #print i, pdata.GetCellType(i)

        # Do lines
        if pdata.GetCellType(i) == 3:

            n1 = cell.GetPointId(0)
            n2 = cell.GetPointId(1)

            BlenderAddFace(me, colors, n1, n2)

        # Do poly lines
        if pdata.GetCellType(i) == 4:
            for j in range(cell.GetNumberOfPoints() - 1):

                n1 = cell.GetPointId(j)
                n2 = cell.GetPointId(j + 1)

                BlenderAddFace(me, colors, n1, n2)

        # Do triangles
        if pdata.GetCellType(i) == 5:

            n1 = cell.GetPointId(0)
            n2 = cell.GetPointId(1)
            n3 = cell.GetPointId(2)

            BlenderAddFace(me, colors, n1, n2, n3)

        # Do triangle strips
        if pdata.GetCellType(i) == 6:
            for j in range(cell.GetNumberOfPoints() - 2):
                if (j % 2 == 0):
                    n1 = cell.GetPointId(j)
                    n2 = cell.GetPointId(j + 1)
                    n3 = cell.GetPointId(j + 2)
                else:
                    n1 = cell.GetPointId(j)
                    n2 = cell.GetPointId(j + 2)
                    n3 = cell.GetPointId(j + 1)

                BlenderAddFace(me, colors, n1, n2, n3)

        # Do polygon
        if pdata.GetCellType(i) == 7:
            # Add a vert at the center of the polygon,
            # and break into triangles
            x = 0.0
            y = 0.0
            z = 0.0
            scal = 0.0
            N = cell.GetNumberOfPoints()
            for j in range(N):
                point = pdata.GetPoint(cell.GetPointId(j))
                x = x + point[0]
                y = y + point[1]
                z = z + point[2]
                if (scalars != None):
                    scal = scal + scalars.GetTuple1(j)
            x = x / N
            y = y / N
            z = z / N
            scal = scal / N

            newidx = len(me.verts)
            v = NMesh.Vert(x, y, z)
            me.verts.append(v)
            if (scalars != None):
                color = map(VTKToBlenderColor, plut.GetColor(scal))
                colors.append(NMesh.Col(color[0], color[1], color[2]))

            # Add triangles connecting polynomial sides to new vert
            for j in range(N):
                n1 = cell.GetPointId(j)
                n2 = cell.GetPointId((j + 1) % N)
                n3 = newidx
                BlenderAddFace(me, colors, n1, n2, n3)

        # Do pixel
        if pdata.GetCellType(i) == 8:
            n1 = cell.GetPointId(0)
            n2 = cell.GetPointId(1)
            n3 = cell.GetPointId(2)
            n4 = cell.GetPointId(3)

            BlenderAddFace(me, colors, n1, n2, n3, n4)

        # Do quad
        if pdata.GetCellType(i) == 9:
            n1 = cell.GetPointId(0)
            n2 = cell.GetPointId(1)
            n3 = cell.GetPointId(2)
            n4 = cell.GetPointId(3)

            BlenderAddFace(me, colors, n1, n2, n3, n4)

    if not me.materials:
        newmat = Material.New()
        if (colors != None):
            newmat.mode |= Material.Modes.VCOL_PAINT
        me.materials.append(newmat)

    if (newmesh == 0):
        me.update()

    return me
示例#16
0
def readDSF(path):
    baddsf=(0, "Invalid DSF file", path)

    h=file(path, 'rb')
    h.seek(0, 2)
    hlen=h.tell()
    h.seek(0, 0)
    if h.read(8)!='XPLNEDSF' or unpack('<I',h.read(4))!=(1,) or h.read(4)!='DAEH':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    headend=h.tell()+l-8
    if h.read(4)!='PORP':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    properties=[]
    c=h.read(l-9).split('\0')
    h.read(1)
    overlay=0
    for i in range(0, len(c)-1, 2):
        if c[i]=='sim/overlay': overlay=int(c[i+1])
        elif c[i]=='sim/south': lat=int(c[i+1])
        elif c[i]=='sim/west': lon=int(c[i+1])
        properties.append((c[i],c[i+1]))
    h.seek(headend)
    if overlay:
        # Overlay DSF - bail early
        h.close()
        raise IOError, (0, "This is an overlay DSF", path)

    # Definitions Atom
    if h.read(4)!='NFED':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    defnend=h.tell()+l-8
    terrain=objects=polygons=network=[]
    while h.tell()<defnend:
        c=h.read(4)
        (l,)=unpack('<I', h.read(4))
        if l==8:
            pass	# empty
        elif c=='TRET':
            terrain=h.read(l-9).replace('\\','/').replace(':','/').split('\0')
            h.read(1)
        elif c=='TJBO':
            objects=h.read(l-9).replace('\\','/').replace(':','/').split('\0')
            h.read(1)
        elif c=='YLOP':
            polygons=h.read(l-9).replace('\\','/').replace(':','/').split('\0')
            h.read(1)
        elif c=='WTEN':
            networks=h.read(l-9).replace('\\','/').replace(':','/').split('\0')
            h.read(1)
        else:
            h.seek(l-8, 1)

    # Geodata Atom
    if h.read(4)!='DOEG':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    geodend=h.tell()+l-8
    pool=[]
    scal=[]
    while h.tell()<geodend:
        c=h.read(4)
        (l,)=unpack('<I', h.read(4))
        if c=='LOOP':
            thispool=[]
            (n,)=unpack('<I', h.read(4))
            (p,)=unpack('<B', h.read(1))
            for i in range(p):
                thisplane=[]
                (e,)=unpack('<B', h.read(1))
                if e==0 or e==1:
                    last=0
                    for j in range(n):
                        (d,)=unpack('<H', h.read(2))
                        if e==1: d=(last+d)&65535
                        thisplane.append(d)
                        last=d
                elif e==2 or e==3:
                    last=0
                    while(len(thisplane))<n:
                        (r,)=unpack('<B', h.read(1))
                        if (r&128):
                            (d,)=unpack('<H', h.read(2))
                            for j in range(r&127):
                                if e==3:
                                    thisplane.append((last+d)&65535)
                                    last=(last+d)&65535
                                else:
                                    thisplane.append(d)
                        else:
                            for j in range(r):
                                (d,)=unpack('<H', h.read(2))
                                if e==3: d=(last+d)&65535
                                thisplane.append(d)
                                last=d
                else:
                    raise IOError, baddsf
                thispool.append(thisplane)
            pool.append(thispool)
        elif c=='LACS':
            thisscal=[]
            for i in range(0, l-8, 8):
                d=unpack('<2f', h.read(8))
                thisscal.append(d)
            scal.append(thisscal)
        else:
            h.seek(l-8, 1)

    # Rescale pool and transform to one list per entry
    if len(scal)!=len(pool): raise(IOError)
    newpool=[]
    for i in range(len(pool)):
        curpool=pool[i]
        n=len(curpool[0])
        newpool=[[] for j in range(n)]
        for plane in range(len(curpool)):
            (scale,offset)=scal[i][plane]
            scale=scale/65535
            for j in range(n):
                newpool[j].append(curpool[plane][j]*scale+offset)
        pool[i]=newpool

    # Commands Atom
    if h.read(4)!='SDMC':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    cmdsend=h.tell()+l-8
    curpool=0
    idx=0
    near=0
    far=-1
    flags=0	# 0=physical, 1=overlay
    f=[[[],[]] for i in range(len(terrain))]
    v=[[[],[]] for i in range(len(terrain))]
    t=[[[],[]] for i in range(len(terrain))]
    pscale=99.0/(hlen-geodend)
    progress=0
    while h.tell()<cmdsend:
        now=int((h.tell()-geodend)*pscale)
        if progress!=now:
            progress=now
            Window.DrawProgressBar(progress/100.0, "Importing %2d%%"%progress)

        (c,)=unpack('<B', h.read(1))
        if c==1:	# Coordinate Pool Select
            (curpool,)=unpack('<H', h.read(2))

        elif c==2:	# Junction Offset Select
            h.read(4)	# not implemented

        elif c==3:	# Set Definition
            (idx,)=unpack('<B', h.read(1))

        elif c==4:	# Set Definition
            (idx,)=unpack('<H', h.read(2))

        elif c==5:	# Set Definition
            (idx,)=unpack('<I', h.read(4))

        elif c==6:	# Set Road Subtype
            h.read(1)	# not implemented

        elif c==7:	# Object
            h.read(2)	# not implemented

        elif c==8:	# Object Range
            h.read(4)	# not implemented

        elif c==9:	# Network Chain
            (l,)=unpack('<B', h.read(1))
            h.read(l*2)	# not implemented

        elif c==10:	# Network Chain Range
            h.read(4)	# not implemented

        elif c==11:	# Network Chain
            (l,)=unpack('<B', h.read(1))
            h.read(l*4)	# not implemented

        elif c==12:	# Polygon
            (param,l)=unpack('<HB', h.read(3))
            h.read(l*2)	# not implemented

        elif c==13:	# Polygon Range (DSF2Text uses this one)
            (param,first,last)=unpack('<HHH', h.read(6))	# not implemented

        elif c==14:	# Nested Polygon
            (param,n)=unpack('<HB', h.read(3))
            for i in range(n):
                (l,)=unpack('<B', h.read(1))
                h.read(l*2)	# not implemented

        elif c==15:	# Nested Polygon Range (DSF2Text uses this one too)
            (param,n)=unpack('<HB', h.read(3))
            h.read((n+1)*2)	# not implemented

        elif c==16:	# Terrain Patch
            pass

        elif c==17:	# Terrain Patch w/ flags
            (flags,)=unpack('<B', h.read(1))
            flags-=1

        elif c==18:	# Terrain Patch w/ flags & LOD
            (flags,near,far)=unpack('<Bff', h.read(9))
            flags-=1

        elif c==23:	# Patch Triangle
            (l,)=unpack('<B', h.read(1))
            n=len(v[idx][flags])
            for i in range(n,n+l,3):
                f[idx][flags].append([i+2,i+1,i])
            for i in range(l):
                (d,)=unpack('<H', h.read(2))
                p=pool[curpool][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])


        elif c==24:	# Patch Triangle - cross-pool
            (l,)=unpack('<B', h.read(1))
            n=len(v[idx][flags])
            for i in range(n,n+l,3):
                f[idx][flags].append([i+2,i+1,i])
            for i in range(l):
                (c,d)=unpack('<HH', h.read(4))
                p=pool[c][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        elif c==25:	# Patch Triangle Range
            (first,last)=unpack('<HH', h.read(4))
            n=len(v[idx][flags])
            for i in range(n,n+last-first,3):
                f[idx][flags].append([i+2,i+1,i])
            for d in range(first,last):
                p=pool[curpool][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        #elif c==26:	# Patch Triangle Strip (not used by DSF2Text)
        #elif c==27:
        #elif c==28:

        elif c==29:	# Patch Triangle Fan
            (l,)=unpack('<B', h.read(1))
            n=len(v[idx][flags])
            for i in range(1,l-1):
                f[idx][flags].append([n+i+1,n+i,n])
            for i in range(l):
                (d,)=unpack('<H', h.read(2))
                p=pool[curpool][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        elif c==30:	# Patch Triangle Fan - cross-pool
            (l,)=unpack('<B', h.read(1))
            n=len(v[idx][flags])
            for i in range(1,l-1):
                f[idx][flags].append([n+i+1,n+i,n])
            for i in range(l):
                (c,d)=unpack('<HH', h.read(4))
                p=pool[c][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        elif c==31:	# Patch Triangle Fan Range
            (first,last)=unpack('<HH', h.read(4))
            n=len(v[idx][flags])
            for i in range(1,last-first-1):
                f[idx][flags].append([n+i+1,n+i,n])
            for d in range(first, last):
                p=pool[curpool][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        elif c==32:	# Comment
            (l,)=unpack('<B', h.read(1))
            h.read(l)

        elif c==33:	# Comment
            (l,)=unpack('<H', h.read(2))
            h.read(l)

        elif c==34:	# Comment
            (l,)=unpack('<I', h.read(4))
            h.read(l)

        else:
            raise IOError, (c, "Unrecognised command (%d)" % c, c)

    h.close()

    Window.DrawProgressBar(0.99, "Realising")

    scene=Scene.GetCurrent()
    scene.layers=[1,2]

    for flags in [0]:# was [1,0]:	# overlay first so overlays
        for idx in range(len(terrain)):
            if not f[idx][flags]: continue
            if idx:
                name=basename(terrain[idx])[:-4]
                if flags: name=name+'.2'
                if terrain[idx] in libterrain:
                    (texture, angle, xscale, zscale)=readTER(libterrain[terrain[idx]])
                elif exists(join(dirname(path), pardir, pardir, terrain[idx])):
                    (texture, angle, xscale, zscale)=readTER(abspath(join(dirname(path), pardir, pardir, terrain[idx])))
                else:
                    raise IOError(0, 'Terrain %s not found' % terrain[idx], terrain[idx])
                try:
                    mat=Material.Get(name)
                except:
                    mat=Material.New(name)
                    mat.rgbCol=[1.0, 1.0, 1.0]
                    mat.spec=0
                    try:
                        img=Image.Get(basename(texture))
                    except:
                        img=Image.Load(texture)
                    tex=Texture.New(name)
                    tex.setType('Image')
                    tex.image=img
                    mat.setTexture(0, tex)
                    if flags:
                        mat.zOffset=1
                        mat.mode |= Material.Modes.ZTRANSP
                    mtex=mat.getTextures()[0]
                    mtex.size=(xscale*250, zscale*250, 0)
                    mtex.zproj=Texture.Proj.NONE
                    if t[idx][flags]:
                        mtex.texco=Texture.TexCo.UV
                    else:
                        mtex.texco=Texture.TexCo.GLOB
            else:
                name=terrain[idx]
                mat=Material.New(terrain[idx])
                mat.rgbCol=[0.1, 0.1, 0.2]
                mat.spec=0

            mesh=Mesh.New(name)
            mesh.mode &= ~(Mesh.Modes.TWOSIDED|Mesh.Modes.AUTOSMOOTH)
            mesh.mode |= Mesh.Modes.NOVNORMALSFLIP
            mesh.materials += [mat]
            mesh.verts.extend(v[idx][flags])
            mesh.faces.extend(f[idx][flags])
            if t[idx][flags]:
                faceno=0
                for face in mesh.faces:
                    face.uv=[Vector(t[idx][flags][i][0], t[idx][flags][i][1]) for i in f[idx][flags][faceno]]
                    face.image=img
                    faceno+=1
            mesh.update()

            ob = Object.New("Mesh", name)
            ob.link(mesh)
            scene.objects.link(ob)
            ob.Layer=flags+1
            ob.addProperty('terrain', terrain[idx])

            mesh.sel=True
            mesh.remDoubles(0.001)	# must be after linked to object
            mesh.sel=False

        if 0:	# Unreliable
            for face in mesh.faces:
                for v in face.verts:
                    if v.co[2]!=0.0:
                        break
                else:
                    face.mat=1	# water

    lamp=Lamp.New("Lamp", "Sun")
    ob = Object.New("Lamp", "Sun")
    ob.link(lamp)
    scene.objects.link(ob)
    lamp.type=1
    ob.Layer=3
    ob.setLocation(500, 500, 1000)
示例#17
0
	def testAC3DImport(self):

		FACE_TWOSIDE = Mesh.FaceModes['TWOSIDE']
		FACE_TEX = Mesh.FaceModes['TEX']
		MESH_AUTOSMOOTH = Mesh.Modes['AUTOSMOOTH']

		MAT_MODE_ZTRANSP = Material.Modes['ZTRANSP']
		MAT_MODE_TRANSPSHADOW = Material.Modes['TRANSPSHADOW']

		scene = self.scene

		bl_images = {} # loaded texture images
		missing_textures = [] # textures we couldn't find

		objlist = self.objlist[1:] # skip 'world'

		bmat = []
		has_transp_mats = False
		for mat in self.mlist:
			name = mat[0]
			m = Material.New(name)
			m.rgbCol = (mat[1][0], mat[1][1], mat[1][2])
			m.amb = mat[2]
			m.emit = mat[3]
			m.specCol = (mat[4][0], mat[4][1], mat[4][2])
			m.spec = mat[5]
			m.alpha = mat[6]
			if m.alpha < 1.0:
				m.mode |= MAT_MODE_ZTRANSP
				has_transp_mats = True
			bmat.append(m)

		if has_transp_mats:
			for mat in bmat:
				mat.mode |= MAT_MODE_TRANSPSHADOW

		obj_idx = 0 # index of current obj in loop
		for obj in objlist:
			if obj.type == AC_GROUP:
				continue
			elif obj.type == AC_LIGHT:
				light = Lamp.New('Lamp')
				object = scene.objects.new(light, obj.name)
				#object.select(True)
				obj.bl_obj = object
				if obj.data:
					light.name = obj.data
				continue

			# type AC_POLY:

			# old .ac files used empty meshes as groups, convert to a real ac group
			if not obj.vlist and obj.kids:
				obj.type = AC_GROUP
				continue

			mesh = Mesh.New()
			object = scene.objects.new(mesh, obj.name)
			#object.select(True)
			obj.bl_obj = object
			if obj.data: mesh.name = obj.data
			mesh.degr = obj.crease # will auto clamp to [1, 80]

			if not obj.vlist: # no vertices? nothing more to do
				continue

			mesh.verts.extend(obj.vlist)

			objmat_indices = []
			for mat in bmat:
				if bmat.index(mat) in obj.matlist:
					objmat_indices.append(bmat.index(mat))
					mesh.materials += [mat]
					if DISPLAY_TRANSP and mat.alpha < 1.0:
						object.transp = True

			for e in obj.elist:
				mesh.edges.extend(e)

			if obj.flist_v:
				mesh.faces.extend(obj.flist_v)

				facesnum = len(mesh.faces)

				if facesnum == 0: # shouldn't happen, of course
					continue

				mesh.faceUV = True

				# checking if the .ac file had duplicate faces (Blender ignores them)
				if facesnum != len(obj.flist_v):
					# it has, ugh. Let's clean the uv list:
					lenfl = len(obj.flist_v)
					flist = obj.flist_v
					uvlist = obj.flist_uv
					cfglist = obj.flist_cfg
					for f in flist:
						f.sort()
					fi = lenfl
					while fi > 0: # remove data related to duplicates
						fi -= 1
						if flist[fi] in flist[:fi]:
							uvlist.pop(fi)
							cfglist.pop(fi)

				img = None
				if obj.tex != '':
					if obj.tex in bl_images.keys():
						img = bl_images[obj.tex]
					elif obj.tex not in missing_textures:
						texfname = None
						objtex = obj.tex
						baseimgname = bsys.basename(objtex)
						if bsys.exists(objtex) == 1:
							texfname = objtex
						elif bsys.exists(bsys.join(self.importdir, objtex)):
							texfname = bsys.join(self.importdir, objtex)
						else:
							if baseimgname.find('\\') > 0:
								baseimgname = bsys.basename(objtex.replace('\\','/'))
							objtex = bsys.join(self.importdir, baseimgname)
							if bsys.exists(objtex) == 1:
								texfname = objtex
							else:
								objtex = bsys.join(TEXTURES_DIR, baseimgname)
								if bsys.exists(objtex):
									texfname = objtex
						if texfname:
							try:
								img = Image.Load(texfname)
								# Commented because it's unnecessary:
								#img.xrep = int(obj.texrep[0])
								#img.yrep = int(obj.texrep[1])
								if img:
									bl_images[obj.tex] = img
							except:
								inform("Couldn't load texture: %s" % baseimgname)
						else:
							missing_textures.append(obj.tex)
							inform("Couldn't find texture: %s" % baseimgname)

				for i in range(facesnum):
					f = obj.flist_cfg[i]
					fmat = f[0]
					is_smooth = f[1]
					twoside = f[2]
					bface = mesh.faces[i]
					bface.smooth = is_smooth
					if twoside: bface.mode |= FACE_TWOSIDE
					if img:
						bface.mode |= FACE_TEX
						bface.image = img
					bface.mat = objmat_indices.index(fmat)
					fuv = obj.flist_uv[i]
					if obj.texoff:
						uoff = obj.texoff[0]
						voff = obj.texoff[1]
						urep = obj.texrep[0]
						vrep = obj.texrep[1]
						for uv in fuv:
							uv[0] *= urep
							uv[1] *= vrep
							uv[0] += uoff
							uv[1] += voff

					mesh.faces[i].uv = fuv

				# finally, delete the 1st vertex we added to prevent vindices == 0
				mesh.verts.delete(0)

				mesh.calcNormals()

				mesh.mode = MESH_AUTOSMOOTH

				# subdiv: create SUBSURF modifier in Blender
				if SUBDIV and obj.subdiv > 0:
					subdiv = obj.subdiv
					subdiv_render = subdiv
					# just to be safe:
					if subdiv_render > 6: subdiv_render = 6
					if subdiv > 3: subdiv = 3
					modif = object.modifiers.append(Modifier.Types.SUBSURF)
					modif[Modifier.Settings.LEVELS] = subdiv
					modif[Modifier.Settings.RENDLEVELS] = subdiv_render

			obj_idx += 1

		self.build_hierarchy()
		scene.update()
示例#18
0
def ImportPSK(infile):
    print "Importing file: ", infile
    pskFile = file(infile, 'rb')

    #
    mesh = Mesh.New('mesh01')

    # read general header
    header = axChunkHeader()
    header.Load(pskFile)
    header.Dump()

    # read the PNTS0000 header
    header.Load(pskFile)
    header.Dump()

    axPoints = []
    for i in range(0, header.dataCount):
        point = axPoint()
        point.Load(pskFile)

        axPoints.append(point)

        #mesh.verts.extend([[point.x, point.y, point.z]])

    # read the VTXW0000 header
    header.Load(pskFile)
    header.Dump()

    xyzList = []
    uvList = []
    axVerts = []
    for i in range(0, header.dataCount):
        vert = axVertex()
        vert.Load(pskFile)
        #vert.Dump()

        axVerts.append(vert)

        xyzList.append(
            Vector([
                axPoints[vert.pointIndex].x, axPoints[vert.pointIndex].y,
                axPoints[vert.pointIndex].z
            ]))
        uvList.append(Vector([vert.u, vert.v]))

    mesh.verts.extend(xyzList)

    # read the FACE0000 header
    header.Load(pskFile)
    header.Dump()

    axTriangles = []
    for i in range(0, header.dataCount):
        tri = axTriangle()
        tri.Load(pskFile)
        #tri.Dump()

        axTriangles.append(tri)

    SGlist = []
    for i in range(0, header.dataCount):
        tri = axTriangles[i]

        mesh.faces.extend(tri.indexes)

        uvData = []
        uvData.append(uvList[tri.indexes[0]])
        uvData.append(uvList[tri.indexes[1]])
        uvData.append(uvList[tri.indexes[2]])
        mesh.faces[i].uv = uvData

        # collect a list of the smoothing groups
        if SGlist.count(tri.smoothingGroups) == 0:
            SGlist.append(tri.smoothingGroups)

        # assign a material index to the face
        #mesh.faces[-1].materialIndex = SGlist.index(indata[5])
        mesh.faces[i].mat = tri.materialIndex

    mesh.update()
    meshObject = Object.New('Mesh', 'PSKMesh')
    meshObject.link(mesh)

    scene = Scene.GetCurrent()
    scene.link(meshObject)

    # read the MATT0000 header
    header.Load(pskFile)
    header.Dump()

    for i in range(0, header.dataCount):
        data = unpack('64s6i', pskFile.read(88))
        matName = asciiz(data[0])
        print("creating material", matName)

        if matName == "":
            matName = "no_texture"

        try:
            mat = Material.Get(matName)
        except:
            #print("creating new material:", matName)
            mat = Material.New(matName)

            # create new texture
            texture = Texture.New(matName)
            texture.setType('Image')

            # texture to material
            mat.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL)

    # read the REFSKELT header
    header.Load(pskFile)
    header.Dump()

    axReferenceBones = []
    for i in range(0, header.dataCount):
        axReferenceBones.append(axReferenceBone())
        axReferenceBones[i].Load(pskFile)
        #axReferenceBones[i].Dump()

        quat = axReferenceBones[i].quat

        if i == 0:
            axReferenceBones[i].parentIndex = -1
            quat.y = -quat.y
            #quat.inverse()
        else:
            quat.inverse()

    # create an armature skeleton
    armData = Armature.Armature("PSK")
    armData.drawAxes = True

    armObject = Object.New('Armature', "ReferenceBones")
    armObject.link(armData)

    scene = Scene.GetCurrent()
    scene.objects.link(armObject)

    armData.makeEditable()

    editBones = []
    for i in range(0, header.dataCount):
        refBone = axReferenceBones[i]

        refBone.name = refBone.name.replace(' ', '_')

        print("processing bone ", refBone.name)

        #if refBone.position.length == 0:
        #refBone.Dump()

        editBone = Armature.Editbone()
        editBone.name = refBone.name
        #editBone.length = refBone.position.length

        if refBone.parentIndex >= 0:
            refParent = axReferenceBones[refBone.parentIndex]
            parentName = refParent.name
            #print type(parentName)
            print("looking for parent bone", parentName)
            #parent = armData.bones[parentName]
            #parent.
            #

            editBone.head = refParent.position.copy()

            editParent = editBones[refBone.parentIndex]
            #editParent = armData.bones[editBones[refBone.parentIndex].name]
            #editParent = armData.bones[parentName]
            editBone.parent = editParent

            #editBone.tail = refBone.position
            #editBone.matrix = refBone.quat.toMatrix()
            #m = Matrix(QuatToMatrix(refParent.quat))
            #rotatedPos = m * refBone.position.copy()
            rotatedPos = refParent.quat * refBone.position.copy()
            editBone.tail = refParent.position + rotatedPos
            refBone.position = refParent.position + rotatedPos
            #editBone.tail = refBone.position = refParent.position + refBone.position

            q1 = refParent.quat.copy()
            q2 = refBone.quat.copy()
            refBone.quat = QuatMultiply1(q1, q2)

            #editBone.matrix = refBone.quat.toMatrix()
            #matrix = Matrix(refParent.quat.toMatrix() * refBone.quat.toMatrix())
            #m1 = refParent.quat.copy().toMatrix()
            #m2 = refBone.quat.toMatrix()

            #refBone.quat = matrix.toQuat()

            #editBone.options = [Armature.HINGE]
            #editBone.options = [Armature.HINGE, Armature.CONNECTED]
            editBone.options = [Armature.CONNECTED]

        else:
            editBone.head = Vector(0, 0, 0)
            editBone.tail = refBone.position.copy()
            #editBone.tail = refBone.quat.toMatrix() * refBone.position
            #editBone.options = [Armature.HINGE]

            #editBone.matrix = refBone.quat.toMatrix()

        editBones.append(editBone)
        armData.bones[editBone.name] = editBone

    # only update after adding all edit bones or it will crash Blender !!!
    armData.update()

    print("done processing reference bones")

    #for editBone in editBones:
    #armData.makeEditable()
    #armData.bones[editBone.name] = editBone

    #armData.update()

    armObject.makeDisplayList()
    scene.update()
    Window.RedrawAll()

    # read the RAWWEIGHTS header
    header.Load(pskFile)
    header.Dump()

    axBoneWeights = []
    for i in range(0, header.dataCount):
        axBoneWeights.append(axBoneWeight())
        axBoneWeights[i].Load(pskFile)

        #if i < 10:
        #   axBoneWeights[i].Dump()

    # calculate the vertex groups
    vertGroupCreated = []
    for i in range(0, len(axReferenceBones)):
        vertGroupCreated.append(0)

    for i in range(0, len(axReferenceBones)):
        refBone = axReferenceBones[i]

        for boneWeight in axBoneWeights:

            if boneWeight.boneIndex == i:

                # create a vertex group for this bone if not done yet
                if vertGroupCreated[i] == 0:
                    print('creating vertex group:', refBone.name)
                    mesh.addVertGroup(refBone.name)
                    vertGroupCreated[i] = 1

                for j in range(0, len(axVerts)):
                    axVert = axVerts[j]

                    #vertList.append(boneWeight.pointIndex)
                    if boneWeight.pointIndex == axVert.pointIndex:
                        mesh.assignVertsToGroup(refBone.name, [j],
                                                boneWeight.weight,
                                                Mesh.AssignModes.ADD)

        #mesh.assignVertsToGroup(refBone.name, vertList, )

    armObject.makeParentDeform([meshObject], 0, 0)

    pskFile.close()

    Window.RedrawAll()

    print "PSK2Blender completed"
示例#19
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")
示例#20
0
    def testAC3DImport(self):

        FACE_TWOSIDE = Mesh.FaceModes['TWOSIDE']
        FACE_TEX = Mesh.FaceModes['TILES']
        #FACE_TEX = Mesh.FaceModes['TEX']
        MESH_AUTOSMOOTH = Mesh.Modes['AUTOSMOOTH']

        MAT_MODE_ZTRANSP = Material.Modes['ZTRANSP']
        MAT_MODE_TRANSPSHADOW = Material.Modes['TRANSPSHADOW']

        scene = self.scene

        bl_images = {}  # loaded texture images
        missing_textures = []  # textures we couldn't find
        bl_textures = {}  # loaded textures

        objlist = self.objlist[1:]  # skip 'world'

        #bmat = []
        bmat = {}
        m = None
        has_transp_mats = False
        for mat in self.mlist:
            name = mat[0]
            #			if name=='':
            name = 'BaseMaterial'
            if m == None:
                m = Material.New(name)

            m.rgbCol = (mat[1][0], mat[1][1], mat[1][2])
            m.amb = mat[2]
            m.emit = mat[3]
            m.specCol = (mat[4][0], mat[4][1], mat[4][2])
            m.spec = mat[5]
            m.alpha = mat[6]
            #force it to zero because that is how Speed Dreams / Torcs work
            m.alpha = 0.0
            if m.alpha < 1.0:
                m.mode |= MAT_MODE_ZTRANSP
                has_transp_mats = True
#			bmat[name]=m

#		if has_transp_mats:
#			for mat in bmat:
#				mat.mode |= MAT_MODE_TRANSPSHADOW

        obj_idx = 0  # index of current obj in loop
        for obj in objlist:
            if obj.type == AC_GROUP:
                continue
            elif obj.type == AC_LIGHT:
                light = Lamp.New('Lamp')
                object = scene.objects.new(light, obj.name)
                #object.select(True)
                obj.bl_obj = object
                if obj.data:
                    light.name = obj.data
                continue

            # type AC_POLY:

            # old .ac files used empty meshes as groups, convert to a real ac group
            if not obj.vlist and obj.kids:
                obj.type = AC_GROUP
                continue

            mesh = Mesh.New()
            object = scene.objects.new(mesh, obj.name)
            #object.select(True)
            obj.bl_obj = object
            if obj.data: mesh.name = obj.data
            mesh.degr = obj.crease  # will auto clamp to [1, 80]

            if not obj.vlist:  # no vertices? nothing more to do
                continue

            #Setup UV Layers
            mesh.addUVLayer("ImageUV")
            mesh.addUVLayer("ShadowUV")
            mesh.activeUVLayer = "ImageUV"

            mesh.verts.extend(obj.vlist)

            objmat_indices = []

            for e in obj.elist:
                mesh.edges.extend(e)

            if obj.flist_v:
                mesh.faces.extend(obj.flist_v)

                facesnum = len(mesh.faces)

                if facesnum == 0:  # shouldn't happen, of course
                    continue

                mesh.faceUV = True

                # checking if the .ac file had duplicate faces (Blender ignores them)
                if facesnum != len(obj.flist_v):
                    # it has, ugh. Let's clean the uv list:
                    lenfl = len(obj.flist_v)
                    flist = obj.flist_v
                    uvlist = obj.flist_uv
                    uvlist2 = obj.flist_uv2
                    cfglist = obj.flist_cfg
                    for f in flist:
                        f.sort()
                    fi = lenfl
                    while fi > 0:  # remove data related to duplicates
                        fi -= 1
                        if flist[fi] in flist[:fi]:
                            uvlist.pop(fi)
                            cfglist.pop(fi)
                            if len(uvlist2) > 0:
                                uvlist2.pop(fi)

                img = None
                img2 = None

                if obj.tex != '':
                    if obj.tex in bl_images.keys():
                        img = bl_images[obj.tex]
                    elif obj.tex not in missing_textures:
                        texfname = None
                        objtex = obj.tex
                        baseimgname = bsys.basename(objtex)
                        if bsys.exists(objtex) == 1:
                            texfname = objtex
                        else:
                            if baseimgname.find('\\') > 0:
                                baseimgname = bsys.basename(
                                    objtex.replace('\\', '/'))
                            objtex = bsys.join(self.importdir, baseimgname)
                            if bsys.exists(objtex) == 1:
                                texfname = objtex
                            else:
                                objtex = bsys.join(TEXTURES_DIR2, baseimgname)
                                if bsys.exists(objtex):
                                    texfname = objtex
                                else:
                                    inform(
                                        "Couldn't find texture in alt path %s"
                                        % TEXTURES_DIR2)
                        if texfname:
                            try:
                                img = Image.Load(texfname)
                                # Commented because it's unnecessary:
                                #img.xrep = int(obj.texrep[0])
                                #img.yrep = int(obj.texrep[1])
                                if img:
                                    bl_images[obj.tex] = img
                            except:
                                inform("THROW:  Couldn't load texture: %s" %
                                       baseimgname)
                        else:
                            missing_textures.append(obj.tex)
                            inform("Couldn't find texture: %s" % baseimgname)

                if obj.tex2 != '':
                    if obj.tex2 in bl_images.keys():
                        img2 = bl_images[obj.tex2]
                    elif obj.tex2 not in missing_textures:
                        texfname = None
                        objtex2 = obj.tex2
                        baseimgname = bsys.basename(objtex2)
                        if bsys.exists(objtex2) == 1:
                            texfname = objtex2
                        else:
                            if baseimgname.find('\\') > 0:
                                baseimgname = bsys.basename(
                                    objtex2.replace('\\', '/'))
                            objtex2 = bsys.join(self.importdir, baseimgname)
                            if bsys.exists(objtex) == 1:
                                texfname = objtex2
                            else:
                                objtex2 = bsys.join(TEXTURES_DIR2, baseimgname)
                                if bsys.exists(objtex2):
                                    texfname = objtex2
                                else:
                                    inform(
                                        "Couldn't find texture in alt path %s"
                                        % objtex2)

                        if texfname:
                            try:
                                img2 = Image.Load(texfname)
                                # Commented because it's unnecessary:
                                #img.xrep = int(obj.texrep[0])
                                #img.yrep = int(obj.texrep[1])
                                if img2:
                                    bl_images[obj.tex2] = img2
                            except:
                                inform("THROW:  Couldn't load texture: %s" %
                                       baseimgname)
                        else:
                            missing_textures.append(obj.tex2)
                            inform("Couldn't find texture: %s" % baseimgname)

                if obj.tex not in bmat.keys():
                    if img:
                        #Create a new material with a texture attached to it
                        m1 = Material.New(obj.tex)
                        m1.rgbCol = m.rgbCol
                        m1.amb = m.amb
                        m1.emit = m.emit
                        m1.specCol = m.specCol
                        m1.spec = m.spec
                        m1.alpha = m.alpha
                        texname = 'Tex%s' % obj.tex
                        texname2 = 'Tex2%s' % obj.tex

                        if img:
                            iname = img.getName()
                            if iname not in bl_textures.keys():
                                basetex = Texture.New(iname)
                                basetex.setType('Image')
                                map1 = Texture.MapTo.COL | Texture.MapTo.ALPHA
                                basetex.image = img
                                bl_textures[iname] = basetex

                            basetex = bl_textures[iname]
                            m1.setTexture(0, basetex, Texture.TexCo.UV, map1)

                        if img2:
                            iname2 = img2.getName()
                            if iname2 not in bl_textures.keys():
                                basetex2 = Texture.New(iname2)
                                basetex2.setType('Image')
                                map2 = Texture.MapTo.COL
                                basetex2.image = img2
                                bl_textures[iname2] = basetex2
                            else:
                                map2 = Texture.MapTo.COL

                            basetex2 = bl_textures[iname2]
                            m1.setTexture(1, basetex2, Texture.TexCo.UV, map2)

                        if m1.alpha < 1.0:
                            m1.mode |= MAT_MODE_ZTRANSP
                            has_transp_mats = True

                        mtextures = m1.getTextures()
                        tunit = 0
                        for mtex in mtextures:
                            if not (mtex == None):
                                if tunit == 1:
                                    mtex.uvlayer = "ShadowUV"
                                    mtex.colfac = 0.3
                                    tunit = tunit + 1
                                if tunit == 0:
                                    mtex.uvlayer = "ImageUV"

                                    tunit = tunit + 1

                        bmat[obj.tex] = m1

                if obj.tex != '':
                    if obj.tex in bl_images.keys():
                        img = bl_images[obj.tex]

                #TODO attach correct materials to objects
                if obj.tex in bmat.keys():
                    mat1 = bmat[obj.tex]
                    if len(mesh.materials) == 0:
                        mesh.materials += [mat1]
                else:
                    inform('Material %s not found\n' % obj.tex)

                for i in range(facesnum):
                    f = obj.flist_cfg[i]
                    fmat = f[0]
                    is_smooth = f[1]
                    twoside = f[2]
                    bface = mesh.faces[i]
                    bface.smooth = is_smooth
                    if twoside: bface.mode |= FACE_TWOSIDE
                    if img:
                        bface.mode |= FACE_TEX
                        bface.image = img
                    #TODO handle material properly
                    #bface.mat = objmat_indices.index(fmat)
                    bface.mat = 0
                    fuv = obj.flist_uv[i]
                    if len(obj.flist_uv2) > 0:
                        fuv2 = obj.flist_uv2[i]

                    if obj.texoff:
                        uoff = obj.texoff[0]
                        voff = obj.texoff[1]
                        urep = obj.texrep[0]
                        vrep = obj.texrep[1]
                        for uv in fuv:
                            uv[0] *= urep
                            uv[1] *= vrep
                            uv[0] += uoff
                            uv[1] += voff

                        if len(fuv2) > 0:
                            for uv2 in fuv2:
                                uv2[0] *= urep
                                uv2[1] *= vrep
                                uv2[0] += uoff
                                uv2[1] += voff

                    mesh.activeUVLayer = "ImageUV"
                    mesh.faces[i].uv = fuv

                    if len(fuv2) > 0:
                        mesh.activeUVLayer = "ShadowUV"
                        mesh.faces[i].uv = fuv2
#						for uv2 in fuv2:
#							inform('UV2 coords %.5f %.5f\n' % (uv2[0],uv2[1]))

                    mesh.activeUVLayer = "ImageUV"

                # finally, delete the 1st vertex we added to prevent vindices == 0
                mesh.verts.delete(0)

                mesh.calcNormals()

                mesh.mode = MESH_AUTOSMOOTH

            obj_idx += 1

        self.build_hierarchy()
        scene.update()
示例#21
0
def geometry_to_blender(geom, bld_mesh=None, discretizer=None):
    """Create a blender mesh
	
	Paint the faces too if needed
	
	:Parameters:
	 - `geom` (pgl.Geometry) - the geometry to transform
	 - `bld_mesh` (Mesh) - a mesh in which to append the shape.
	                       If None, a blank new one will be created
	 - `discretizer` (Discretizer) - algorithm to triangulate the geometry
	
	:Returns Type: Mesh
	"""
    #create bld_mesh
    if bld_mesh is None:
        if geom.isNamed():
            name = geom.name
        else:
            name = "pglgeom%d" % geom.getId()

        bld_mesh = Mesh.New(name)

    #geometry (mesh)
    if discretizer is None:
        d = Discretizer()
    else:
        d = discretizer

    geom.apply(d)
    geom = d.result

    #fill mesh
    pts = array(geom.pointList)
    nbv = len(bld_mesh.verts)
    faces = nbv + array(geom.indexList)

    bld_mesh.verts.extend(pts)
    nbf = len(bld_mesh.faces)
    bld_mesh.faces.extend(faces.tolist())

    #set vertex colors if needed
    mat = None
    if not geom.isColorListToDefault():
        bld_mesh.vertexColors = True

        #create material to render mesh colors
        try:
            mat = Material.Get("default_vtx_mat")
        except NameError:
            mat = Material.New("default_vtx_mat")
            mat.mode += Material.Modes['VCOL_PAINT']

        bld_mesh.materials = [mat]

        #modify color list to duplicate colors per face per vertex
        if geom.colorPerVertex and geom.isColorIndexListToDefault():
            #each vertex has a color
            for i, inds in enumerate(faces):
                face = bld_mesh.faces[nbf + i]
                for j, v in enumerate(face):
                    col = face.col[j]
                    pglcol = geom.colorList[geom.indexList[i][j]]
                    col.r = pglcol.red
                    col.g = pglcol.green
                    col.b = pglcol.blue
                    col.a = pglcol.alpha
        elif geom.colorPerVertex and not geom.isColorIndexListToDefault():
            #each local vertex of each face has a color
            for i, inds in enumerate(geom.colorIndexList):
                face = bld_mesh.faces[nbf + i]
                for j, v in enumerate(face):
                    col = face.col[j]
                    pglcol = geom.colorList[inds[j]]
                    col.r = pglcol.red
                    col.g = pglcol.green
                    col.b = pglcol.blue
                    col.a = pglcol.alpha
        else:
            #each face has a color
            for i, col in enumerate(geom.colorList):
                face = bld_mesh.faces[nbf + i]
                R, G, B, A = col.red, col.green, col.blue, col.alpha
                for j, v in enumerate(face):
                    col = face.col[j]
                    col.r = R
                    col.g = G
                    col.b = B
                    col.a = A


#		#assign
#		for fid in xrange(nb,len(bld_mesh.faces) ) :
#			face = bld_mesh.faces[fid]
#			for i,v in enumerate(face) :
#				col = face.col[i]
#				col.r = ambient.red
#				col.g = ambient.green
#				col.b = ambient.blue

#	for vtx in bld_mesh.verts :
#		vtx.sel = 0

#return
    return bld_mesh, mat
示例#22
0
def texture_read(filename):
    global gMat
    global gTexObj
    global gTextureBpp
    global gTextureWidth
    global gTextureHeight
    global gTextureImage

    try:
        file = open(filename, "rb")

        tim_id = struct.unpack("<L", file.read(4))[0]
        if (tim_id != 0x10):
            print "%s not a TIM file" % filename
            file.close()
            return 0

        tim_type = struct.unpack("<L", file.read(4))[0]
        tim_offset = struct.unpack("<L", file.read(4))[0]
        file.seek(4, 1)
        num_colors = struct.unpack("<H", file.read(2))[0]
        num_palettes = struct.unpack("<H", file.read(2))[0]

        gTextureBpp = 16
        if tim_type == 0x08:
            gTextureBpp = 4
        if tim_type == 0x09:
            gTextureBpp = 8

        txPalettes = []
        if gTextureBpp < 16:
            for i in range(num_palettes):
                palette = []
                for j in range(num_colors):
                    value = struct.unpack("<H", file.read(2))[0]
                    r = (value << 3) & 0xf8
                    g = (value >> 2) & 0xf8
                    b = (value >> 7) & 0xf8
                    r |= r >> 5
                    g |= g >> 5
                    b |= b >> 5
                    r = float(r) / 255.0
                    g = float(g) / 255.0
                    b = float(b) / 255.0
                    palette.append([r, g, b])
                txPalettes.append(palette)

        file.seek(tim_offset + 16)
        gTextureWidth = struct.unpack("<H", file.read(2))[0]
        if gTextureBpp == 4:
            gTextureWidth <<= 2
        if gTextureBpp == 8:
            gTextureWidth <<= 1
        gTextureHeight = struct.unpack("<H", file.read(2))[0]
        #print "Texture: %dx" % gTextureWidth + "%d" % gTextureHeight

        gTextureImage = Image.New("image", gTextureWidth, gTextureHeight, 24)
        if gTextureBpp == 4:
            for y in range(gTextureHeight):
                if (y & 15) == 0:
                    Blender.Window.DrawProgressBar(
                        float(y) / gTextureHeight, "Loading texture")
                i = 0
                j = 0
                mi = gTextureWidth / num_palettes
                for x in range(gTextureWidth / 2):
                    c = struct.unpack("B", file.read(1))[0]
                    c1 = (c >> 4) & 0xf
                    r = txPalettes[j][c1][0]
                    g = txPalettes[j][c1][1]
                    b = txPalettes[j][c1][2]
                    gTextureImage.setPixelF(x * 2, y, (r, g, b, 1.0))
                    c2 = c & 0xf
                    r = txPalettes[j][c2][0]
                    g = txPalettes[j][c2][1]
                    b = txPalettes[j][c2][2]
                    gTextureImage.setPixelF(x * 2 + 1, y, (r, g, b, 1.0))
                    i += 2
                    if (i >= mi):
                        i = 0
                        j += 1
        elif gTextureBpp == 8:
            for y in range(gTextureHeight):
                if (y & 15) == 0:
                    Blender.Window.DrawProgressBar(
                        float(y) / gTextureHeight, "Loading texture")
                i = 0
                j = 0
                mi = gTextureWidth / num_palettes
                for x in range(gTextureWidth):
                    c = struct.unpack("B", file.read(1))[0]
                    r = txPalettes[j][c][0]
                    g = txPalettes[j][c][1]
                    b = txPalettes[j][c][2]
                    gTextureImage.setPixelF(x, y, (r, g, b, 1.0))
                    i += 1
                    if (i >= mi):
                        i = 0
                        j += 1

        elif gTextureBpp == 16:
            for y in range(gTextureHeight):
                if (y & 15) == 0:
                    Blender.Window.DrawProgressBar(
                        float(y) / gTextureHeight, "Loading texture")
                for x in range(gTextureWidth):
                    c = struct.unpack("<H", file.read(2))[0]
                    r = (c << 3) & 0xf8
                    g = (c >> 2) & 0xf8
                    b = (c >> 7) & 0xf8
                    r |= r >> 5
                    g |= g >> 5
                    b |= b >> 5
                    r = float(r) / 255.0
                    g = float(g) / 255.0
                    b = float(b) / 255.0
                    gTextureImage.setPixelF(x, y, (r, g, b, 1.0))

        # Create texture
        gTexObj = Texture.New("emd_tex")
        gTexObj.setType("Image")
        gTexObj.setImage(gTextureImage)

        # Create material
        gMat = Material.New("emd_mat")
        gMat.mode |= Material.Modes.TEXFACE
        gMat.mode |= Material.Modes.SHADELESS
        gMat.setTexture(0, gTexObj, Texture.TexCo.UV)

    except IOError, (errno, strerror):
        file.close()
        return 0