Пример #1
0
def importFromFileToMesh(path):
  scene = pyassimp.load(path)
  if len(scene.meshes) == 0:
    print "assimp_importer: found no mesh, abort"
    return None
  elif len(scene.meshes) > 1:
    print "assimp_importer: found %s meshes, abort", len(scene.meshes)
    return None
  else:
    faces = scene.meshes[0].faces
    vertices = scene.meshes[0].vertices
    result = ROSMeshTriangleMesh()
    for vertex in vertices:
      ros_point = ROSPoint()
      ros_point.x = vertex[0]
      ros_point.y = vertex[1]
      ros_point.z = vertex[2]
      result.vertices.append(ros_point)
    for face in faces:
      if len(face.indices) != 3:
        print "WARNING: Triangle contained $s instead of 3 indicies", len(face.indices)
      ros_triangle = ROSTriangleIndices()
      ros_triangle.vertex_indices = [face.indices[0], face.indices[1], face.indices[2]]
      result.triangles.append(ros_triangle)
  pyassimp.release(scene)
  return result
    def makeMesh(self, name, pose, filename):
        scene = pyassimp.load(filename)
        if not scene.meshes:
            rospy.logerr('Unable to load mesh')
            return

        mesh = Mesh()
        for face in scene.meshes[0].faces:
            triangle = MeshTriangle()
            if len(face.indices) == 3:
                triangle.vertex_indices = [face.indices[0],
                                           face.indices[1],
                                           face.indices[2]]
            mesh.triangles.append(triangle)
        for vertex in scene.meshes[0].vertices:
            point = Point()
            point.x = vertex[0]
            point.y = vertex[1]
            point.z = vertex[2]
            mesh.vertices.append(point)
        pyassimp.release(scene)

        o = CollisionObject()
        o.header.stamp = rospy.Time.now()
        o.header.frame_id = self._fixed_frame
        o.id = name
        o.meshes.append(mesh)
        o.mesh_poses.append(pose)
        o.operation = o.ADD
        return o
Пример #3
0
 def __init__(self, filename):
     self.model = pyassimp.load(filename)
     self.vertices = numpy.array(flatten(self.model.meshes[0].vertices), numpy.float32)
     self.make_indices()
     # NOTE: this drops the W from UVW-coordinates.
     self.texcoords = numpy.array([item for sublist in self.model.meshes[0].texcoords[0] for item in sublist[:2]], numpy.float32)
     self.normals = numpy.array(flatten(self.model.meshes[0].normals), numpy.float32)
Пример #4
0
 def __make_mesh(self, name, pose, filename):
     co = CollisionObject()
     scene = pyassimp.load(filename)
     if not scene.meshes:
         raise MoveItCommanderException("There are no meshes in the file")
     co.operation = CollisionObject.ADD
     co.id = name
     co.header = pose.header
     
     mesh = Mesh()
     for face in scene.meshes[0].faces:
         triangle = MeshTriangle()
         if len(face.indices) == 3:
             triangle.vertex_indices = [face.indices[0], face.indices[1], face.indices[2]]
         mesh.triangles.append(triangle)
     for vertex in scene.meshes[0].vertices:
         point = Point()
         point.x = vertex[0]
         point.y = vertex[1]
         point.z = vertex[2]
         mesh.vertices.append(point)
     co.meshes = [mesh]
     co.mesh_poses = [pose.pose]
     pyassimp.release(scene)
     return co
Пример #5
0
def main():
    scene = pyassimp.load(options.filename, aiProcessFlags)

    for index, mesh in enumerate(scene.meshes):
        if(options.bJSON):
            writeMeshJSON(mesh, scene.materials[mesh.mMaterialIndex], scene.mRootNode[0].mTransformation)
        else:
            writeMesh(mesh)
    
    # Finally release the model
    pyassimp.release(scene)
