def read(filename): '''Read points in x, y, z format from file''' #start = time.clock() file = open(filename, "rb") objname = Blender.sys.splitext(Blender.sys.basename(filename))[0] me = NMesh.GetRaw() # Collect data from RAW format for line in file.readlines(): try: try: f1, f2, f3, f4 = map(float, line.split()) except: # raw triangle so take first three only #f1, f2, f3, f4, f5, f6, f7, f8, f9 = map(float, line.split()) f1, f2, f3 = map(float, line.split()) v = NMesh.Vert(f1, f2, f3) me.verts.append(v) except: continue NMesh.PutRaw(me, objname) Blender.Object.GetSelected()[0].name = objname Blender.Redraw() Blender.Window.DrawProgressBar(1.0, '') # clear progressbar file.close() #end = time.clock() #seconds = " in %.2f %s" % (end-start, "seconds") message = "Successfully imported " + Blender.sys.basename(filename)# + seconds meshtools.print_boxed(message)
def createDoodad(indexArray,facec,minsi,maxsi,minhei,maxhei,selec,amtmin,amtmax,facpercent): global doodadMesh global seltopsonly global tosel doodadMesh = NMesh.GetRaw() theamt = round(randnum(amtmin,amtmax),0) theamt = int(theamt) tosel = selec for i in range(0,(theamt)): if randnum(0,1) <= facpercent: index = round(randnum(1,len(indexArray)),0) index = indexArray[(int(index) - 1)] Xsi = randnum(minsi,maxsi) Ysi = randnum(minsi,maxsi) hei = randnum(minhei,maxhei) #Determine orientation orient = int(round(randnum(0.0,3.0))) #face to use as range facer = Face() facer.v.extend([facec.v[orient],facec.v[fixvertindex(1+orient)],facec.v[fixvertindex(2+orient)],facec.v[fixvertindex(3+orient)]]) if index == 1: singleBox(facer,Xsi,Ysi,hei) if index == 2: doubleBox(facer,Xsi,Ysi,hei) if index == 3: tripleBox(facer,Xsi,Ysi,hei) if index == 4: LShape(facer,Xsi,Ysi,hei) if index == 5: TShape(facer,Xsi,Ysi,hei) if index == 6: if randnum(0.0,1.0) > .5: SShape(facer,Xsi,Ysi,hei) else: ZShape(facer,Xsi,Ysi,hei) return doodadMesh
def Torus(MajorRadius, MinorRadius, MajorDivisions, MinorDivisions, StartMinorAngle, Smooth): # deg 2 rad StartMinorAngle = (StartMinorAngle * 2 * pi) / 180 def MakeVertexRing(vertex_list, angle): m = Mathutils.RotationMatrix(angle, 3, "z") for i in xrange(MinorDivisions): phi = (pi * 2 * i / MinorDivisions) + StartMinorAngle x = MajorRadius + MinorRadius * cos(phi) y = 0.0 z = MinorRadius * sin(phi) v = Mathutils.Vector([x, y, z]) v = Mathutils.VecMultMat(v, m) vertex_list.append(NMesh.Vert(v.x, v.y, v.z)) ######### Creates a new mesh poly = NMesh.GetRaw() angle = 0 da = 360.0 / MajorDivisions for _ in xrange(MajorDivisions): MakeVertexRing(poly.verts, angle) angle += da ######## Make faces for i in xrange(MajorDivisions): ring1_num = MinorDivisions * i ring2_num = MinorDivisions * ((i + 1) % MajorDivisions) for j in xrange(MinorDivisions): f = NMesh.Face() f.smooth = Smooth f.v.append(poly.verts[ring1_num + j]) f.v.append(poly.verts[ring1_num + (j + 1) % MinorDivisions]) f.v.append(poly.verts[ring2_num + (j + 1) % MinorDivisions]) f.v.append(poly.verts[ring2_num + j]) poly.faces.append(f) polyObj = NMesh.PutRaw(poly) return polyObj
def Disc( InnerRadius, OuterRadius, Segments, Subdivisions ): poly = NMesh.GetRaw() #### Make vertices dr = (OuterRadius - InnerRadius)/Subdivisions r = InnerRadius da = pi*2/Segments for _ in xrange(Subdivisions+1): alpha = 0.0 for i in range(0,Segments): x = r * cos(alpha) y = r * sin(alpha) alpha += da poly.verts.append( NMesh.Vert(x,y,0.0) ) r += dr #### Make faces for i in xrange(Subdivisions): ring0 = Segments * i ring1 = Segments * (i+1) for j in xrange(Segments): f = NMesh.Face() j0 = j j1 = (j+1) % Segments f.v.append(poly.verts[ring0 + j0]) f.v.append(poly.verts[ring0 + j1]) f.v.append(poly.verts[ring1 + j1]) f.v.append(poly.verts[ring1 + j0]) poly.faces.append(f) ######### Creates a new Object with the new Mesh polyObj = NMesh.PutRaw(poly) return polyObj
def export_mesh(self, mesh, obj): file = self.file name = obj.name meshname = obj.getData(name_only=True) nmesh = NMesh.GetRaw(meshname) nmesh.transform(obj.matrixWorld) file.write("solid " + name + "\n") n_tri = 0 # number of tris in STL n_face = len(nmesh.faces) for i in range(0, n_face): face = nmesh.faces[i] nx = face.no[0] ny = face.no[1] nz = face.no[2] n_vert = len(face.v) if n_vert > 2: file.write("facet normal " + str(nx) + " " + str(ny) + " " + str(nz) + "\n") file.write(" outer loop") for j in range(0, 3): vert = face.v[j] file.write("\n vertex") for k in range(0, 3): file.write(" " + str(vert[k])) file.write("\n endloop\n") file.write("endfacet\n") n_tri = n_tri + 1 if n_vert > 3: file.write("facet normal " + str(nx) + " " + str(ny) + " " + str(nz) + "\n") file.write(" outer loop") for j in [0, 2, 3]: vert = face.v[j] file.write("\n vertex") for k in range(0, 3): file.write(" " + str(vert[k])) file.write("\n endloop\n") file.write("endfacet\n") n_tri = n_tri + 1 file.write("endsolid\n")
import Blender import math, sys from Blender import NMesh, Object, Scene from math import * PATH = "/home/carlos/" # La ruta donde se salvara el OREj nframes = 50 object = Object.GetSelected() objname = object[0].name meshname = object[0].data.name mesh = NMesh.GetRaw(meshname) filename = PATH + objname + ".orj" file = open(filename, "w") std = sys.stdout # Asociamos stdout al fichero .orj sys.stdout = file print "# Objeto OREj:", objname print "# Vertices Totales:", len(mesh.verts) print "# Caras Totales:", len(mesh.faces) # Escribimos toda la lista de vertices (v x y z) for vertex in mesh.verts: x, y, z = vertex.co print "v %f %f %f" % (x, y, z) # Escribimos toda la lista de caras (f v1 v2 v3 ...) for face in mesh.faces: print "f", face.v.reverse() # Invertimos las normales for vertex in face.v:
# 3DNPcam # # Use this script with a scene scriptlink # Don't forget to link your Camera to an Empty with a "Track To"-Constraint import Blender from Blender import Scene, NMesh import math from math import * scene = Scene.GetCurrent() context = scene.getRenderingContext() obj = Blender.Object.Get("Camera") frame = context.currentFrame() camspheremesh = NMesh.GetRaw("CameraBoss") camsphereobj = Blender.Object.Get('CameraBoss') vertamount = len(camspheremesh.verts) size = camsphereobj.getSize() if frame <= vertamount: vert = camspheremesh.verts[frame - 1] else: vert = camspheremesh.verts[vertamount] obj.setLocation(vert.co[0] * size[0], vert.co[1] * size[1], vert.co[2] * size[2])
def ParseMesh( self, szMeshName ): print "\tfound Mesh", szMeshName self.FindNextCharacter( '{' ) nHierarchyLevel = 1 aLineTokens = self.TokeniseLine() aVertices = self.ParseVec3Array( int( aLineTokens[ 0 ])) aLineTokens = self.TokeniseLine() aFaces = self.ParseFaceArray( int( aLineTokens[ 0 ])) aMaterialList = [] while self.m_uLineIndex < self.m_uLineCount: uBaseLine = self.m_uLineIndex aLineTokens = self.TokeniseLine() strToken = aLineTokens[ 0 ].lower() if "material" == strToken: aMaterialList.append( self.ParseMaterial() ) elif "meshmateriallist" == strToken: nHierarchyLevel += 1 self.FindNextCharacter( '{' ) aLineTokens = self.TokeniseLine() uMaterialCount = int( aLineTokens[ 0 ]) aLineTokens = self.TokeniseLine() aMaterialFaces = self.ParseIntArray( int( aLineTokens[ 0 ])) print "\tMaterial Count =", uMaterialCount, "Material Faces =", len( aMaterialFaces ) elif "meshnormals" == strToken: self.FindBracePair() # nHierarchyLevel += 1 # self.FindNextCharacter( '{' ) # aLineTokens = self.TokeniseLine() # aNormals = self.ParseVec3Array( int( aLineTokens[ 0 ])) # aLineTokens = self.TokeniseLine() # aNormalFaces = self.ParseFaceArray( int( aLineTokens[ 0 ])) # print "\tNormal count =", len( aNormals ), "Normal Faces =", len( aNormalFaces ) elif "meshtexturecoords" == strToken: nHierarchyLevel += 1 self.FindNextCharacter( '{' ) aLineTokens = self.TokeniseLine() aTexCoords = self.ParseVec2Array( int( aLineTokens[ 0 ])) elif "skinweights" == strToken: self.ParseSkinWeights() elif "xskinmeshheader" == strToken: self.ParseXSkinMeshHeader() elif -1 != string.find( self.m_aLines[ uBaseLine ], '}' ): nHierarchyLevel -= 1 if 0 == nHierarchyLevel: print "End Mesh" break else: print "Unexpected Mesh Token '", strToken, "' on line", self.m_uLineIndex break print "Vertex count =", len( aVertices ), "Face Count =", len( aFaces ), "Tex Coord count =", len( aTexCoords ) meshCurrent = NMesh.GetRaw() for vertex in aVertices: v3Vertex = Blender.Mathutils.Vector( vertex ) * self.matrix meshCurrent.verts.append( NMesh.Vert( v3Vertex[ 0 ], v3Vertex[ 2 ], v3Vertex[ 1 ])) # aMaterialList = [] # material = Material.New( "Material_Test" ) # material.rgbCol = [ float(words[0]), float(words[1]), float(words[2]) ] # material.setAlpha( float(words[3]) ) # aMaterialList.append( material ) # meshCurrent.setMaterials( aMaterialList ) # meshCurrent.update() aImageList = [] uFaceIndex = 0 for material in aMaterialList: szFileName = self.szDirectoryName + '\\' + material[ 0 ] print "Loading Image " + szFileName aImageList.append( Image.Load( szFileName )) for face in aFaces: faceNew = NMesh.Face() faceNew.v.append( meshCurrent.verts[ face[ 0 ]]) faceNew.uv.append( (aTexCoords[ face[ 0 ]][ 0 ], -aTexCoords[ face[ 0 ]][ 1 ]) ) faceNew.v.append( meshCurrent.verts[ face[ 2 ]]) faceNew.uv.append( (aTexCoords[ face[ 2 ]][ 0 ], -aTexCoords[ face[ 2 ]][ 1 ]) ) faceNew.v.append( meshCurrent.verts[ face[ 1 ]]) faceNew.uv.append( (aTexCoords[ face[ 1 ]][ 0 ], -aTexCoords[ face[ 1 ]][ 1 ]) ) faceNew.image = aImageList[ aMaterialFaces[ uFaceIndex ]] # faceNew.materialIndex = uMaterialIndex # faceNew.smooth = 1 meshCurrent.faces.append( faceNew ) uFaceIndex += 1 NMesh.PutRaw( meshCurrent, self.szModelName + "_" + str( self.uMeshIndex ), 1 ) self.uMeshIndex += 1 meshCurrent.update()
s = sin(angle) for (x,y,z) in vertex_list: X = c*x - s*y Y = s*x + c*y Z = z polygon_vertex_list.append( NMesh.Vert(X,Y,Z) ) def deg2rad(angle): return pi*angle/180.0 def rad2deg(angle): return 180*angle/pi ######### Creates a new mesh poly = NMesh.GetRaw() #### make vertexes vert = MakeVertexRectange() if UseAngles: da = float(EndAngle-StartAngle)/Segments angle = StartAngle segments = Segments+1 else: da = 360.0/Segments angle = 0.0 segments = Segments angle = deg2rad(angle) da = deg2rad(da)
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
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 Cylinder(Radius, Height, Segments, Divisions, CapDivisions, Smooth): def MakeVertexRing(vertex_list, r, z): for i in xrange(Segments): phi = (pi * 2 * i / Segments) x = r * cos(phi) y = r * sin(phi) vertex_list.append(Blender.NMesh.Vert(x, y, z)) ######### Creates a new mesh poly = NMesh.GetRaw() #### make vertexes dr = Radius / CapDivisions r = dr for _ in xrange(CapDivisions): MakeVertexRing(poly.verts, r, 0.0) r += dr r = Radius dz = Height / Divisions z = 0.0 for _ in xrange(Divisions): MakeVertexRing(poly.verts, r, z) z += dz dr = Radius / CapDivisions r = Radius for _ in xrange(CapDivisions): MakeVertexRing(poly.verts, r, Height) r -= dr #### Make faces tvc = 2 * (CapDivisions - 1) + Divisions + 1 for i in xrange(tvc): ring1_num = Segments * i ring2_num = Segments * (i + 1) for j in xrange(Segments): j0 = j j1 = (j + 1) % Segments f = Blender.NMesh.Face() f.smooth = Smooth f.v.append(poly.verts[ring1_num + j0]) f.v.append(poly.verts[ring1_num + j1]) f.v.append(poly.verts[ring2_num + j1]) f.v.append(poly.verts[ring2_num + j0]) poly.faces.append(f) #### Cap caps poly.verts.append(Blender.NMesh.Vert(0, 0, 0)) poly.verts.append(Blender.NMesh.Vert(0, 0, Height)) for j in xrange(Segments): j0 = j j1 = (j + 1) % Segments f = Blender.NMesh.Face() f.smooth = Smooth f.v.append(poly.verts[-2]) f.v.append(poly.verts[j0]) f.v.append(poly.verts[j1]) poly.faces.append(f) f = Blender.NMesh.Face() f.smooth = Smooth f.v.append(poly.verts[-1]) f.v.append(poly.verts[-(j0 + 3)]) f.v.append(poly.verts[-(j1 + 3)]) poly.faces.append(f) polyObj = NMesh.PutRaw(poly) return polyObj
face = Face() xmin = Vector([0,0,0]) xmax = Vector([0,0,0]) ymin = Vector([0,0,0]) ymax = Vector([0,0,0]) mxmin = Vector([0,0,0]) mxmax = Vector([0,0,0]) mymin = Vector([0,0,0]) mymax = Vector([0,0,0]) doodadCenter = Vector([0,0,0]) orientation = 0 center = Vector([0,0,0]) tosel = 0 seltopsonly = 0 tempx = [] doodadMesh = NMesh.GetRaw() global materialArray global reassignMats global thereAreMats global currmat global doodSideMat global doodTopMat #face is the face to add the doodad to. #sizeX and sizeY are values from 0.0 to 1.0 that represents a percentage the face that is covered by the doodad. #height is how tall the doodad is. def settings(seltops,matArr,reasMats,therMats,sidemat,topmat): global seltopsonly global materialArray
def polyhedron(n, l, rx, ry, rz): me = NMesh.GetRaw() nverts = 0 # Crea if (n == 1): nv = 4 nf = 4 setpoly(me, nv, nf, VertsT, FacesT) theta = AxisTT[Trat.val][Tran.val - 1] phi = AxisTP[Trat.val][Tran.val - 1] if (n == 2): nv = 8 nf = 12 setpoly(me, nv, nf, VertsC, FacesC) theta = AxisCT[Trat.val][Tran.val - 1] phi = AxisCP[Trat.val][Tran.val - 1] if (n == 3): nv = 6 nf = 8 setpoly(me, nv, nf, VertsO, FacesO) theta = AxisOT[Trat.val][Tran.val - 1] phi = AxisOP[Trat.val][Tran.val - 1] if (n == 4): nv = 20 nf = 36 setpoly(me, nv, nf, VertsD, FacesD) theta = AxisDT[Trat.val][Tran.val - 1] phi = AxisDP[Trat.val][Tran.val - 1] if (n == 5): nv = 12 nf = 20 setpoly(me, nv, nf, VertsI, FacesI) theta = AxisIT[Trat.val][Tran.val - 1] phi = AxisIP[Trat.val][Tran.val - 1] # Rotazione Poliedrica alpha = Trav.val * 3.14159265358979 / 180 ct = cos(theta) st = sin(theta) cp = cos(phi) sp = sin(phi) ca = cos(alpha) sa = sin(alpha) for i in range(0, nv): x1a = me.verts[i].co[0] x2a = me.verts[i].co[1] x3a = me.verts[i].co[2] # Rotazione dell'asse z sull'asse di rotazione x1b = x1a * ct * cp + x2a * ct * sp - x3a * st x2b = -x1a * sp + x2a * cp x3b = x1a * st * cp + x2a * st * sp + x3a * ct # Rotazione di alfa x1c = x1b * ca - x2b * sa x2c = x1b * sa + x2b * ca x3c = x3b # Riallineamento dell'asse z me.verts[i].co[0] = x1c * ct * cp - x2c * sp + x3c * st * cp me.verts[i].co[1] = x1c * ct * sp + x2c * cp + x3c * st * sp me.verts[i].co[2] = -x1c * st + x3c * ct obj = NMesh.PutRaw(me) # Ridimensiona obj.SizeX = l obj.SizeY = l obj.SizeZ = l # Rotazione alla Blender obj.RotX = rx * 3.14159265358979 / 180 obj.RotY = ry * 3.14159265358979 / 180 obj.RotZ = rz * 3.14159265358979 / 180 Blender.Redraw()
# Import pour visualiser dans Blender # Roucheyrolles Benjamin # Licence Pro SIL Image et Son 2006/2007 import Blender from Blender import NMesh objmesh='terrain' rawfile=open("filepath:\\Fractal\\fractal.raw","r") tabraw=rawfile.readlines() rawfile.close() mesh=NMesh.GetRaw() for ligne in tabraw: ligne=ligne.replace('\n','') l=ligne.split(' ') # Création des coordonnées x=float(l[0]) y=float(l[1]) z=float(l[2]) v=NMesh.Vert(x,y,z) mesh.verts.append(v) NMesh.PutRaw(mesh,objmesh) for i in range(0,n-1,1): for j in range(0,n-1,1):
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")
#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, #OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #============================================================================= # This script must run from a editor window in Blender. It take a mesh from the scene and # export it to a vtk PolyData # Este script debe ser ejecutado desde una ventada editora de texto de Blender # se encarga de tomar una malla presente en la escena de Blender (el nombre de la # malla debe ser introducido en el propio script) y pasarla a un polydata de vtk import vtk import Blender from Blender import NMesh import Tex_VTKBlender reload (Tex_VTKBlender) #Se incluye de forma manual el nombre de la malla a convertir me = NMesh.GetRaw("Put the mesh name to export here") pdata = Tex_VTKBlender.BlenderToPolyData(me) esc = vtk.vtkPolyDataWriter() # También se debe indicar la ubicación y nombre del nuevo archivo .vtk creado esc.SetFileName("the name of the .vtk file") esc.SetInput(pdata) vtk.vtkPolyDataWriter.Write(esc)