Ejemplo n.º 1
0
 def draw_triangle_strip(self, *data):
     glBegin(GL_TRIANGLE_STRIP)
     for normal, vectors in data:
         glNormal3fv(normal)
         for vector in vectors:
             glVertex(vector)
     glEnd()
Ejemplo n.º 2
0
    def __gen_gl_code(faces, mtls, normals, vertices, texcoords):
        gl_list = glGenLists(1)
        glNewList(gl_list, GL_COMPILE)
        glEnable(GL_TEXTURE_2D)
        glFrontFace(GL_CCW)
        for face in faces:
            face_vertices, face_normals, texture_coords, material = face

            try:
                mtl = mtls[material]
                if 'texture_Kd' in mtl:
                    # use diffuse texmap
                    glBindTexture(GL_TEXTURE_2D, mtl['texture_Kd'])
                else:
                    # just use diffuse colour
                    glColor(mtl['Kd'])
            except KeyError:
                print("Key error" + str(material))
                glColor((1, 1, 1))

            glBegin(GL_POLYGON)
            for i in range(len(face_vertices)):
                if face_normals[i] > 0:
                    glNormal3fv(normals[face_normals[i] - 1])
                if texture_coords[i] > 0:
                    glTexCoord2fv(texcoords[texture_coords[i] - 1])
                glVertex3fv(vertices[face_vertices[i] - 1])
            glEnd()
        glDisable(GL_TEXTURE_2D)
        glEndList()
        return gl_list
Ejemplo n.º 3
0
 def draw_quad_strip(self, *data):
     glBegin(GL_QUAD_STRIP)
     for normal, vectors in data:
         glNormal3fv(normal)
         for vector in vectors:
             glVertex(vector)
     glEnd()
Ejemplo n.º 4
0
 def draw_quad_strip(self, *data):
     glBegin(GL_QUAD_STRIP)
     for normal, vectors in data:
         glNormal3fv(normal)
         for vector in vectors:
             glVertex(vector)
     glEnd()
Ejemplo n.º 5
0
    def draw(self, origin, color=(0.2, 0.2, 0.2, 1.0), drawFaces=True):
        edges = (
            (0, 1),
            (0, 2),
            (0, 4),
            (1, 3),
            (1, 5),
            (7, 3),
            (7, 5),
            (7, 6),
            (6, 2),
            (6, 4),
            (3, 2),
            (5, 4)
        )
        ground = (4, 6, 2, 0)

        normal = get_plane_normal(ground, self.vertices_points_list, -self._center)
        normal_tuple = normal.get_tuple()

        glBegin(GL_QUADS)
        for vertex in ground:
            glColor4fv(color)
            glNormal3fv(normal_tuple)
            glVertex3fv(self.vertices_points_list[vertex] - origin)
        glEnd()

        glBegin(GL_LINES)
        for edge in edges:
            for vertex in edge:
                glColor4fv((0.0, 0.0, 0.0, 1.0))
                glNormal3fv((0.0, 0.0, 0.0))
                glVertex3fv(self.vertices_points_list[vertex] - origin)
        glEnd()
Ejemplo n.º 6
0
 def draw_polygon(self, *data):
     glBegin(GL_POLYGON)
     for normal, vectors in data:
         glNormal3fv(normal)
         for vector in vectors:
             glVertex(vector)
     glEnd()
Ejemplo n.º 7
0
 def draw_polygon(self, *data):
     glBegin(GL_POLYGON)
     for normal, vectors in data:
         glNormal3fv(normal)
         for vector in vectors:
             glVertex(vector)
     glEnd()
Ejemplo n.º 8
0
 def draw_triangle_strip(self, *data):
     glBegin(GL_TRIANGLE_STRIP)
     for normal, vectors in data:
         glNormal3fv(normal)
         for vector in vectors:
             glVertex(vector)
     glEnd()
Ejemplo n.º 9
0
 def quad(self, a, b, c, d, n):
     # draw a quad
     glBegin(GL_QUADS)
     glNormal3fv(self.normals[n])
     glVertex3fv(self.vertices[a])
     glVertex3fv(self.vertices[b])
     glVertex3fv(self.vertices[c])
     glVertex3fv(self.vertices[d])
     glEnd()
Ejemplo n.º 10
0
 def quad(self, a, b, c, d, n):
     # draw a quad
     glBegin(GL_QUADS)
     glNormal3fv(self.normals[n])
     glVertex3fv(self.vertices[a])
     glVertex3fv(self.vertices[b])
     glVertex3fv(self.vertices[c])
     glVertex3fv(self.vertices[d])
     glEnd()
Ejemplo n.º 11
0
 def onevert(vertex_index):
     glNormal3fv(surfaceNormals[vertex_index])
     # This needs to be done before glVertex3fv.
     if nc > 0 and color_first: use_color(surfaceColors[vertex_index])
     glVertex3fv(surfacePoints[vertex_index])
     # Old code did it here -- used wrong colors sometimes.
     if nc > 0 and not color_first:
         use_color(surfaceColors[vertex_index])
         pass
     return
Ejemplo n.º 12
0
 def onevert(vertex_index):
     glNormal3fv(surfaceNormals[vertex_index])
     # This needs to be done before glVertex3fv.
     if nc > 0 and color_first: use_color(surfaceColors[vertex_index])
     glVertex3fv(surfacePoints[vertex_index])
     # Old code did it here -- used wrong colors sometimes.
     if nc > 0 and not color_first:
         use_color(surfaceColors[vertex_index])
         pass
     return
Ejemplo n.º 13
0
def drawtriangle_strip_worker(params):
    """ 
    Draw a triangle strip using a list of triangle vertices
    and (optional) normals.
    """
    # Note: See the code in class ColorSorter for GL_COLOR_MATERIAL objects.
    
    # piotr 080904 - This method could be optimized by using vertex
    # arrays or VBOs.
    
    (triangles, normals, colors) = params

    # It needs to support two-sided triangles, therefore we disable
    # culling and enable two-sided lighting. These settings have to be 
    # turned back to default setting.
    
    glDisable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE)

    # Use color material mode if colors are present.
    
    if colors:
        glEnable(GL_COLOR_MATERIAL)

    glBegin(GL_TRIANGLE_STRIP)
    if normals:
        if colors:
            for p in range(len(triangles)):
                n = normals[p]
                v = triangles[p]
                c = colors[p]
                glNormal3fv(n)
                glColor3fv(c[:3])
                glVertex3fv(v)
        else:
            for p in range(len(triangles)):
                n = normals[p]
                v = triangles[p]
                glNormal3fv(n)
                glVertex3fv(v)
    else:
        for v in triangles:
            glVertex3fv(v)
    glEnd()

    if colors:
        glDisable(GL_COLOR_MATERIAL)

    # piotr 080904 - are these settings really default?

    glEnable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE)

    return
Ejemplo n.º 14
0
 def draw(self, origin):
     edge = (0, 1)
     verticies = (
         self.source_point - origin, self.fixed_point - origin
     )
     glBegin(GL_LINES)
     for vertex in edge:
         glColor4fv((0.5, 0.5, 0.3, 1.0))
         glNormal3fv((0.0, 0.0, 0.0))
         glVertex3fv(verticies[vertex])
     glEnd()
Ejemplo n.º 15
0
def drawtriangle_strip_worker(params):
    """
    Draw a triangle strip using a list of triangle vertices
    and (optional) normals.
    """
    # Note: See the code in class ColorSorter for GL_COLOR_MATERIAL objects.

    # piotr 080904 - This method could be optimized by using vertex
    # arrays or VBOs.

    (triangles, normals, colors) = params

    # It needs to support two-sided triangles, therefore we disable
    # culling and enable two-sided lighting. These settings have to be
    # turned back to default setting.

    glDisable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE)

    # Use color material mode if colors are present.

    if colors:
        glEnable(GL_COLOR_MATERIAL)

    glBegin(GL_TRIANGLE_STRIP)
    if normals:
        if colors:
            for p in range(len(triangles)):
                n = normals[p]
                v = triangles[p]
                c = colors[p]
                glNormal3fv(n)
                glColor3fv(c[:3])
                glVertex3fv(v)
        else:
            for p in range(len(triangles)):
                n = normals[p]
                v = triangles[p]
                glNormal3fv(n)
                glVertex3fv(v)
    else:
        for v in triangles:
            glVertex3fv(v)
    glEnd()

    if colors:
        glDisable(GL_COLOR_MATERIAL)

    # piotr 080904 - are these settings really default?

    glEnable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE)

    return
Ejemplo n.º 16
0
 def draw(self):
     glDisable(GL_LIGHTING)  # note: the colors here don't work without this
     glBegin(GL_QUADS)
     for face in faces:
         face_normal = facenormal(face)
         for vert in faceverts(face):
             color = (fix(vert[0]), fix(vert[1]), fix(vert[2]))
             glColor3fv(color)
             glNormal3fv(face_normal)
             glVertex3fv(vert)
     glEnd()
     glEnable(GL_LIGHTING)
Ejemplo n.º 17
0
 def draw(self):
     glDisable(GL_LIGHTING) # note: the colors here don't work without this
     glBegin(GL_QUADS)
     for face in faces:
         face_normal = facenormal(face)
         for vert in faceverts(face):
             color = (fix(vert[0]), fix(vert[1]), fix(vert[2]))
             glColor3fv(color)
             glNormal3fv(face_normal)
             glVertex3fv(vert)
     glEnd()
     glEnable(GL_LIGHTING)
Ejemplo n.º 18
0
    def draw(self, origin, color=(0.45, 0.45, 0.45, 1.0), drawFaces=True):
        edges = (
            (0, 1),
            (0, 2),
            (0, 4),
            (1, 3),
            (1, 5),
            (7, 3),
            (7, 5),
            (7, 6),
            (6, 2),
            (6, 4),
            (3, 2),
            (5, 4)
        )
        surfaces = (
            (0, 2, 6, 4),
            (5, 7, 3, 1),
            (4, 6, 7, 5),
            (1, 3, 2, 0),
            (6, 2, 3, 7),
            (1, 0, 4, 5)
        )

        verticies = self.vertices_points_list(BoxVertexOrderEnum.ZYX)
        verticiesInOrigin = []

        for v in verticies:
            verticiesInOrigin.append(v - origin)

        if drawFaces:
            glBegin(GL_QUADS)
            for surface in surfaces:
                normal = get_plane_normal(surface, self.vertices_points_list, self._center)
                normal_tuple = normal.get_tuple()
                for vertex in surface:
                    glColor4fv(color)
                    glNormal3fv(normal_tuple)
                    glVertex3fv(verticiesInOrigin[vertex])
            glEnd()

        glBegin(GL_LINES)
        for edge in edges:
            for vertex in edge:
                glColor4fv((0.0, 0.0, 0.0, 1.0))
                glNormal3fv((0.0, 0.0, 0.0))
                glVertex3fv(verticiesInOrigin[vertex])
        glEnd()