Пример #6
0
def main(filename=None):
    filename = filename or DEFAULT_MODEL
    scene = pyassimp.load(filename)
    
    #the model we load
    print("MODEL:", filename)
    print()
    
    #write some statistics
    print("SCENE:")
    print("  meshes:", len(scene.meshes))
    print("  materials:", len(scene.materials))
    print("  textures:", len(scene.textures))
    print()
    
    print("MESHES:")
    for index, mesh in enumerate(scene.meshes):
        print("  MESH", index+1)
        print("    material:", mesh.mMaterialIndex+1)
        print("    vertices:", len(mesh.vertices))
        print("    first 3 verts:", mesh.vertices[:3])
        #if len(mesh.normals):
        #        print "    first 3 normals:", mesh.normals[:3]
        print("    colors:", len(mesh.colors))
        tc = mesh.texcoords
        print("    texture-coords 1:", len(tc[0]), "first3:", tc[0][:3])
        print("    texture-coords 2:", len(tc[1]), "first3:", tc[1][:3])
        print("    texture-coords 3:", len(tc[2]), "first3:", tc[2][:3])
        print("    texture-coords 4:", len(tc[3]), "first3:", tc[3][:3])
        print("    uv-component-count:", len(mesh.mNumUVComponents))
        print("    faces:", len(mesh.faces), "first:", [f.indices for f in mesh.faces[:3]])
        print("    bones:", len(mesh.bones), "first:", [b.mName for b in mesh.bones[:3]])
        print()

    print("MATERIALS:")
    for index, material in enumerate(scene.materials):
        print("  MATERIAL", index+1)
        properties = pyassimp.GetMaterialProperties(material)
        for key in properties:
            print("    %s: %s" % (key, properties[key]))
    print()
    
    print("TEXTURES:")
    for index, texture in enumerate(scene.textures):
        print("  TEXTURE", index+1)
        print("    width:", texture.mWidth)
        print("    height:", texture.mHeight)
        print("    hint:", texture.achFormatHint)
        print("    data (size):", texture.mWidth*texture.mHeight)
   
    # Finally release the model
    pyassimp.release(scene)
Пример #7
0
def Load(fileName):
    Model = os.path.join(os.path.dirname(__file__), fileName)
    scene = pyassimp.load(Model)
    newModel = Mesh()
    for index, mesh in enumerate(scene.meshes): #On suppose qu'il n'y a qu'un mesh par fichier, la fonction ne renvoyant qu'un mesh
        for index, vertices in enumerate(mesh.vertices):
            newModel.m_vertices.insert(index, vector3(vertices[0],vertices[1],vertices[2]))
        for index, face in enumerate(mesh.faces):
            newModel.m_faces.insert(index, vector3(face.indices[0],face.indices[1],face.indices[2]))
        for index, normal in enumerate(mesh.normals):
            newModel.m_normals.insert(index, vector3(normal[0],normal[1],normal[2]))
    pyassimp.release(scene)
    return newModel
Пример #8
0
def main():
    scene = pyassimp.load(MODEL)

    # the model we load
    print "MODEL:", MODEL
    print

    # write some statistics
    print "SCENE:"
    print "  meshes:", len(scene.meshes)
    print "  materials:", len(scene.materials)
    print "  textures:", len(scene.textures)
    print

    print "MESHES:"
    for index, mesh in enumerate(scene.meshes):
        print "  MESH", index + 1
        print "    material:", mesh.mMaterialIndex + 1
        print "    vertices:", len(mesh.vertices)
        print "    first:", mesh.vertices[:3]
        print "    colors:", len(mesh.colors)
        tc = mesh.texcoords
        print "    texture-coords 1:", len(tc[0]), "first:", tc[0][:3]
        print "    texture-coords 2:", len(tc[1]), "first:", tc[1][:3]
        print "    texture-coords 3:", len(tc[2]), "first:", tc[2][:3]
        print "    texture-coords 4:", len(tc[3]), "first:", tc[3][:3]
        print "    uv-component-count:", len(mesh.mNumUVComponents)
        print "    faces:", len(mesh.faces), "first:", [f.indices for f in mesh.faces[:3]]
        print "    bones:", len(mesh.bones), "first:", [b.mName for b in mesh.bones[:3]]
        print

    print "MATERIALS:"
    for index, material in enumerate(scene.materials):
        print "  MATERIAL", index + 1
        properties = pyassimp.GetMaterialProperties(material)
        for key in properties:
            print "    %s: %s" % (key, properties[key])
    print

    print "TEXTURES:"
    for index, texture in enumerate(scene.textures):
        print "  TEXTURE", index + 1
        print "    width:", texture.mWidth
        print "    height:", texture.mHeight
        print "    hint:", texture.achFormatHint
        print "    data (size):", texture.mWidth * texture.mHeight

    # Finally release the model
    pyassimp.release(scene)
