Пример #1
0
    def draw(self):
        """
        Draws each frame.
        """
        print("draw()")
        # DRAW STUFF HERE
        glDisable(GL_TEXTURE_RECTANGLE_ARB)
        glColor4f(1.0, 0.8, 0.2, 1.0)
        glPushMatrix()
        glScale(0.5, 0.5, 1.0)
        draw_square()
        glPopMatrix()

        glColor4f(1.0, 1.0, 0.0, 0.8)
        num = 64
        for i in range(num):
            x = (i / float(num)) * 4 - 2
            draw_line(float(x), -2.0, float(x), 2.0)
            draw_line(-2.0, float(x), 2.0, float(x))

        if self.texture_id is not None:
            glColor4f(1.0, 1.0, 1.0, 1.0)
            glEnable(GL_TEXTURE_RECTANGLE_ARB)
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.texture_id)
            glPushMatrix()
            glScale(0.4, 0.3, 1.0)
            draw_textured_square(320, 240)
            glPopMatrix()
        else:
            print "No texture to draw"
Пример #2
0
    def draw(self):
        """
        Draws each frame.
        """
        print("draw()")
        # DRAW STUFF HERE
        glDisable(GL_TEXTURE_RECTANGLE_ARB)
        glColor4f(1.0, 0.8, 0.2, 1.0)
        glPushMatrix()
        glScale(0.5, 0.5, 1.0)
        draw_square()
        glPopMatrix()

        glColor4f(1.0, 1.0, 0.0, 0.8)
        num = 64
        for i in range(num):
            x = (i / float(num)) * 4 - 2
            draw_line(float(x), -2.0, float(x), 2.0)
            draw_line(-2.0, float(x), 2.0, float(x))

        if self.texture_id is not None:
            glColor4f(1.0, 1.0, 1.0, 1.0)
            glEnable(GL_TEXTURE_RECTANGLE_ARB)
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.texture_id)
            glPushMatrix()
            glScale(0.4, 0.3, 1.0)
            draw_textured_square(320, 240)
            glPopMatrix()
        else:
            print "No texture to draw"
Пример #3
0
 def draw(self):
     '''Draw the svg on screen'''
     with gx_matrix:
         glTranslate(self.x, self.y, 0)
         glScale(self._scale_x, self._scale_y, 1)
         glTranslate(self.anchor_x, self.anchor_y, 0)
         self.svg_object.draw()
Пример #4
0
 def draw(self):
     '''Draw the svg on screen'''
     with gx_matrix:
         glTranslate(self.x, self.y, 0)
         glScale(self._scale_x, self._scale_y, 1)
         glTranslate(self.anchor_x, self.anchor_y, 0)
         self.svg_object.draw()