Ejemplo n.º 19
0
def create_gl_list(shape):
    from OpenGL.GL import glGenLists, glNewList, glFrontFace, glBegin, glEnd, glEndList, glNormal3fv, glVertex3fv, \
        GL_COMPILE, GL_CCW, GL_TRIANGLES
    vertices = shape['vertices']
    normals = shape['normals']
    indices = shape['indices']
    gl_list = glGenLists(1)
    glNewList(gl_list, GL_COMPILE)
    glFrontFace(GL_CCW)
    glBegin(GL_TRIANGLES)
    for idx in indices:
        glNormal3fv(normals[idx])
        glVertex3fv(vertices[idx])
    glEnd()
    glEndList()
    return gl_list
Ejemplo n.º 20
0
def drawtriangle_strip_worker(params):
    """ 
    Draw a triangle strip using a list of triangle vertices
    and (optional) normals.
    """
    (triangles, normals, colors) = params

    #glEnable(GL_LIGHTING)

    glDisable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE)

    if colors:
        glEnable(GL_COLOR_MATERIAL)

    #glPolygonMode(GL_FRONT, GL_FILL)
    #glPolygonMode(GL_BACK, GL_FILL)
    # glPolygonOffset(0.0, 10.0)    

    glBegin(GL_TRIANGLE_STRIP)
    if normals:
        if colors:
            for p in range(len(triangles)):
                n = normals[p]
                v = triangles[p]
                c = colors[p]
                glNormal3fv(n)
                glColor3fv(c[:3])
                glVertex3fv(v)
        else:
            for p in range(len(triangles)):
                n = normals[p]
                v = triangles[p]
                glNormal3fv(n)
                glVertex3fv(v)
    else:
        for v in triangles:
            glVertex3fv(v)
    glEnd()

    if colors:
        glDisable(GL_COLOR_MATERIAL)

    glEnable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE)

    return
Ejemplo n.º 21
0
def drawtriangle_strip_worker(params):
    """ 
    Draw a triangle strip using a list of triangle vertices
    and (optional) normals.
    """
    (triangles, normals, colors) = params

    #glEnable(GL_LIGHTING)

    glDisable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE)

    if colors:
        glEnable(GL_COLOR_MATERIAL)

    #glPolygonMode(GL_FRONT, GL_FILL)
    #glPolygonMode(GL_BACK, GL_FILL)
    # glPolygonOffset(0.0, 10.0)

    glBegin(GL_TRIANGLE_STRIP)
    if normals:
        if colors:
            for p in range(len(triangles)):
                n = normals[p]
                v = triangles[p]
                c = colors[p]
                glNormal3fv(n)
                glColor3fv(c[:3])
                glVertex3fv(v)
        else:
            for p in range(len(triangles)):
                n = normals[p]
                v = triangles[p]
                glNormal3fv(n)
                glVertex3fv(v)
    else:
        for v in triangles:
            glVertex3fv(v)
    glEnd()

    if colors:
        glDisable(GL_COLOR_MATERIAL)

    glEnable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE)

    return
Ejemplo n.º 22
0
    def draw(self, origin):
        self.draw_inside(origin)
        edges = (
            (0, 1),
            (0, 2),
            (0, 4),
            (1, 3),
            (1, 5),
            (7, 3),
            (7, 5),
            (7, 6),
            (6, 2),
            (6, 4),
            (3, 2),
            (5, 4)
        )
        surfaces = (
            #    Surface((0,2,6,4),(0,0,1)), #ground
            Surface((5, 7, 3, 1), (0, 0, 1)),  # ceiling
            Surface((4, 6, 7, 5), (1, 0, 0)),  # back face
            Surface((6, 2, 3, 7), (0, 1, 0)),  # left face looking from source
            Surface((1, 0, 4, 5), (0, -1, 0))  # right face looking from source

        )

        verticies = self.vertices_points_list(BoxVertexOrderEnum.ZYX)
        verticiesInOrigin = []
        for v in verticies:
            verticiesInOrigin.append(v - origin)

        glBegin(GL_QUADS)
        for surface in surfaces:
            for vertex in surface.edges:
                glColor4fv((0.4, 0.4, 0.4, 1.0))
                glNormal3fv(surface.normal)
                glVertex3fv(verticiesInOrigin[vertex])
        glEnd()

        glBegin(GL_LINES)
        for edge in edges:
            for vertex in edge:
                glColor4fv((0.0, 0.0, 0.0, 1.0))
                glNormal3fv((0.0, 0.0, 0.0))
                glVertex3fv(verticiesInOrigin[vertex])
        glEnd()
Ejemplo n.º 23
0
    def draw(self, origin):
        self.draw_parable(origin)
        edges = (
            (0, 1),
            (0, 2),
            (0, 4),
            (1, 3),
            (1, 5),
            (7, 3),
            (7, 5),
            (7, 6),
            (6, 2),
            (6, 4),
            (3, 2),
            (5, 4)
        )

        #    edges = ()
        surfaces = (
            (1, 3, 2, 0),
            (1, 0, 4, 5),
            (0, 2, 6, 4),
            (1, 3, 7, 5),
            (7, 3, 2, 6)
        )

        light = (1, 3, 2, 0)

        normal = get_plane_normal(light, self.vertices_points_list, self._center)
        normal_tuple = normal.get_tuple()
        glBegin(GL_QUADS)
        for vertex in light:
            glNormal3fv(normal_tuple)
            glColor4fv((1.0, 1.0, 1.0, 1.0))
            glVertex3fv(self.vertices_points_list[vertex] - origin)
        glEnd()

        glBegin(GL_LINES)
        for edge in edges:
            for vertex in edge:
                glColor4fv((0.0, 0.0, 0.0, 1.0))
                glNormal3fv((0.0, 0.0, 0.0))
                glVertex3fv(self.vertices_points_list[vertex] - origin)
        glEnd()
Ejemplo n.º 24
0
    def draw_parable(self, origin):
        number_levels = int(self.angle_ouverture / self.angle_levels)
        #    self.points_per_level = len(self.points_parable)
        glBegin(GL_QUADS)
        for j in range(number_levels - 2):
            for i in range(self.points_per_level):
                glColor4fv((0.95, 0.95, 0, 1.0))
                glNormal3fv((0.0, 0.0, 0.0))
                glVertex3fv(self.points_parable[i % self.points_per_level + (j + 1) * self.points_per_level] - origin)
                glVertex3fv(self.points_parable[i + 1 + (j + 1) * self.points_per_level] - origin)
                glVertex3fv(self.points_parable[(i + 1) % self.points_per_level + j * self.points_per_level] - origin)
                glVertex3fv(self.points_parable[i + j * self.points_per_level] - origin)
        glEnd()
        glBegin(GL_LINES)
        for j in range(number_levels):
            for i in range(self.points_per_level):
                glColor4fv((0.5, 0.5, 0.5, 1.0))
                glNormal3fv((0.0, 0.0, 0.0))
                glVertex3fv(self.points_parable[i + j * self.points_per_level] - origin)
                glVertex3fv(self.points_parable[(i + 1) % self.points_per_level + j * self.points_per_level] - origin)
        glEnd()

        glBegin(GL_LINES)
        for i in range(len(self.points_parable) - self.points_per_level):
            for j in (i, i + self.points_per_level):
                glColor4fv((0.5, 0.5, 0.5, 1.0))
                glNormal3fv((0.0, 0.0, 0.0))
                glVertex3fv(self.points_parable[j] - origin)
        glEnd()
Ejemplo n.º 25
0
    def build_from_mesh_data(self, mesh_data: MeshData):
        """Uses a loaded mesh to create 3d geometry to store in the view.

        All groups in the mesh will pre-computed and stored by name.

        :param mesh_data: the source data that 3d geometry will be pre-computed from.
        """
        material_library = mesh_data.material_library

        for key in mesh_data.groups:
            new_gl_list = glGenLists(1)  # pylint: disable=assignment-from-no-return
            glNewList(new_gl_list, GL_COMPILE)

            group = mesh_data.groups[key]

            glEnable(GL_TEXTURE_2D)
            glFrontFace(GL_CCW)

            for face in group.faces:
                self._apply_material(
                    material_library.get_material_by_name(face.material))

                # Polygon (N verts) with optional normals and tex coords
                glBegin(GL_POLYGON)
                for i in range(face.vertex_count):
                    normal_index = face.normal_ids[i]
                    if normal_index > 0:
                        glNormal3fv(mesh_data.normals[normal_index - 1])
                    tex_coord_index = face.tex_ids[i]
                    if tex_coord_index > 0:
                        glTexCoord2fv(mesh_data.tex_coords[tex_coord_index -
                                                           1])
                    glVertex3fv(mesh_data.vertices[face.position_ids[i] - 1])
                glEnd()

            glDisable(GL_TEXTURE_2D)
            glEndList()

            self._display_lists[key] = new_gl_list
Ejemplo n.º 26
0
    def render(self):
        if self.list < 0:
            self.list = glGenLists(1)
            glNewList(self.list, GL_COMPILE)

            for n, f in enumerate(self.faces):
                glMaterialfv(GL_FRONT, GL_DIFFUSE, self.colors[n])
                glMaterialfv(GL_FRONT, GL_SPECULAR, self.colors[n])
                glMaterialf(GL_FRONT, GL_SHININESS, 50.0)
                glColor4fv(self.colors[n])

                glBegin(GL_POLYGON)
                if self.colors[n][0] > 0:
                    glNormal3fv(self.normals[n])

                for i in f:
                    if self.colors[n][1] > 0:
                        glNormal3fv(self.vnormals[i])
                    glVertex3fv(self.vertices[i])
                glEnd()
            glEndList()
        glCallList(self.list)
Ejemplo n.º 27
0
    def _render_cube():
        """Pre renders a unit-size cube, with normals, centered at the origin.
        """
        # build each of the 6 faces
        for face_index in range(6):
            # calculate normal and vertices for this face
            vertex_normal = [0.0, 0.0, 0.0]
            vertex_pos_options1 = [-1.0, 1.0, 1.0, -1.0]
            vertex_pos_options2 = [1.0, 1.0, -1.0, -1.0]
            face_index_even = ((face_index % 2) == 0)
            # odd and even faces point in opposite directions
            normal_dir = 1.0 if face_index_even else -1.0
            if face_index < 2:
                # -X and +X faces (vert positions differ in Y,Z)
                vertex_normal[0] = normal_dir
                v1i = 1
                v2i = 2
            elif face_index < 4:
                # -Y and +Y faces (vert positions differ in X,Z)
                vertex_normal[1] = normal_dir
                v1i = 0
                v2i = 2
            else:
                # -Z and +Z faces (vert positions differ in X,Y)
                vertex_normal[2] = normal_dir
                v1i = 0
                v2i = 1

            vertex_pos = list(vertex_normal)

            # Polygon (N verts) with optional normals and tex coords
            glBegin(GL_POLYGON)
            for vert_index in range(4):
                vertex_pos[v1i] = vertex_pos_options1[vert_index]
                vertex_pos[v2i] = vertex_pos_options2[vert_index]
                glNormal3fv(vertex_normal)
                glVertex3fv(vertex_pos)
            glEnd()