def make_mesh(co, name, pose, filename, scale = (1, 1, 1)):
    #print("make_mesh(name=%s filename=%s)" % (name, filename))
    scene = pyassimp.load(filename)
    if not scene.meshes or len(scene.meshes) == 0:
        raise MoveItCommanderException("There are no meshes in the file")
    if len(scene.meshes[0].faces) == 0:
        raise MoveItCommanderException("There are no faces in the mesh")
    co.operation = CollisionObject.ADD
    co.id = name
    co.header = pose.header

    mesh = Mesh()
    first_face = scene.meshes[0].faces[0]
    if hasattr(first_face, '__len__'):
        for face in scene.meshes[0].faces:
            if len(face) == 3:
                triangle = MeshTriangle()
                triangle.vertex_indices = [face[0], face[1], face[2]]
                mesh.triangles.append(triangle)
    elif hasattr(first_face, 'indices'):
        for face in scene.meshes[0].faces:
            if len(face.indices) == 3:
                triangle = MeshTriangle()
                triangle.vertex_indices = [face.indices[0],
                                           face.indices[1],
                                           face.indices[2]]
                mesh.triangles.append(triangle)
    else:
        raise MoveItCommanderException("Unable to build triangles from mesh due to mesh object structure")
    for vertex in scene.meshes[0].vertices:
        point = Point()
        point.x = vertex[0]*scale[0]
        point.y = vertex[1]*scale[1]
        point.z = vertex[2]*scale[2]
        mesh.vertices.append(point)
    if not isinstance(co.meshes, list):
        co.meshes = []
    co.meshes += [mesh]

    if not isinstance(co.mesh_poses, list):
        co.mesh_poses = []
    co.mesh_poses += [pose.pose]

    pyassimp.release(scene)
    return co
Пример #10
0
    def __make_mesh(name, pose, filename, scale=(1, 1, 1)):
        co = CollisionObject()
        if pyassimp is False:
            raise MoveItCommanderException(
                "Pyassimp needs patch https://launchpadlibrarian.net/319496602/patchPyassim.txt"
            )
        scene = pyassimp.load(filename)
        if not scene.meshes or len(scene.meshes) == 0:
            raise MoveItCommanderException("There are no meshes in the file")
        if len(scene.meshes[0].faces) == 0:
            raise MoveItCommanderException("There are no faces in the mesh")
        co.operation = CollisionObject.ADD
        co.id = name
        co.header = pose.header

        mesh = Mesh()
        first_face = scene.meshes[0].faces[0]
        if hasattr(first_face, '__len__'):
            for face in scene.meshes[0].faces:
                if len(face) == 3:
                    triangle = MeshTriangle()
                    triangle.vertex_indices = [face[0], face[1], face[2]]
                    mesh.triangles.append(triangle)
        elif hasattr(first_face, 'indices'):
            for face in scene.meshes[0].faces:
                if len(face.indices) == 3:
                    triangle = MeshTriangle()
                    triangle.vertex_indices = [
                        face.indices[0], face.indices[1], face.indices[2]
                    ]
                    mesh.triangles.append(triangle)
        else:
            raise MoveItCommanderException(
                "Unable to build triangles from mesh due to mesh object structure"
            )
        for vertex in scene.meshes[0].vertices:
            point = Point()
            point.x = vertex[0] * scale[0]
            point.y = vertex[1] * scale[1]
            point.z = vertex[2] * scale[2]
            mesh.vertices.append(point)
        co.meshes = [mesh]
        co.mesh_poses = [pose.pose]
        pyassimp.release(scene)
        return co
