def ObjExport(FILE, Name, type): #================================ global returncode global vertexcount global uvcount global Transform global multiflag global exporttype vertexcount = 0 uvcount = 0 returncode = 0 print("Writing %s..." % Name) FILE.write( "# Wavefront OBJ (1.0) exported by lynx's OBJ import/export script\n\n" ) Objects = Object.GetSelected() if Objects == []: print("You have not selected an object!") returncode = 4 else: for object in Objects: MtlList = [] if len(Objects) > 1 or exporttype > 1: Transform = CreateMatrix(object, Transform) multiflag = 1 mesh = NMesh.GetRawFromObject(object.name) ObjName = mesh.name has_uvco = mesh.hasVertexUV() FILE.write("# Meshname:\t%s\n" % ObjName) faces = mesh.faces materials = mesh.materials Vertices = mesh.verts GlobalMaterials = Material.Get() if len(materials) > 1 and len(GlobalMaterials) > 0 and type < 4: CreateMtlFile(Name, materials, MtlList) # Total Vertices and faces; comment if not useful FILE.write("# Total number of Faces:\t%s\n" % len(faces)) FILE.write("# Total number of Vertices:\t%s\n" % len(Vertices)) FILE.write("\n") # print first image map for uvcoords to use # to be updated when we get access to other textures if mesh.hasFaceUV(): FILE.write("# UV Texture:\t%s\n\n" % mesh.hasFaceUV()) if len(materials) > 1 and len(GlobalMaterials) > 0 and type < 3: UseLayers(faces, Vertices, MtlList, has_uvco, FILE, ObjName, Name) elif len(materials) > 1 and len(GlobalMaterials) > 0 and type == 3: UseMtl(faces, Vertices, MtlList, has_uvco, FILE, ObjName, Name) else: Standard(faces, Vertices, has_uvco, FILE, ObjName)
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
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.")
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
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
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
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
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)
def MATERIALS(self, meshlist, me): for meobj in meshlist: me.getFromObject(meobj) mats = me.materials mbuf = [] mlist = self.mlist for m in mats: if not m: continue name = m.name if name not in mlist: mlist.append(name) M = Material.Get(name) material = 'MATERIAL "%s"' % name mirCol = "%s %s %s" % (Round_s( M.mirCol[0]), Round_s(M.mirCol[1]), Round_s( M.mirCol[2])) rgb = "rgb %s %s %s" % (Round_s(M.R), Round_s( M.G), Round_s(M.B)) ambval = Round_s(M.amb) amb = "amb %s %s %s" % (ambval, ambval, ambval) spec = "spec %s %s %s" % (Round_s( M.specCol[0]), Round_s( M.specCol[1]), Round_s(M.specCol[2])) if AC3D_4: emit = Round_s(M.emit) emis = "emis %s %s %s" % (emit, emit, emit) shival = int(M.spec * 64) else: emis = "emis 0 0 0" shival = 72 shi = "shi %s" % shival trans = "trans %s" % (Round_s(1 - M.alpha)) if MIRCOL_AS_AMB: amb = "amb %s" % mirCol if MIRCOL_AS_EMIS: emis = "emis %s" % mirCol mbuf.append("%s %s %s %s %s %s %s\n" \ % (material, rgb, amb, emis, spec, shi, trans)) self.mlist = mlist self.mbuf.append("".join(mbuf))
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
def _set_color(self, args): self.material = Material.Get('floor') self.material.setRGBCol(args['floor_color'])
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)
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]
def imgImport(imgPath): global CUROFFS, PARAMS ###################################### # Load the image ###################################### try: img = Image.Load(imgPath) imgDimensions = img.getSize() # do this to ensure the data is available except: Blender.Draw.PupMenu('Error%t|Unsupported image format for "'+ imgPath.split('\\')[-1].split('/')[-1] +'"') return if PARAMS['PackImage']: img.pack() name = Blender.sys.makename(imgPath, strip = 1) ###################################### # Construct the mesh ###################################### me = Mesh.New(name) # Calculate Dimensions from Image Size dim = [float(i)/PARAMS['PPU'] for i in imgDimensions] v = [[dim[0], dim[1], 0], [-dim[0], dim[1], 0], [-dim[0], -dim[1], 0], [dim[0], -dim[1], 0]] me.verts.extend(v) me.faces.extend([0, 1, 2, 3]) me.faces[0].image = img me.faces[0].uv = [Vector(1.0, 1.0), Vector(0.0, 1.0), Vector(0.0, 0.0), Vector(1.0, 0.0)] if PARAMS['MakeTransp']: me.faces[0].transp = Mesh.FaceTranspModes.ALPHA ###################################### # Modify the Material ###################################### mat = None if not PARAMS['NewMat']: mat = PARAMS['Materials'][PARAMS['MaterialId']].__copy__() mat.setName(name) else: mat = Material.New(name) properties = PARAMS['MatProps'] mat.setRGBCol(properties['Col']) mat.setRef(properties['Ref']) mat.setSpec(properties['Spec']) mat.setHardness(properties['Hard']) mat.setAlpha(properties['Alpha']) if properties['Shadeless']: mat.mode |= Material.Modes.SHADELESS if properties['ZTransp']: mat.mode |= Material.Modes.ZTRANSP properties = PARAMS['TexProps'] tex = Texture.New(name) tex.setType('Image') tex.setImage(img) if properties['UseAlpha']: tex.useAlpha = Texture.ImageFlags.USEALPHA if properties['CalcAlpha']: tex.calcAlpha = Texture.ImageFlags.CALCALPHA if properties['ExtendMode']: tex.setExtend('Extend') if PARAMS['ImageProp'] == Image.Sources.SEQUENCE: properties = PARAMS['SeqProps'] img.source = PARAMS['ImageProp'] # Needs to be done here, otherwise an error with earlier getSize() tex.animStart = properties['StartFr'] tex.animOffset = properties['Offs'] tex.animFrames = properties['Frames'] tex.autoRefresh = properties['AutoRefresh'] tex.cyclic = properties['Cyclic'] texMapSetters = Texture.TexCo.UV # PARAMS['TexMapTo']['Col'] (and alpha) will either be 0 or 1 because its from a toggle, otherwise this line doesn't work texChanSetters = Texture.MapTo.COL * PARAMS['TexMapTo']['Col'] | Texture.MapTo.ALPHA * PARAMS['TexMapTo']['Alpha'] mat.setTexture(PARAMS['TexChannel'], tex, texMapSetters, texChanSetters) me.materials += [mat] ###################################### # Object Construction ###################################### ob = scn.objects.new(me, name) p = Vector(ob.getLocation()) # Should be the origin, but just to be safe, get it ob.setLocation((CUROFFS * PARAMS['ObOffset']) + p) return
def 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
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()
def ObjImport(file, Name, filename): #========================= vcount = 0 vncount = 0 vtcount = 0 fcount = 0 gcount = 0 setcount = 0 groupflag = 0 objectflag = 0 mtlflag = 0 baseindex = 0 basevtcount = 0 basevncount = 0 matindex = 0 pointList = [] uvList = [] normalList = [] faceList = [] materialList = [] imagelist = [] uv = [] lines = file.readlines() linenumber = 1 for line in lines: words = line.split() if words and words[0] == "#": pass # ignore comments elif words and words[0] == "v": vcount = vcount + 1 x = float(words[1]) y = float(words[2]) z = float(words[3]) pointList.append([x, y, z]) elif words and words[0] == "vt": vtcount = vtcount + 1 u = float(words[1]) v = float(words[2]) uvList.append([u, v]) elif words and words[0] == "vn": vncount = vncount + 1 i = float(words[1]) j = float(words[2]) k = float(words[3]) normalList.append([i, j, k]) elif words and words[0] == "f": fcount = fcount + 1 vi = [] # vertex indices ti = [] # texture indices ni = [] # normal indices words = words[1:] lcount = len(words) for index in (xrange(lcount)): if words[index].find("/") == -1: vindex = int(words[index]) if vindex < 0: vindex = baseindex + vindex + 1 vi.append(vindex) else: vtn = words[index].split("/") vindex = int(vtn[0]) if vindex < 0: vindex = baseindex + vindex + 1 vi.append(vindex) if len(vtn) > 1 and vtn[1]: tindex = int(vtn[1]) if tindex < 0: tindex = basevtcount + tindex + 1 ti.append(tindex) if len(vtn) > 2 and vtn[2]: nindex = int(vtn[2]) if nindex < 0: nindex = basevncount + nindex + 1 ni.append(nindex) faceList.append([vi, ti, ni, matindex]) elif words and words[0] == "o": ObjectName = words[1] objectflag = 1 #print "Name is %s" % ObjectName elif words and words[0] == "g": groupflag = 1 index = len(words) if objectflag == 0: objectflag = 1 if index > 1: ObjectName = words[1].join("_") GroupName = words[1].join("_") else: ObjectName = "Default" GroupName = "Default" #print "Object name is %s" % ObjectName #print "Group name is %s" % GroupName else: if index > 1: GroupName = join(words[1], "_") else: GroupName = "Default" #print "Group name is %s" % GroupName if mtlflag == 0: matindex = AddMeshMaterial(GroupName, materialList, matindex) gcount = gcount + 1 if fcount > 0: baseindex = vcount basevncount = vncount basevtcount = vtcount elif words and words[0] == "mtllib": # try to export materials directory, dummy = os.split(filename) filename = os.join(directory, words[1]) print "try to import : ", filename try: file = open(filename, "r") except: print "no material file %s" % filename else: mtlflag = 0 file = open(filename, "r") line = file.readline() mtlflag = 1 while line: words = line.split() if words and words[0] == "newmtl": name = words[1] line = file.readline() # Ns ? words = line.split() while words[0] not in ["Ka", "Kd", "Ks", "map_Kd"]: line = file.readline() words = line.split() if words[0] == "Ka": Ka = [ float(words[1]), float(words[2]), float(words[3]) ] line = file.readline() # Kd words = line.split() if words[0] == "Kd": Kd = [ float(words[1]), float(words[2]), float(words[3]) ] line = file.readline() # Ks words = line.split() if words[0] == "Ks": Ks = [ float(words[1]), float(words[2]), float(words[3]) ] if words[0] == "map_Kd": Kmap = words[1] img = os.join(directory, Kmap) im = Blender.Image.Load(img) words = line.split() matindex = AddGlobalMaterial(name, matindex) matlist = Material.Get() if len(matlist) > 0: if name != 'defaultMat': material = matlist[matindex] material.R = Kd[0] material.G = Kd[1] material.B = Kd[2] try: material.specCol[0] = Ks[0] material.specCol[1] = Ks[1] material.specCol[2] = Ks[2] except: pass try: alpha = 1 - ((Ka[0] + Ka[1] + Ka[2]) / 3) except: pass try: material.alpha = alpha except: pass try: img = os.join(directory, Kmap) im = Blender.Image.Load(img) imagelist.append(im) t = Blender.Texture.New(Kmap) t.setType('Image') t.setImage(im) material.setTexture(0, t) material.getTextures()[0].texco = 16 except: pass else: material = matlist[matindex] material.R = 0.8 material.G = 0.8 material.B = 0.8 material.specCol[0] = 0.5 material.specCol[1] = 0.5 material.specCol[2] = 0.5 img = os.join(directory, Kmap) im = Blender.Image.Load(img) imagelist.append(im) t = Blender.Texture.New(Kmap) t.setType('Image') t.setImage(im) material.setTexture(0, t) material.getTextures()[0].texco = 16 else: mtlflag = 0 line = file.readline() file.close() elif words and words[0] == "usemtl": if mtlflag == 1: name = words[1] matindex = AddMeshMaterial(name, materialList, matindex) elif words: print "%s: %s" % (linenumber, words) linenumber = linenumber + 1 file.close() # import in Blender print "import into Blender ..." mesh = NMesh.GetRaw() i = 0 while i < vcount: x, y, z = pointList[i] vert = NMesh.Vert(x, y, z) mesh.verts.append(vert) i = i + 1 if vtcount > 0: #mesh.hasFaceUV() = 1 print("Object has uv coordinates") if len(materialList) > 0: for m in materialList: try: M = Material.Get(m) mesh.materials.append(M) except: pass total = len(faceList) i = 0 for f in faceList: if i % 1000 == 0: print("Progress = " + str(i) + "/" + str(total)) i = i + 1 vi, ti, ni, matindex = f face = NMesh.Face() if len(materialList) > 0: face.mat = matindex limit = len(vi) setcount = setcount + len(vi) c = 0 while c < limit: m = vi[c] - 1 if vtcount > 0 and len(ti) > c: n = ti[c] - 1 if vncount > 0 and len(ni) > c: p = ni[c] - 1 if vtcount > 0: try: u, v = uvList[n] except: pass """ # multiply uv coordinates by 2 and add 1. Apparently blender uses uv range of 1 to 3 (not 0 to 1). mesh.verts[m].uvco[0] = (u*2)+1 mesh.verts[m].uvco[1] = (v*2)+1 """ if vncount > 0: if p > len(normalList): print("normal len = " + str(len(normalList)) + " vector len = " + str(len(pointList))) print("p = " + str(p)) x, y, z = normalList[p] mesh.verts[m].no[0] = x mesh.verts[m].no[1] = y mesh.verts[m].no[2] = z c = c + 1 if len(vi) < 5: for index in vi: face.v.append(mesh.verts[index - 1]) if vtcount > 0: for index in ti: u, v = uvList[index - 1] face.uv.append((u, v)) if len(imagelist) > 0: face.image = imagelist[0] #print if vcount > 0: face.smooth = 1 mesh.faces.append(face) print "all other (general) polygons ..." for f in faceList: vi, ti, ni, matindex = f if len(vi) > 4: # export the polygon as edges print("Odd face, vertices = " + str(len(vi))) for i in range(len(vi) - 2): face = NMesh.Face() if len(materialList) > 0: face.mat = matindex face.v.append(mesh.verts[vi[0] - 1]) face.v.append(mesh.verts[vi[i + 1] - 1]) face.v.append(mesh.verts[vi[i + 2] - 1]) if vtcount > 0: if len(ti) > i + 2: u, v = uvList[ti[0] - 1] face.uv.append((u, v)) u, v = uvList[ti[i + 1] - 1] face.uv.append((u, v)) u, v = uvList[ti[i + 2] - 1] face.uv.append((u, v)) mesh.faces.append(face) NMesh.PutRaw(mesh, Name, 1) print("Total number of vertices is " + str(vcount)) print("Total number of faces is " + str(len(faceList))) print("Total number of sets is " + str(setcount)) print("Finished importing " + str(Name) + ".obj")
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
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)
def write(filename): editmode = Window.EditMode() if editmode: Window.EditMode(0) print "Start export" out = file(filename, "w") for material in Material.get(): out.write('Material %s\n' % (material.name)) out.write( 'Diffuse %f %f %f %f\n' % (material.R, material.G, material.B, material.getTranslucency())) out.write('Ambient %f\n' % (material.amb)) out.write('Specular %f %f %f %f\n' % (material.getSpecCol()[0], material.getSpecCol()[1], material.getSpecCol()[2], material.getSpecTransp())) for object in Blender.Object.Get(): if (object.getType() == "Mesh"): out.write('%s %s\n' % (object.getType(), object.getName())) index_list = [] mesh = NMesh.GetRawFromObject(object.name) for face in mesh.faces: for n in range(len(face.v)): index_list.append(face.v[n].index) out.write('%s\n' % (len(mesh.faces))) # Write the number of faces out.write('%s\n' % (len(object.data.verts))) # Write the number of vertices out.write('%s\n' % (len(index_list))) # Write the number of indices for material in mesh.materials: out.write('Material %s\n' % material.name) out.write('Loc %f %f %f\n' % (object.matrixWorld[3][0], object.matrixWorld[3][1], object.matrixWorld[3][2])) for vert in object.data.verts: out.write('v %f %f %f n %f %f %f\n' % (vert.co.x, vert.co.y, vert.co.z, vert.no.x, vert.no.y, vert.no.z)) for index in index_list: out.write('i %s\n' % (index)) elif (object.getType() == "Camera"): data = object.data cam = Camera.get(data.name) out.write('Camera %s\n' % (data.name)) out.write('Right %f %f %f\n' % (object.getMatrix()[0][0], object.getMatrix()[0][1], object.getMatrix()[0][2])) out.write('Up %f %f %f\n' % (object.getMatrix()[1][0], object.getMatrix()[1][1], object.getMatrix()[1][2])) out.write('Forward %f %f %f\n' % (object.getMatrix()[2][0], object.getMatrix()[2][1], object.getMatrix()[2][2])) out.write('Loc %f %f %f\n' % (object.getLocation()[0], object.getLocation()[1], object.getLocation()[2])) out.write('Far %f\n' % (cam.getClipEnd())) out.write('Near %f\n' % (cam.getClipStart())) out.write('FOV %f\n' % (2.0 * math.atan(16.0 / cam.getLens()))) elif object.getType() == "Lamp": data = object.data light = Lamp.get(data.name) if light.type == Lamp.Types.Lamp: out.write('Light Type Unsupported') elif light.type == Lamp.Types.Spot: out.write('Light Type Unsupported') elif light.type == Lamp.Types.Sun: out.write('Light %s\n' % (data.name)) out.write('Type Omni\n') out.write('Color %f %f %f\n' % (light.R, light.G, light.B)) out.write('Right %f %f %f\n' % (object.getMatrix()[0][0], object.getMatrix()[0][1], object.getMatrix()[0][2])) out.write('Up %f %f %f\n' % (object.getMatrix()[1][0], object.getMatrix()[1][1], object.getMatrix()[1][2])) out.write('Forward %f %f %f\n' % (object.getMatrix()[2][0], object.getMatrix()[2][1], object.getMatrix()[2][2])) out.write('Loc %f %f %f\n' % (object.matrixWorld[3][0], object.matrixWorld[3][1], object.matrixWorld[3][2])) else: out.write('Light Type Unsupported') out.close() print "End export"
def CreateMtlFile(name, MeshMaterials, MtlList): #================================================ global gFilename # try to export materials directory, mtlname = os.split(gFilename.val) mtlname = name + ".mtl" filename = os.join(directory, mtlname) file = open(filename, "w") file.write("# Materials for %s.\n" % (name + ".obj")) file.write("# Created by Blender.\n") file.write( "# These files must be in the same directory for the materials to be read correctly.\n\n" ) MatList = Material.Get() print str(MeshMaterials) MtlNList = [] for m in MatList: MtlNList.append(m.name) counter = 1 found = 0 for material in MeshMaterials: for mtl in MtlList: if material == mtl: found = 1 MtlList.append(material) if found == 0: file.write("newmtl %s \n" % material.name) index = 0 print material, MatList while index < len(MatList): if material.name == MatList[index].name: mtl = MatList[index] index = len(MatList) found = 1 index = index + 1 if found == 1: alpha = mtl.getAlpha() file.write(" Ka %s %s %s \n" % (round( 1 - alpha, 5), round(1 - alpha, 5), round(1 - alpha, 5))) file.write(" Kd %s %s %s \n" % (round(mtl.R, 5), round(mtl.G, 5), round(mtl.B, 5))) file.write(" Ks %s %s %s \n" % (round(mtl.specCol[0], 5), round( mtl.specCol[1], 5), round(mtl.specCol[2], 5))) file.write(" illum 1\n") else: file.write(" Ka %s %s %s \n" % (0, 0, 0)) file.write(" Kd %s %s %s \n" % (1, 1, 1)) file.write(" Ks %s %s %s \n" % (1, 1, 1)) file.write(" illum 1\n") found = 0 file.flush() file.close()
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
path_config = Registry.GetKey(reg_name, True) if (not path_config): Draw.PupMenu("Config Error|Go to Misc>Nebula Config") else: file2.setassign("home", str(path_config["home"])) file2.setassign("proj", str(path_config["proj"])) file2.setassign("bin", str(path_config["bin"])) file2.setassign("export", str(path_config["export"])) file2.setassign("anims", str(path_config["anims"])) file2.setassign("gfxlib", str(path_config["gfxlib"])) file2.setassign("meshes", str(path_config["meshes"])) file2.setassign("textures", str(path_config["textures"])) if (n2exporter.DoStartupChecks()): n2exporter.Init() mats = Material.Get() n2mats = n2exporter.Getn2Materials() n2_shaders = n2exporter.Getn2Shaders() bl_mats = [] #mat_dict = {} n2exporter.BuildLookupTable() bl_mats = n2exporter.lookup_table.keys() n2mat = None # Get current objects material if any an set as active material objs = Object.GetSelected() if (len(objs) and objs[0].getType() == "Mesh" and len(objs[0].getData(mesh=1).materials) and objs[0].getData(mesh=1).materials[0] != None):
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"
# 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]
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
# create master for organelle bg = bl.newEmpty('organelle_%d'%orga.number) g = Geom('organelle_%d'%orga.number) bl.addObjectToScene(sc,bg) gs = Geom('surface') bgs = bl.newEmpty('surface') bl.addObjectToScene(sc,bgs, parent=bg) gc = Geom('cytoplasm') bgc = bl.newEmpty('cytoplasm') bl.addObjectToScene(sc,bgc, parent=bg) orgaToMasterGeom[orga] = g orgaToMasterGeom[orga.number] = gs orgaToMasterGeom[-orga.number] = gc tetobj,tetmesh = bl.createsNmesh('surfaceMesh',orga.vertices,orga.vnormals,orga.faces) tetobj.setMaterials([Material.Get("wire")]) tetobj.colbits = 1<<0 #objMAt tetobj.setDrawMode(32)#drawwire tetobj.setDrawType(2)#wire #tet = IndexedPolygons('surfaceMesh', vertices=orga.vertices, # faces=orga.faces, normals=orga.vnormals, # inheritFrontPolyMode=False, # frontPolyMode='line', # inheritCulling=0, culling='none', # inheritShading=0, shading='flat') #vi.AddObject(tet, parent=g) bl.addObjectToScene(sc,tetobj, parent=bg) #cp = vi.clipP[0] #vi.GUI.clipvar[0][0].set(1) #tet.AddClipPlane( cp, 1, False)
def write(filename): editmode = Window.EditMode() if editmode: Window.EditMode(0) print "Start export" out = file(filename, "w") for material in Material.get(): out.write('Material %s\n' % (material.name)) out.write('Diffuse %f %f %f %f\n' % (material.R, material.G, material.B, material.getTranslucency())) out.write('Ambient %f\n' % (material.amb)) out.write('Specular %f %f %f %f\n' % (material.getSpecCol()[0], material.getSpecCol()[1], material.getSpecCol()[2], material.getSpecTransp())) for object in Blender.Object.Get(): if(object.getType() == "Mesh"): out.write('%s %s\n' % (object.getType(), object.getName())) index_list = [] mesh = NMesh.GetRawFromObject(object.name) for face in mesh.faces: for n in range(len(face.v)): index_list.append(face.v[n].index) out.write('%s\n' % (len(mesh.faces)) ) # Write the number of faces out.write('%s\n' % (len(object.data.verts)) ) # Write the number of vertices out.write('%s\n' % (len(index_list)) ) # Write the number of indices for material in mesh.materials: out.write('Material %s\n' % material.name) out.write('Loc %f %f %f\n' % (object.matrixWorld[3][0], object.matrixWorld[3][1], object.matrixWorld[3][2])) for vert in object.data.verts: out.write( 'v %f %f %f n %f %f %f\n' % (vert.co.x, vert.co.y, vert.co.z, vert.no.x, vert.no.y, vert.no.z)) for index in index_list: out.write( 'i %s\n' % (index) ) elif(object.getType() == "Camera"): data = object.data cam = Camera.get(data.name) out.write('Camera %s\n' % (data.name)) out.write('Right %f %f %f\n' % (object.getMatrix()[0][0], object.getMatrix()[0][1], object.getMatrix()[0][2])) out.write('Up %f %f %f\n' % (object.getMatrix()[1][0], object.getMatrix()[1][1], object.getMatrix()[1][2])) out.write('Forward %f %f %f\n' % (object.getMatrix()[2][0], object.getMatrix()[2][1], object.getMatrix()[2][2])) out.write('Loc %f %f %f\n' % (object.getLocation()[0], object.getLocation()[1], object.getLocation()[2])) out.write('Far %f\n' % (cam.getClipEnd())) out.write('Near %f\n' % (cam.getClipStart())) out.write('FOV %f\n' % (2.0 * math.atan(16.0/cam.getLens()))) elif object.getType() == "Lamp": data = object.data light = Lamp.get(data.name) if light.type == Lamp.Types.Lamp: out.write('Light Type Unsupported') elif light.type == Lamp.Types.Spot: out.write('Light Type Unsupported') elif light.type == Lamp.Types.Sun: out.write('Light %s\n' % (data.name)) out.write('Type Omni\n') out.write('Color %f %f %f\n' % (light.R, light.G, light.B)) out.write('Right %f %f %f\n' % (object.getMatrix()[0][0], object.getMatrix()[0][1], object.getMatrix()[0][2])) out.write('Up %f %f %f\n' % (object.getMatrix()[1][0], object.getMatrix()[1][1], object.getMatrix()[1][2])) out.write('Forward %f %f %f\n' % (object.getMatrix()[2][0], object.getMatrix()[2][1], object.getMatrix()[2][2])) out.write('Loc %f %f %f\n' % (object.matrixWorld[3][0], object.matrixWorld[3][1], object.matrixWorld[3][2])) else: out.write('Light Type Unsupported') out.close() print "End export"
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")
def set_material_color(material_name, color): material = Material.Get(material_name) material.setRGBCol(color)
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()