Ejemplo n.º 28
0
    def renderizar(self):

        i = 0
        j = 0
        while i < len(Esfera.normais_esfera):
            glNormal3fv(Esfera.normais_esfera[i])
            i += 1
            glVertex3fv((self.posicao.coords[0] + Esfera.pontos_esfera[j][0],
                         self.posicao.coords[1] + Esfera.pontos_esfera[j][1],
                         self.posicao.coords[2] + Esfera.pontos_esfera[j][2]))
            j += 1
            glVertex3fv((self.posicao.coords[0] + Esfera.pontos_esfera[j][0],
                         self.posicao.coords[1] + Esfera.pontos_esfera[j][1],
                         self.posicao.coords[2] + Esfera.pontos_esfera[j][2]))
            j += 1
            glVertex3fv((self.posicao.coords[0] + Esfera.pontos_esfera[j][0],
                         self.posicao.coords[1] + Esfera.pontos_esfera[j][1],
                         self.posicao.coords[2] + Esfera.pontos_esfera[j][2]))
            j += 1
            glVertex3fv((self.posicao.coords[0] + Esfera.pontos_esfera[j][0],
                         self.posicao.coords[1] + Esfera.pontos_esfera[j][1],
                         self.posicao.coords[2] + Esfera.pontos_esfera[j][2]))
            j += 1
Ejemplo n.º 29
0
def setup_drawer():
    """
    Set up the usual constant display lists in the current OpenGL context.

    WARNING: THIS IS ONLY CORRECT IF ONLY ONE GL CONTEXT CONTAINS DISPLAY LISTS
    -- or more precisely, only the GL context this has last been called in (or
    one which shares its display lists) will work properly with the routines in
    drawer.py, since the allocated display list names are stored in globals set
    by this function, but in general those names might differ if this was called
    in different GL contexts.
    """
    #bruce 060613 added docstring, cleaned up display list name allocation
    # bruce 071030 renamed from setup to setup_drawer

    spherelistbase = glGenLists(numSphereSizes)
    sphereList = []
    for i in range(numSphereSizes):
        sphereList += [spherelistbase + i]
        glNewList(sphereList[i], GL_COMPILE)
        glBegin(GL_TRIANGLE_STRIP)  # GL_LINE_LOOP to see edges.
        stripVerts = getSphereTriStrips(i)
        for vertNorm in stripVerts:
            glNormal3fv(vertNorm)
            glVertex3fv(vertNorm)
            continue
        glEnd()
        glEndList()
        continue
    drawing_globals.sphereList = sphereList

    # Sphere triangle-strip vertices for each level of detail.
    # (Cache and re-use the work of making them.)
    # Can use in converter-wrappered calls like glVertexPointerfv,
    # but the python arrays are re-copied to C each time.
    sphereArrays = []
    for i in range(numSphereSizes):
        sphereArrays += [getSphereTriStrips(i)]
        continue
    drawing_globals.sphereArrays = sphereArrays

    # Sphere glDrawArrays triangle-strip vertices for C calls.
    # (Cache and re-use the work of converting a C version.)
    # Used in thinly-wrappered calls like glVertexPointer.
    sphereCArrays = []
    for i in range(numSphereSizes):
        CArray = numpy.array(sphereArrays[i], dtype=numpy.float32)
        sphereCArrays += [CArray]
        continue
    drawing_globals.sphereCArrays = sphereCArrays

    # Sphere indexed vertices.
    # (Cache and re-use the work of making the indexes.)
    # Can use in converter-wrappered calls like glDrawElementsui,
    # but the python arrays are re-copied to C each time.
    sphereElements = []  # Pairs of lists (index, verts) .
    for i in range(numSphereSizes):
        sphereElements += [indexVerts(sphereArrays[i], .0001)]
        continue
    drawing_globals.sphereElements = sphereElements

    # Sphere glDrawElements index and vertex arrays for C calls.
    sphereCIndexTypes = []  # numpy index unsigned types.
    sphereGLIndexTypes = []  # GL index types for drawElements.
    sphereCElements = []  # Pairs of numpy arrays (Cindex, Cverts) .
    for i in range(numSphereSizes):
        (index, verts) = sphereElements[i]
        if len(index) < 256:
            Ctype = numpy.uint8
            GLtype = GL_UNSIGNED_BYTE
        else:
            Ctype = numpy.uint16
            GLtype = GL_UNSIGNED_SHORT
            pass
        sphereCIndexTypes += [Ctype]
        sphereGLIndexTypes += [GLtype]
        sphereCIndex = numpy.array(index, dtype=Ctype)
        sphereCVerts = numpy.array(verts, dtype=numpy.float32)
        sphereCElements += [(sphereCIndex, sphereCVerts)]
        continue
    drawing_globals.sphereCIndexTypes = sphereCIndexTypes
    drawing_globals.sphereGLIndexTypes = sphereGLIndexTypes
    drawing_globals.sphereCElements = sphereCElements

    if glGetString(GL_EXTENSIONS).find("GL_ARB_vertex_buffer_object") >= 0:

        # A GLBufferObject version for glDrawArrays.
        sphereArrayVBOs = []
        for i in range(numSphereSizes):
            vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB, sphereCArrays[i],
                                 GL_STATIC_DRAW)
            sphereArrayVBOs += [vbo]
            continue
        drawing_globals.sphereArrayVBOs = sphereArrayVBOs

        # A GLBufferObject version for glDrawElements indexed verts.
        sphereElementVBOs = []  # Pairs of (IBO, VBO)
        for i in range(numSphereSizes):
            ibo = GLBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB,
                                 sphereCElements[i][0], GL_STATIC_DRAW)
            vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB, sphereCElements[i][1],
                                 GL_STATIC_DRAW)
            sphereElementVBOs += [(ibo, vbo)]
            continue
        drawing_globals.sphereElementVBOs = sphereElementVBOs

        ibo.unbind()
        vbo.unbind()
        pass

    #bruce 060415
    drawing_globals.wiresphere1list = wiresphere1list = glGenLists(1)
    glNewList(wiresphere1list, GL_COMPILE)
    didlines = {}  # don't draw each triangle edge more than once

    def shoulddoline(v1, v2):
        # make sure not list (unhashable) or Numeric array (bug in __eq__)
        v1 = tuple(v1)
        v2 = tuple(v2)
        if (v1, v2) not in didlines:
            didlines[(v1, v2)] = didlines[(v2, v1)] = None
            return True
        return False

    def doline(v1, v2):
        if shoulddoline(v1, v2):
            glVertex3fv(v1)
            glVertex3fv(v2)
        return

    glBegin(GL_LINES)
    ocdec = getSphereTriangles(1)
    for tri in ocdec:
        #e Could probably optim this more, e.g. using a vertex array or VBO or
        #  maybe GL_LINE_STRIP.
        doline(tri[0], tri[1])
        doline(tri[1], tri[2])
        doline(tri[2], tri[0])
    glEnd()
    glEndList()

    drawing_globals.CylList = CylList = glGenLists(1)
    glNewList(CylList, GL_COMPILE)
    glBegin(GL_TRIANGLE_STRIP)
    for (vtop, ntop, vbot, nbot) in drawing_globals.cylinderEdges:
        glNormal3fv(nbot)
        glVertex3fv(vbot)
        glNormal3fv(ntop)
        glVertex3fv(vtop)
    glEnd()
    glEndList()

    drawing_globals.CapList = CapList = glGenLists(1)
    glNewList(CapList, GL_COMPILE)
    glNormal3fv(drawing_globals.cap0n)
    glBegin(GL_POLYGON)
    for p in drawing_globals.drum0:
        glVertex3fv(p)
    glEnd()
    glNormal3fv(drawing_globals.cap1n)
    glBegin(GL_POLYGON)
    #bruce 060609 fix "ragged edge" bug in this endcap: drum1 -> drum2
    for p in drawing_globals.drum2:
        glVertex3fv(p)
    glEnd()
    glEndList()

    drawing_globals.diamondGridList = diamondGridList = glGenLists(1)
    glNewList(diamondGridList, GL_COMPILE)
    glBegin(GL_LINES)
    for p in drawing_globals.digrid:
        glVertex(p[0])
        glVertex(p[1])
    glEnd()
    glEndList()

    drawing_globals.lonsGridList = lonsGridList = glGenLists(1)
    glNewList(lonsGridList, GL_COMPILE)
    glBegin(GL_LINES)
    for p in drawing_globals.lonsEdges:
        glVertex(p[0])
        glVertex(p[1])
    glEnd()
    glEndList()

    drawing_globals.CubeList = CubeList = glGenLists(1)
    glNewList(CubeList, GL_COMPILE)
    glBegin(GL_QUAD_STRIP)
    # note: CubeList has only 4 faces of the cube; only suitable for use in
    # wireframes; see also solidCubeList [bruce 051215 comment reporting
    # grantham 20051213 observation]
    glVertex((-1, -1, -1))
    glVertex((1, -1, -1))
    glVertex((-1, 1, -1))
    glVertex((1, 1, -1))
    glVertex((-1, 1, 1))
    glVertex((1, 1, 1))
    glVertex((-1, -1, 1))
    glVertex((1, -1, 1))
    glVertex((-1, -1, -1))
    glVertex((1, -1, -1))
    glEnd()
    glEndList()

    drawing_globals.solidCubeList = solidCubeList = glGenLists(1)
    glNewList(solidCubeList, GL_COMPILE)
    glBegin(GL_QUADS)
    for i in xrange(len(drawing_globals.cubeIndices)):
        avenormals = V(0, 0, 0)  #bruce 060302 fixed normals for flat shading
        for j in xrange(4):
            nTuple = tuple(
                drawing_globals.cubeNormals[drawing_globals.cubeIndices[i][j]])
            avenormals += A(nTuple)
        avenormals = norm(avenormals)
        for j in xrange(4):
            vTuple = tuple(drawing_globals.cubeVertices[
                drawing_globals.cubeIndices[i][j]])
            #bruce 060302 made size compatible with glut.glutSolidCube(1.0)
            vTuple = A(vTuple) * 0.5
            glNormal3fv(avenormals)
            glVertex3fv(vTuple)
    glEnd()
    glEndList()

    drawing_globals.rotSignList = rotSignList = glGenLists(1)
    glNewList(rotSignList, GL_COMPILE)
    glBegin(GL_LINE_STRIP)
    for ii in xrange(len(drawing_globals.rotS0n)):
        glVertex3fv(tuple(drawing_globals.rotS0n[ii]))
    glEnd()
    glBegin(GL_LINE_STRIP)
    for ii in xrange(len(drawing_globals.rotS1n)):
        glVertex3fv(tuple(drawing_globals.rotS1n[ii]))
    glEnd()
    glBegin(GL_TRIANGLES)
    for v in drawing_globals.arrow0Vertices + drawing_globals.arrow1Vertices:
        glVertex3f(v[0], v[1], v[2])
    glEnd()
    glEndList()

    drawing_globals.linearArrowList = linearArrowList = glGenLists(1)
    glNewList(linearArrowList, GL_COMPILE)
    glBegin(GL_TRIANGLES)
    for v in drawing_globals.linearArrowVertices:
        glVertex3f(v[0], v[1], v[2])
    glEnd()
    glEndList()

    drawing_globals.linearLineList = linearLineList = glGenLists(1)
    glNewList(linearLineList, GL_COMPILE)
    glEnable(GL_LINE_SMOOTH)
    glBegin(GL_LINES)
    glVertex3f(0.0, 0.0, -drawing_globals.halfHeight)
    glVertex3f(0.0, 0.0, drawing_globals.halfHeight)
    glEnd()
    glDisable(GL_LINE_SMOOTH)
    glEndList()

    drawing_globals.circleList = circleList = glGenLists(1)
    glNewList(circleList, GL_COMPILE)
    glBegin(GL_LINE_LOOP)
    for ii in range(60):
        x = cos(ii * 2.0 * pi / 60)
        y = sin(ii * 2.0 * pi / 60)
        glVertex3f(x, y, 0.0)
    glEnd()
    glEndList()

    # piotr 080405
    drawing_globals.filledCircleList = filledCircleList = glGenLists(1)
    glNewList(filledCircleList, GL_COMPILE)
    glBegin(GL_POLYGON)
    for ii in range(60):
        x = cos(ii * 2.0 * pi / 60)
        y = sin(ii * 2.0 * pi / 60)
        glVertex3f(x, y, 0.0)
    glEnd()
    glEndList()

    drawing_globals.lineCubeList = lineCubeList = glGenLists(1)
    glNewList(lineCubeList, GL_COMPILE)
    glBegin(GL_LINES)
    cvIndices = [
        0, 1, 2, 3, 4, 5, 6, 7, 0, 3, 1, 2, 5, 6, 4, 7, 0, 4, 1, 5, 2, 6, 3, 7
    ]
    for i in cvIndices:
        glVertex3fv(tuple(drawing_globals.cubeVertices[i]))
    glEnd()
    glEndList()

    # Debug Preferences
    from utilities.debug_prefs import debug_pref, Choice_boolean_True
    from utilities.debug_prefs import Choice_boolean_False
    choices = [Choice_boolean_False, Choice_boolean_True]

    # 20060314 grantham
    initial_choice = choices[drawing_globals.allow_color_sorting_default]
    drawing_globals.allow_color_sorting_pref = debug_pref(
        "Use Color Sorting?",
        initial_choice,
        prefs_key=drawing_globals.allow_color_sorting_prefs_key)
    #bruce 060323 removed non_debug = True for A7 release, changed default
    #value to False (far above), and changed its prefs_key so developers
    #start with the new default value.
    #russ 080225: Added.
    initial_choice = choices[drawing_globals.use_color_sorted_dls_default]
    drawing_globals.use_color_sorted_dls_pref = debug_pref(
        "Use Color-sorted Display Lists?",
        initial_choice,
        prefs_key=drawing_globals.use_color_sorted_dls_prefs_key)
    #russ 080225: Added.
    initial_choice = choices[drawing_globals.use_color_sorted_vbos_default]
    drawing_globals.use_color_sorted_vbos_pref = debug_pref(
        "Use Color-sorted Vertex Buffer Objects?",
        initial_choice,
        prefs_key=drawing_globals.use_color_sorted_vbos_prefs_key)

    #russ 080403: Added drawing variant selection
    variants = [
        "0. OpenGL 1.0 - glBegin/glEnd tri-strips vertex-by-vertex.",
        "1. OpenGL 1.1 - glDrawArrays from CPU RAM.",
        "2. OpenGL 1.1 - glDrawElements indexed arrays from CPU RAM.",
        "3. OpenGL 1.5 - glDrawArrays from graphics RAM VBO.",
        "4. OpenGL 1.5 - glDrawElements, verts in VBO, index in CPU.",
        "5. OpenGL 1.5 - VBO/IBO buffered glDrawElements."
    ]
    drawing_globals.use_drawing_variant = debug_pref(
        "GLPane: drawing method",
        Choice(names=variants,
               values=range(len(variants)),
               defaultValue=drawing_globals.use_drawing_variant_default),
        prefs_key=drawing_globals.use_drawing_variant_prefs_key)

    # temporarily always print this, while default setting might be in flux,
    # and to avoid confusion if the two necessary prefs are set differently
    # [bruce 080305]
    if (drawing_globals.allow_color_sorting_pref
            and drawing_globals.use_color_sorted_dls_pref):
        print "\nnote: this session WILL use color sorted display lists"
    else:
        print "\nnote: this session will NOT use color sorted display lists"
    if (drawing_globals.allow_color_sorting_pref
            and drawing_globals.use_color_sorted_vbos_pref):
        print "note: this session WILL use", \
              "color sorted Vertex Buffer Objects\n"
    else:
        print "note: this session will NOT use", \
              "color sorted Vertex Buffer Objects\n"

    # 20060313 grantham Added use_c_renderer debug pref, can
    # take out when C renderer used by default.
    if drawing_globals.quux_module_import_succeeded:
        initial_choice = choices[drawing_globals.use_c_renderer_default]
        drawing_globals.use_c_renderer = (debug_pref(
            "Use native C renderer?",
            initial_choice,
            prefs_key=drawing_globals.use_c_renderer_prefs_key))
        #bruce 060323 removed non_debug = True for A7 release, and changed
        # its prefs_key so developers start over with the default value.

    #initTexture('C:\\Huaicai\\atom\\temp\\newSample.png', 128,128)
    return  # from setup_drawer