Пример #11
0
def create_mesh(name,
                pose,
                filename,
                scale=(1, 1, 1),
                frame_id='/world_frame'):
    co = CollisionObject()
    scene = pyassimp.load(str(exo.Tools.parsePath(filename)))
    if not scene.meshes or len(scene.meshes) == 0:
        raise Exception("There are no meshes in the file")
    if len(scene.meshes[0].faces) == 0:
        raise Exception("There are no faces in the mesh")
    co.operation = CollisionObject.ADD
    co.id = name
    co.header.frame_id = frame_id

    mesh = Mesh()
    first_face = scene.meshes[0].faces[0]
    if hasattr(first_face, '__len__'):
        for face in scene.meshes[0].faces:
            if len(face) == 3:
                triangle = MeshTriangle()
                triangle.vertex_indices = [face[0], face[1], face[2]]
                mesh.triangles.append(triangle)
    elif hasattr(first_face, 'indices'):
        for face in scene.meshes[0].faces:
            if len(face.indices) == 3:
                triangle = MeshTriangle()
                triangle.vertex_indices = [
                    face.indices[0], face.indices[1], face.indices[2]
                ]
                mesh.triangles.append(triangle)
    else:
        raise Exception("Unable to build triangles from mesh")
    for vertex in scene.meshes[0].vertices:
        point = Point()
        point.x = vertex[0] * scale[0]
        point.y = vertex[1] * scale[1]
        point.z = vertex[2] * scale[2]
        mesh.vertices.append(point)
    co.meshes = [mesh]
    co.mesh_poses = [pose]
    pyassimp.release(scene)
    return co
    def __make_mesh(name, pose, filename, scale=(1, 1, 1)):
        co = CollisionObject()
        if pyassimp is False:
            raise MoveItCommanderException(
                "Pyassimp needs patch https://launchpadlibrarian.net/319496602/patchPyassim.txt")
        scene = pyassimp.load(filename)
        if not scene.meshes or len(scene.meshes) == 0:
            raise MoveItCommanderException("There are no meshes in the file")
        if len(scene.meshes[0].faces) == 0:
            raise MoveItCommanderException("There are no faces in the mesh")
        co.operation = CollisionObject.ADD
        co.id = name
        co.header = pose.header

        mesh = Mesh()
        first_face = scene.meshes[0].faces[0]
        if hasattr(first_face, '__len__'):
            for face in scene.meshes[0].faces:
                if len(face) == 3:
                    triangle = MeshTriangle()
                    triangle.vertex_indices = [face[0], face[1], face[2]]
                    mesh.triangles.append(triangle)
        elif hasattr(first_face, 'indices'):
            for face in scene.meshes[0].faces:
                if len(face.indices) == 3:
                    triangle = MeshTriangle()
                    triangle.vertex_indices = [face.indices[0],
                                               face.indices[1],
                                               face.indices[2]]
                    mesh.triangles.append(triangle)
        else:
            raise MoveItCommanderException("Unable to build triangles from mesh due to mesh object structure")
        for vertex in scene.meshes[0].vertices:
            point = Point()
            point.x = vertex[0] * scale[0]
            point.y = vertex[1] * scale[1]
            point.z = vertex[2] * scale[2]
            mesh.vertices.append(point)
        co.meshes = [mesh]
        co.mesh_poses = [pose.pose]
        pyassimp.release(scene)
        return co
Пример #13
0
    def makeMesh(self, name, ps, filename):
        """
        Make a mesh collision object

        :param name: Name of the object
        :param ps: A pose stamped object pose message
        :param filename: The mesh file to load
        """
        if not use_pyassimp:
            rospy.logerr("pyassimp is broken on your platform, cannot load meshes")
            return
        scene = pyassimp.load(filename)
        if not scene.meshes:
            rospy.logerr("Unable to load mesh")
            return

        mesh = Mesh()
        for face in scene.meshes[0].faces:
            triangle = MeshTriangle()
            if len(face.indices) == 3:
                triangle.vertex_indices = [
                    face.indices[0],
                    face.indices[1],
                    face.indices[2],
                ]
            mesh.triangles.append(triangle)
        for vertex in scene.meshes[0].vertices:
            point = Point()
            point.x = vertex[0]
            point.y = vertex[1]
            point.z = vertex[2]
            mesh.vertices.append(point)
        pyassimp.release(scene)

        o = CollisionObject()
        o.header.stamp = rospy.Time.now()
        o.header.frame_id = ps.header.frame_id
        o.id = name
        o.meshes.append(mesh)
        o.mesh_poses.append(ps.pose)
        o.operation = o.ADD
        return o
