Example #1
0
    def init_data(self,normalization=True):
        verts, faces, normals, nothin = io.read_mesh("data/%s_normalized6.obj"%(self.mesh_name))

        if normalization:
           centroid = np.mean(verts, axis=0, keepdims=True)
           furthest_distance = np.amax(np.sqrt(np.sum((verts - centroid) ** 2, axis=-1)), keepdims=True)
          # verts = (verts - centroid) / furthest_distance

        print('--furthest_distance,',furthest_distance)
        #verts = verts*1.3
        meshdata = md.MeshData(vertices=verts, faces=faces)
        self.mesh = MyMeshData()
        self.mesh.set_vertices(verts)
        self.mesh.set_faces(faces)
        colors = np.tile(DEFAULT_COLOR, (verts.shape[0], 1))
        self.mesh.set_vertex_colors(colors)
        vertices, filled, outline = self.mesh.get_glTriangles()
        self.set_data(vertices, filled, outline)

        self.faces = self.mesh.get_faces()
        # print(faces.shape)
        face_normals = self.mesh.get_face_normals()
        vertices = self.mesh.get_vertices()
        # print(type(vertices))
        self.vertice_wrapper = np.ones([vertices.shape[0], 4])
        self.vertice_wrapper[:, :-1] = verts

        self.face_normals_wrapper = np.ones([face_normals.shape[0], 4])
        self.face_normals_wrapper[:, :-1] = face_normals