Ejemplo n.º 30
0
    def draw_inside(self, origin):
        edges = (
            (0, 1),
            (0, 2),
            (0, 4),
            (1, 3),
            (1, 5),
            (7, 3),
            (7, 5),
            (7, 6),
            (6, 2),
            (6, 4),
            (3, 2),
            (5, 4),
            # windows inside
            (8, 9),
            (9, 10),
            (10, 11),
            (11, 8),
            # window outside
            (12, 13),
            (13, 14),
            (14, 15),
            (15, 12),
            # wall between windows
            (8, 12),
            (9, 13),
            (10, 14),
            (11, 15)

        )
        surfaces_inside = (
            #####inside
            Surface((5, 7, 6, 4), (-1, 0, 0)),
            Surface((5, 4, 0, 1), (0, 1, 0)),
            Surface((7, 3, 2, 6), (0, -1, 0)),
            Surface((4, 6, 2, 0), (0, 0, 1)),
            Surface((1, 3, 7, 5), (0, 0, 1))
        )
        surfaces_outside = (
            #####outside front face
            Surface((16, 17, 12, 15), (-1, 0, 0)),
            Surface((19, 13, 12, 17), (-1, 0, 0)),
            Surface((13, 19, 18, 14), (-1, 0, 0)),
            Surface((16, 15, 14, 18), (-1, 0, 0)),
            #####
            Surface((8, 11, 15, 12), (0, -1, 0)),
            Surface((12, 13, 9, 8), (0, 0, -1)),
            Surface((13, 14, 10, 9), (0, 1, 0)),
            Surface((14, 15, 11, 10), (0, 0, 1))
        )
        verticies = self.sommets_extras
        verticiesInOrigin = []
        for v in verticies:
            verticiesInOrigin.append(v - origin)
        glBegin(GL_QUADS)
        for surface in surfaces_outside:
            for vertex in surface.edges:
                glColor4fv((0.4, 0.4, 0.4, 1.0))
                glNormal3fv(surface.normal)
                glVertex3fv(verticiesInOrigin[vertex])
        for surface in surfaces_inside:
            for vertex in surface.edges:
                glColor4fv((0.6, 0.6, 0.6, 1.0))
                glNormal3fv(surface.normal)
                glVertex3fv(verticiesInOrigin[vertex])
        glEnd()
        glBegin(GL_LINES)
        for edge in edges:
            for vertex in edge:
                glColor4fv((0.0, 0.0, 0.0, 1.0))
                glNormal3fv((0.0, 0.0, 0.0))
                glVertex3fv(verticiesInOrigin[vertex])
        glEnd()