Пример #14
0
def importFromFileToTIN(path):
  scene = pyassimp.load(path)
  results = []
  for index, mesh in enumerate(scene.meshes):
    prefix = 'TIN('
    postfix = ')'
    infix = ''
    triangles = mesh.faces
    vertices = mesh.vertices
    triangle_strings = []
    for triangle in triangles:
      indices = triangle.indices
      triangle_strings.append('((%f %f %f, %f %f %f, %f %f %f, %f %f %f))' \
              % (vertices[indices[0]].x, vertices[indices[0]].y, vertices[indices[0]].z, \
                 vertices[indices[1]].x, vertices[indices[1]].y, vertices[indices[1]].z, \
                 vertices[indices[2]].x, vertices[indices[2]].y, vertices[indices[2]].z, \
                 vertices[indices[0]].x, vertices[indices[0]].y, vertices[indices[0]].z))
    infix = ",".join(triangle_strings)
  tin_string = prefix + infix + postfix
  results.append(tin_string)
  pyassimp.release(scene)
  return results
    def makeMesh(self, name, pose, filename):
        if not use_pyassimp:
            rospy.logerr(
                'pyassimp is broken on your platform, cannot load meshes')
            return
        scene = pyassimp.load(filename)
        if not scene.meshes:
            rospy.logerr('Unable to load mesh')
            return

        mesh = Mesh()
        for face in scene.meshes[0].faces:
            triangle = MeshTriangle()
            if hasattr(face, "indices"):
                if len(face.indices) == 3:
                    triangle.vertex_indices = [
                        face.indices[0], face.indices[1], face.indices[2]
                    ]
            else:
                triangle.vertex_indices = [face[0], face[1], face[2]]

            mesh.triangles.append(triangle)
        for vertex in scene.meshes[0].vertices:
            point = Point()
            point.x = vertex[0]
            point.y = vertex[1]
            point.z = vertex[2]
            mesh.vertices.append(point)
        pyassimp.release(scene)

        o = CollisionObject()
        o.header.stamp = rospy.Time.now()
        o.header.frame_id = self._fixed_frame
        o.id = name
        o.meshes.append(mesh)
        o.mesh_poses.append(pose)
        o.operation = o.ADD
        return o
Пример #16
0
#!/usr/bin/env python

import rospy

rospy.init_node("stl")

file_name = rospy.get_param("~file_name")

if False:
    import vtk
    reader = vtk.vtkSTLReader()
    reader.SetFileName(fil_name)
    reader.Update()
    polydata = reader.GetOutput()
    print polydata.GetPoints()
    print polydata.GetPolys()

from pyassimp import pyassimp

scene = pyassimp.load(file_name)
print scene
mesh = scene.meshes[0]

print dir(mesh)
print mesh.faces[0].indices
# print mesh.vertices
# print mesh.

# TODO(lucasw) convert the vertices and indices to a shape_msg/Mesh
Пример #17
0
 def _load(self, filename):
     self.model = pyassimp.load(filename.encode('ascii'))
     self.meshes = []
     for index, mesh in enumerate(self.model.meshes):
         self.meshes.append(Mesh(mesh))