Example #2
0
    def update(self, t, crazyflies):
        if len(self.cfs) == 0:
            verts, faces, normals, nothin = io.read_mesh(CF_MESH_PATH)
            for i, cf in enumerate(crazyflies):
                color = cf.ledRGB
                mesh = scene.visuals.Mesh(parent=self.view.scene,
                    vertices=verts, faces=faces,
                    color=color, shading='smooth')
                mesh.transform = transforms.MatrixTransform()
                self.cfs.append(mesh)
                self.color_cache.append(color)

        for i in range(0, len(self.cfs)):
            x, y, z = crazyflies[i].position()
            roll, pitch, yaw = crazyflies[i].rpy()
            self.cfs[i].transform.reset()
            self.cfs[i].transform.rotate(90, (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(roll), (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(pitch), (0, 1, 0))
            self.cfs[i].transform.rotate(math.degrees(yaw), (0, 0, 1))
            self.cfs[i].transform.scale((0.001, 0.001, 0.001))
            self.cfs[i].transform.translate((x, y, z))
            # vispy does not do this check
            color = crazyflies[i].ledRGB
            if color != self.color_cache[i]:
                self.color_cache[i] = color
                self.cfs[i].color = color # sets dirty flag

        self.canvas.app.process_events()
Example #3
0
def load_and_cache_mesh(file_path, url=None):
    """Load and save a binary-cached version of a mesh"""
    vertices, faces, normals, texcoords = io.read_mesh(file_path)
    if url is None:
        np.savez(file_path, vertices=vertices, faces=faces, normals=normals)
    else:
        np.savez(file_path, vertices=vertices, faces=faces, normals=normals, url=url)
    return vertices, faces, normals, texcoords
Example #4
0
 def load_mesh(self):
     verts, faces, normals, texcoords = io.read_mesh('mesh.obj')
     data = np.zeros(verts.shape[0], [('vertex', np.float32, 3),
                         ('normal', np.float32, 3)])
     data['vertex'] = verts
     data['normal'] = normals
     vertexbuffer = gloo.VertexBuffer(data)
     self.indices = gloo.IndexBuffer(faces)
     self.program.bind(vertexbuffer)
Example #5
0
def create_sphere():
    vtype = [('a_position', np.float32, 3),
             ('a_texcoord', np.float32, 3)]
    V, F, N, T = io.read_mesh(Path('./obj/sphere.obj'))
    f_buf = gloo.IndexBuffer(F)
    v_buf = np.zeros(len(V), dtype=vtype)
    v_buf['a_position'] = V
    v_buf['a_texcoord'] = T
    v_buf = gloo.VertexBuffer(v_buf)
    return v_buf, f_buf
Example #6
0
def drawOutput(organism):
    fname1 = 'teapot.obj'
    fname2 = 'sphere.obj'
    fig = plot.Fig(title=TITLE)
    fig[0, 0].mesh(*io.read_mesh(fname1)[:2])
        
    arr = io.read_mesh(fname2)[:2]
    for dot in organism:
        a = arr
        for elem in a[0]:
            elem[0] = elem[0] * 1 + dot[0]
            elem[1] = elem[1] * 1 + dot[1]
            elem[2] = elem[2] * 1 + dot[2]
        #print('workin')
    fig[0, 0].mesh(*arr, color=(1, 1, 0.1))
    
    vispy.
            
    app.run()
Example #7
0
def teapot ():
    # this data type will keep the data recieved from the obj file organized.
    # vispy will automatically separate out the attributes included here and
    # set the vertex shader accordingly.
    vtype = [('a_position', np.float32, 3),
             ('a_normal', np.float32, 3)]
    # the last return value will be None since this object does not have any texture coordinates.
    V, F, N, _ = io.read_mesh(Path('./obj/teapot.obj'))
    vertices = np.zeros( len(V), dtype=vtype )
    vertices['a_position'] = V
    vertices['a_normal'] = N
    return vertices, F
Example #8
0
    def __init__(self):
        visuals.Visual.__init__(self)

        # Create an interesting mesh shape for demonstration.
        fname = io.load_data_file('orig/triceratops.obj.gz')
        vertices, faces, normals, tex = io.read_mesh(fname)

        self._ibo = gloo.IndexBuffer(faces)

        self.program = visuals.shaders.ModularProgram(vertex_shader,
                                                      fragment_shader)
        self.program.vert['position'] = gloo.VertexBuffer(vertices)
Example #9
0
def load_and_cache_mesh(file_path, url=None):
    '''Load and save a binary-cached version of a mesh'''
    vertices, faces, normals, texcoords = io.read_mesh(file_path)
    if url is None:
        np.savez(file_path, vertices=vertices, faces=faces, normals=normals)
    else:
        np.savez(file_path,
                 vertices=vertices,
                 faces=faces,
                 normals=normals,
                 url=url)
    return vertices, faces, normals, texcoords
Example #10
0
def test_wavefront():
    """Test wavefront reader"""
    fname_mesh = load_data_file('orig/triceratops.obj.gz')
    fname_out = op.join(temp_dir, 'temp.obj')
    mesh1 = read_mesh(fname_mesh)
    assert_raises(IOError, read_mesh, 'foo.obj')
    assert_raises(ValueError, read_mesh, op.abspath(__file__))
    assert_raises(ValueError, write_mesh, fname_out, *mesh1, format='foo')
    write_mesh(fname_out, mesh1[0], mesh1[1], mesh1[2], mesh1[3])
    assert_raises(IOError, write_mesh, fname_out, *mesh1)
    write_mesh(fname_out, *mesh1, overwrite=True)
    mesh2 = read_mesh(fname_out)
    assert_equal(len(mesh1), len(mesh2))
    for m1, m2 in zip(mesh1, mesh2):
        if m1 is None:
            assert_equal(m2, None)
        else:
            assert_allclose(m1, m2, rtol=1e-5)
    # test our efficient normal calculation routine
    assert_allclose(mesh1[2], _slow_calculate_normals(mesh1[0], mesh1[1]),
                    rtol=1e-7, atol=1e-7)
    def __init__(self):
        visuals.Visual.__init__(self)

        # Create an interesting mesh shape for demonstration.
        fname = io.load_data_file('orig/triceratops.obj.gz')
        vertices, faces, normals, tex = io.read_mesh(fname)

        self._ibo = gloo.IndexBuffer(faces)

        self.program = visuals.shaders.ModularProgram(vertex_shader,
                                                      fragment_shader)
        self.program.vert['position'] = gloo.VertexBuffer(vertices)
Example #12
0
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(512, 512),
                            title='Monkey',
                            keys='interactive')
        verts, faces, normals, texcoords = io.read_mesh(
            "../model/monkey/monkey.obj")
        obj = MeshData(verts, faces)

        self.program = gloo.Program(vert=vertex, frag=fragment)

        V = verts.astype('float32')

        F = obj.get_faces().astype('uint32')

        E = obj.get_edges().astype('uint32')

        C = np.array([(1, 1, 1, 1)])
        for i in range(len(V) - 1):
            if i % 2 != 0:
                C = np.append(C, [(1, 1, 1, 1)], axis=0)
            else:
                C = np.append(C, [(0, 0, 0, 1)], axis=0)

        self.program['a_position'] = V
        self.program['a_color'] = C.astype('float32')
        self.F = gloo.IndexBuffer(F)
        self.E = gloo.IndexBuffer(E)

        gloo.set_viewport(0, 0, *self.physical_size)
        gloo.set_polygon_offset(1.0, 1.0)

        # intialize transformation matrix
        view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        projection = np.eye(4, dtype=np.float32)

        # set view
        view = translate((0, 0, -5))
        self.program['u_model'] = model
        self.program['u_view'] = view
        self.program['u_projection'] = projection

        # bind a timer
        self.timer = app.Timer('auto', self.on_timer)
        self.theta = 0.0
        self.phi = 0.0
        self.timer.start()

        # show the canvas
        self.show()
Example #13
0
    def __init__(self):
        visuals.Visual.__init__(self, vertex_shader, fragment_shader)

        # Create an interesting mesh shape for demonstration.
        fname = io.load_data_file('orig/triceratops.obj.gz')
        vertices, faces, normals, tex = io.read_mesh(fname)

        self._ibo = gloo.IndexBuffer(faces)

        self.shared_program.vert['position'] = gloo.VertexBuffer(vertices)
        # self.program.vert['normal'] = gloo.VertexBuffer(normals)
        self.set_gl_state('additive', cull_face=False)
        self._draw_mode = 'triangles'
        self._index_buffer = self._ibo
Example #14
0
    def __init__(self):
        visuals.Visual.__init__(self, vertex_shader, fragment_shader)

        # Create an interesting mesh shape for demonstration.
        fname = io.load_data_file('orig/triceratops.obj.gz')
        vertices, faces, normals, tex = io.read_mesh(fname)

        self._ibo = gloo.IndexBuffer(faces)

        self.shared_program.vert['position'] = gloo.VertexBuffer(vertices)
        # self.program.vert['normal'] = gloo.VertexBuffer(normals)
        self.set_gl_state('additive', cull_face=False)
        self._draw_mode = 'triangles'
        self._index_buffer = self._ibo
Example #15
0
def test_wavefront():
    """Test wavefront reader"""
    fname_mesh = load_data_file('orig/triceratops.obj.gz')
    fname_out = op.join(temp_dir, 'temp.obj')
    mesh1 = read_mesh(fname_mesh)
    assert_raises(IOError, read_mesh, 'foo.obj')
    assert_raises(ValueError, read_mesh, op.abspath(__file__))
    assert_raises(ValueError, write_mesh, fname_out, *mesh1, format='foo')
    write_mesh(fname_out, mesh1[0], mesh1[1], mesh1[2], mesh1[3])
    assert_raises(IOError, write_mesh, fname_out, *mesh1)
    write_mesh(fname_out, *mesh1, overwrite=True)
    mesh2 = read_mesh(fname_out)
    assert_equal(len(mesh1), len(mesh2))
    for m1, m2 in zip(mesh1, mesh2):
        if m1 is None:
            assert_equal(m2, None)
        else:
            assert_allclose(m1, m2, rtol=1e-5)
    # test our efficient normal calculation routine
    assert_allclose(mesh1[2],
                    _slow_calculate_normals(mesh1[0], mesh1[1]),
                    rtol=1e-7,
                    atol=1e-7)
Example #16
0
    def update(self, t, crazyflies):
        if len(self.cfs) == 0:
            verts, faces, normals, nothin = io.read_mesh(CF_MESH_PATH)
            for i, cf in enumerate(crazyflies):
                color = cf.ledRGB
                mesh = scene.visuals.Mesh(
                    parent=self.view.scene,
                    vertices=verts,
                    faces=faces,
                    color=color,
                    shading="smooth",
                )
                mesh.light_dir = (0.1, 0.1, 1.0)
                mesh.shininess = 0.01
                mesh.ambient_light_color = [0.5] * 3
                mesh.transform = transforms.MatrixTransform()
                self.cfs.append(mesh)
                self.color_cache.append(color)

        positions = np.stack(cf.position() for cf in crazyflies)

        for i in range(0, len(self.cfs)):
            x, y, z = crazyflies[i].position()
            roll, pitch, yaw = crazyflies[i].rpy()
            self.cfs[i].transform.reset()
            self.cfs[i].transform.rotate(-90, (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(roll), (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(pitch), (0, 1, 0))
            self.cfs[i].transform.rotate(math.degrees(yaw), (0, 0, 1))
            self.cfs[i].transform.scale((0.002, 0.002, -0.002))
            self.cfs[i].transform.translate(positions[i])
            # vispy does not do this check
            color = crazyflies[i].ledRGB
            if color != self.color_cache[i]:
                self.color_cache[i] = color
                self.cfs[i].color = color  # sets dirty flag

        # Update graph line segments to match new Crazyflie positions.
        if self.graph is not None:
            for k, (i, j) in enumerate(self.graph_edges):
                self.graph_lines[2 * k, :] = positions[i]
                self.graph_lines[2 * k + 1, :] = positions[j]
            self.graph.set_data(self.graph_lines)

        self.canvas.app.process_events()
Example #17
0
def test_meshio():
    '''Test meshio i/o'''
    vertices = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.], [-.0, 1.0, 0.],
                         [1.0, 1.0, 0.]])

    faces = np.array([[0, 1, 3], [1, 2, 3]])
    fname_out = op.join(temp_dir, 'temp.vtk')
    write_mesh(fname_out,
               vertices=vertices,
               faces=faces,
               normals=None,
               texcoords=None,
               overwrite=True,
               reshape_faces=False)
    out_vertices, out_faces, _, _ = read_mesh(fname_out)

    assert np.all(np.abs(out_vertices - vertices) < 1.0e-14)
    assert np.all(out_faces == faces)