Ejemplo n.º 31
0
def setup_drawer():
    """
    Set up the usual constant display lists in the current OpenGL context.

    WARNING: THIS IS ONLY CORRECT IF ONLY ONE GL CONTEXT CONTAINS DISPLAY LISTS
    -- or more precisely, only the GL context this has last been called in (or
    one which shares its display lists) will work properly with the routines in
    drawer.py, since the allocated display list names are stored in globals set
    by this function, but in general those names might differ if this was called
    in different GL contexts.
    """
    #bruce 060613 added docstring, cleaned up display list name allocation
    # bruce 071030 renamed from setup to setup_drawer

    spherelistbase = glGenLists(numSphereSizes)
    sphereList = []
    for i in range(numSphereSizes):
        sphereList += [spherelistbase+i]
        glNewList(sphereList[i], GL_COMPILE)
        glBegin(GL_TRIANGLE_STRIP) # GL_LINE_LOOP to see edges.
        stripVerts = getSphereTriStrips(i)
        for vertNorm in stripVerts:
            glNormal3fv(vertNorm)
            glVertex3fv(vertNorm)
            continue
        glEnd()
        glEndList()
        continue
    drawing_globals.sphereList = sphereList

    # Sphere triangle-strip vertices for each level of detail.
    # (Cache and re-use the work of making them.)
    # Can use in converter-wrappered calls like glVertexPointerfv,
    # but the python arrays are re-copied to C each time.
    sphereArrays = []
    for i in range(numSphereSizes):
        sphereArrays += [getSphereTriStrips(i)]
        continue
    drawing_globals.sphereArrays = sphereArrays

    # Sphere glDrawArrays triangle-strip vertices for C calls.
    # (Cache and re-use the work of converting a C version.)
    # Used in thinly-wrappered calls like glVertexPointer.
    sphereCArrays = []
    for i in range(numSphereSizes):
        CArray = numpy.array(sphereArrays[i], dtype=numpy.float32)
        sphereCArrays += [CArray]
        continue
    drawing_globals.sphereCArrays = sphereCArrays

    # Sphere indexed vertices.
    # (Cache and re-use the work of making the indexes.)
    # Can use in converter-wrappered calls like glDrawElementsui,
    # but the python arrays are re-copied to C each time.
    sphereElements = []             # Pairs of lists (index, verts) .
    for i in range(numSphereSizes):
        sphereElements += [indexVerts(sphereArrays[i], .0001)]
        continue
    drawing_globals.sphereElements = sphereElements

    # Sphere glDrawElements index and vertex arrays for C calls.
    sphereCIndexTypes = []          # numpy index unsigned types.
    sphereGLIndexTypes = []         # GL index types for drawElements.
    sphereCElements = []            # Pairs of numpy arrays (Cindex, Cverts) .
    for i in range(numSphereSizes):
        (index, verts) = sphereElements[i]
        if len(index) < 256:
            Ctype = numpy.uint8
            GLtype = GL_UNSIGNED_BYTE
        else:
            Ctype = numpy.uint16
            GLtype = GL_UNSIGNED_SHORT
            pass
        sphereCIndexTypes += [Ctype]
        sphereGLIndexTypes += [GLtype]
        sphereCIndex = numpy.array(index, dtype=Ctype)
        sphereCVerts = numpy.array(verts, dtype=numpy.float32)
        sphereCElements += [(sphereCIndex, sphereCVerts)]
        continue
    drawing_globals.sphereCIndexTypes = sphereCIndexTypes
    drawing_globals.sphereGLIndexTypes = sphereGLIndexTypes
    drawing_globals.sphereCElements = sphereCElements

    if glGetString(GL_EXTENSIONS).find("GL_ARB_vertex_buffer_object") >= 0:

        # A GLBufferObject version for glDrawArrays.
        sphereArrayVBOs = []
        for i in range(numSphereSizes):
            vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB,
                                 sphereCArrays[i], GL_STATIC_DRAW)
            sphereArrayVBOs += [vbo]
            continue
        drawing_globals.sphereArrayVBOs = sphereArrayVBOs

        # A GLBufferObject version for glDrawElements indexed verts.
        sphereElementVBOs = []              # Pairs of (IBO, VBO)
        for i in range(numSphereSizes):
            ibo = GLBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB,
                                 sphereCElements[i][0], GL_STATIC_DRAW)
            vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB,
                                 sphereCElements[i][1], GL_STATIC_DRAW)
            sphereElementVBOs += [(ibo, vbo)]
            continue
        drawing_globals.sphereElementVBOs = sphereElementVBOs

        ibo.unbind()
        vbo.unbind()
        pass

    #bruce 060415
    drawing_globals.wiresphere1list = wiresphere1list = glGenLists(1)
    glNewList(wiresphere1list, GL_COMPILE)
    didlines = {} # don't draw each triangle edge more than once

    def shoulddoline(v1,v2):
        # make sure not list (unhashable) or Numeric array (bug in __eq__)
        v1 = tuple(v1)
        v2 = tuple(v2)
        if (v1,v2) not in didlines:
            didlines[(v1,v2)] = didlines[(v2,v1)] = None
            return True
        return False
    def doline(v1,v2):
        if shoulddoline(v1,v2):
            glVertex3fv(v1)
            glVertex3fv(v2)
        return
    glBegin(GL_LINES)
    ocdec = getSphereTriangles(1)
    for tri in ocdec:
        #e Could probably optim this more, e.g. using a vertex array or VBO or
        #  maybe GL_LINE_STRIP.
        doline(tri[0], tri[1])
        doline(tri[1], tri[2])
        doline(tri[2], tri[0])
    glEnd()
    glEndList()

    drawing_globals.CylList = CylList = glGenLists(1)
    glNewList(CylList, GL_COMPILE)
    glBegin(GL_TRIANGLE_STRIP)
    for (vtop, ntop, vbot, nbot) in drawing_globals.cylinderEdges:
        glNormal3fv(nbot)
        glVertex3fv(vbot)
        glNormal3fv(ntop)
        glVertex3fv(vtop)
    glEnd()
    glEndList()

    drawing_globals.CapList = CapList = glGenLists(1)
    glNewList(CapList, GL_COMPILE)
    glNormal3fv(drawing_globals.cap0n)
    glBegin(GL_POLYGON)
    for p in drawing_globals.drum0:
        glVertex3fv(p)
    glEnd()
    glNormal3fv(drawing_globals.cap1n)
    glBegin(GL_POLYGON)
    #bruce 060609 fix "ragged edge" bug in this endcap: drum1 -> drum2
    for p in drawing_globals.drum2:
        glVertex3fv(p)
    glEnd()
    glEndList()

    drawing_globals.diamondGridList = diamondGridList = glGenLists(1)
    glNewList(diamondGridList, GL_COMPILE)
    glBegin(GL_LINES)
    for p in drawing_globals.digrid:
        glVertex(p[0])
        glVertex(p[1])
    glEnd()
    glEndList()

    drawing_globals.lonsGridList = lonsGridList = glGenLists(1)
    glNewList(lonsGridList, GL_COMPILE)
    glBegin(GL_LINES)
    for p in drawing_globals.lonsEdges:
        glVertex(p[0])
        glVertex(p[1])
    glEnd()
    glEndList()

    drawing_globals.CubeList = CubeList = glGenLists(1)
    glNewList(CubeList, GL_COMPILE)
    glBegin(GL_QUAD_STRIP)
    # note: CubeList has only 4 faces of the cube; only suitable for use in
    # wireframes; see also solidCubeList [bruce 051215 comment reporting
    # grantham 20051213 observation]
    glVertex((-1,-1,-1))
    glVertex(( 1,-1,-1))
    glVertex((-1, 1,-1))
    glVertex(( 1, 1,-1))
    glVertex((-1, 1, 1))
    glVertex(( 1, 1, 1))
    glVertex((-1,-1, 1))
    glVertex(( 1,-1, 1))
    glVertex((-1,-1,-1))
    glVertex(( 1,-1,-1))
    glEnd()
    glEndList()

    drawing_globals.solidCubeList = solidCubeList = glGenLists(1)
    glNewList(solidCubeList, GL_COMPILE)
    glBegin(GL_QUADS)
    for i in xrange(len(drawing_globals.cubeIndices)):
        avenormals = V(0,0,0) #bruce 060302 fixed normals for flat shading 
        for j in xrange(4) :    
            nTuple = tuple(
                drawing_globals.cubeNormals[drawing_globals.cubeIndices[i][j]])
            avenormals += A(nTuple)
        avenormals = norm(avenormals)
        for j in xrange(4) :    
            vTuple = tuple(
                drawing_globals.cubeVertices[drawing_globals.cubeIndices[i][j]])
            #bruce 060302 made size compatible with glut.glutSolidCube(1.0)
            vTuple = A(vTuple) * 0.5
            glNormal3fv(avenormals)
            glVertex3fv(vTuple)
    glEnd()
    glEndList()                

    drawing_globals.rotSignList = rotSignList = glGenLists(1)
    glNewList(rotSignList, GL_COMPILE)
    glBegin(GL_LINE_STRIP)
    for ii in xrange(len(drawing_globals.rotS0n)):
        glVertex3fv(tuple(drawing_globals.rotS0n[ii]))
    glEnd()
    glBegin(GL_LINE_STRIP)
    for ii in xrange(len(drawing_globals.rotS1n)):
        glVertex3fv(tuple(drawing_globals.rotS1n[ii]))
    glEnd()
    glBegin(GL_TRIANGLES)
    for v in drawing_globals.arrow0Vertices + drawing_globals.arrow1Vertices:
        glVertex3f(v[0], v[1], v[2])
    glEnd()
    glEndList()

    drawing_globals.linearArrowList = linearArrowList = glGenLists(1)
    glNewList(linearArrowList, GL_COMPILE)
    glBegin(GL_TRIANGLES)
    for v in drawing_globals.linearArrowVertices:
        glVertex3f(v[0], v[1], v[2])
    glEnd()
    glEndList()

    drawing_globals.linearLineList = linearLineList = glGenLists(1)
    glNewList(linearLineList, GL_COMPILE)
    glEnable(GL_LINE_SMOOTH)
    glBegin(GL_LINES)
    glVertex3f(0.0, 0.0, -drawing_globals.halfHeight)
    glVertex3f(0.0, 0.0, drawing_globals.halfHeight)
    glEnd()
    glDisable(GL_LINE_SMOOTH)
    glEndList()

    drawing_globals.circleList = circleList = glGenLists(1)
    glNewList(circleList, GL_COMPILE)
    glBegin(GL_LINE_LOOP)
    for ii in range(60):
        x = cos(ii*2.0*pi/60)
        y = sin(ii*2.0*pi/60)
        glVertex3f(x, y, 0.0)
    glEnd()    
    glEndList()

    # piotr 080405
    drawing_globals.filledCircleList = filledCircleList = glGenLists(1)
    glNewList(filledCircleList, GL_COMPILE)
    glBegin(GL_POLYGON)
    for ii in range(60):
        x = cos(ii*2.0*pi/60)
        y = sin(ii*2.0*pi/60)
        glVertex3f(x, y, 0.0)
    glEnd()    
    glEndList()

    drawing_globals.lineCubeList = lineCubeList = glGenLists(1)
    glNewList(lineCubeList, GL_COMPILE)
    glBegin(GL_LINES)
    cvIndices = [0,1, 2,3, 4,5, 6,7, 0,3, 1,2, 5,6, 4,7, 0,4, 1,5, 2,6, 3,7]
    for i in cvIndices:
        glVertex3fv(tuple(drawing_globals.cubeVertices[i]))
    glEnd()    
    glEndList()

    # Debug Preferences
    from utilities.debug_prefs import debug_pref, Choice_boolean_True
    from utilities.debug_prefs import Choice_boolean_False
    choices = [Choice_boolean_False, Choice_boolean_True]

    # 20060314 grantham
    initial_choice = choices[drawing_globals.allow_color_sorting_default]
    drawing_globals.allow_color_sorting_pref = debug_pref(
        "Use Color Sorting?", initial_choice,
        prefs_key = drawing_globals.allow_color_sorting_prefs_key)
        #bruce 060323 removed non_debug = True for A7 release, changed default
        #value to False (far above), and changed its prefs_key so developers
        #start with the new default value.
    #russ 080225: Added.
    initial_choice = choices[drawing_globals.use_color_sorted_dls_default]
    drawing_globals.use_color_sorted_dls_pref = debug_pref(
        "Use Color-sorted Display Lists?", initial_choice,
        prefs_key = drawing_globals.use_color_sorted_dls_prefs_key)
    #russ 080225: Added.
    initial_choice = choices[drawing_globals.use_color_sorted_vbos_default]
    drawing_globals.use_color_sorted_vbos_pref = debug_pref(
        "Use Color-sorted Vertex Buffer Objects?", initial_choice,
        prefs_key = drawing_globals.use_color_sorted_vbos_prefs_key)

    #russ 080403: Added drawing variant selection
    variants = [
        "0. OpenGL 1.0 - glBegin/glEnd tri-strips vertex-by-vertex.",
        "1. OpenGL 1.1 - glDrawArrays from CPU RAM.",
        "2. OpenGL 1.1 - glDrawElements indexed arrays from CPU RAM.",
        "3. OpenGL 1.5 - glDrawArrays from graphics RAM VBO.",
        "4. OpenGL 1.5 - glDrawElements, verts in VBO, index in CPU.",
        "5. OpenGL 1.5 - VBO/IBO buffered glDrawElements."]
    drawing_globals.use_drawing_variant = debug_pref(
        "GLPane: drawing method",
        Choice(names = variants, values = range(len(variants)),
               defaultValue = drawing_globals.use_drawing_variant_default),
        prefs_key = drawing_globals.use_drawing_variant_prefs_key)

    # temporarily always print this, while default setting might be in flux,
    # and to avoid confusion if the two necessary prefs are set differently
    # [bruce 080305]
    if (drawing_globals.allow_color_sorting_pref and
        drawing_globals.use_color_sorted_dls_pref):
        print "\nnote: this session WILL use color sorted display lists"
    else:
        print "\nnote: this session will NOT use color sorted display lists"
    if (drawing_globals.allow_color_sorting_pref and
        drawing_globals.use_color_sorted_vbos_pref):
        print "note: this session WILL use", \
              "color sorted Vertex Buffer Objects\n"
    else:
        print "note: this session will NOT use", \
              "color sorted Vertex Buffer Objects\n"

    # 20060313 grantham Added use_c_renderer debug pref, can
    # take out when C renderer used by default.
    if drawing_globals.quux_module_import_succeeded:
        initial_choice = choices[drawing_globals.use_c_renderer_default]
        drawing_globals.use_c_renderer = (
            debug_pref("Use native C renderer?",
                       initial_choice,
                       prefs_key = drawing_globals.use_c_renderer_prefs_key))
            #bruce 060323 removed non_debug = True for A7 release, and changed
            # its prefs_key so developers start over with the default value.

    #initTexture('C:\\Huaicai\\atom\\temp\\newSample.png', 128,128)
    return # from setup_drawer