Пример #18
0
def main():
	# check arguments are valid
	if (len(argv) != 3):
		print("Please give the waypoint xml file as the first "\
			"parameter, and the folder \ncontaining the obj files "\
			"as the second: \neg. 'python pathing.py waypoints.xml "\
			"obj-file-directory'")
		exit()

	# load xml from unity
	waypoints = parse_waypoints(argv[1])
	for waypoint in waypoints:
		waypoint['paths'] = dict()
	# print(waypoints)

	# find all .obj files in the given directory
	if(not os.access(argv[2], os.F_OK)):
		print("Folder specified does not exist.")
		print("Please make sure the second argument is an absolute "\
				"path to a folder containing .obj files.")
		exit()
	obj_filenames = [join(argv[2], f) for f in os.listdir(argv[2]) \
		if isfile(join(argv[2], f)) and f[-4:] == '.obj']
	if(not obj_filenames):
		print("No .obj files in folder specified.")
		print("Please make sure the second argument is an absolute "\
				"path to a folder containing .obj files.")
		exit()
	# print(obj_filenames)

	# populate the graph with nodes
	g = Graph()
	for filename in obj_filenames:
		scene = pyassimp.load(filename)
		for mesh in scene.meshes:
			for face in mesh.faces:
				vs = [mesh.vertices[i] for i in face.indices]
				# minus signs compensate for unity's transformations
				# this looks like a difference between left-handed and
				# right-handed co-ordinate systems.
				v0 = (-vs[0].x, vs[0].y, vs[0].z)
				v1 = (-vs[1].x, vs[1].y, vs[1].z)
				v2 = (-vs[2].x, vs[2].y, vs[2].z)
				
				g.add_node(v0)
				g.add_node(v1)
				g.add_node(v2)

				# these weights get replaced later based on the weighting
				# of heuristics used
				g.add_edge_two_way(v0, v1, 0)
				g.add_edge_two_way(v0, v2, 0)
				g.add_edge_two_way(v1, v2, 0)

	# add a 'node' entry to each waypoint. This entry is the label used to
	# identify the waypoint with its corresponding graph node.
	for waypoint in waypoints:
		for node in g.nodes:
			if(close(waypoint['pos'], node)):
				waypoint['node'] = node
				break
	# for waypoint in waypoints:
	# 	if('node' in waypoint):
	# 		print(waypoint['node'])
	# print waypoints, "\n\n"

	# generate weights
	weights = list(product(xrange(6, 11, 1), xrange(0, 5, 1), xrange(0, 5, 1)))
	weights = [(float(x[0])/10, float(x[1])/10, float(x[2])/10) \
				for x in weights if sum(x) == 10]
	# print(weights)

	# find the astar path between every waypoint for each weighting
	for weight in weights:
		h = make_heuristic(weight)

		# modify graph edges based on this heuristic
		for node in g.nodes:
			for edge in g.edges[node]:
				edge['dist'] = h(node, edge['to'])

		# for each pair of waypoints
		for i in xrange(len(waypoints)-1):
			for j in xrange(i+1, len(waypoints)):
				# TODO: timing here
				repetitions = 50
				totaltime = 0
				for k in xrange(repetitions):
					start = time()
					shortest = g.astar(waypoints[i]['node'], \
										waypoints[j]['node'], \
										h)
					end = time()
					totaltime += end - start
				if(shortest):
					shortest['time'] = totaltime/repetitions
					if(weight not in waypoints[i]['paths']):
						waypoints[i]['paths'][weight] = list()
					waypoints[i]['paths'][weight].append(shortest)

					other = dict(shortest)
					other['path'] = list(shortest['path'])
					other['path'].reverse()
					if(weight not in waypoints[j]['paths']):
						waypoints[j]['paths'][weight] = list()
					waypoints[j]['paths'][weight].append(other)
				else:
					print 'No path between', waypoints[i]['title'], 'and', \
							waypoints[j]['title']

	# find the average times taken for each weighting
	# results = dict() # maps each weight to an average time and cost
	print('Times:')
	for weight in weights:
		totaltime = 0
		totalpaths = 0
		for waypoint in waypoints:
			for path in waypoint['paths'][weight]:
				totaltime += path['time']
				totalpaths += 1
		print weight, ":", float(totaltime)/float(totalpaths)

	print('Distances:')
	for weight in weights:
		totalcost = 0
		totalpaths = 0
		for waypoint in waypoints:
			for path in waypoint['paths'][weight]:
				totalcost += path['dist']
				totalpaths += 1
		print weight, ":", float(totalcost)/float(totalpaths)

	# for w in waypoints:
	# 	print w, "\n\n"

	# remove the time entries from the waypoints
	for weight in weights:
		for waypoint in waypoints:
			# print(len(waypoint['paths'][weight]))
			for path in waypoint['paths'][weight]:
				del path['time']

	# save the astar paths to xml
	write_waypoints(waypoints, argv[1][:-4] + '_out.xml')
