示例#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)
示例#2
0
 def GenerateVertices(me, rad, isegs, h, turn):
 	fanglestep = turn /float(isegs)
 	fangle = 0.0
 	while fangle < turn:
 		x = rad * cos(radians(fangle))
 		y = rad * sin(radians(fangle))
 		vert = NMesh.Vert(x, y, h)
 		me.verts.append(vert)
 		fangle += fanglestep
示例#3
0
	def AddYRotatedVertexes(polygon_vertex_list, vertex_list, angle):
		c = cos(angle)
		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) )
示例#4
0
    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))
示例#5
0
def makeLeaf(rotation, translation):
    vector = Vector([
        -leafSizeX.val / 2 * leafFactorButton.val, 0, 0 * leafFactorButton.val,
        1
    ])
    vector = MatMultVec(rotation, vector)
    vector = VecMultMat(vector, translation)
    v = NMesh.Vert(vector.x, vector.y, vector.z)
    foglie.verts.append(v)

    vector = Vector([
        leafSizeX.val / 2 * leafFactorButton.val, 0, 0 * leafFactorButton.val,
        1
    ])
    vector = MatMultVec(rotation, vector)
    vector = VecMultMat(vector, translation)
    v = NMesh.Vert(vector.x, vector.y, vector.z)
    foglie.verts.append(v)

    vector = Vector([
        leafSizeX.val / 2 * leafFactorButton.val, 0,
        leafSizeY.val * leafFactorButton.val, 1
    ])
    vector = MatMultVec(rotation, vector)
    vector = VecMultMat(vector, translation)
    v = NMesh.Vert(vector.x, vector.y, vector.z)
    foglie.verts.append(v)

    vector = Vector([
        -leafSizeX.val / 2 * leafFactorButton.val, 0,
        leafSizeY.val * leafFactorButton.val, 1
    ])
    vector = MatMultVec(rotation, vector)
    vector = VecMultMat(vector, translation)
    v = NMesh.Vert(vector.x, vector.y, vector.z)
    foglie.verts.append(v)
示例#6
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
示例#7
0
def setpoly(me, nv, nf, Verts, Faces):

    for i in range(0, nv):

        v = NMesh.Vert(Verts[0][i], Verts[1][i], Verts[2][i])

        me.verts.append(v)

    for i in range(0, nf):

        f = NMesh.Face()

        f.v.append(me.verts[Faces[0][i]])

        f.v.append(me.verts[Faces[1][i]])

        f.v.append(me.verts[Faces[2][i]])

        f.smooth = 0

        me.faces.append(f)
示例#8
0
			f.v.append(poly.verts[section0+j0])
			f.v.append(poly.verts[section0+j1])
			f.v.append(poly.verts[section1+j1])
			f.v.append(poly.verts[section1+j0])

			poly.faces.append(f)
			
	## caps
	if UseAngles:
	
		# add vertex at center of caps
		X = (InnerRadius + OuterRadius)/2.0
		Y = 0
		Z = Height/2.0

		poly.verts.append( NMesh.Vert( *RotateZvert( (X,Y,Z), deg2rad(StartAngle) ) ) )
		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])
示例#9
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) 
示例#10
0
def make_sel_vert(*co):
    v = NMesh.Vert(*co)
    v.sel = 1
    me.verts.append(v)
    return v
	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()