Example #18
0
  def __init__(self):
    app.Canvas.__init__(self, keys='interactive', size=(800, 600))

    dirname = path.join(path.abspath(path.curdir),'data')
    positions, faces, normals, texcoords = \
      read_mesh(load_data_file('cube.obj', directory=dirname))

    self.filled_buf = gloo.IndexBuffer(faces)

    if False:
      self.program = gloo.Program(VERT_TEX_CODE, FRAG_TEX_CODE)
      self.program['a_position'] = gloo.VertexBuffer(positions)
      self.program['a_texcoord'] = gloo.VertexBuffer(texcoords)
      self.program['u_texture'] = gloo.Texture2D(load_crate())
    else:
      self.program = gloo.Program(VERT_COLOR_CODE, FRAG_COLOR_CODE)
      self.program['a_position'] = gloo.VertexBuffer(positions)
      self.program['u_color'] = 1, 0, 0, 1

    self.view = translate((0, 0, -5))
    self.model = np.eye(4, dtype=np.float32)

    gloo.set_viewport(0, 0, self.physical_size[0], self.physical_size[1])
    self.projection = perspective(45.0, self.size[0] /
                                  float(self.size[1]), 2.0, 10.0)

    self.program['u_projection'] = self.projection

    self.program['u_model'] = self.model
    self.program['u_view'] = self.view

    self.theta = 0
    self.phi = 0

    gloo.set_clear_color('gray')
    gloo.set_state('opaque')
    gloo.set_polygon_offset(1, 1)

    self._timer = app.Timer('auto', connect=self.on_timer, start=True)

    self.show()