Ejemplo n.º 32
0
def draw_vane( bond, a1p, a2p, ord_pi, rad, col ):
    """
    Draw a vane (extending on two opposite sides of the bond axis) [#doc more];
    use ord_pi to determine how intense it is (not yet sure how, maybe by mixing
    in bgcolor??);

    a1p and a2p should be unit vectors perp to bond and no more than 90 degrees
    apart when seen along it; they should be in the bond's coordinate system.

    rad is inner radius of vanes, typically the cylinder radius for the sigma
    bond graphic.

    If col is not boolean false, use it as the vane color; otherwise, use a
    constant color which might be influenced by the pi orbital occupancy.
    """
    from utilities.debug_prefs import debug_pref
    from utilities.debug_prefs import Choice_boolean_True, Choice_boolean_False
    ## twisted = debug_pref('pi vanes/ribbons', Choice_boolean_False)
    # one of ['multicyl','vane','ribbon']
    pi_bond_style = env.prefs[ pibondStyle_prefs_key]
    twisted = (pi_bond_style == 'ribbon')
    poles = debug_pref('pi vanes/poles', Choice_boolean_True)
    draw_outer_edges = debug_pref('pi vanes/draw edges', Choice_boolean_True)
        #bruce 050730 new feature, so that edge-on vanes are still visible
    draw_normals = debug_pref('pi vanes/draw normals', Choice_boolean_False)
    print_vane_params = debug_pref('pi vanes/print params',
                                   Choice_boolean_False)
    if print_vane_params:
        print "draw vane",a1p,vlen(a1p),a2p,vlen(a2p),ord_pi
    if twisted:
        d12 = dot(a1p, a2p)
        ## assert d12 >= 0.0
        if d12 < 0.0:
            d12 = 0.0
        if d12 > 1.0:
            d12 = 1.0
        twist = math.acos(d12) # in radians
            # this is numerically inaccurate (since d12 is) near d12 == 1.0, but
            # that's ok, since it's only compared to threshholds (by ceil())
            # which correspond to d12 values not near 1.0.
            # (#e btw, we could optim the common case (ntwists == 1) by
            #  inverting this comparison to get the equivalent threshhold for
            #  d12.)
        maxtwist = MAXTWIST # debug_pref doesn't yet have a PrefsType for this
        # number of segments needed, to limit each segment's twist to MAXTWIST
        ntwists = max(1, int( math.ceil( twist / maxtwist ) ))
        pass
    if col:
        color = col
    else:
        #bruce 050804: initial test of bond color prefs; inadequate in several
        #  ways ###@@@
        from foundation.preferences import prefs_context
        prefs = prefs_context()
        from utilities.prefs_constants import bondVaneColor_prefs_key
        #k I hope this color tuple of floats is in the correct prefs format
        color = prefs.get(bondVaneColor_prefs_key)
        # protect following code from color being None (which causes bus error,
        # maybe in PyOpenGL)
        assert len(color) == 3
        
        ###@@@ it would be much faster to update this pref (or almost any
        # graphics color pref) if the OpenGL command to set the color was in its
        # own display list, redefined when the redraw starts, and called from
        # inside every other display list that needs it.  Then when you changed
        # it, gl_update would be enough -- the chunk display lists would not
        # need to be remade.
        
        ###@@@ problems include:
        # - being fast enough
        # + dflt should be specified in just one place, and earlier than in this
        #   place, so it can show up in prefs ui before this runs (in fact, even
        #   earlier than when this module is first imported, which might be only
        #   when needed),
        # - existing prefs don't have all the color vars needed (eg no
        #   toolong-highlighted color)
        # - being able to track them only when finally used, not when pulled
        #   into convenience vars before final use -- this might even be an
        #   issue if we precompute a formula from a color-pref, but only count
        #   it as used if that result is used.  (we could decide to track the
        #   formula res as a separate thing, i suppose)
##    a1pos = bond.atom1.posn()
##    a2pos = bond.atom2.posn()
    a1pos, c1, center, c2, a2pos, toolong = bond.geom
    if not toolong:
        c1 = c2 = center # don't know if needed
    x_axis = a2pos - a1pos
    # from 1 to 2.5, with 1 moved out to shrink width according to ord_pi
    width = 1.5 * ord_pi
    inner, outer = 2.5 - width, 2.5
    radius_pairs = [(outer, inner, outer), (-inner, -outer, -outer)]
        # the order within each pair matters, since it affects the polys drawn
        # below being CW or CCW!  but for purposes of edges, we also have to
        # know which one is *really* outer...  thus the third elt (edge_outer)
        # of the tuple.
    # OpenGL code
    #e could optim this to use Numeric calcs and OpenGL vertex array, with
    #  vertex normals and smooth shading, maybe even color ramp of some kind...
    #e want polygon outlines?
    #e want a 1d texture to emphasize the vane's ribbonness & help show ord_pi?
    glDisable(GL_CULL_FACE)
    #bruce 051215 use apply_material(color) instead of glMaterialfv, partly to
    # prevent bug of passing 3-tuple to glMaterialfv, partly to make the vanes
    # appear specular, partly to thereby fix bug 1216 (which was probably caused
    # by not setting specular color here, thus letting it remain from whatever
    # happened to be drawn just before). If we decide vanes should *not* appear
    # specular, we have to actively turn off specular color here rather than
    # ignoring the issue.  One way would be to create and use some new
    # functionality like apply_material(color, specular=False).
    apply_material(color)
    # gl args partly guessed #e should add specularity, shininess...
    ## glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE)
        # For vane lighting to be correct, two-sided polygon lighting is
        # required, and every polygon's vertex winding order (CCW) has to match
        # its normal vector, as both are produced by the following code. This
        # means that any changes to the orders of lists of vertices or vectors
        # in this code have to be considered carefully.  But it's ok if a1p and
        # a2p are negated (fortunately, since calling code arbitrarily negates
        # them), since this reverses the poly scan directions in two ways at
        # once (e.g. via pvec and perpvec in the quads case below).  (For ribbon
        # option, it's only ok if they're negated together; for quads case,
        # independent negation is ok.  I'm pretty sure calling code only negates
        # them together.)  [bruce 050725]
    for outer, inner, edge_outer in radius_pairs:
        normals = []
        edgeverts = []
        if twisted:
            glBegin(GL_TRIANGLE_STRIP)
            for i in range(1+ntwists):
                t = float(i) / ntwists # 0.0 to 1.0
                # one minus t (python syntax doesn't let me name it just 1mt)
                _1mt = 1.0 - t
                #e could optimize, not sure it matters
                axispos = _1mt * a1pos + t * a2pos
                # let it get smaller in the middle for large twist (rather than
                # using angles in calc)
                pvec = _1mt * a1p + t * a2p
                # (rationale: shows weakness of bond. real reason: programmer is
                # in a hurry.)
                    #e btw, it might be better to show twist by mismatch of
                    #  larger rectangular vanes, in the middle; and it's faster
                    #  to draw.
                # Could also "* ord_pi" rather than using color, if we worked
                # out proper min radius.
                ## pvec *= (rad * 2.5)
                perpvec = norm(cross(x_axis, pvec))
                # test shows this is needed not only for smoothness, but to make
                # the lighting work at all
                glNormal3fv( perpvec)
                outervert = axispos + pvec * rad * outer
                innervert = axispos + pvec * rad * inner
                glVertex3fv( outervert)
                ## not needed, since the same normal as above
                ## glNormal3fv( perpvec)
                glVertex3fv( innervert)
                #e color? want to smooth-shade it using atom colors, or the
                #  blue/gray for bond order, gray in center?
                if draw_normals:
                    normals.append(( axispos + pvec * rad * edge_outer,
                                     perpvec ))
                if draw_outer_edges:
                    edgeverts.append( axispos + pvec * rad * edge_outer )
            glEnd()
        else:
            glBegin(GL_QUADS)
            for axispos, axispos_c, pvec, normalfactor in \
                    [(a1pos,c1,a1p,-1), (a2pos,c2,a2p,1)]:
                perpvec = norm(cross(x_axis, pvec)) * normalfactor
                glNormal3fv( perpvec)
                glVertex3fv( axispos   + pvec * rad * inner)
                glVertex3fv( axispos   + pvec * rad * outer)
                glVertex3fv( axispos_c + pvec * rad * outer)
                    # This (axispos_c + pvec * rad * outer) would be the corner
                    # we connect by a line, even when not draw_outer_edges, if
                    # outer == edge_outer -- but it might or might not be.
                glVertex3fv( axispos_c + pvec * rad * inner)
                if draw_normals:
                    normals.append(( axispos/2.0 +
                                       axispos_c/2.0 + pvec * rad * edge_outer,
                                     perpvec ))
                if draw_outer_edges:
                    # Kluge to reverse order of first loop body but not second.
                    edgeverts.reverse()
                    edgeverts.append( axispos_c + pvec * rad * edge_outer)
                    edgeverts.append( axispos   + pvec * rad * edge_outer)
                else:
                    # At least connect the halves of each vane, so that twist
                    # doesn't make them look like 2 vanes.
                    edgeverts.append( axispos_c + pvec * rad * edge_outer)
            glEnd()
##            glBegin(GL_LINES)
##            glColor3fv(color)
##            for axispos, axispos_c, pvec in [(a1pos,c1,a1p), (a2pos,c2,a2p)]:
##                glVertex3fv( axispos_c + pvec * rad * outer)
##            glEnd()
        glDisable(GL_LIGHTING) # for lines... don't know if this matters
        if poles:
            glBegin(GL_LINES)
            glColor3fv(color)
            for axispos, pvec in [(a1pos,a1p), (a2pos,a2p)]:
                glVertex3fv( axispos + pvec * rad *  outer)
                glVertex3fv( axispos + pvec * rad * -outer)
            glEnd()
        if normals:
            glBegin(GL_LINES)
            glColor3fv(white)
            for base, vec in normals:
                glVertex3fv(base)
                glVertex3fv(base + vec)
            glEnd()
        if edgeverts:
            glBegin(GL_LINE_STRIP)
            glColor3fv(color)
            for vert in edgeverts:
                glVertex3fv(vert)
            glEnd()
        glEnable(GL_LIGHTING)
    glEnable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE)
    return