示例#12
0
def add_mesh(file, start_offset, num_mesh):
    global gRelPos
    global gTextureBpp

    #rx = (num_mesh-len(gRelPos)) * 10.0
    #ry = 0
    #rz = 0
    #if num_mesh<len(gRelPos):
    #	rx = gRelPos[num_mesh][0]
    #	ry = gRelPos[num_mesh][1]
    #	rz = gRelPos[num_mesh][2]
    rx = (num_mesh / 5) * 10.0
    ry = (num_mesh % 5) * 10.0
    rz = 0

    tri_vtx_offset = start_offset + struct.unpack("<L", file.read(4))[0]
    tri_vtx_count = struct.unpack("<L", file.read(4))[0]
    tri_nor_offset = start_offset + struct.unpack("<L", file.read(4))[0]
    tri_nor_count = struct.unpack("<L", file.read(4))[0]
    tri_offset = start_offset + struct.unpack("<L", file.read(4))[0]
    tri_count = struct.unpack("<L", file.read(4))[0]
    tri_tex_offset = start_offset + struct.unpack("<L", file.read(4))[0]

    quad_vtx_offset = start_offset + struct.unpack("<L", file.read(4))[0]
    quad_vtx_count = struct.unpack("<L", file.read(4))[0]
    quad_nor_offset = start_offset + struct.unpack("<L", file.read(4))[0]
    quad_nor_count = struct.unpack("<L", file.read(4))[0]
    quad_offset = start_offset + struct.unpack("<L", file.read(4))[0]
    quad_count = struct.unpack("<L", file.read(4))[0]
    quad_tex_offset = start_offset + struct.unpack("<L", file.read(4))[0]

    mesh = Blender.NMesh.GetRaw()

    if tri_count > 0:
        file.seek(tri_vtx_offset)
        for i in range(tri_vtx_count):
            #print "Reading triangle vertex %d" % i
            x = float(struct.unpack("<h", file.read(2))[0]) / 100.0
            x += rx
            y = float(struct.unpack("<h", file.read(2))[0]) / 100.0
            y += ry
            z = float(struct.unpack("<h", file.read(2))[0]) / 100.0
            z += rz
            w = float(struct.unpack("<h", file.read(2))[0]) / 100.0
            mesh.verts.append(NMesh.Vert(x, -y, z))

        # nor_list = []
        # file.seek(tri_nor_offset)
        # for i in range(tri_nor_count):
        # 	x = float(struct.unpack("<H",file.read(2))[0]) / 4096.0
        # 	y = float(struct.unpack("<H",file.read(2))[0]) / 4096.0
        # 	z = float(struct.unpack("<H",file.read(2))[0]) / 4096.0
        # 	w = float(struct.unpack("<H",file.read(2))[0]) / 4096.0
        # 	nor_list.append(x,y,z)

        # Read uv info
        uv_list = []
        file.seek(tri_tex_offset)
        for i in range(tri_count):
            # often, num_palette = offset, so don't bother
            u0 = struct.unpack("B", file.read(1))[0]
            v0 = struct.unpack("B", file.read(1))[0]
            num_palette = struct.unpack("<H", file.read(2))[0] & 0x1f
            u1 = struct.unpack("B", file.read(1))[0]
            v1 = struct.unpack("B", file.read(1))[0]
            offset = struct.unpack("<H", file.read(2))[0] & 0x3f
            if gTextureBpp == 4:
                offset <<= 6 + 2
            elif gTextureBpp == 8:
                offset <<= 6 + 1
            elif gTextureBpp == 16:
                offset <<= 6
            u2 = struct.unpack("B", file.read(1))[0]
            v2 = struct.unpack("B", file.read(1))[0]
            unknown = struct.unpack("<H", file.read(2))[0]

            u0 = float(u0 + offset) / float(gTextureWidth)
            u1 = float(u1 + offset) / float(gTextureWidth)
            u2 = float(u2 + offset) / float(gTextureWidth)
            v0 = float(v0) / float(gTextureHeight)
            v1 = float(v1) / float(gTextureHeight)
            v2 = float(v2) / float(gTextureHeight)

            uv_list.append([u0, v0])
            uv_list.append([u1, v1])
            uv_list.append([u2, v2])

        file.seek(tri_offset)
        for i in range(tri_count):
            #print "Reading triangle face %d" % i
            n0 = struct.unpack("<H", file.read(2))[0]
            v0 = struct.unpack("<H", file.read(2))[0]
            n1 = struct.unpack("<H", file.read(2))[0]
            v1 = struct.unpack("<H", file.read(2))[0]
            n2 = struct.unpack("<H", file.read(2))[0]
            v2 = struct.unpack("<H", file.read(2))[0]
            f = NMesh.Face()
            uv = uv_list[i * 3]
            f.uv.append((uv[0], uv[1]))
            uv = uv_list[i * 3 + 1]
            f.uv.append((uv[0], uv[1]))
            uv = uv_list[i * 3 + 2]
            f.uv.append((uv[0], uv[1]))
            f.v.append(mesh.verts[v0])
            f.v.append(mesh.verts[v1])
            f.v.append(mesh.verts[v2])
            f.mode |= NMesh.FaceModes.TEX
            f.transp = NMesh.FaceTranspModes.SOLID
            f.flag = NMesh.FaceFlags.ACTIVE
            mesh.faces.append(f)

    if quad_count > 0:
        start_vtx_count = 0
        if (quad_vtx_offset != tri_vtx_offset) or (quad_vtx_count !=
                                                   tri_vtx_count):
            start_vtx_count = tri_vtx_count
            file.seek(quad_vtx_offset)
            for i in range(quad_vtx_count):
                #print "Reading quad vertex %d" % i
                x = float(struct.unpack("<h", file.read(2))[0]) / 100.0
                x += rx
                y = float(struct.unpack("<h", file.read(2))[0]) / 100.0
                y += ry
                z = float(struct.unpack("<h", file.read(2))[0]) / 100.0
                z += rz
                w = float(struct.unpack("<h", file.read(2))[0]) / 100.0
                mesh.verts.append(NMesh.Vert(x, -y, z))

        # nor_list = []
        # if (quad_nor_offset != tri_nor_offset) or (quad_nor_count != tri_nor_count):
        # 	file.seek(quad_nor_offset)
        # 		for i in range(tri_quad_count):
        # 			x = float(struct.unpack("<H",file.read(2))[0]) / 4096.0
        # 			y = float(struct.unpack("<H",file.read(2))[0]) / 4096.0
        # 			z = float(struct.unpack("<H",file.read(2))[0]) / 4096.0
        # 			w = float(struct.unpack("<H",file.read(2))[0]) / 4096.0
        # 			nor_list.append(x,y,z)

        # Read uv info
        uv_list = []
        file.seek(quad_tex_offset)
        for i in range(quad_count):
            # often, num_palette = offset, so don't bother
            u0 = struct.unpack("B", file.read(1))[0]
            v0 = struct.unpack("B", file.read(1))[0]
            num_palette = struct.unpack("<H", file.read(2))[0] & 0x1f
            u1 = struct.unpack("B", file.read(1))[0]
            v1 = struct.unpack("B", file.read(1))[0]
            offset = struct.unpack("<H", file.read(2))[0] & 0x3f
            if gTextureBpp == 4:
                offset <<= 6 + 2
            elif gTextureBpp == 8:
                offset <<= 6 + 1
            elif gTextureBpp == 16:
                offset <<= 6
            u2 = struct.unpack("B", file.read(1))[0]
            v2 = struct.unpack("B", file.read(1))[0]
            unknown = struct.unpack("<H", file.read(2))[0]
            u3 = struct.unpack("B", file.read(1))[0]
            v3 = struct.unpack("B", file.read(1))[0]
            unknown = struct.unpack("<H", file.read(2))[0]

            u0 = float(u0 + offset) / float(gTextureWidth)
            u1 = float(u1 + offset) / float(gTextureWidth)
            u2 = float(u2 + offset) / float(gTextureWidth)
            u3 = float(u3 + offset) / float(gTextureWidth)
            v0 = float(v0) / float(gTextureHeight)
            v1 = float(v1) / float(gTextureHeight)
            v2 = float(v2) / float(gTextureHeight)
            v3 = float(v3) / float(gTextureHeight)

            uv_list.append([u0, v0])
            uv_list.append([u1, v1])
            uv_list.append([u2, v2])
            uv_list.append([u3, v3])

        file.seek(quad_offset)
        for i in range(quad_count):
            #print "Reading quad face %d" % i
            n0 = struct.unpack("<H", file.read(2))[0]
            v0 = struct.unpack("<H", file.read(2))[0]
            n1 = struct.unpack("<H", file.read(2))[0]
            v1 = struct.unpack("<H", file.read(2))[0]
            n2 = struct.unpack("<H", file.read(2))[0]
            v2 = struct.unpack("<H", file.read(2))[0]
            n3 = struct.unpack("<H", file.read(2))[0]
            v3 = struct.unpack("<H", file.read(2))[0]
            f = NMesh.Face()
            uv = uv_list[i * 4]
            f.uv.append((uv[0], uv[1]))
            uv = uv_list[i * 4 + 1]
            f.uv.append((uv[0], uv[1]))
            uv = uv_list[i * 4 + 3]
            f.uv.append((uv[0], uv[1]))
            uv = uv_list[i * 4 + 2]
            f.uv.append((uv[0], uv[1]))
            f.v.append(mesh.verts[start_vtx_count + v0])
            f.v.append(mesh.verts[start_vtx_count + v1])
            f.v.append(mesh.verts[start_vtx_count + v3])
            f.v.append(mesh.verts[start_vtx_count + v2])
            f.mode |= NMesh.FaceModes.TEX
            f.transp = NMesh.FaceTranspModes.SOLID
            f.flag = NMesh.FaceFlags.ACTIVE
            mesh.faces.append(f)

    mesh.materials.append(gMat)
    return mesh
