Esempio n. 1
0
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)
Esempio n. 2
0
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
Esempio n. 3
0
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
Esempio n. 4
0
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):
		f = NMesh.Face()
		f.v.append(mesh.verts[i*n+j])
		f.v.append(mesh.verts[i*n+j+1])
		f.v.append(mesh.verts[(i+1)*n+j+1])
		f.v.append(mesh.verts[(i+1)*n+j])
		f.smooth=1
		mesh.faces.append(f)

NMesh.PutRaw(mesh,objmesh) 
	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()
Esempio n. 6
0
#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 a .vtk file and 
# import it to the scene in Blender
import vtk
import Blender
from Blender import NMesh
import Tex_VTKBlender
reload(Tex_VTKBlender)
#Cargamos ahora la malla de vtk empleada en ESQUI
reader = vtk.vtkPolyDataReader()
reader.SetFileName("Poner aqui el nombre del archivo .vtk a importar a Blender")

mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(reader.GetOutput())

me = NMesh.New()
me = Tex_VTKBlender.PolyDataMapperToBlender(mapper)
try:
	# Si estamos con la API BPython 2.42
	NMesh.PutRaw(me)
else:
	# Si estamos con la API BPython 2.36
	Blender.Scene.AddMesh(me) 
Esempio n. 7
0
		poly.verts.append( NMesh.Vert( *RotateZvert( (X,Y,Z), deg2rad(EndAngle) ) ) )

		# and make faces
		for i in xrange(vps):
			f0			= NMesh.Face()
			f1			= NMesh.Face()
			f0.smooth	= Smooth
			f1.smooth	= Smooth

			i0 = i
			i1 = (i+1) % vps

			f0.v.append(poly.verts[-2])
			f0.v.append(poly.verts[i0])
			f0.v.append(poly.verts[i1])

			f1.v.append(poly.verts[-1])
			f1.v.append(poly.verts[-(i0+3)])
			f1.v.append(poly.verts[-(i1+3)])
			
			poly.faces.append(f0)
			poly.faces.append(f1)

	polyObj = NMesh.PutRaw(poly)
	return polyObj

Blender.Redraw()

# vim: ts=4 sw=4

Esempio n. 8
0
def makeTree():
    #INIZIO PROGRAMMA
    print "-------------------"
    global leafTexture, stemTexture
    global tronco, foglie
    n = baseResolutionButton.val
    #Creo Mesh del tronco
    tronco = NMesh.GetRaw("stemMesh")
    if (tronco == None): tronco = NMesh.GetRaw()
    tronco.verts = []
    tronco.faces = []

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

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

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

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

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

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

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

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

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

        leafMat.setTexture(0, leafTex)

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

        #Associo materiale
        foglie.materials.append(leafMat)

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

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

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

        stemMat.setTexture(0, stemTex)

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

        #Associo materiale
        tronco.materials.append(stemMat)

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

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

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

        tronco.update()
        foglie.update()

    DrawProgressBar(1.0, "Finished")
Esempio n. 9
0
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")
Esempio n. 10
0
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
Esempio n. 11
0
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()