Ejemplo n.º 33
0
def setup_drawer():
    """
    Set up the usual constant display lists in the current OpenGL context.

    WARNING: THIS IS ONLY CORRECT IF ONLY ONE GL CONTEXT CONTAINS DISPLAY LISTS
    -- or more precisely, only the GL context this has last been called in (or
    one which shares its display lists) will work properly with the routines in
    drawer.py, since the allocated display list names are stored in globals set
    by this function, but in general those names might differ if this was called
    in different GL contexts.
    """
    spherelistbase = glGenLists(_NUM_SPHERE_SIZES)
    sphereList = []
    for i in range(_NUM_SPHERE_SIZES):
        sphereList += [spherelistbase+i]
        glNewList(sphereList[i], GL_COMPILE)
        glBegin(GL_TRIANGLE_STRIP) # GL_LINE_LOOP to see edges
        stripVerts = getSphereTriStrips(i)
        for vertNorm in stripVerts:
            glNormal3fv(vertNorm)
            glVertex3fv(vertNorm)
            continue
        glEnd()
        glEndList()
        continue
    drawing_globals.sphereList = sphereList

    # Sphere triangle-strip vertices for each level of detail.
    # (Cache and re-use the work of making them.)
    # Can use in converter-wrappered calls like glVertexPointerfv,
    # but the python arrays are re-copied to C each time.
    sphereArrays = []
    for i in range(_NUM_SPHERE_SIZES):
        sphereArrays += [getSphereTriStrips(i)]
        continue
    drawing_globals.sphereArrays = sphereArrays

    # Sphere glDrawArrays triangle-strip vertices for C calls.
    # (Cache and re-use the work of converting a C version.)
    # Used in thinly-wrappered calls like glVertexPointer.
    sphereCArrays = []
    for i in range(_NUM_SPHERE_SIZES):
        CArray = numpy.array(sphereArrays[i], dtype = numpy.float32)
        sphereCArrays += [CArray]
        continue
    drawing_globals.sphereCArrays = sphereCArrays

    # Sphere indexed vertices.
    # (Cache and re-use the work of making the indexes.)
    # Can use in converter-wrappered calls like glDrawElementsui,
    # but the python arrays are re-copied to C each time.
    sphereElements = []             # Pairs of lists (index, verts) .
    for i in range(_NUM_SPHERE_SIZES):
        sphereElements += [indexVerts(sphereArrays[i], .0001)]
        continue
    drawing_globals.sphereElements = sphereElements

    # Sphere glDrawElements index and vertex arrays for C calls.
    sphereCIndexTypes = []          # numpy index unsigned types.
    sphereGLIndexTypes = []         # GL index types for drawElements.
    sphereCElements = []            # Pairs of numpy arrays (Cindex, Cverts) .
    for i in range(_NUM_SPHERE_SIZES):
        (index, verts) = sphereElements[i]
        if len(index) < 256:
            Ctype = numpy.uint8
            GLtype = GL_UNSIGNED_BYTE
        else:
            Ctype = numpy.uint16
            GLtype = GL_UNSIGNED_SHORT
            pass
        sphereCIndexTypes += [Ctype]
        sphereGLIndexTypes += [GLtype]
        sphereCIndex = numpy.array(index, dtype = Ctype)
        sphereCVerts = numpy.array(verts, dtype = numpy.float32)
        sphereCElements += [(sphereCIndex, sphereCVerts)]
        continue
    drawing_globals.sphereCIndexTypes = sphereCIndexTypes
    drawing_globals.sphereGLIndexTypes = sphereGLIndexTypes
    drawing_globals.sphereCElements = sphereCElements

    if glGetString(GL_EXTENSIONS).find("GL_ARB_vertex_buffer_object") >= 0:

        # A GLBufferObject version for glDrawArrays.
        sphereArrayVBOs = []
        for i in range(_NUM_SPHERE_SIZES):
            vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB,
                                 sphereCArrays[i], GL_STATIC_DRAW)
            sphereArrayVBOs += [vbo]
            continue
        drawing_globals.sphereArrayVBOs = sphereArrayVBOs

        # A GLBufferObject version for glDrawElements indexed verts.
        sphereElementVBOs = []              # Pairs of (IBO, VBO)
        for i in range(_NUM_SPHERE_SIZES):
            ibo = GLBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB,
                                 sphereCElements[i][0], GL_STATIC_DRAW)
            vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB,
                                 sphereCElements[i][1], GL_STATIC_DRAW)
            sphereElementVBOs += [(ibo, vbo)]
            continue
        drawing_globals.sphereElementVBOs = sphereElementVBOs

        ibo.unbind()
        vbo.unbind()
        pass

    #bruce 060415
    drawing_globals.wiresphere1list = wiresphere1list = glGenLists(1)
    glNewList(wiresphere1list, GL_COMPILE)
    didlines = {} # don't draw each triangle edge more than once

    def shoulddoline(v1,v2):
        # make sure not list (unhashable) or Numeric array (bug in __eq__)
        v1 = tuple(v1)
        v2 = tuple(v2)
        if (v1,v2) not in didlines:
            didlines[(v1,v2)] = didlines[(v2,v1)] = None
            return True
        return False
    def doline(v1,v2):
        if shoulddoline(v1,v2):
            glVertex3fv(v1)
            glVertex3fv(v2)
        return
    glBegin(GL_LINES)
    ocdec = getSphereTriangles(1)
    for tri in ocdec:
        #e Could probably optim this more, e.g. using a vertex array or VBO or
        #  maybe GL_LINE_STRIP.
        doline(tri[0], tri[1])
        doline(tri[1], tri[2])
        doline(tri[2], tri[0])
    glEnd()
    glEndList()

    drawing_globals.CylList = CylList = glGenLists(1)
    glNewList(CylList, GL_COMPILE)
    glBegin(GL_TRIANGLE_STRIP)
    for (vtop, ntop, vbot, nbot) in drawing_globals.cylinderEdges:
        glNormal3fv(nbot)
        glVertex3fv(vbot)
        glNormal3fv(ntop)
        glVertex3fv(vtop)
    glEnd()
    glEndList()

    drawing_globals.CapList = CapList = glGenLists(1)
    glNewList(CapList, GL_COMPILE)
    glNormal3fv(drawing_globals.cap0n)
    glBegin(GL_POLYGON)
    for p in drawing_globals.drum0:
        glVertex3fv(p)
    glEnd()
    glNormal3fv(drawing_globals.cap1n)
    glBegin(GL_POLYGON)
    #bruce 060609 fix "ragged edge" bug in this endcap: drum1 -> drum2
    for p in drawing_globals.drum2:
        glVertex3fv(p)
    glEnd()
    glEndList()

    drawing_globals.diamondGridList = diamondGridList = glGenLists(1)
    glNewList(diamondGridList, GL_COMPILE)
    glBegin(GL_LINES)
    for p in drawing_globals.digrid:
        glVertex(p[0])
        glVertex(p[1])
    glEnd()
    glEndList()

    drawing_globals.lonsGridList = lonsGridList = glGenLists(1)
    glNewList(lonsGridList, GL_COMPILE)
    glBegin(GL_LINES)
    for p in drawing_globals.lonsEdges:
        glVertex(p[0])
        glVertex(p[1])
    glEnd()
    glEndList()

    drawing_globals.CubeList = CubeList = glGenLists(1)
    glNewList(CubeList, GL_COMPILE)
    glBegin(GL_QUAD_STRIP)
    # note: CubeList has only 4 faces of the cube; only suitable for use in
    # wireframes; see also solidCubeList [bruce 051215 comment reporting
    # grantham 20051213 observation]
    glVertex((-1,-1,-1))
    glVertex(( 1,-1,-1))
    glVertex((-1, 1,-1))
    glVertex(( 1, 1,-1))
    glVertex((-1, 1, 1))
    glVertex(( 1, 1, 1))
    glVertex((-1,-1, 1))
    glVertex(( 1,-1, 1))
    glVertex((-1,-1,-1))
    glVertex(( 1,-1,-1))
    glEnd()
    glEndList()

    drawing_globals.solidCubeList = solidCubeList = glGenLists(1)
    glNewList(solidCubeList, GL_COMPILE)
    glBegin(GL_QUADS)
    for i in xrange(len(drawing_globals.cubeIndices)):
        avenormals = V(0,0,0) #bruce 060302 fixed normals for flat shading
        for j in xrange(4) :
            nTuple = tuple(
                drawing_globals.cubeNormals[drawing_globals.cubeIndices[i][j]])
            avenormals += A(nTuple)
        avenormals = norm(avenormals)
        for j in xrange(4) :
            vTuple = tuple(
                drawing_globals.cubeVertices[drawing_globals.cubeIndices[i][j]])
            #bruce 060302 made size compatible with glut.glutSolidCube(1.0)
            vTuple = A(vTuple) * 0.5
            glNormal3fv(avenormals)
            glVertex3fv(vTuple)
    glEnd()
    glEndList()

    drawing_globals.rotSignList = rotSignList = glGenLists(1)
    glNewList(rotSignList, GL_COMPILE)
    glBegin(GL_LINE_STRIP)
    for ii in xrange(len(drawing_globals.rotS0n)):
        glVertex3fv(tuple(drawing_globals.rotS0n[ii]))
    glEnd()
    glBegin(GL_LINE_STRIP)
    for ii in xrange(len(drawing_globals.rotS1n)):
        glVertex3fv(tuple(drawing_globals.rotS1n[ii]))
    glEnd()
    glBegin(GL_TRIANGLES)
    for v in drawing_globals.arrow0Vertices + drawing_globals.arrow1Vertices:
        glVertex3f(v[0], v[1], v[2])
    glEnd()
    glEndList()

    drawing_globals.linearArrowList = linearArrowList = glGenLists(1)
    glNewList(linearArrowList, GL_COMPILE)
    glBegin(GL_TRIANGLES)
    for v in drawing_globals.linearArrowVertices:
        glVertex3f(v[0], v[1], v[2])
    glEnd()
    glEndList()

    drawing_globals.linearLineList = linearLineList = glGenLists(1)
    glNewList(linearLineList, GL_COMPILE)
    glEnable(GL_LINE_SMOOTH)
    glBegin(GL_LINES)
    glVertex3f(0.0, 0.0, -drawing_globals.halfHeight)
    glVertex3f(0.0, 0.0, drawing_globals.halfHeight)
    glEnd()
    glDisable(GL_LINE_SMOOTH)
    glEndList()

    drawing_globals.circleList = circleList = glGenLists(1)
    glNewList(circleList, GL_COMPILE)
    glBegin(GL_LINE_LOOP)
    for ii in range(60):
        x = cos(ii*2.0*pi/60)
        y = sin(ii*2.0*pi/60)
        glVertex3f(x, y, 0.0)
    glEnd()
    glEndList()

    # piotr 080405
    drawing_globals.filledCircleList = filledCircleList = glGenLists(1)
    glNewList(filledCircleList, GL_COMPILE)
    glBegin(GL_POLYGON)
    for ii in range(60):
        x = cos(ii*2.0*pi/60)
        y = sin(ii*2.0*pi/60)
        glVertex3f(x, y, 0.0)
    glEnd()
    glEndList()

    drawing_globals.lineCubeList = lineCubeList = glGenLists(1)
    glNewList(lineCubeList, GL_COMPILE)
    glBegin(GL_LINES)
    cvIndices = [0,1, 2,3, 4,5, 6,7, 0,3, 1,2, 5,6, 4,7, 0,4, 1,5, 2,6, 3,7]
    for i in cvIndices:
        glVertex3fv(tuple(drawing_globals.cubeVertices[i]))
    glEnd()
    glEndList()

    #initTexture('C:\\Huaicai\\atom\\temp\\newSample.png', 128,128)
    return # from setup_drawer
