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 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 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 set_material_color(material_name, color): material = Material.Get(material_name) material.setRGBCol(color)
def _set_color(self, args): self.material = Material.Get('floor') self.material.setRGBCol(args['floor_color'])
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 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"
# 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 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 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 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")
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 mat_map(file, idnt, mat_name): mapTable = { 0: '*MAP_AMBIENT', 1: '*MAP_DIFFUSE', 2: '*MAP_SPECULAR', 3: '*MAP_SHINE', 4: '*MAP_SHINESTRENGTH', 5: '*MAP_SELFILLUM', 6: '*MAP_OPACITY', 7: '*MAP_FILTERCOLOR', 8: '*MAP_BUMP', 9: '*MAP_REFLECT', 10: '*MAP_REFRACT', 11: '*MAP_REFRACT' } tex_list = [[], [], [], [], [], [], [], [], [], [], [], []] mat = Material.Get(mat_name) MTexes = mat.getTextures() for current_MTex in MTexes: if current_MTex is not None: # MAP_SUBNO 0 = *MAP_AMBIENT if current_MTex.mapto & Texture.MapTo.AMB: map_getTex(current_MTex, 0, (current_MTex.dvar * current_MTex.varfac), tex_list) # MAP_SUBNO 1 = *MAP_DIFFUSE = COL = 1 elif current_MTex.mapto & Texture.MapTo.COL: map_getTex(current_MTex, 1, current_MTex.colfac, tex_list) # MAP_SUBNO 2 = *MAP_SPECULAR (Color)= CSP or SPEC? = 4 elif current_MTex.mapto & Texture.MapTo.CSP: map_getTex(current_MTex, 2, current_MTex.colfac, tex_list) # MAP_SUBNO 3 = *MAP_SHINE (Spec Level) = SPEC or CSP? = 32 elif current_MTex.mapto & Texture.MapTo.SPEC: map_getTex(current_MTex, 3, (current_MTex.dvar * current_MTex.varfac), tex_list) # MAP_SUBNO 4 = *MAP_SHINESTRENGTH (Gloss) = HARD = 256 elif current_MTex.mapto & Texture.MapTo.HARD: map_getTex(current_MTex, 4, (current_MTex.dvar * current_MTex.varfac), tex_list) # MAP_SUBNO 5 = *MAP_SELFILLUM # MAP_SUBNO 6 = *MAP_OPACITY = ALPHA = 128 elif current_MTex.mapto & Texture.MapTo.ALPHA: map_getTex(current_MTex, 6, (current_MTex.dvar * current_MTex.varfac), tex_list) # MAP_SUBNO 7 = *MAP_FILTERCOLOR # MAP_SUBNO 8 = *MAP_BUMP = NOR = 2 elif current_MTex.mapto & Texture.MapTo.NOR: map_getTex(current_MTex, 8, (current_MTex.norfac / 25), tex_list) # MAP_SUBNO 9 = *MAP_REFLECT elif current_MTex.mapto & Texture.MapTo.REF: map_getTex(current_MTex, 9, (current_MTex.norfac / 25), tex_list) # MAP_SUBNO 10 = *MAP_REFRACT (refraction) # MAP_SUBNO 11 = *MAP_REFRACT (displacement) elif current_MTex.mapto & Texture.MapTo.DISP: map_getTex(current_MTex, 11, (current_MTex.norfac / 25), tex_list) # Write maps for current_LI in tex_list: subNo = tex_list.index(current_LI) for current_MTex in current_LI: tex = current_MTex[0].tex if tex.type == Texture.Types.IMAGE: map_image(file, idnt, current_MTex, subNo, tex, mapTable[subNo])