Example #19
0
def mesh_viewer(fname, camera="arcball", bgcolor="black"):

    canvas = scene.SceneCanvas(keys="interactive", show=True, bgcolor=bgcolor)
    view = canvas.central_widget.add_view()

    view.camera = camera

    verts, faces, normals, nothin = io.read_mesh(fname)
    vc = np.zeros((len(verts), 4))
    fc = np.zeros((len(faces), 4))

    vc[:, 3] = 1
    vc[:, 0] = 1

    fc[:, 3] = 1
    fc[:, 1] = 1
    mesh = scene.visuals.Mesh(vertices=verts,
                              faces=faces,
                              face_colors=fc,
                              vertex_colors=vc,
                              mode="triangles")
    view.add(mesh)
    app.run()
Example #20
0
    def update(self, t, crazyflies):
        if len(self.cfs) == 0:
            verts, faces, normals, nothin = io.read_mesh(
                os.path.join(os.path.dirname(__file__), "crazyflie2.obj.gz"))
            for i in range(0, len(crazyflies)):
                mesh = scene.visuals.Mesh(vertices=verts,
                                          shading='smooth',
                                          faces=faces,
                                          parent=self.view.scene)
                mesh.transform = transforms.MatrixTransform()
                self.cfs.append(mesh)

        for i in range(0, len(self.cfs)):
            x, y, z = crazyflies[i].position()
            roll, pitch, yaw = crazyflies[i].rpy()
            self.cfs[i].transform.reset()
            self.cfs[i].transform.rotate(90, (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(roll), (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(pitch), (0, 1, 0))
            self.cfs[i].transform.rotate(math.degrees(yaw), (0, 0, 1))
            self.cfs[i].transform.scale((0.001, 0.001, 0.001))
            self.cfs[i].transform.translate((x, y, z))

        self.canvas.app.process_events()
Example #21
0
    vhandle.append(mesh.add_vertex(np.array([1.5, 0.5, 0])))

    # Add faces
    faces = [[0, 1, 3], [1, 2, 3], [2, 4, 3]]
    for v in faces:
        face_vhandles = []
        face_vhandles.append(vhandle[v[0]])
        face_vhandles.append(vhandle[v[1]])
        face_vhandles.append(vhandle[v[2]])
        mesh.add_face(face_vhandles)

    decimated = decimate(mesh, 3)
    print(decimated.n_vertices())
    print(mesh.n_vertices())

    assert decimated.n_vertices() == 3


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('input_mesh')
    parser.add_argument('output_mesh')
    parser.add_argument('--vertices', type=int, default=6890)
    args = parser.parse_args()

    mesh = openmesh.read_trimesh(args.input_mesh)
    decimated = decimate(mesh, args.vertices)
    openmesh.write_mesh(args.output_mesh, decimated)
    vertices1, faces1, normals, nothin  = read_mesh("faust_ref.obj")
    vertices2, faces, normals, nothin  = read_mesh("testtest.obj")
Example #22
0
FRAG_CODE = """
uniform sampler2D u_texture;
varying vec2 v_texcoord;

void main()
{
    float ty = v_texcoord.y;
    float tx = sin(ty*50.0)*0.01 + v_texcoord.x;
    gl_FragColor = texture2D(u_texture, vec2(tx, ty));
}
"""


# Read cube data
positions, faces, normals, texcoords = \
    read_mesh(load_data_file('orig/cube.obj'))
colors = np.random.uniform(0, 1, positions.shape).astype('float32')

faces_buffer = gloo.IndexBuffer(faces.astype(np.uint16))


class Canvas(app.Canvas):

    def __init__(self, **kwargs):
        app.Canvas.__init__(self, size=(400, 400), **kwargs)

        self.program = gloo.Program(VERT_CODE, FRAG_CODE)

        # Set attributes
        self.program['a_position'] = gloo.VertexBuffer(positions)
        self.program['a_texcoord'] = gloo.VertexBuffer(texcoords)
Example #23
0
fragment = """
void main() {
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
"""

program = gloo.Program(vertex, fragment)

program['a_position'] = np.c_[
    np.random.uniform(-0.5, +0.5, 1000).astype(np.float32),
    np.random.uniform(-0.5, +0.5, 1000).astype(np.float32)]
''''''
fname1 = 'teapot.obj'
fname2 = 'sphere.obj'
fig = plot.Fig()
fig[0, 0].mesh(*io.read_mesh(fname1)[:2])
fig[0, 0].mesh(*io.read_mesh(fname2)[:2])
''''''


@c.connect
def on_resize(event):
    gloo.set_viewport(0, 0, *event.size)


@c.connect
def on_draw(event):
    gloo.clear((0, 0, 0, 1))
    program.draw('points')

Example #24
0
import argparse

from vispy import app, scene
from vispy.io import read_mesh, load_data_file
from vispy.scene.visuals import Mesh
from vispy.scene import transforms
from vispy.visuals.filters import ShadingFilter, WireframeFilter

parser = argparse.ArgumentParser()
default_mesh = load_data_file('orig/triceratops.obj.gz')
parser.add_argument('--mesh', default=default_mesh)
parser.add_argument('--shininess', default=100)
parser.add_argument('--wireframe-width', default=1)
args, _ = parser.parse_known_args()

vertices, faces, normals, texcoords = read_mesh(args.mesh)

canvas = scene.SceneCanvas(keys='interactive', bgcolor='white')
view = canvas.central_widget.add_view()

view.camera = 'arcball'
view.camera.depth_value = 1e3

# Create a colored `MeshVisual`.
mesh = Mesh(vertices, faces, color=(.5, .7, .5, 1))
mesh.transform = transforms.MatrixTransform()
mesh.transform.rotate(90, (1, 0, 0))
mesh.transform.rotate(-45, (0, 0, 1))
view.add(mesh)

# Use filters to affect the rendering of the mesh.
Example #25
0
FRAG_CODE = """
uniform sampler2D u_texture;
varying vec2 v_texcoord;

void main()
{   
    float ty = v_texcoord.y;
    float tx = sin(ty*50.0)*0.01 + v_texcoord.x;
    gl_FragColor = texture2D(u_texture, vec2(tx, ty));
}
"""


# Read cube data
positions, faces, normals, texcoords = io.read_mesh('cube.obj')
colors = np.random.uniform(0,1,positions.shape).astype('float32')

faces_buffer = oogl.ElementBuffer(faces.astype(np.uint16))


class Canvas(app.Canvas):
    
    def __init__(self, **kwargs):
        app.Canvas.__init__(self, **kwargs)
        self.geometry = 0, 0, 400, 400
        
        self.program = oogl.Program(VERT_CODE, FRAG_CODE)
        
        # Set attributes
        self.program['a_position'] = oogl.VertexBuffer(positions)
Example #26
0
FRAG_CODE = """
uniform sampler2D u_texture;
varying vec2 v_texcoord;

void main()
{
    float ty = v_texcoord.y;
    float tx = sin(ty*50.0)*0.01 + v_texcoord.x;
    gl_FragColor = texture2D(u_texture, vec2(tx, ty));
}
"""

# Read cube data
positions, faces, normals, texcoords = \
    read_mesh(load_data_file('orig/cube.obj'))
colors = np.random.uniform(0, 1, positions.shape).astype('float32')

faces_buffer = gloo.IndexBuffer(faces.astype(np.uint16))


class Canvas(app.Canvas):
    def __init__(self, **kwargs):
        app.Canvas.__init__(self, **kwargs)
        self.geometry = 0, 0, 400, 400

        self.program = gloo.Program(VERT_CODE, FRAG_CODE)

        # Set attributes
        self.program['a_position'] = gloo.VertexBuffer(positions)
        self.program['a_texcoord'] = gloo.VertexBuffer(texcoords)
Example #27
0
 def __init__(self):
     GpaphicBlueprint.__init__(self)
     vertices, indices, normals, _ = io.read_mesh('3.obj')
     self._mesh = Mesh(vertices, indices)
     self._color = (1, .5, .2)
     self.buildProgram()
Example #28
0
"""
Surface normals wireframe
=========================

Display a 3D mesh with normals and wireframe
"""

from vispy.io import read_mesh, load_data_file
import napari

vert, faces, _, _ = read_mesh(load_data_file('orig/triceratops.obj.gz'))

# put the mesh right side up, scale it up (napari#3477) and fix faces handedness
vert *= -100
faces = faces[:, ::-1]

viewer = napari.Viewer(ndisplay=3)
surface = viewer.add_surface(data=(vert, faces))

# enable normals and wireframe
surface.normals.face.visible = True
surface.normals.vertex.visible = True
surface.wireframe.visible = True

if __name__ == '__main__':
    napari.run()
Example #29
0
    def update(self, t, crazyflies):
        if len(self.cfs) == 0:
            verts, faces, normals, nothin = io.read_mesh(CF_MESH_PATH)
            for i, cf in enumerate(crazyflies):
                color = cf.ledRGB
                mesh = scene.visuals.Mesh(
                    parent=self.view.scene,
                    vertices=verts,
                    faces=faces,
                    color=color,
                    shading="smooth",
                )
                mesh.light_dir = (0.1, 0.1, 1.0)
                mesh.shininess = 0.01
                mesh.ambient_light_color = [0.5] * 3
                mesh.transform = transforms.MatrixTransform()
                self.cfs.append(mesh)
                self.led_color_cache.append(color)

        if self.ellipsoid_radii is not None and self.ellipsoids is None:
            sphere_mesh = geometry.create_sphere(radius=1.0)
            self.ellipsoids = [
                scene.visuals.Mesh(
                    parent=self.view.scene,
                    meshdata=sphere_mesh,
                    color=ELLIPSOID_COLOR_OK,
                    shading="smooth",
                ) for _ in self.cfs
            ]
            for ell in self.ellipsoids:
                ell.light_dir = (0.1, 0.1, 1.0)
                ell.shininess = 0.0
                ell.ambient_light_color = [0.5] * 3
                ell.transform = transforms.MatrixTransform()

        positions = np.stack([cf.position() for cf in crazyflies])

        for i in range(0, len(self.cfs)):
            x, y, z = crazyflies[i].position()
            roll, pitch, yaw = crazyflies[i].rpy()
            self.cfs[i].transform.reset()
            self.cfs[i].transform.rotate(-90, (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(roll), (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(pitch), (0, 1, 0))
            self.cfs[i].transform.rotate(math.degrees(yaw), (0, 0, 1))
            self.cfs[i].transform.scale((0.002, 0.002, -0.002))
            self.cfs[i].transform.translate(positions[i])
            # vispy does not do this check
            color = crazyflies[i].ledRGB
            if color != self.led_color_cache[i]:
                self.led_color_cache[i] = color
                self.cfs[i].color = color  # sets dirty flag

        # Update graph line segments to match new Crazyflie positions.
        if self.graph is not None:
            for k, (i, j) in enumerate(self.graph_edges):
                self.graph_lines[2 * k, :] = positions[i]
                self.graph_lines[2 * k + 1, :] = positions[j]
            self.graph.set_data(self.graph_lines)

        # Update collsiion ellipsoids.
        if self.ellipsoids is not None:
            colliding = util.check_ellipsoid_collisions(
                positions, self.ellipsoid_radii)
            for i, pos in enumerate(positions):
                ell = self.ellipsoids[i]
                tf = ell.transform
                tf.reset()
                tf.scale(self.ellipsoid_radii)
                tf.translate(pos)
                new_color = ELLIPSOID_COLOR_COLLISION if colliding[
                    i] else ELLIPSOID_COLOR_OK
                if not (new_color
                        == ell.color):  # vispy Color lacks != override.
                    ell.color = new_color

        self.canvas.app.process_events()
Example #30
0
 def _parseObjFile(self, filename):
     """ """
     self._vertices, self._faces, self._normals, self._textureCoords = read_mesh(self._filePath + filename)
Example #31
0
from vispy import app, scene
from vispy.io import imread, load_data_file, read_mesh
from vispy.scene.visuals import Mesh
from vispy.scene import transforms
from vispy.visuals.filters import TextureFilter

parser = argparse.ArgumentParser()
parser.add_argument('--shading',
                    default='smooth',
                    choices=['none', 'flat', 'smooth'],
                    help="shading mode")
args, _ = parser.parse_known_args()

mesh_path = load_data_file('spot/spot.obj.gz')
texture_path = load_data_file('spot/spot.png')
vertices, faces, normals, texcoords = read_mesh(mesh_path)
texture = np.flipud(imread(texture_path))

canvas = scene.SceneCanvas(keys='interactive',
                           bgcolor='white',
                           size=(800, 600))
view = canvas.central_widget.add_view()

view.camera = 'arcball'
# Adapt the depth to the scale of the mesh to avoid rendering artefacts.
view.camera.depth_value = 10 * (vertices.max() - vertices.min())

shading = None if args.shading == 'none' else args.shading
mesh = Mesh(vertices, faces, shading=shading, color='white')
mesh.transform = transforms.MatrixTransform()
mesh.transform.rotate(90, (1, 0, 0))
Example #32
0
FRAG_CODE = """
uniform sampler2D u_texture;
varying vec2 v_texcoord;

void main()
{
    float ty = v_texcoord.y;
    float tx = sin(ty*50.0)*0.01 + v_texcoord.x;
    gl_FragColor = texture2D(u_texture, vec2(tx, ty));
}
"""


# Read cube data
positions, faces, normals, texcoords = read_mesh(load_data_file("orig/cube.obj"))
colors = np.random.uniform(0, 1, positions.shape).astype("float32")

faces_buffer = gloo.IndexBuffer(faces.astype(np.uint16))


class Canvas(app.Canvas):
    def __init__(self, **kwargs):
        app.Canvas.__init__(self, size=(400, 400), **kwargs)

        self.program = gloo.Program(VERT_CODE, FRAG_CODE)

        # Set attributes
        self.program["a_position"] = gloo.VertexBuffer(positions)
        self.program["a_texcoord"] = gloo.VertexBuffer(texcoords)
Example #33
0
    def update(self, t, crazyflies, spheres=[], obstacles=[], crumb=None):
        if len(self.cfs
               ) == 0:  # add the crazyflies if they don't exist already
            verts, faces, normals, nothin = io.read_mesh(
                os.path.join(os.path.dirname(__file__), "crazyflie2.obj.gz"))
            for i in range(0, len(crazyflies)):
                mesh = scene.visuals.Mesh(vertices=verts,
                                          shading='smooth',
                                          faces=faces,
                                          parent=self.view.scene)
                mesh.transform = transforms.MatrixTransform()
                self.cfs.append(mesh)

        if crumb is not None:  # add breadcrumb trails behind drones if requested.
            if len(self.crumbs) == 0 or np.linalg.norm(self.crumbs[-1] -
                                                       crumb) > 0.05:
                # Only add them if drone is sufficiently far from the last breakcrumb.
                self.crumbs.append(crumb)
                self.markers.set_data(np.array(self.crumbs),
                                      size=5,
                                      face_color='black',
                                      edge_color='black')
        elif self.crumbs:
            self.markers.set_data(np.array([[1e10, 1e10]]))
            self.crumbs = []

        if spheres:  # sphere: (position, color)
            if not self.spheres:
                for pos, color in spheres:
                    self.spheres.append(
                        scene.visuals.Sphere(radius=.02,
                                             color=color,
                                             parent=self.view.scene))
                    self.spheres[-1].transform = transforms.STTransform(
                        translate=pos)
            for i, (pos, color) in enumerate(spheres):
                self.spheres[i].transform.translate = pos

        if obstacles:  # cube : (position, size)
            if not self.obstacles:
                for pos, size, _ in obstacles:
                    self.obstacles.append(
                        scene.visuals.Cube(size=size,
                                           color=random.choice(
                                               get_color_names()),
                                           parent=self.view.scene))
                    self.obstacles[-1].transform = transforms.STTransform(
                        translate=pos)
            for i, (pos, size, _) in enumerate(obstacles):
                self.obstacles[i].transform.translate = pos

        # update the location of the crazyflies if they have changed
        for i in range(0, len(self.cfs)):
            x, y, z = crazyflies[i].position(t)
            roll, pitch, yaw = crazyflies[i].rpy(t)
            self.cfs[i].transform.reset()
            self.cfs[i].transform.rotate(90, (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(roll), (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(pitch), (0, 1, 0))
            self.cfs[i].transform.rotate(math.degrees(yaw), (0, 0, 1))
            self.cfs[i].transform.scale((0.001, 0.001, 0.001))
            self.cfs[i].transform.translate((x, y, z))

        self.canvas.app.process_events()  # redraw the canvas
from vispy import scene, io

canvas = scene.SceneCanvas(keys='interactive', show=True)
view = canvas.central_widget.add_view()

verts, faces, normals, nothing = io.read_mesh("output/000002._mesh.obj")

mesh = scene.visuals.Mesh(vertices=verts, faces=faces, shading='smooth')

view.add(mesh)

view.camera = scene.TurntableCamera()
view.camera.depth_value = 10

if __name__ == '__main__':
    canvas.app.run()
Example #35
0
import time

canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True)

# Set up a viewbox to display the cube with interactive arcball
view = canvas.central_widget.add_view()
view.bgcolor = '#efefef'
view.camera = 'turntable'
view.padding = 100

color = Color("#3f51b5")

# cube = scene.visuals.Cube(size=1, color=color, edge_color="black",
#                           parent=view.scene)

verts, faces, normals, nothin = io.read_mesh("crazyflie2.obj.gz")

cfs = []
# cftransforms = []
for i in range(0, 10):
    mesh = scene.visuals.Mesh(vertices=verts,
                              shading='smooth',
                              faces=faces,
                              parent=view.scene)
    mesh.transform = transforms.MatrixTransform()
    cfs.append(mesh)

# cube_transform = transforms.MatrixTransform()
# mesh.transform = cube_transform
theta = 0
lastTime = time.time()
    json_object = {
        'mesh_indices': vertices,
        'predicted_vertex_indices': pred,
    }
    with open(out_File_Name, 'wt') as f:
        json.dump(json_object, f)
    #print (pred.shape)


#data_path = '/home/eman/Documents/PhD/pytorch_geometric-master/examples/Test Meshes/shapify/' #shapify data
#data_path = '/home/eman/Documents/PhD/pytorch_geometric-master/examples/ALL_FAUST/' #FAUST data
data_path = '/home/eman/Documents/PhD/body-modeling-master_initial/smpl-viewer/Data-survey-smpl/AllData/'  #SMPL data
dirs = os.listdir(data_path)

for data_size in range(len(dirs)):
    vertices, faces, normals, nothin = read_mesh(data_path + dirs[data_size])
    out_File_Name = dirs[data_size] + '.json'

    print(vertices.shape)
    print(faces.shape)
    vertices = vertices.astype(np.float)
    faces = faces.astype(np.int32)
    vertices = torch.tensor(vertices, dtype=torch.float)
    faces = torch.tensor(faces.T, dtype=torch.long)
    data = Data(pos=vertices)
    data.face = faces
    data = transforms.FaceToEdge()(data)
    data.face = None
    data.x = torch.ones((data.num_nodes, 1))
    data = transforms.Cartesian()(data)
    test_loader = DataLoader(data, batch_size=1)
Example #37
0
    meshes = []

    for data_size in range(len(dirs)):
        prediction_file = dirs[data_size] + '.json'
        with open(prediction_file, 'rt') as f:
            prediction_data = json.load(f)

        mesh_indices = prediction_data['mesh_indices']
        mesh_index = None if len(mesh_indices) == 0 else mesh_indices[0]
        predicted_indices = np.array(
            prediction_data['predicted_vertex_indices'][:], dtype=int)

        test_Mesh = data_path + dirs[data_size]
        #vertices, faces, normals, nothin  = read_mesh(args.mesh_file)
        test_vertices, test_faces, normals, nothin = read_mesh(test_Mesh)

        #if vertices.max() > 1e3:
        #	vertices /= 1e3

        if test_vertices.max() > 1e3:
            test_vertices /= 1e3

        n_vertices = len(test_vertices)

        assert n_vertices == len(predicted_indices), \
        'number of vertices do not match {:d} != {:d}' \
        .format(n_vertices, len(predicted_indices))

        prediction_vertex_values = predicted_indices
Example #38
0
}
"""

FRAG_CODE = """
uniform sampler2D u_texture;
varying vec2 v_texcoord;
void main()
{
    float ty = v_texcoord.y;
    float tx = sin(ty*20.0)*0.05 + v_texcoord.x;
    gl_FragColor = texture2D(u_texture, vec2(tx, ty));
}
"""

# Read cube data (replace 'cube.obj' with 'teapot.obj'
positions, faces, normals, texcoords = io.read_mesh('cube.obj')
colors = np.random.uniform(0, 1, positions.shape).astype('float32')


class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self)
        self.size = 400, 400
        self.init_transforms()

        self.timer = app.Timer(1.0 / 60)
        self.timer.connect(self.update_transforms)
        self.timer.start()

    def on_initialize(self, event):
        gl.glClearColor(1, 1, 1, 1)
Example #39
0
# -*- coding: utf-8 -*-
# vispy: gallery 30
# -----------------------------------------------------------------------------
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
"""Show how to display mesh normals on a mesh."""

from vispy import app, scene
from vispy.io import read_mesh, load_data_file
from vispy.scene.visuals import Mesh, MeshNormals
from vispy.visuals.filters import WireframeFilter


mesh_file = load_data_file('orig/triceratops.obj.gz')
vertices, faces, _, _ = read_mesh(mesh_file)

mesh = Mesh(vertices, faces, shading='flat')
meshdata = mesh.mesh_data

wireframe_filter = WireframeFilter(color='lightblue')
mesh.attach(wireframe_filter)

face_normals = MeshNormals(meshdata, primitive='face', color='yellow')
vertex_normals = MeshNormals(meshdata, primitive='vertex', color='orange',
                             width=2)

canvas = scene.SceneCanvas(keys='interactive', bgcolor='white')
view = canvas.central_widget.add_view()
view.camera = 'arcball'
view.add(mesh)