Пример #19
0
def load_model(filename):
    return pyassimp.load(filename)
Пример #20
0
#!/usr/bin/env python

import rospy

from pyassimp import pyassimp

rospy.init_node("stl")

file_name = rospy.get_param("~file_name")

if False:
    import vtk
    reader = vtk.vtkSTLReader()
    reader.SetFileName(fil_name)
    reader.Update()
    polydata = reader.GetOutput()
    print polydata.GetPoints()
    print polydata.GetPolys()


scene = pyassimp.load(file_name)
print scene
mesh = scene.meshes[0]

print dir(mesh)
print mesh.faces[0].indices
# print mesh.vertices
# print mesh.

# TODO(lucasw) convert the vertices and indices to a shape_msg/Mesh
Пример #21
0
# process = process | 0x2 # JoinIdenticalVertices
process = process | 0x8 # Triangulate
process = process | 0x40 # Generate smooth normals
process = process | 0x100 # PretransformVertices (bake graph transforms, remove anmations)
process = process | 0x400 # ValidateDataStructure
process = process | 0x800 # ImproveCacheLocality
process = process | 0x1000 # RemoveRudendantMaterials
process = process | 0x1000 # RemoveRudendantMaterials
process = process | 0x2000 # FixInfacingNormals
process = process | 0x8000 # SortByPType
process = process | 0x10000 # FindDegenerates
process = process | 0x40000 # GenUVCoords - ake mapping functions as explicit coordinates.
process = process | 0x80000 # PretransformUVCoords
process = process | 0x200000 #OptimizeMeshes

scene = pyassimp.load(input_filename, process) # , process

o.write('{\n')
o.write('    "meshes": [\n')

textures = {}

def process_texture(filename):
	tex_fname = os.path.split(filename)[1]
	tex_in_path = os.path.abspath(base_path + '/' + filename)
	tex_out_path = output_dir + '/' + tex_fname.lower()
	
	if not tex_fname in textures:
		tex = Image.open(tex_in_path)
		ow2 = math.floor(math.log(tex.size[0]) / math.log(2))
		oh2 = math.floor(math.log(tex.size[1]) / math.log(2))