Пример #5
0
def main(path=None):
    glutInit(sys.argv)

    if sys.platform == 'darwin':
        if not path:
            path = dialog()

    if not path:
        sys.exit(0)

    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE)
    glutInitWindowPosition(0, 0)
    glutInitWindowSize(730, 650)

    win = glutCreateWindow(b'MIDI Player')

    (width, height, img) = read_image(join(dirname(__file__), 'mixer.ppm'))
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
                 GL_UNSIGNED_BYTE, img)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)

    glMatrixMode(GL_TEXTURE)
    glLoadIdentity()
    glScale(1 / width, 1 / height, 1)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, 730, 0, 650, 0, 1)

    player = Player(win, path, width, height)

    glutDisplayFunc(player.display_func)
    glutKeyboardFunc(player.keyboard_func)
    glutMouseFunc(player.mouse_func)
    glutMotionFunc(player.motion_func)
    glutIdleFunc(player.process_events)

    submenus = []
    for instrument in range(128):
        if instrument % 8 == 0:
            submenus.append([
                families[instrument // 8],
                glutCreateMenu(player.change_instrument)
            ])
        glutAddMenuEntry(instruments[instrument].encode('ascii'), instrument)
    glutCreateMenu(player.change_instrument)
    for family, submenu in submenus:
        glutAddSubMenu(family.encode('ascii'), submenu)
    glutAttachMenu(GLUT_RIGHT_BUTTON)

    glutMainLoop()
Пример #6
0
def main(path=None):
    glutInit(sys.argv)

    if sys.platform == 'darwin':
        if not path:
            path = dialog()

    if not path:
        sys.exit(0)

    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE)
    glutInitWindowPosition(0, 0)
    glutInitWindowSize(730, 650)

    win = glutCreateWindow(b'MIDI Player')

    (width, height, img) = read_image(join(dirname(__file__), 'mixer.ppm'))
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0,
                 GL_RGB, GL_UNSIGNED_BYTE, img)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)

    glMatrixMode(GL_TEXTURE)
    glLoadIdentity()
    glScale(1/width, 1/height, 1)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, 730, 0, 650, 0, 1)

    player = Player(win, path, width, height)

    glutDisplayFunc(player.display_func)
    glutKeyboardFunc(player.keyboard_func)
    glutMouseFunc(player.mouse_func)
    glutMotionFunc(player.motion_func)
    glutIdleFunc(player.process_events)

    submenus = []
    for instrument in range(128):
        if instrument % 8 == 0:
            submenus.append([families[instrument // 8],
                             glutCreateMenu(player.change_instrument)])
        glutAddMenuEntry(instruments[instrument].encode('ascii'), instrument)
    glutCreateMenu(player.change_instrument)
    for family, submenu in submenus:
        glutAddSubMenu(family.encode('ascii'), submenu)
    glutAttachMenu(GLUT_RIGHT_BUTTON)

    glutMainLoop()
Пример #7
0
    def draw_sphere(
            self,
            sphere_position,
            sphere_radius,
            contours=45,
            color=RGBA(0.2, 0.5, 0.5, 0.5),
    ):

        glPushMatrix()
        glTranslatef(sphere_position[0], sphere_position[1],
                     sphere_position[2])
        glScale(sphere_radius, sphere_radius, sphere_radius)
        self.sphere.draw(color, primitive_type=GL_LINE_STRIP)
        glPopMatrix()
Пример #8
0
def scale(*args):
   ''' Scale the model in x-, y-, and z-directions.

   syntax:
      scale(s)
      scale(sx, sy, sz)
      scale([sx, sy, sz])
   '''

   if len(args) == 1 and type(args[0]) == float:
      sx = sy = sz = args[0]
   else:
      sx, sy, sz = Vector.helper(*args).data()

   glScale(sx, sy, sz)
Пример #9
0
 def draw(self):
     """Render the link with OpenGL"""
     glPushMatrix()
     glTranslatef(self.pos[0], self.pos[1], self.pos[2])  # move to location
     glMultMatrixf(self.q_rot.transformation_matrix.T
                   )  # then rotate to desired orientation
     glScale(self.size[0], self.size[1],
             self.size[2])  # scale to the desired size
     glColor3f(self.color[0], self.color[1],
               self.color[2])  # set the drawing color
     self.draw_cube()
     glPopMatrix()
     glBegin(GL_LINES)
     glVertex3fv(self.pos + self.get_r())
     glVertex3fv(self.pos + self.get_r() + self.display_force)
     glEnd()
Пример #10
0
 def RenderScene(self):
     """draws the actual descriptor"""
     glClear(GL_COLOR_BUFFER_BIT)
     glMatrixMode(GL_MODELVIEW)
     glLoadIdentity()
     glPushMatrix()
     glTranslatef(-1.0, 0.0, 0.0)
     # draw at -1.0/0.0 - 0.0/1.0
     self.map.Draw(self.descriptor)
     glPopMatrix()
     glPushMatrix()
     # draw at 0.0/0.0 - 1.0/1.0 (standard)
     self.graph.Draw()
     glPopMatrix()
     glPushMatrix()
     glTranslatef(-1.0, -1.0, 0.0)
     # draw at -1.0/-1.0 - 0.0/1.0
     glScale(2.0, 1.0, 1.0)
     self.text.Draw()
     glPopMatrix()
     glutSwapBuffers()
Пример #11
0
Файл: map.py Проект: reims/wesen
 def Draw(self, descriptor=[]):
     """Draws a map with all objects in the world,
     according to the descriptor."""
     GuiObject.Draw(self)
     # TODO get rid of any frame mechanism parts here
     frame = self._getFrameData()["frame"]
     glTranslatef(frame, 2 * frame, 0.0)
     # moving away from the frame
     blockSize = (1 - 2 * frame) / self.worldLength
     scaleFactor = blockSize
     # data = narray(reduce(lambda a,b: a + b,
     # 		     map(self.__descToArray,
     # 			 descriptor)),
     # 	      "f");
     if len(descriptor) > 0:
         # valuesPerObject = len(self.__descToArray(descriptor[0]))
         if self._vbo is None:
             self._BuildData(descriptor)
         for _id, obj in self._dirty_objects.items():
             self._UpdateObject(_id, obj)
         self._dirty_objects = {}
         glTranslatef(frame, 2 * frame, 0.0)
         # moving away from the frame
         glScale(scaleFactor, scaleFactor, 1.0)
         self._vbo.bind()
         self._vbo.copy_data()
         try:
             glEnableClientState(GL_VERTEX_ARRAY)
             glEnableClientState(GL_COLOR_ARRAY)
             # 2 coordinates with 4 color values with 4 bytes each in
             # between
             glVertexPointer(2, GL_FLOAT, 24, self._vbo)
             # 4 color values with 2 coordinates with 4 bytes each in
             # between
             glColorPointer(4, GL_FLOAT, 24, self._vbo + 8)
             glDrawArrays(GL_TRIANGLES, 0, 3 * 2 * (self._max_index + 1))
         finally:
             self._vbo.unbind()
             glDisableClientState(GL_VERTEX_ARRAY)
             glDisableClientState(GL_COLOR_ARRAY)
Пример #12
0
Файл: map.py Проект: reims/wesen
 def Draw(self, descriptor=[]):
     """Draws a map with all objects in the world,
     according to the descriptor."""
     GuiObject.Draw(self)
     # TODO get rid of any frame mechanism parts here
     frame = self._getFrameData()["frame"]
     glTranslatef(frame, 2 * frame, 0.0)
     # moving away from the frame
     blockSize = (1 - 2 * frame) / self.worldLength
     scaleFactor = blockSize
     # data = narray(reduce(lambda a,b: a + b,
     # 		     map(self.__descToArray,
     # 			 descriptor)),
     # 	      "f");
     if len(descriptor) > 0:
         #valuesPerObject = len(self.__descToArray(descriptor[0]))
         if self._vbo is None:
             self._BuildData(descriptor)
         for _id, obj in self._dirty_objects.items():
             self._UpdateObject(_id, obj)
         self._dirty_objects = {}
         glTranslatef(frame, 2 * frame, 0.0)
         # moving away from the frame
         glScale(scaleFactor, scaleFactor, 1.0)
         self._vbo.bind()
         self._vbo.copy_data()
         try:
             glEnableClientState(GL_VERTEX_ARRAY)
             glEnableClientState(GL_COLOR_ARRAY)
             # 2 coordinates with 4 color values with 4 bytes each in
             # between
             glVertexPointer(2, GL_FLOAT, 24, self._vbo)
             # 4 color values with 2 coordinates with 4 bytes each in
             # between
             glColorPointer(4, GL_FLOAT, 24, self._vbo + 8)
             glDrawArrays(GL_TRIANGLES, 0, 3 * 2 * (self._max_index + 1))
         finally:
             self._vbo.unbind()
             glDisableClientState(GL_VERTEX_ARRAY)
             glDisableClientState(GL_COLOR_ARRAY)
Пример #13
0
    def drawCube(self):
        glPushMatrix()
        glLoadIdentity()
        glTranslate(0.0, 0.0, -50.0)
        glScale(20.0, 20.0, 20.0)
        glRotate(self.yRotDeg, 0.2, 1.0, 0.3)
        glTranslate(-0.5, -0.5, -0.5)
        glColor3f(1, 1, 1)

        glBegin(GL_LINES)

        glVertex3f(0., 0., 0.)
        glVertex3f(1., 0., 0.)
        glVertex3f(1., 0., 0.)
        glVertex3f(1., 1., 0.)
        glVertex3f(1., 1., 0.)
        glVertex3f(0., 1., 0.)
        glVertex3f(0., 1., 0.)
        glVertex3f(0., 0., 0.)

        glVertex3f(0., 0., 1.)
        glVertex3f(1., 0., 1.)
        glVertex3f(1., 0., 1.)
        glVertex3f(1., 1., 1.)
        glVertex3f(1., 1., 1.)
        glVertex3f(0., 1., 1.)
        glVertex3f(0., 1., 1.)
        glVertex3f(0., 0., 1.)

        glVertex3f(0., 0., 0.)
        glVertex3f(0., 0., 1.)
        glVertex3f(1., 0., 0.)
        glVertex3f(1., 0., 1.)
        glVertex3f(1., 1., 0.)
        glVertex3f(1., 1., 1.)
        glVertex3f(0., 1., 0.)
        glVertex3f(0., 1., 1.)
        glEnd()
        glPopMatrix()
Пример #14
0
    def display(self):

        glLoadIdentity()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        gluLookAt(self.cam_pos.x, self.cam_pos.y, self.cam_pos.z,
                  self.cam_focus.x, self.cam_focus.y, self.cam_focus.z, 0, 1,
                  0)

        self.level.draw()

        glLoadIdentity()

        gluLookAt(0, -0.5, 2.5, 0, 0, 0, 0, 1, 0)

        wdth = 0.3
        glTranslate(
            0.0 -
            (len(self.level.solomon.current_state.keys()) - 1) * wdth / 2.0,
            -1.3, 0)

        if debug == True:
            for k in self.level.solomon.current_state.keys():
                col = "red"
                if self.level.solomon.current_state[k]: col = "green"
                glMaterialfv(GL_FRONT, GL_DIFFUSE, colours[col])
                glutSolidCube(wdth - 0.02)
                glTranslate(wdth, 0, 0)
                glPushMatrix()
                #glLoadIdentity()
                glScale(0.005, 0.01, -0.01)
                glTranslate(-90, 4, -20)
                #glTranslate(-180,-70,0)
                glTranslate(-wdth, 0, 0)
                self.letters.drawString(k[:4])
                glPopMatrix()

        glLoadIdentity()

        gluLookAt(0, -0.5, 2.5, 0, 0, 0, 0, 1, 0)

        wdth = 0.2

        joystick_actions = [x for x in dir(self.joystick) if x[0:2] == "is"]
        glTranslate(0.0 - (len(joystick_actions) - 1) * wdth / 2.0, -1.0, 0)

        if debug == True:
            for k in joystick_actions:
                #print(k)
                col = "red"
                if getattr(self.joystick, k)(self.keys): col = "green"
                glMaterialfv(GL_FRONT, GL_DIFFUSE, colours[col])
                glutSolidCube(wdth - 0.02)
                glTranslate(wdth, 0, 0)
                glPushMatrix()
                #glLoadIdentity()
                glScale(0.005, 0.01, -0.01)
                glTranslate(-45, 0, -20)
                #glTranslate(-180,-70,0)
                glTranslate(-wdth, 0, 0)
                self.letters.drawString(k[2:4])
                glPopMatrix()

        glLoadIdentity()

        gluLookAt(0, 0, 2.5, 0, 0, 0, 0, 1, 0)

        glScale(0.01, 0.01, -0.01)
        glTranslate(-180, -70, 0)

        if debug == True:
            self.letters.drawString('X:' + str(self.level.solomon.x) + ' Y:' +
                                    str(self.level.solomon.y))
            glTranslate(0, 0 - 15, 0)
            gx, gy = int(self.level.solomon.x), int(self.level.solomon.y)
            self.letters.drawString('G {0} on: {1} below: {2}'.format(
                str((gx, gy)), self.level.grid[gy][gx],
                self.level.grid[gy - 1][gx]))
            glTranslate(0, 0 - 15, 0)
            self.letters.drawString('')

        glutSwapBuffers()
Пример #15
0
    def draw(self):
        if self.delegate is None:
            # 070210 -- but I'm not sure if this is a complete ###KLUGE, or good but ought to be done more generally,
            # or if it would be better to do it totally differently by instantiating None into something like Spacer(). ##k
            return

        glMatrixMode(GL_MODELVIEW)  # not needed
        glPushMatrix()
        glLoadIdentity()
        try:
            glpane = self.env.glpane
            aspect = glpane.aspect  # revised by bruce 070919
            corner = self.corner
            delegate = self.delegate
            want_depth = self.want_depth
            # note about cov_depth:
            ## self.near = 0.25
            ## self.far = 12.0
            # so I predict cov_depth is 0.75 / 11.75 == 0.063829787234042548
            # but let's print it from a place that computes it, and see.
            # ... hmm, only place under that name is in selectMode.py, and that prints 0.765957458814 -- I bet it's something
            # different, but not sure. ###k (doesn't matter for now)

            # modified from _setup_modelview:

            saveplace = self.transient_state  # see if this fixes the bug 061211 1117a mentioned below -- it does, use it.
            # BUG (probably not related to this code, but not known for sure):
            # mousewheel zoom makes checkboxes inside DrawInCorner
            # either not highlight, or if they are close enough to
            # the center of the screen (I guess), highlight in the
            # wrong size and place. For more info and a partial theory,
            # see the 081202 update in DisplayListChunk.py docstring.
            # Before I realized the connection to DisplayListChunk,
            # I tried using saveplace = self.per_frame_state instead of
            # self.transient_state above, but that had no effect on the bug.
            # That was before I fixed some bugs in same_vals related to
            # numpy.ndarray, when I was plagued with mysterious behavior
            # from those in my debug code (since solved), but I tried it
            # again afterwards and it still doesn't fix this bug, which
            # makes sense if my partial theory about it is true.
            #
            # In principle (unrelated to this bug), I'm dubious we're
            # storing this state in the right place, but I won't change
            # it for now (see related older comments below).
            #
            # Note: I fixed the bug in another way, by changing
            # Highlightable's projection option to default True.
            # [bruce 081202]

            if glpane.current_glselect or (0 and 'KLUGE' and hasattr(
                    saveplace, '_saved_stuff')):
                # kluge did make it faster; still slow, and confounded by the highlighting-delay bug;
                # now I fixed that bug, and now it seems only normally slow for this module -- ok for now.

                # when that cond is false, we have a nonstandard projection matrix
                # (see also the related comments in save_coords_if_safe in Highlightable.py)
                # [bruce 081204 comment]

                x1, y1, z1 = saveplace._saved_stuff  # this is needed to make highlighting work!
                ###BUG [061211 1117a; fixed now, see above, using saveplace = self.transient_state]:
                # if we click on an object in testexpr_15d (with DrawInCorner used for other objs in the testbed)
                # before it has a chance to show its highlighted form, at least after a recent reload, we get an attrerror here.
                # Easy to repeat in the test conditions mentioned (on g5). Not sure how it can affect a different obj (self)
                # than the one clicked on too quickly. Best fix would be to let glpane give us the requested info,
                # which is usually the same for all callers anyway, and the same across reloads (just not across resizes).
                # But it does depend on want_depth, and (via gluUnProject) on the current modelview coords
                # (and projection coords if we ever changed them). So it's not completely clear how to combine ease, efficiency,
                # and safety, for that optim in general, even w/o needing this bugfix.
                #    But the bug is easy to hit, so needs a soon fix... maybe memoize it with a key corresponding to your own
                # assumed choice of modelview coords and want_depth? Or maybe enough to put it into the transient_state? TRY THAT. works.
                if _DEBUG_SAVED_STUFF:
                    print "_DEBUG_SAVED_STUFF: retrieved", x1, y1, z1
            else:
                x1, y1, z1 = saveplace._saved_stuff = \
                             gluUnProject(glpane.width, glpane.height, want_depth)
                # max x and y, i.e. right top
                # (note, to get the min x and y we'd want to pass (0, 0, want_depth),
                #  since these are windows coords -- (0, 0) is bottom left corner (not center))
                #
                # Note: Using gluUnProject is probably better than knowing and reversing _setup_projection,
                # since it doesn't depend on knowing the setup code, except meaning of glpane height & width attrs,
                # and knowing that origin is centered between them and 0.
                if _DEBUG_SAVED_STUFF:
                    print "_DEBUG_SAVED_STUFF: saved", x1, y1, z1


##            print x1,y1,z1
# use glScale to compensate for zoom * scale in _setup_projection,
# for error in PIXELS, and for want_depth != cov_depth
            x1wish = glpane.width / 2.0 * PIXELS  # / 2.0 because in these coords, screen center indeed has x == y == 0
            r = x1 / x1wish
            glScale(r, r, r)
            ##            x1 /= r
            ##            y1 /= r
            z1 /= r
            # now the following might work except for z, so fix z here
            glTranslatef(0.0, 0.0, z1)
            del x1, y1  # not presently used
            if _DEBUG_SAVED_STUFF:
                print "_DEBUG_SAVED_STUFF:     r = %r, translated z by z1 == %r" % (
                    r, z1)

            # I don't think we need to usage-track glpane height & width (or scale or zoomFactor etc)
            # since we'll redraw when those change, and redo this calc every time we draw.
            # The only exception would be if we're rendering into a display list.
            # I don't know if this code (gluUnProject) would even work in that case.
            # [I think I wrote a similar comment in some other file earlier today. #k]

            # move to desired corner, and align it with same corner of lbox
            # (#e could use an alignment prim for the corner if we had one)

            if corner in corner_abbrevs:
                # normalize how corner is expressed, into a 2-tuple of +-1's
                corner = corner_abbrevs[corner]

            x, y = corner

            if x == -1:  # left
                x_offset = -glpane.width / 2.0 * PIXELS + delegate.bleft
            elif x == +1:  # right
                x_offset = +glpane.width / 2.0 * PIXELS - delegate.bright
            elif x == 0:  # center(x)
                x_offset = 0
                # note: before 070210 this was (+ delegate.bleft - delegate.bright) / 2.0,
                # which has an unwanted (since unavoidable) centering effect; use explicit Center if desired.
            else:
                print "invalid corner", corner  ###
                raise ValueError, "invalid corner %r" % (corner, )

            if y == -1:  # bottom
                y_offset = -glpane.height / 2.0 * PIXELS + delegate.bbottom
            elif y == +1:  # top
                y_offset = +glpane.height / 2.0 * PIXELS - delegate.btop
            elif y == 0:  # center(y)
                y_offset = 0
                # note: # note: before 070210 this was (+ delegate.bbottom - delegate.btop) / 2.0
            else:
                print "invalid corner", corner  ###
                raise ValueError, "invalid corner %r" % (corner, )

            offset = (x_offset, y_offset)
            glTranslatef(offset[0], offset[1], 0.0)

            if _DEBUG_SAVED_STUFF:
                print "_DEBUG_SAVED_STUFF:     offset =", offset

            self.drawkid(delegate)  ## delegate.draw()

        finally:
            glMatrixMode(GL_MODELVIEW)  # not needed
            glPopMatrix()

        return
Пример #16
0
    def draw(self):
        if self.delegate is None:
            # 070210 -- but I'm not sure if this is a complete ###KLUGE, or good but ought to be done more generally,
            # or if it would be better to do it totally differently by instantiating None into something like Spacer(). ##k
            return
        
        glMatrixMode(GL_MODELVIEW) # not needed
        glPushMatrix()
        glLoadIdentity()
        try:
            glpane = self.env.glpane
            aspect = glpane.aspect # revised by bruce 070919
            corner = self.corner
            delegate = self.delegate
            want_depth = self.want_depth
                # note about cov_depth:
                ## self.near = 0.25
                ## self.far = 12.0
                # so I predict cov_depth is 0.75 / 11.75 == 0.063829787234042548
                # but let's print it from a place that computes it, and see.
                # ... hmm, only place under that name is in selectMode.py, and that prints 0.765957458814 -- I bet it's something
                # different, but not sure. ###k (doesn't matter for now)

            # modified from _setup_modelview:

            saveplace = self.transient_state # see if this fixes the bug 061211 1117a mentioned below -- it does, use it.
                # BUG (probably not related to this code, but not known for sure):
                # mousewheel zoom makes checkboxes inside DrawInCorner
                # either not highlight, or if they are close enough to
                # the center of the screen (I guess), highlight in the
                # wrong size and place. For more info and a partial theory,
                # see the 081202 update in DisplayListChunk.py docstring.
                # Before I realized the connection to DisplayListChunk,
                # I tried using saveplace = self.per_frame_state instead of
                # self.transient_state above, but that had no effect on the bug.
                # That was before I fixed some bugs in same_vals related to
                # numpy.ndarray, when I was plagued with mysterious behavior
                # from those in my debug code (since solved), but I tried it
                # again afterwards and it still doesn't fix this bug, which
                # makes sense if my partial theory about it is true.
                #
                # In principle (unrelated to this bug), I'm dubious we're
                # storing this state in the right place, but I won't change
                # it for now (see related older comments below).
                #
                # Note: I fixed the bug in another way, by changing
                # Highlightable's projection option to default True.
                # [bruce 081202]
            
            if glpane.current_glselect or (0 and 'KLUGE' and hasattr(saveplace, '_saved_stuff')):
                            # kluge did make it faster; still slow, and confounded by the highlighting-delay bug;
                            # now I fixed that bug, and now it seems only normally slow for this module -- ok for now.
                
                # when that cond is false, we have a nonstandard projection matrix
                # (see also the related comments in save_coords_if_safe in Highlightable.py)
                # [bruce 081204 comment]

                x1, y1, z1 = saveplace._saved_stuff # this is needed to make highlighting work!
                ###BUG [061211 1117a; fixed now, see above, using saveplace = self.transient_state]:
                # if we click on an object in testexpr_15d (with DrawInCorner used for other objs in the testbed)
                # before it has a chance to show its highlighted form, at least after a recent reload, we get an attrerror here.
                # Easy to repeat in the test conditions mentioned (on g5). Not sure how it can affect a different obj (self)
                # than the one clicked on too quickly. Best fix would be to let glpane give us the requested info,
                # which is usually the same for all callers anyway, and the same across reloads (just not across resizes).
                # But it does depend on want_depth, and (via gluUnProject) on the current modelview coords
                # (and projection coords if we ever changed them). So it's not completely clear how to combine ease, efficiency,
                # and safety, for that optim in general, even w/o needing this bugfix.
                #    But the bug is easy to hit, so needs a soon fix... maybe memoize it with a key corresponding to your own
                # assumed choice of modelview coords and want_depth? Or maybe enough to put it into the transient_state? TRY THAT. works.
                if _DEBUG_SAVED_STUFF:
                    print "_DEBUG_SAVED_STUFF: retrieved", x1, y1, z1
            else:
                x1, y1, z1 = saveplace._saved_stuff = \
                             gluUnProject(glpane.width, glpane.height, want_depth)
                                # max x and y, i.e. right top
                # (note, to get the min x and y we'd want to pass (0, 0, want_depth),
                #  since these are windows coords -- (0, 0) is bottom left corner (not center))
                #
                # Note: Using gluUnProject is probably better than knowing and reversing _setup_projection,
                # since it doesn't depend on knowing the setup code, except meaning of glpane height & width attrs,
                # and knowing that origin is centered between them and 0.
                if _DEBUG_SAVED_STUFF:
                    print "_DEBUG_SAVED_STUFF: saved", x1, y1, z1
##            print x1,y1,z1
            # use glScale to compensate for zoom * scale in _setup_projection,
            # for error in PIXELS, and for want_depth != cov_depth
            x1wish = glpane.width / 2.0 * PIXELS # / 2.0 because in these coords, screen center indeed has x == y == 0
            r = x1 / x1wish
            glScale(r, r, r) 
##            x1 /= r
##            y1 /= r
            z1 /= r
            # now the following might work except for z, so fix z here
            glTranslatef( 0.0, 0.0, z1)
            del x1, y1 # not presently used
            if _DEBUG_SAVED_STUFF:
                print "_DEBUG_SAVED_STUFF:     r = %r, translated z by z1 == %r" % (r, z1)
            
            # I don't think we need to usage-track glpane height & width (or scale or zoomFactor etc)
            # since we'll redraw when those change, and redo this calc every time we draw.
            # The only exception would be if we're rendering into a display list.
            # I don't know if this code (gluUnProject) would even work in that case.
            # [I think I wrote a similar comment in some other file earlier today. #k]
            
            # move to desired corner, and align it with same corner of lbox
            # (#e could use an alignment prim for the corner if we had one)

            if corner in corner_abbrevs:
                # normalize how corner is expressed, into a 2-tuple of +-1's
                corner = corner_abbrevs[corner]

            x, y = corner

            if x == -1: # left
                x_offset = - glpane.width / 2.0 * PIXELS + delegate.bleft
            elif x == +1: # right
                x_offset = + glpane.width / 2.0 * PIXELS - delegate.bright
            elif x == 0: # center(x)
                x_offset = 0
                    # note: before 070210 this was (+ delegate.bleft - delegate.bright) / 2.0,
                    # which has an unwanted (since unavoidable) centering effect; use explicit Center if desired.
            else:
                print "invalid corner",corner###
                raise ValueError, "invalid corner %r" % (corner,)
                
            if y == -1: # bottom
                y_offset = - glpane.height / 2.0 * PIXELS + delegate.bbottom
            elif y == +1: # top
                y_offset = + glpane.height / 2.0 * PIXELS - delegate.btop
            elif y == 0: # center(y)
                y_offset = 0
                    # note: # note: before 070210 this was (+ delegate.bbottom - delegate.btop) / 2.0
            else:
                print "invalid corner",corner###
                raise ValueError, "invalid corner %r" % (corner,)

            offset = (x_offset, y_offset)
            glTranslatef(offset[0], offset[1], 0.0)

            if _DEBUG_SAVED_STUFF:
                print "_DEBUG_SAVED_STUFF:     offset =", offset
            
            self.drawkid( delegate) ## delegate.draw()
            
        finally:
            glMatrixMode(GL_MODELVIEW) # not needed
            glPopMatrix()

        return
Пример #17
0
    def draw(self):
        if self.delegate is None:
            # 070210 -- but I'm not sure if this is a complete ###KLUGE, or good but ought to be done more generally,
            # or if it would be better to do it totally differently by instantiating None into something like Spacer(). ##k
            return
        
        glMatrixMode(GL_MODELVIEW) # not needed
        glPushMatrix()
        glLoadIdentity()
        try:
            glpane = self.env.glpane
##            aspect = 1.0 ###WRONG -- should use glpane.aspect (which exists as of 070919)
            aspect = glpane.aspect # revised by bruce 070919, UNTESTED
            corner = self.corner
            delegate = self.delegate
            want_depth = self.want_depth
                # note about cov_depth:
                ## self.near = 0.25
                ## self.far = 12.0
                # so I predict cov_depth is 0.75 / 11.75 == 0.063829787234042548
                # but let's print it from a place that computes it, and see.
                # ... hmm, only place under that name is in selectMode.py, and that prints 0.765957458814 -- I bet it's something
                # different, but not sure. ###k (doesn't matter for now)

            # modified from _setup_modelview:

            saveplace = self.transient_state # see if this fixes the bug 061211 1117a mentioned below -- it does, use it.
            if glpane.current_glselect or (0 and 'KLUGE' and hasattr(saveplace, '_saved_stuff')):
                            # kluge did make it faster; still slow, and confounded by the highlighting-delay bug;
                            # now I fixed that bug, and now it seems only normally slow for this module -- ok for now.
                x1, y1, z1 = saveplace._saved_stuff # this is needed to make highlighting work!
                ###BUG [061211 1117a; fixed now, see above, using saveplace = self.transient_state]:
                # if we click on an object in testexpr_15d (with DrawInCorner used for other objs in the testbed)
                # before it has a chance to show its highlighted form, at least after a recent reload, we get an attrerror here.
                # Easy to repeat in the test conditions mentioned (on g5). Not sure how it can affect a different obj (self)
                # than the one clicked on too quickly. Best fix would be to let glpane give us the requested info,
                # which is usually the same for all callers anyway, and the same across reloads (just not across resizes).
                # But it does depend on want_depth, and (via gluUnProject) on the current modelview coords
                # (and projection coords if we ever changed them). So it's not completely clear how to combine ease, efficiency,
                # and safety, for that optim in general, even w/o needing this bugfix.
                #    But the bug is easy to hit, so needs a soon fix... maybe memoize it with a key corresponding to your own
                # assumed choice of modelview coords and want_depth? Or maybe enough to put it into the transient_state? TRY THAT. works.
            else:
                x1, y1, z1 = saveplace._saved_stuff = gluUnProject(glpane.width, glpane.height, want_depth) # max x and y, i.e. right top
                # (note, min x and y would be (0,0,want_depth), since these are windows coords, 0,0 is bottom left corner (not center))
                # Note: Using gluUnProject is probably better than knowing and reversing _setup_projection,
                # since it doesn't depend on knowing the setup code, except meaning of glpane height & width attrs,
                # and knowing that origin is centered between them.
##            print x1,y1,z1
            x1wish = glpane.width / 2.0 * PIXELS # / 2.0 because in these coords, screen center indeed has x == y == 0
            r = x1/x1wish
            glScale(r,r,r) # compensate for zoom*scale in _setup_projection, for error in PIXELS, and for want_depth != cov_depth
##            x1 /= r
##            y1 /= r
            z1 /= r
            # now the following might work except for z, so fix z here
            glTranslatef( 0.0, 0.0, z1)
            del x1,y1 # not presently used
            
            # I don't think we need to usage-track glpane height & width (or scale or zoomFactor etc)
            # since we'll redraw when those change, and redo this calc every time we draw.
            # The only exception would be if we're rendering into a display list.
            # I don't know if this code (gluUnProject) would even work in that case.
            # [I think I wrote a similar comment in some other file earlier today. #k]
            
            # move to desired corner, and align it with same corner of lbox
            # (#e could use an alignment prim for the corner if we had one)

            if corner in corner_abbrevs:
                # normalize how corner is expressed, into a 2-tuple of +-1's
                corner = corner_abbrevs[corner]

            x, y = corner

            if x == -1: # left
                x_offset = - glpane.width / 2.0 * PIXELS + delegate.bleft
            elif x == +1: # right
                x_offset = + glpane.width / 2.0 * PIXELS - delegate.bright
            elif x == 0: # center(x)
                x_offset = 0
                    # note: before 070210 this was (+ delegate.bleft - delegate.bright) / 2.0,
                    # which has an unwanted (since unavoidable) centering effect; use explicit Center if desired.
            else:
                print "invalid corner",corner###
                raise ValueError, "invalid corner %r" % (corner,)
                
            if y == -1: # bottom
                y_offset = - glpane.height / 2.0 * PIXELS + delegate.bbottom
            elif y == +1: # top
                y_offset = + glpane.height / 2.0 * PIXELS - delegate.btop
            elif y == 0: # center(y)
                y_offset = 0
                    # note: # note: before 070210 this was (+ delegate.bbottom - delegate.btop) / 2.0
            else:
                print "invalid corner",corner###
                raise ValueError, "invalid corner %r" % (corner,)

            offset = (x_offset, y_offset)
            glTranslatef(offset[0], offset[1], 0.0)
            
            self.drawkid( delegate) ## delegate.draw()
            
        finally:
            glMatrixMode(GL_MODELVIEW) # not needed
            glPopMatrix()

        return
Пример #18
0
    def draw(self):
        if self.delegate is None:
            # 070210 -- but I'm not sure if this is a complete ###KLUGE, or good but ought to be done more generally,
            # or if it would be better to do it totally differently by instantiating None into something like Spacer(). ##k
            return

        glMatrixMode(GL_MODELVIEW)  # not needed
        glPushMatrix()
        glLoadIdentity()
        try:
            glpane = self.env.glpane
            ##            aspect = 1.0 ###WRONG -- should use glpane.aspect (which exists as of 070919)
            aspect = glpane.aspect  # revised by bruce 070919, UNTESTED
            corner = self.corner
            delegate = self.delegate
            want_depth = self.want_depth
            # note about cov_depth:
            ## self.near = 0.25
            ## self.far = 12.0
            # so I predict cov_depth is 0.75 / 11.75 == 0.063829787234042548
            # but let's print it from a place that computes it, and see.
            # ... hmm, only place under that name is in selectMode.py, and that prints 0.765957458814 -- I bet it's something
            # different, but not sure. ###k (doesn't matter for now)

            # modified from _setup_modelview:

            saveplace = (
                self.transient_state
            )  # see if this fixes the bug 061211 1117a mentioned below -- it does, use it.
            if glpane.current_glselect or (0 and "KLUGE" and hasattr(saveplace, "_saved_stuff")):
                # kluge did make it faster; still slow, and confounded by the highlighting-delay bug;
                # now I fixed that bug, and now it seems only normally slow for this module -- ok for now.
                x1, y1, z1 = saveplace._saved_stuff  # this is needed to make highlighting work!
                ###BUG [061211 1117a; fixed now, see above, using saveplace = self.transient_state]:
                # if we click on an object in testexpr_15d (with DrawInCorner used for other objs in the testbed)
                # before it has a chance to show its highlighted form, at least after a recent reload, we get an attrerror here.
                # Easy to repeat in the test conditions mentioned (on g5). Not sure how it can affect a different obj (self)
                # than the one clicked on too quickly. Best fix would be to let glpane give us the requested info,
                # which is usually the same for all callers anyway, and the same across reloads (just not across resizes).
                # But it does depend on want_depth, and (via gluUnProject) on the current modelview coords
                # (and projection coords if we ever changed them). So it's not completely clear how to combine ease, efficiency,
                # and safety, for that optim in general, even w/o needing this bugfix.
                #    But the bug is easy to hit, so needs a soon fix... maybe memoize it with a key corresponding to your own
                # assumed choice of modelview coords and want_depth? Or maybe enough to put it into the transient_state? TRY THAT. works.
            else:
                x1, y1, z1 = saveplace._saved_stuff = gluUnProject(
                    glpane.width, glpane.height, want_depth
                )  # max x and y, i.e. right top
                # (note, min x and y would be (0,0,want_depth), since these are windows coords, 0,0 is bottom left corner (not center))
                # Note: Using gluUnProject is probably better than knowing and reversing _setup_projection,
                # since it doesn't depend on knowing the setup code, except meaning of glpane height & width attrs,
                # and knowing that origin is centered between them.
            ##            print x1,y1,z1
            x1wish = glpane.width / 2.0 * PIXELS  # / 2.0 because in these coords, screen center indeed has x == y == 0
            r = x1 / x1wish
            glScale(
                r, r, r
            )  # compensate for zoom*scale in _setup_projection, for error in PIXELS, and for want_depth != cov_depth
            ##            x1 /= r
            ##            y1 /= r
            z1 /= r
            # now the following might work except for z, so fix z here
            glTranslatef(0.0, 0.0, z1)
            del x1, y1  # not presently used

            # I don't think we need to usage-track glpane height & width (or scale or zoomFactor etc)
            # since we'll redraw when those change, and redo this calc every time we draw.
            # The only exception would be if we're rendering into a display list.
            # I don't know if this code (gluUnProject) would even work in that case.
            # [I think I wrote a similar comment in some other file earlier today. #k]

            # move to desired corner, and align it with same corner of lbox
            # (#e could use an alignment prim for the corner if we had one)

            if corner in corner_abbrevs:
                # normalize how corner is expressed, into a 2-tuple of +-1's
                corner = corner_abbrevs[corner]

            x, y = corner

            if x == -1:  # left
                x_offset = -glpane.width / 2.0 * PIXELS + delegate.bleft
            elif x == +1:  # right
                x_offset = +glpane.width / 2.0 * PIXELS - delegate.bright
            elif x == 0:  # center(x)
                x_offset = 0
                # note: before 070210 this was (+ delegate.bleft - delegate.bright) / 2.0,
                # which has an unwanted (since unavoidable) centering effect; use explicit Center if desired.
            else:
                print "invalid corner", corner  ###
                raise ValueError, "invalid corner %r" % (corner,)

            if y == -1:  # bottom
                y_offset = -glpane.height / 2.0 * PIXELS + delegate.bbottom
            elif y == +1:  # top
                y_offset = +glpane.height / 2.0 * PIXELS - delegate.btop
            elif y == 0:  # center(y)
                y_offset = 0
                # note: # note: before 070210 this was (+ delegate.bbottom - delegate.btop) / 2.0
            else:
                print "invalid corner", corner  ###
                raise ValueError, "invalid corner %r" % (corner,)

            offset = (x_offset, y_offset)
            glTranslatef(offset[0], offset[1], 0.0)

            self.drawkid(delegate)  ## delegate.draw()

        finally:
            glMatrixMode(GL_MODELVIEW)  # not needed
            glPopMatrix()

        return
Пример #19
0
    def draw_residuals(self, result):

        glMatrixMode(GL_PROJECTION)
        glPushMatrix()
        glLoadIdentity()
        glOrtho(0, 1, 0, 1, -1, 1)  # gl coord convention

        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()

        glTranslatef(0.01, 0.01, 0)

        glScale(1.5, 1.5, 1)

        glColor4f(1, 1, 1, 0.3)
        glBegin(GL_QUADS)
        glVertex3f(0, 0, 0)
        glVertex3f(0, 0.15, 0)
        glVertex3f(0.15, 0.15, 0)
        glVertex3f(0.15, 0, 0)
        glEnd()

        glTranslatef(0.01, 0.01, 0)

        glScale(0.13, 0.13, 1)

        vertices = [[0, 0], [0, 1]]
        glutils.draw_polyline(vertices,
                              thickness=2,
                              color=RGBA(1.0, 1.0, 1.0, 0.9))
        vertices = [[0, 0], [1, 0]]
        glutils.draw_polyline(vertices,
                              thickness=2,
                              color=RGBA(1.0, 1.0, 1.0, 0.9))

        glScale(1, 0.33, 1)

        vertices = [[0, 1], [1, 1]]
        glutils.draw_polyline(vertices,
                              thickness=1,
                              color=RGBA(1.0, 1.0, 1.0, 0.9))
        vertices = [[0, 2], [1, 2]]
        glutils.draw_polyline(vertices,
                              thickness=1,
                              color=RGBA(1.0, 1.0, 1.0, 0.9))
        vertices = [[0, 3], [1, 3]]
        glutils.draw_polyline(vertices,
                              thickness=1,
                              color=RGBA(1.0, 1.0, 1.0, 0.9))

        try:

            vertices = list(
                zip(
                    np.clip((np.asarray(result["debug_info"]["angles"]) - 10) /
                            40.0, 0, 1),
                    np.clip(
                        np.log10(np.array(result["debug_info"]["residuals"])) +
                        2,
                        0.1,
                        3.9,
                    ),
                ))

            alpha = 0.2 / (len(result["debug_info"]["angles"])**0.2)
            size = 2 + 10 / (len(result["debug_info"]["angles"])**0.1)

            glutils.draw_points(vertices,
                                size=size,
                                color=RGBA(255 / 255, 165 / 255, 0, alpha))

        except:

            pass

        glPopMatrix()
        glMatrixMode(GL_PROJECTION)
        glPopMatrix()
Пример #20
0
    def on_draw(self):
         
        glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA)

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()
        
        glTranslate(self.translatex, self.translatey, self.depth)
        
        if self.autoRun:
            glRotate(self.rotx,  0, 1, 0)
        
        else:
            # Perform arcball rotation.
            glScale(1,-1,1)
            glMultMatrixf(self.arcball.transform)
            glScale(1,-1,1)
        
        with displayListify("cubeTranslate") as shouldLeave:
            if shouldLeave: raise LeaveWith
                
            # Scale the co-ordinates so that they are correct
            glScale(2/128, 2/128, 2/128)
            
            glColor(0.25, 0.25, 0.25, 1)
            glutWireCube(255)
            
            glTranslate(-128, -128, -128)
        
        with displayListify("allPoints") as shouldLeave:
            if shouldLeave: raise LeaveWith
            
            with SaveMatrix():
                # Flip the co-ordinates and translate upwards
                glScale(1,-1,1)
                glColor(0.25, 0.25, 0.25, 0.5)
                glTranslate(0,-255,0)
                glPointSize(pointSize)
                for dat in reversed(vLists):
                    glTranslate(0., 0., 1./nChunks*255)
                    dat.draw(GL_POINTS)

        with displayListify("axisLabels") as shouldLeave:
            if shouldLeave: raise LeaveWith
        #if True:
            with SaveMatrix():
                glTranslate(128,0,0)
                self.makeLabel("End").draw()
                
                glTranslate(0,0,255)
                self.makeLabel("Beginning").draw()
                
                with SaveMatrix():
                    glTranslate(-128,128,0)
                    glRotate(90,0,0,1)
                    self.makeLabel("Byte 1").draw()
                
                glTranslate(0,255,0)
                self.makeLabel("Byte 2").draw()
        
        with displayListify("fileName") as shouldLeave:
            if shouldLeave: raise LeaveWith
            glLoadIdentity()
            
            with SaveMatrix():
                glColor(1,0,0)
                glTranslate(0,-2.2,-4)
                glScale(1/64, 1/64, 1/64)
                l = self.makeLabel(basename(currentInputFile))
                l.color = (0, 128, 230, 255)
                l.draw()
        
        glTranslate(0,0,-1)
        
        if self.autoRun:
        
            if self.rotx > 360 - 45:
                vlist = vertex_list(4, ('v2i', (-1, -1, 1, -1, 1, 1, -1, 1)))
                glColor(0,0,0,(self.rotx-(360-45))/45)
                vlist.draw(GL_QUADS)
                
            if self.rotx < 45:
                vlist = vertex_list(4, ('v2i', (-1, -1, 1, -1, 1, 1, -1, 1)))
                glColor(0,0,0,1-(self.rotx/45))
                vlist.draw(GL_QUADS)