Ejemplo n.º 34
0
def draw_vane( bond, a1p, a2p, ord_pi, rad, col ):
    """
    Draw a vane (extending on two opposite sides of the bond axis) [#doc more];
    use ord_pi to determine how intense it is (not yet sure how, maybe by mixing
    in bgcolor??);

    a1p and a2p should be unit vectors perp to bond and no more than 90 degrees
    apart when seen along it; they should be in the bond's coordinate system.

    rad is inner radius of vanes, typically the cylinder radius for the sigma
    bond graphic.

    If col is not boolean false, use it as the vane color; otherwise, use a
    constant color which might be influenced by the pi orbital occupancy.
    """
    from utilities.debug_prefs import debug_pref
    from utilities.debug_prefs import Choice_boolean_True, Choice_boolean_False
    ## twisted = debug_pref('pi vanes/ribbons', Choice_boolean_False)
    # one of ['multicyl','vane','ribbon']
    pi_bond_style = env.prefs[ pibondStyle_prefs_key]
    twisted = (pi_bond_style == 'ribbon')
    poles = debug_pref('pi vanes/poles', Choice_boolean_True)
    draw_outer_edges = debug_pref('pi vanes/draw edges', Choice_boolean_True)
        #bruce 050730 new feature, so that edge-on vanes are still visible
    draw_normals = debug_pref('pi vanes/draw normals', Choice_boolean_False)
    print_vane_params = debug_pref('pi vanes/print params',
                                   Choice_boolean_False)
    if print_vane_params:
        print "draw vane",a1p,vlen(a1p),a2p,vlen(a2p),ord_pi
    if twisted:
        d12 = dot(a1p, a2p)
        ## assert d12 >= 0.0
        if d12 < 0.0:
            d12 = 0.0
        if d12 > 1.0:
            d12 = 1.0
        twist = math.acos(d12) # in radians
            # this is numerically inaccurate (since d12 is) near d12 == 1.0, but
            # that's ok, since it's only compared to threshholds (by ceil())
            # which correspond to d12 values not near 1.0.
            # (#e btw, we could optim the common case (ntwists == 1) by
            #  inverting this comparison to get the equivalent threshhold for
            #  d12.)
        maxtwist = MAXTWIST # debug_pref doesn't yet have a PrefsType for this
        # number of segments needed, to limit each segment's twist to MAXTWIST
        ntwists = max(1, int( math.ceil( twist / maxtwist ) ))
        pass
    if col:
        color = col
    else:
        #bruce 050804: initial test of bond color prefs; inadequate in several
        #  ways #######@@@@@@@
        from foundation.preferences import prefs_context
        prefs = prefs_context()
        from utilities.prefs_constants import bondVaneColor_prefs_key
        #k I hope this color tuple of floats is in the correct prefs format
        color = prefs.get(bondVaneColor_prefs_key)
        # protect following code from color being None (which causes bus error,
        # maybe in PyOpenGL)
        assert len(color) == 3
        
        #####@@@@@ it would be much faster to update this pref (or almost any
        # graphics color pref) if the OpenGL command to set the color was in its
        # own display list, redefined when the redraw starts, and called from
        # inside every other display list that needs it.  Then when you changed
        # it, gl_update would be enough -- the chunk display lists would not
        # need to be remade.
        
        ###@@@ problems include:
        # - being fast enough
        # + dflt should be specified in just one place, and earlier than in this
        #   place, so it can show up in prefs ui before this runs (in fact, even
        #   earlier than when this module is first imported, which might be only
        #   when needed),
        # - existing prefs don't have all the color vars needed (eg no
        #   toolong-highlighted color)
        # - being able to track them only when finally used, not when pulled
        #   into convenience vars before final use -- this might even be an
        #   issue if we precompute a formula from a color-pref, but only count
        #   it as used if that result is used.  (we could decide to track the
        #   formula res as a separate thing, i suppose)
##    a1pos = bond.atom1.posn()
##    a2pos = bond.atom2.posn()
    a1pos, c1, center, c2, a2pos, toolong = bond.geom
    if not toolong:
        c1 = c2 = center # don't know if needed
    x_axis = a2pos - a1pos
    # from 1 to 2.5, with 1 moved out to shrink width according to ord_pi
    width = 1.5 * ord_pi
    inner, outer = 2.5 - width, 2.5
    radius_pairs = [(outer, inner, outer), (-inner, -outer, -outer)]
        # the order within each pair matters, since it affects the polys drawn
        # below being CW or CCW!  but for purposes of edges, we also have to
        # know which one is *really* outer...  thus the third elt (edge_outer)
        # of the tuple.
    # OpenGL code
    #e could optim this to use Numeric calcs and OpenGL vertex array, with
    #  vertex normals and smooth shading, maybe even color ramp of some kind...
    #e want polygon outlines?
    #e want a 1d texture to emphasize the vane's ribbonness & help show ord_pi?
    glDisable(GL_CULL_FACE)
    #bruce 051215 use apply_material(color) instead of glMaterialfv, partly to
    # prevent bug of passing 3-tuple to glMaterialfv, partly to make the vanes
    # appear specular, partly to thereby fix bug 1216 (which was probably caused
    # by not setting specular color here, thus letting it remain from whatever
    # happened to be drawn just before). If we decide vanes should *not* appear
    # specular, we have to actively turn off specular color here rather than
    # ignoring the issue.  One way would be to create and use some new
    # functionality like apply_material(color, specular=False).
    apply_material(color)
    # gl args partly guessed #e should add specularity, shininess...
    ## glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE)
        # For vane lighting to be correct, two-sided polygon lighting is
        # required, and every polygon's vertex winding order (CCW) has to match
        # its normal vector, as both are produced by the following code. This
        # means that any changes to the orders of lists of vertices or vectors
        # in this code have to be considered carefully.  But it's ok if a1p and
        # a2p are negated (fortunately, since calling code arbitrarily negates
        # them), since this reverses the poly scan directions in two ways at
        # once (e.g. via pvec and perpvec in the quads case below).  (For ribbon
        # option, it's only ok if they're negated together; for quads case,
        # independent negation is ok.  I'm pretty sure calling code only negates
        # them together.)  [bruce 050725]
    for outer, inner, edge_outer in radius_pairs:
        normals = []
        edgeverts = []
        if twisted:
            glBegin(GL_TRIANGLE_STRIP)
            for i in range(1+ntwists):
                t = float(i) / ntwists # 0.0 to 1.0
                # one minus t (python syntax doesn't let me name it just 1mt)
                _1mt = 1.0 - t
                #e could optimize, not sure it matters
                axispos = _1mt * a1pos + t * a2pos
                # let it get smaller in the middle for large twist (rather than
                # using angles in calc)
                pvec = _1mt * a1p + t * a2p
                # (rationale: shows weakness of bond. real reason: programmer is
                # in a hurry.)
                    #e btw, it might be better to show twist by mismatch of
                    #  larger rectangular vanes, in the middle; and it's faster
                    #  to draw.
                # Could also "* ord_pi" rather than using color, if we worked
                # out proper min radius.
                ## pvec *= (rad * 2.5)
                perpvec = norm(cross(x_axis, pvec))
                # test shows this is needed not only for smoothness, but to make
                # the lighting work at all
                glNormal3fv( perpvec)
                outervert = axispos + pvec * rad * outer
                innervert = axispos + pvec * rad * inner
                glVertex3fv( outervert)
                ## not needed, since the same normal as above
                ## glNormal3fv( perpvec)
                glVertex3fv( innervert)
                #e color? want to smooth-shade it using atom colors, or the
                #  blue/gray for bond order, gray in center?
                if draw_normals:
                    normals.append(( axispos + pvec * rad * edge_outer,
                                     perpvec ))
                if draw_outer_edges:
                    edgeverts.append( axispos + pvec * rad * edge_outer )
            glEnd()
        else:
            glBegin(GL_QUADS)
            for axispos, axispos_c, pvec, normalfactor in \
                    [(a1pos,c1,a1p,-1), (a2pos,c2,a2p,1)]:
                perpvec = norm(cross(x_axis, pvec)) * normalfactor
                glNormal3fv( perpvec)
                glVertex3fv( axispos   + pvec * rad * inner)
                glVertex3fv( axispos   + pvec * rad * outer)
                glVertex3fv( axispos_c + pvec * rad * outer)
                    # This (axispos_c + pvec * rad * outer) would be the corner
                    # we connect by a line, even when not draw_outer_edges, if
                    # outer == edge_outer -- but it might or might not be.
                glVertex3fv( axispos_c + pvec * rad * inner)
                if draw_normals:
                    normals.append(( axispos/2.0 +
                                       axispos_c/2.0 + pvec * rad * edge_outer,
                                     perpvec ))
                if draw_outer_edges:
                    # Kluge to reverse order of first loop body but not second.
                    edgeverts.reverse()
                    edgeverts.append( axispos_c + pvec * rad * edge_outer)
                    edgeverts.append( axispos   + pvec * rad * edge_outer)
                else:
                    # At least connect the halves of each vane, so that twist
                    # doesn't make them look like 2 vanes.
                    edgeverts.append( axispos_c + pvec * rad * edge_outer)
            glEnd()
##            glBegin(GL_LINES)
##            glColor3fv(color)
##            for axispos, axispos_c, pvec in [(a1pos,c1,a1p), (a2pos,c2,a2p)]:
##                glVertex3fv( axispos_c + pvec * rad * outer)
##            glEnd()
        glDisable(GL_LIGHTING) # for lines... don't know if this matters
        if poles:
            glBegin(GL_LINES)
            glColor3fv(color)
            for axispos, pvec in [(a1pos,a1p), (a2pos,a2p)]:
                glVertex3fv( axispos + pvec * rad *  outer)
                glVertex3fv( axispos + pvec * rad * -outer)
            glEnd()
        if normals:
            glBegin(GL_LINES)
            glColor3fv(white)
            for base, vec in normals:
                glVertex3fv(base)
                glVertex3fv(base + vec)
            glEnd()
        if edgeverts:
            glBegin(GL_LINE_STRIP)
            glColor3fv(color)
            for vert in edgeverts:
                glVertex3fv(vert)
            glEnd()
        glEnable(GL_LIGHTING)
    glEnable(GL_CULL_FACE)
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE)
    return