示例#13
0
 def GenerateVertex(me, x, y, z):
 	vert = NMesh.Vert(x, y, z)
 	me.verts.append(vert)
示例#14
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")
示例#15
0
def addMesh(file):
    tmd_header_size = 12

    vtx_offset = tmd_header_size + struct.unpack("<L", file.read(4))[0]
    vtx_count = struct.unpack("<L", file.read(4))[0]
    nor_offset = tmd_header_size + struct.unpack("<L", file.read(4))[0]
    nor_count = struct.unpack("<L", file.read(4))[0]
    pri_offset = tmd_header_size + struct.unpack("<L", file.read(4))[0]
    pri_count = struct.unpack("<L", file.read(4))[0]
    unknown = struct.unpack("<L", file.read(4))[0]

    mesh = Blender.NMesh.GetRaw()
    mesh.hasVertexColours(1)

    # Read vertices
    file.seek(vtx_offset)
    for i in range(vtx_count):
        x = float(struct.unpack("<h", file.read(2))[0]) / 100.0
        y = float(struct.unpack("<h", file.read(2))[0]) / 100.0
        z = float(struct.unpack("<h", file.read(2))[0]) / 100.0
        w = float(struct.unpack("<h", file.read(2))[0]) / 100.0
        mesh.verts.append(NMesh.Vert(x, y, z))

    # Read normals
    file.seek(nor_offset)
    normals = []
    for i in range(nor_count):
        x = float(struct.unpack("<h", file.read(2))[0]) / 4096.0
        y = float(struct.unpack("<h", file.read(2))[0]) / 4096.0
        z = float(struct.unpack("<h", file.read(2))[0]) / 4096.0
        w = float(struct.unpack("<h", file.read(2))[0]) / 4096.0
        normals.append([x, y, z])

    # Read primitives
    file.seek(pri_offset)
    for i in range(pri_count):
        unknown1 = struct.unpack("B", file.read(1))[0]
        pri_length = struct.unpack("B", file.read(1))[0] * 4
        unknown2 = struct.unpack("B", file.read(1))[0]
        pri_type = struct.unpack("B", file.read(1))[0]

        cur_file_pos = file.tell()

        if (pri_type == 0x20) or (pri_type == 0x22):
            # Coloured triangle
            r = struct.unpack("B", file.read(1))[0]
            g = struct.unpack("B", file.read(1))[0]
            b = struct.unpack("B", file.read(1))[0]
            a = struct.unpack("B", file.read(1))[0]

            n = struct.unpack("<H", file.read(2))[0]
            v0 = struct.unpack("<H", file.read(2))[0]
            v1 = struct.unpack("<H", file.read(2))[0]
            v2 = struct.unpack("<H", file.read(2))[0]

            f = NMesh.Face()
            f.v.append(mesh.verts[v0])
            f.v.append(mesh.verts[v1])
            f.v.append(mesh.verts[v2])
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            mesh.faces.append(f)
        elif (pri_type == 0x24):
            # Gourauded triangle
            r0 = struct.unpack("B", file.read(1))[0]
            g0 = struct.unpack("B", file.read(1))[0]
            b0 = struct.unpack("B", file.read(1))[0]
            a0 = struct.unpack("B", file.read(1))[0]

            r1 = struct.unpack("B", file.read(1))[0]
            g1 = struct.unpack("B", file.read(1))[0]
            b1 = struct.unpack("B", file.read(1))[0]
            a1 = struct.unpack("B", file.read(1))[0]

            r2 = struct.unpack("B", file.read(1))[0]
            g2 = struct.unpack("B", file.read(1))[0]
            b2 = struct.unpack("B", file.read(1))[0]
            a2 = struct.unpack("B", file.read(1))[0]

            n = struct.unpack("<H", file.read(2))[0]
            v0 = struct.unpack("<H", file.read(2))[0]
            v1 = struct.unpack("<H", file.read(2))[0]
            v2 = struct.unpack("<H", file.read(2))[0]

            f = NMesh.Face()
            f.v.append(mesh.verts[v0])
            f.v.append(mesh.verts[v1])
            f.v.append(mesh.verts[v2])
            f.col.append(Blender.NMesh.Col(r0, g0, b0, 255))
            f.col.append(Blender.NMesh.Col(r1, g1, b1, 255))
            f.col.append(Blender.NMesh.Col(r2, g2, b2, 255))
            mesh.faces.append(f)
        elif (pri_type == 0x28):
            # Coloured quad
            r = struct.unpack("B", file.read(1))[0]
            g = struct.unpack("B", file.read(1))[0]
            b = struct.unpack("B", file.read(1))[0]
            a = struct.unpack("B", file.read(1))[0]

            n = struct.unpack("<H", file.read(2))[0]
            v0 = struct.unpack("<H", file.read(2))[0]
            v1 = struct.unpack("<H", file.read(2))[0]
            v2 = struct.unpack("<H", file.read(2))[0]
            v3 = struct.unpack("<H", file.read(2))[0]

            f = NMesh.Face()
            f.v.append(mesh.verts[v0])
            f.v.append(mesh.verts[v1])
            f.v.append(mesh.verts[v3])
            f.v.append(mesh.verts[v2])
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            mesh.faces.append(f)
        elif (pri_type == 0x2c):
            # Gourauded quad
            r0 = struct.unpack("B", file.read(1))[0]
            g0 = struct.unpack("B", file.read(1))[0]
            b0 = struct.unpack("B", file.read(1))[0]
            a0 = struct.unpack("B", file.read(1))[0]

            r1 = struct.unpack("B", file.read(1))[0]
            g1 = struct.unpack("B", file.read(1))[0]
            b1 = struct.unpack("B", file.read(1))[0]
            a1 = struct.unpack("B", file.read(1))[0]

            r2 = struct.unpack("B", file.read(1))[0]
            g2 = struct.unpack("B", file.read(1))[0]
            b2 = struct.unpack("B", file.read(1))[0]
            a2 = struct.unpack("B", file.read(1))[0]

            r3 = struct.unpack("B", file.read(1))[0]
            g3 = struct.unpack("B", file.read(1))[0]
            b3 = struct.unpack("B", file.read(1))[0]
            a3 = struct.unpack("B", file.read(1))[0]

            n = struct.unpack("<H", file.read(2))[0]
            v0 = struct.unpack("<H", file.read(2))[0]
            v1 = struct.unpack("<H", file.read(2))[0]
            v2 = struct.unpack("<H", file.read(2))[0]
            v3 = struct.unpack("<H", file.read(2))[0]

            f = NMesh.Face()
            f.v.append(mesh.verts[v0])
            f.v.append(mesh.verts[v1])
            f.v.append(mesh.verts[v3])
            f.v.append(mesh.verts[v2])
            f.col.append(Blender.NMesh.Col(r0, g0, b0, 255))
            f.col.append(Blender.NMesh.Col(r1, g1, b1, 255))
            f.col.append(Blender.NMesh.Col(r3, g3, b3, 255))
            f.col.append(Blender.NMesh.Col(r2, g2, b2, 255))
            mesh.faces.append(f)
        elif (pri_type == 0x30):
            # Coloured triangle with per-vertex normal
            r = struct.unpack("B", file.read(1))[0]
            g = struct.unpack("B", file.read(1))[0]
            b = struct.unpack("B", file.read(1))[0]
            a = struct.unpack("B", file.read(1))[0]

            n0 = struct.unpack("<H", file.read(2))[0]
            v0 = struct.unpack("<H", file.read(2))[0]
            n1 = struct.unpack("<H", file.read(2))[0]
            v1 = struct.unpack("<H", file.read(2))[0]
            n2 = struct.unpack("<H", file.read(2))[0]
            v2 = struct.unpack("<H", file.read(2))[0]

            f = NMesh.Face()
            f.v.append(mesh.verts[v0])
            f.v.append(mesh.verts[v1])
            f.v.append(mesh.verts[v2])
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            mesh.faces.append(f)
        elif (pri_type == 0x34):
            # Textured triangle with per-vertex normal
            unknown0 = struct.unpack("<H", file.read(2))[0]
            tv0 = struct.unpack("B", file.read(1))[0]
            tu0 = struct.unpack("B", file.read(1))[0]

            unknown1 = struct.unpack("<H", file.read(2))[0]
            tv1 = struct.unpack("B", file.read(1))[0]
            tu1 = struct.unpack("B", file.read(1))[0]

            unknown2 = struct.unpack("<H", file.read(2))[0]
            tv2 = struct.unpack("B", file.read(1))[0]
            tu2 = struct.unpack("B", file.read(1))[0]

            n0 = struct.unpack("<H", file.read(2))[0]
            v0 = struct.unpack("<H", file.read(2))[0]
            n1 = struct.unpack("<H", file.read(2))[0]
            v1 = struct.unpack("<H", file.read(2))[0]
            n2 = struct.unpack("<H", file.read(2))[0]
            v2 = struct.unpack("<H", file.read(2))[0]

            f = NMesh.Face()
            f.v.append(mesh.verts[v0])
            f.v.append(mesh.verts[v1])
            f.v.append(mesh.verts[v2])
            mesh.faces.append(f)
        elif (pri_type == 0x38):
            # Coloured quad with per-vertex normal
            r = struct.unpack("B", file.read(1))[0]
            g = struct.unpack("B", file.read(1))[0]
            b = struct.unpack("B", file.read(1))[0]
            a = struct.unpack("B", file.read(1))[0]

            n0 = struct.unpack("<H", file.read(2))[0]
            v0 = struct.unpack("<H", file.read(2))[0]
            n1 = struct.unpack("<H", file.read(2))[0]
            v1 = struct.unpack("<H", file.read(2))[0]
            n2 = struct.unpack("<H", file.read(2))[0]
            v2 = struct.unpack("<H", file.read(2))[0]
            n3 = struct.unpack("<H", file.read(2))[0]
            v3 = struct.unpack("<H", file.read(2))[0]

            f = NMesh.Face()
            f.v.append(mesh.verts[v0])
            f.v.append(mesh.verts[v1])
            f.v.append(mesh.verts[v3])
            f.v.append(mesh.verts[v2])
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            f.col.append(Blender.NMesh.Col(r, g, b, 255))
            mesh.faces.append(f)

        file.seek(cur_file_pos + pri_length)

    return mesh