Пример #22
0
def main():
	# check arguments are valid
	if (len(argv) != 3):
		print("Please give the waypoint xml file as the first "\
			"parameter, and the folder \ncontaining the obj files "\
			"as the second: \neg. 'python pathing.py waypoints.xml "\
			"obj-file-directory'")
		exit()

	# load xml from unity
	waypoints = parse_waypoints(argv[1])
	# print(waypoints)

	# find all .obj files in the given directory
	if(not os.access(argv[2], os.F_OK)):
		print("Folder specified does not exist.")
		print("Please make sure the second argument is an absolute "\
				"path to a folder containing .obj files.")
		exit()
	obj_filenames = [join(argv[2], f) for f in os.listdir(argv[2]) \
		if isfile(join(argv[2], f)) and f[-4:] == '.obj']
	if(not obj_filenames):
		print("No .obj files in folder specified.")
		print("Please make sure the second argument is an absolute "\
				"path to a folder containing .obj files.")
		exit()
	# print(obj_filenames)

	# load .obj files into a Graph object
	g = Graph()
	for filename in obj_filenames:
		current_scene = pyassimp.load(filename)
		for mesh in current_scene.meshes:
			for face in mesh.faces:
				vs = [mesh.vertices[i] for i in face.indices]
				r = lambda x: round(x, 5)
				# minus signs compensate for unity's transformations
				# this looks like a difference between left-handed and
				# right-handed co-ordinate systems.
				v0 = (-vs[0].x, vs[0].y, vs[0].z)
				v1 = (-vs[1].x, vs[1].y, vs[1].z)
				v2 = (-vs[2].x, vs[2].y, vs[2].z)
				
				g.add_node(v0)
				g.add_node(v1)
				g.add_node(v2)
				
				g.add_edge_two_way(v0, v1, dist(v0, v1))
				g.add_edge_two_way(v0, v2, dist(v0, v2))
				g.add_edge_two_way(v1, v2, dist(v1, v2))

	# add a 'node' entry to each waypoint. This node gives the
	# actual co-ordinates as found in the graph.
	for waypoint in waypoints:
		for node in g.nodes:
			if(close(waypoint['pos'], node)):
				waypoint['node'] = node
				break
	# print waypoints, "\n\n"

	# find the astar path between every waypoint for each weighting
	for waypoint in waypoints:
		waypoint['paths'] = dict()

	weights = [(1,0,0)]#, (0.5, 0.5, 0), (0.5, 0, 0.5)]

	# for each pair of waypoints
	for i in xrange(len(waypoints)-1):
		for j in xrange(i+1, len(waypoints)):
			# for each weighting
			for weight in weights:
				shortest = g.astar(waypoints[i]['node'], \
									waypoints[j]['node'], \
									make_heuristic(weight))
				if(shortest):
					if(weight not in waypoints[i]['paths']):
						waypoints[i]['paths'][weight] = list()
					waypoints[i]['paths'][weight].append(shortest)

					other = dict(shortest)
					other['path'] = list(shortest['path'])
					other['path'].reverse()
					if(weight not in waypoints[j]['paths']):
						waypoints[j]['paths'][weight] = list()
					waypoints[j]['paths'][weight].append(other)
				else:
					print 'No path between', waypoints[i]['title'], 'and', \
							waypoints[j]['title']

	for w in waypoints:
		print w, "\n\n"
	# save the astar paths to xml
	write_waypoints(waypoints, argv[1][:-4] + '_out.xml')
Пример #23
0
#!/usr/bin/env python2.7

import sys
from pyassimp import pyassimp

print("BEGIN")

for obj in sys.argv[1:]:
    try:
        scene = pyassimp.load(obj)
    except pyassimp.AssimpError:
        print("Ei voitu ladata {}".format(obj))
    else:
        xcoords = []
        ycoords = []
        zcoords = []
        for mesh in scene.meshes:
            for vertex in mesh.vertices:
                xcoords.append(vertex[0])
                ycoords.append(vertex[1])
                zcoords.append(vertex[2])

        mincoord = (min(xcoords), min(ycoords), min(zcoords))
        maxcoord = (max(xcoords), max(ycoords), max(zcoords))

        obj = obj.split('/')

        filename = obj[-1]
        filename = filename.replace('_hd.obj', '')
        path = obj[:-1]
Пример #24
0
def attribute(doc, name, data):
    attribute = doc.createElement('attribute')
    attribute.setAttribute('id', name)
    for index, item in enumerate(data):
        components = len(item._fields_)
        typename = type(item[0]).__name__
        position = doc.createElement(typename + str(components))
        for fieldIndex, field in enumerate(item._fields_):
            position.setAttribute(field[0], str(item[fieldIndex]))
        attribute.appendChild(position)
    return attribute

# aiProcess_GenUVCoords | aiProcess_OptimizeMeshes | aiProcess_SortByPType | aiProcess_Triangulate
processing = 0x40000 | 0x200000 | 0x8000 | 0x8
scene = pyassimp.load(sys.argv[1], 8)

doc = minidom.Document()
obj = doc.createElement('object')

intAttrName = ['i','j','k','l']

for index, mesh in enumerate(scene.meshes):
    meshElement = doc.createElement('mesh')
    meshElement.setAttribute('index', str(index))
    # vertices
    positions = attribute(doc, 'position', mesh.vertices)
    meshElement.appendChild(positions)
    # normals
    if any(mesh.normals):
        normals = attribute(doc, 'normal', mesh.normals)