示例#16
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")
示例#17
0
def creaTronco(length, depth, min_length, branch_frequency, direction,
               rotTotal, traslTotal, closure_grow_factor, nTasselli,
               treeGrowSpeed):
    n = baseResolutionButton.val
    cont_nodo = 0
    for actual_length in range(0, length):
        if (depth == 0):
            DrawProgressBar(actual_length / treeLengthButton.val,
                            "Creating Tree...")
        cont_nodo = cont_nodo + 1
        #nTasselli conta il numero di pezzi da disegnare in seguito
        nTasselli = nTasselli + 1
        #Aggiorno fattore di crescita
        closure_grow_factor = closure_grow_factor * closureGrowFactorButton.val
        #Ciclo di creazione tronco
        #print actual_length

        #Randomizzazione della direzione del tassello
        #Trovo due angoli random
        angle1 = random.uniform(-randomGrowFactorButton.val,
                                randomGrowFactorButton.val)
        angle2 = random.uniform(-randomGrowFactorButton.val,
                                randomGrowFactorButton.val)
        rotmat1 = RotationMatrix(angle1, 4, 'x')
        rotmat2 = RotationMatrix(angle2, 4, 'y')
        directionRot = rotmat1 * rotmat2
        rotMat = rotmat1 * rotmat2 * rotTotal
        direction = MatMultVec(directionRot, direction)
        #print direction
        trasl = TranslationMatrix(direction)
        traslTotal = traslTotal * trasl

        #Creo nuovo tassello
        for i in range(0, n):

            x = (tronco.verts[i].co[0]) * closure_grow_factor
            y = (tronco.verts[i].co[1]) * closure_grow_factor
            z = (tronco.verts[i].co[2])
            vector = Vector([x, y, z, 1])
            vector = MatMultVec(rotMat, vector)
            vector = VecMultMat(vector, traslTotal)
            v = NMesh.Vert(vector.x, vector.y, vector.z)
            tronco.verts.append(v)

        #Possibile diramazione
        if ((actual_length > min_length) and (depth < maxDepthButton.val)
                and (cont_nodo >= branch_frequency)):

            for nBranch in range(0, numBranchButton.val):
                #Azzero il contatore della frequenza dei Tasselli
                cont_nodo = 0
                #Calcolo nuova direzione
                #Randomizzazione della direzione del tassello
                #Trovo due angoli random
                anglex = random.uniform(minBranchAngleButton.val,
                                        maxBranchAngleButton.val)
                anglez = random.uniform(0, 360)
                rotmatx = RotationMatrix(anglex, 4, 'x')
                rotmatz = RotationMatrix(anglez, 4, 'z')
                newRotTotal = rotMat * rotmatz * rotmatx
                newDirection = MatMultVec(newRotTotal,
                                          Vector([0, 0, treeGrowSpeed, 1]))

                nTasselli = creaTronco(
                    pow(closureVerticalLengthFactorButton.val, actual_length) *
                    length * closureBranchLengthFactorButton.val, depth + 1,
                    min_length * closureMinBranchHeightButton.val,
                    branch_frequency * closureBranchFrequencyButton.val,
                    newDirection, newRotTotal, traslTotal,
                    closure_grow_factor * closureBranchFactorButton.val,
                    nTasselli, treeGrowSpeed * closureTreeGrowSpeedButton.val)
                #print "Ritorno"
                #actual_length=6

                #Creo tassello di giunzione
                nTasselli = nTasselli + 1
                for i in range(0, n):
                    v = NMesh.Vert(0, 0, 0)
                    tronco.verts.append(v)

                nTasselli = nTasselli + 1
                for i in range(0, n):

                    x = (tronco.verts[i].co[0]) * closure_grow_factor
                    y = (tronco.verts[i].co[1]) * closure_grow_factor
                    z = (tronco.verts[i].co[2])
                    vector = Vector([x, y, z, 1])
                    vector = MatMultVec(rotTotal, vector)
                    vector = VecMultMat(vector, traslTotal)
                    v = NMesh.Vert(vector.x, vector.y, vector.z)
                    tronco.verts.append(v)

        #Possibile Foglia
        if (depth >= leafDepthButton.val):
            for i in range(0, leafPerNodeButton.val):
                #print "Foglia"

                #Calcolo rotazione foglia
                #Trovo tre angoli random
                anglex = random.uniform(-40, 40)
                angley = random.uniform(-40, 40)
                anglez = random.uniform(0, 360)
                rotmatx = RotationMatrix(anglex, 4, 'x')
                rotmaty = RotationMatrix(angley, 4, 'y')
                rotmatz = RotationMatrix(anglez, 4, 'z')
                newLeafRotTotal = rotMat * rotmatz * rotmaty * rotmatx
                makeLeaf(newLeafRotTotal, traslTotal)

    #

    #
    #print nTasselli
    return (nTasselli)
示例#18
0
def PolyDataMapperToBlender(pmapper, me=None):

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

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

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

    scalars = pdata.GetPointData().GetScalars()

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

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

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

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

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

            BlenderAddFace(me, colors, n1, n2)

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

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

                BlenderAddFace(me, colors, n1, n2)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return me