def _Enable(self, side): """Activate the clipping plane""" eqnt = self.eqn * side #eqnt[3] = 0.0 - eqnt[3] GL.glClipPlane(self.clipPlaneNames[self.num], eqnt) GL.glEnable(self.clipPlaneNames[self.num])
def RedoDisplayList(self): #print "Common2d3dObject.RedoDisplayList", self if hasattr(self, 'dpyList') and self.dpyList is not None: lNewList = self.dpyList[0] else: lNewList = GL.glGenLists(1) self.viewer.deleteOpenglList() #lNewList = self.newList lContext = self.viewer.currentCamera.tk.call( self.viewer.currentCamera._w, 'contexttag') #print "lNewList Common2d3dObject.RedoDisplayList", lNewList, lContext, self.name self.dpyList = (lNewList, self.viewer.currentCamera.tk.call( self.viewer.currentCamera._w, 'contexttag')) GL.glNewList(self.dpyList[0], GL.GL_COMPILE) #print '+%d'%self.dpyList[0], lContext, "glNewList Common2d3dObject" if hasattr(self, 'Draw'): status = self.Draw() else: status = 0 #print '*%d'%GL.glGetIntegerv(GL.GL_LIST_INDEX), "glEndList Common2d3dObject" GL.glEndList() if status == 0: self.deleteOpenglList()
def deleteOpenglList(self): #print "Common2d3dObject.deleteOpenglList", self self.redoDspLst = 0 currentcontext = self.viewer.currentCamera.tk.call( self.viewer.currentCamera._w, 'contexttag') if self.dpyList is not None: if currentcontext != self.dpyList[1]: warnings.warn( """deleteOpenglList failed because the current context is the wrong one""" ) #print "currentcontext != self.dpyList[1]", currentcontext, self.dpyList[1] #import traceback;traceback.print_stack() else: #print '-%d'%self.dpyList[0], currentcontext,"glDeleteLists Common2d3dObject" GL.glDeleteLists(self.dpyList[0], 1) self.dpyList = None if self.pickDpyList is not None: if currentcontext != self.pickDpyList[1]: warnings.warn( """deleteOpenglList failed because the current context is the wrong one""" ) #print "currentcontext != self.pickDpyList[1]", currentcontext, self.pickDpyList[1] else: #print '-%d'%self.pickDpyList[0], currentcontext, "glDeleteLists Common2d3dObject2", GL.glDeleteLists(self.pickDpyList[0], 1) self.pickDpyList = None
def test_0031(self ): # example we test glMultMatrixf import Tkinter root = Tkinter.Tk() vi = OGLTkWidget(root) id = Numeric.array([1.,0.,0.,0., 0.,1.,0.,0., 0.,0.,1.,0., 0.,0.,0.,1.], "d") from opengltk.extent import _gllib as gllib #GL.glMultMatrixf(id) try: gllib.cvar.checkArgumentsInCWrapper = 0 GL.glMultMatrixf(id) # calling with bad argument gllib.cvar.checkArgumentsInCWrapper = 1 #import numpy.oldnumeric as Numeric id = Numeric.identity(4).astype('d') try: GL.glMultMatrixf(id) raise RuntimeError('failed to catch type error in wrapper') except TypeError: print 'Type Error caught succefully in wrapper' except ImportError: pass root.after(1000, root.quit ) root.mainloop() root.destroy()
def Draw(self): centers = self.vertexSet.vertices.array if len(centers) == 0: return faces = map(lambda x: [x], range(len(centers))) if self.materials[GL.GL_FRONT] and \ not self.inheritMaterial: fpProp = self.materials[GL.GL_FRONT].prop[:5] fpBind = self.materials[GL.GL_FRONT].binding[:5] else: fpProp = None fpBind = None if self.materials[GL.GL_BACK] and \ not self.inheritMaterial: bpProp = self.materials[GL.GL_BACK].prop[:5] bpBind = self.materials[GL.GL_BACK].binding[:5] else: bpProp = None bpBind = None texCoords = None if self.normals is None: GL.glDisable(GL.GL_LIGHTING) status = glDrawIndexedGeom(GL.GL_POINTS, self.vertexSet.vertices.array, faces, self.normals, texCoords, fpProp, bpProp, fpBind, bpBind, self.frontAndBack, 1) return status
def DrawArrays( mode, count, first=0): """glDrawArrays with default args model - GLenum count - GLsizei first - GLint """ GL.glDrawArrays( mode, first, count)
def RedoDisplayList(self): #print "Common2d3dObject.RedoDisplayList", self if hasattr(self, 'dpyList') and self.dpyList is not None: lNewList = self.dpyList[0] else: lNewList = GL.glGenLists(1) self.viewer.deleteOpenglList() #lNewList = self.newList lContext = self.viewer.currentCamera.tk.call(self.viewer.currentCamera._w, 'contexttag') #print "lNewList Common2d3dObject.RedoDisplayList", lNewList, lContext, self.name self.dpyList = ( lNewList, self.viewer.currentCamera.tk.call(self.viewer.currentCamera._w, 'contexttag') ) GL.glNewList(self.dpyList[0], GL.GL_COMPILE) #print '+%d'%self.dpyList[0], lContext, "glNewList Common2d3dObject" if hasattr(self, 'Draw'): status = self.Draw() else: status = 0 #print '*%d'%GL.glGetIntegerv(GL.GL_LIST_INDEX), "glEndList Common2d3dObject" GL.glEndList() if status == 0: self.deleteOpenglList()
def display(self): GL.glClear( GL.GL_COLOR_BUFFER_BIT) GL.glColor3f( 1.0, 1.0, 1.0) GL.glLoadIdentity() # clear the matrix # viewing transformation GLU.gluLookAt( 0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) GL.glScalef( 1.0, 2.0, 1.0) # modeling transformation GLUT.glutWireCube( 1.0) GL.glFlush()
def initProjection(self): if self.imarray is None: return self.tk.call(self._w, 'makecurrent') GL.glViewport(0, 0, self.width, self.height) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(0, float(self.width), 0, float(self.height), -1.0, 1.0) GL.glMatrixMode(GL.GL_MODELVIEW)
def Configure(self, *dummy): """guillaume: set the opengl viewport""" # unbind <configure, because changing size of togl widget creates such # an event, hence causing an endless loop self.unbind('<Configure>') self.configure(width=self.width, height=self.height) self.bind('<Configure>', self.Configure) GL.glViewport(0, 0, self.width, self.height)
def DisplayFunction(self): """ display function. may be re-implemented by subclass """ #print "Common2d3dObject.DisplayFunction", self if self.dpyList is not None: currentcontext = self.viewer.currentCamera.tk.call(self.viewer.currentCamera._w, 'contexttag') if currentcontext != self.dpyList[1]: warnings.warn("""DisplayFunction failed because the current context is the wrong one""") #print "currentcontext != self.dpyList[1]", currentcontext, self.dpyList[1] else: #print '#%d'%self.dpyList[0], currentcontext, "glCallList Common2d3d" GL.glCallList(self.dpyList[0])
def drawpolygons(self): g = self.geom vertices = g.getVertices() faces = g.getFaces() normals = g.getFNormals() GL.glDisable(GL.GL_CULL_FACE) for i,f in enumerate(faces): GL.glBegin(GL.GL_POLYGON) GL.glNormal3fv(normals[i]) for vi in f: GL.glVertex3fv(vertices[vi]) GL.glEnd() i+=1
def drawpolygons(self): g = self.geom vertices = g.getVertices() faces = g.getFaces() normals = g.getFNormals() GL.glDisable(GL.GL_CULL_FACE) for i, f in enumerate(faces): GL.glBegin(GL.GL_POLYGON) GL.glNormal3fv(normals[i]) for vi in f: GL.glVertex3fv(vertices[vi]) GL.glEnd() i += 1
def trRasterPos3f(self, x, y, z): """ Replacement for glRastePos3f() which avoids the problem with invalid raster pos. """ if self.CurrentTile < 0: # not doing tile rendering right now. Let OpenGL do this. GL.glRasterPos3f(float(x), float(y), float(z)) else: # Get modelview, projection and viewport modelview = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) proj = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = [0, 0, self.CurrentTileWidth, self.CurrentTileHeight]
def trRasterPos3f(self, x, y, z): """ Replacement for glRastePos3f() which avoids the problem with invalid raster pos. """ if self.CurrentTile<0: # not doing tile rendering right now. Let OpenGL do this. GL.glRasterPos3f(float(x), float(y), float(z)) else: # Get modelview, projection and viewport modelview = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) proj = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = [0, 0, self.CurrentTileWidth, self.CurrentTileHeight]
def drawOneLine(self, x1, y1, x2, y2): GL.glBegin(GL.GL_LINES) try: GL.glVertex2f(x1, y1) GL.glVertex2f(x2, y2) finally: GL.glEnd()
def drawOneLine(self, x1, y1, x2, y2): GL.glBegin( GL.GL_LINES) try: GL.glVertex2f( x1, y1) GL.glVertex2f( x2, y2) finally: GL.glEnd()
def doloop(self, name, shademodel, cbdisplay, cbreshape, cbkeyboard): GLUT.glutInit( sys.argv) GLUT.glutInitDisplayMode( GLUT.GLUT_SINGLE | GLUT.GLUT_RGB) GLUT.glutInitWindowSize( 500, 500) GLUT.glutInitWindowPosition( 100, 100) GLUT.glutCreateWindow( name) GL.glClearColor( 0.0, 0.0, 0.0, 0.0) GL.glShadeModel( GL.GL_FLAT) GLUT.glutDisplayFunc( cbdisplay) GLUT.glutReshapeFunc( cbreshape) GLUT.glutKeyboardFunc( cbkeyboard) GLUT.glutTimerFunc(1000, self.exitloop, 0) GLUT.glutMainLoop()
def glMaterialWithCheck(face, property, material, eps=0.001, check=True): """ Only calls glMaterial if the material is different from he current value face can be GL_FRONT or GL_BACK propety can be GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR or GL_EMISSION material is a 3-sequence RGBA, Alpha values are only test for ambient and diffuse properties """ global materialMemory #print 'glMaterialWithCheck', property, material if face==GL.GL_FRONT_AND_BACK: face=GL.GL_FRONT if property==GL.GL_SHININESS: matMem = materialMemory[face] if not check or fabs(matMem[4]-material) > eps: matMem[4] = material #GL.glMaterialfv( face, property, matMem[4] ) GL.glMaterialf( face, property, float(matMem[4]) ) else: if not material.flags.contiguous: material = Numeric.array(material,copy=1) propNum = viewerConst.propNum[property] matMem = materialMemory[face][propNum] ## print 'DIFFERENCE' ## print id(matMem), id(materialMemory[face][propNum]) ## print matMem ## print material ## print fabs(matMem[0]-material[0]) > eps ## print fabs(matMem[1]-material[1]) > eps ## print fabs(matMem[2]-material[2]) > eps ## print (fabs(matMem[3]-material[3]) > eps and propNum in (0,1)) if check: newCol = fabs(matMem[0]-material[0]) > eps or \ fabs(matMem[1]-material[1]) > eps or \ fabs(matMem[2]-material[2]) > eps or \ (fabs(matMem[3]-material[3]) > eps and propNum in (0,1)) else: newCol = True if newCol: #GL.glMaterialfv( face, property, material.tolist() ) #print 'SETTING' gllib.glMaterialfv( face, property, material) matMem[0] = material[0] matMem[1] = material[1] matMem[2] = material[2] matMem[3] = material[3]
def deleteTemplate(self): #print "Ellipsoids.deleteTemplate" # it is asumed the right OpenGL context is active assert self.templateDSPL is not None currentcontext = self.viewer.currentCamera.tk.call(self.viewer.currentCamera._w, 'contexttag') if currentcontext != self.templateDSPL[1]: import traceback;traceback.print_stack() warnings.warn('deleteTemplate failed because the current context is the wrong one') print "currentcontext != self.templateDSPL[1]", currentcontext, self.templateDSPL[1] else: #print '-%d'%self.templateDSPL[0], currentcontext, "glDeleteLists Ellipsoids" #print '-%d'%(self.templateDSPL[0]+1), currentcontext, "glDeleteLists Ellipsoids" #print '-%d'%(self.templateDSPL[0]+2), currentcontext, "glDeleteLists Ellipsoids" GL.glDeleteLists(self.templateDSPL[0], 3) self.templateDSPL = None
def apply(self): """setup current lightmodel for current OpenGL context""" if self.ambient is not None: GL.glLightModelfv(GL.GL_LIGHT_MODEL_AMBIENT, self.ambient); if self.localViewer is True: GL.glLightModelf(GL.GL_LIGHT_MODEL_LOCAL_VIEWER, GL.GL_TRUE); elif self.localViewer is False: GL.glLightModelf(GL.GL_LIGHT_MODEL_LOCAL_VIEWER, GL.GL_FALSE); if self.twoSide is True: GL.glLightModelf(GL.GL_LIGHT_MODEL_TWO_SIDE, GL.GL_TRUE); elif self.twoSide is False: GL.glLightModelf(GL.GL_LIGHT_MODEL_TWO_SIDE, GL.GL_FALSE);
def DisplayFunction(self): """ display function. may be re-implemented by subclass """ #print "Common2d3dObject.DisplayFunction", self if self.dpyList is not None: currentcontext = self.viewer.currentCamera.tk.call( self.viewer.currentCamera._w, 'contexttag') if currentcontext != self.dpyList[1]: warnings.warn( """DisplayFunction failed because the current context is the wrong one""" ) #print "currentcontext != self.dpyList[1]", currentcontext, self.dpyList[1] else: #print '#%d'%self.dpyList[0], currentcontext, "glCallList Common2d3d" GL.glCallList(self.dpyList[0])
def clearCache_cb(self): #print "clearing cache: " vi = self.vf.GUI.VIEWER currentcontext = vi.currentCamera.tk.call(vi.currentCamera._w, 'getcurrentcontext') for dl in self.dpyLists.keys(): if self.dpyLists[dl]is not None: if currentcontext != self.dpyLists[dl][1]: print "currentcontext != self.dpyLists[%d][1]" %(dl,), currentcontext, self.dpyLists[dl][1] c = vi.currentCamera c.tk.call(c._w, 'makecurrent') #import pdb; pdb.set_trace() #print "glDeleteLists TrajPlayerCached", self.dpyLists[dl][0] GL.glDeleteLists(self.dpyLists[dl][0], 1) self.dpyLists.pop(dl)
def clearCache_cb(self): #print "clearing cache: " vi = self.vf.GUI.VIEWER currentcontext = vi.currentCamera.tk.call(vi.currentCamera._w, 'contexttag') for dl in self.dpyLists.keys(): if self.dpyLists[dl]is not None: if currentcontext != self.dpyLists[dl][1]: print "currentcontext != self.dpyLists[%d][1]" %(dl,), currentcontext, self.dpyLists[dl][1] c = vi.currentCamera c.tk.call(c._w, 'makecurrent') #import pdb; pdb.set_trace() #print "glDeleteLists TrajPlayerCached", self.dpyLists[dl][0] GL.glDeleteLists(self.dpyLists[dl][0], 1) self.dpyLists.pop(dl)
def Draw(self): centers = self.getCoords(self.vertexSet.vertices.array) if len(centers) == 0: return #faces = Numeric.zeros((0,3), 'i') else: faces = self.getFaces(len(self.vertexSet.vertices.array)) if self.materials[GL.GL_FRONT] and \ not self.inheritMaterial: fpProp = self.materials[GL.GL_FRONT].prop[:5] fpBind = self.materials[GL.GL_FRONT].binding[:5] else: fpProp = None fpBind = None if self.materials[GL.GL_BACK] and \ not self.inheritMaterial: bpProp = self.materials[GL.GL_BACK].prop[:5] bpBind = self.materials[GL.GL_BACK].binding[:5] else: bpProp = None bpBind = None texCoords = None if self.lighting: if (self.invertNormals) and (self.normals is not None): norms = -self.normals else: norms = self.normals else: norms = None #GL.glDisable(GL.GL_DEPTH_TEST) if self.disableStencil is True: GL.glDisable(GL.GL_STENCIL_TEST) status = glDrawIndexedGeom(GL.GL_LINES, centers.astype('f'), faces, norms, texCoords, fpProp, bpProp, fpBind, bpBind, self.frontAndBack, 1) if self.disableStencil is True: GL.glEnable(GL.GL_STENCIL_TEST) #GL.glEnable(GL.GL_DEPTH_TEST) return status
def imageAsArray(self): width = self.width height = self.height if width is None or height is None: return None nar = Numeric.zeros(3*width*height, Numeric.UnsignedInt8) self.tk.call(self._w, 'makecurrent') GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1) # self.tk.call(self._w, 'swapbuffers') GL.glReadBuffer(GL.GL_BACK) _gllib.glReadPixels( 0, 0, width, height, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, nar) # self.tk.call(self._w, 'swapbuffers') return nar
def imageAsArray(self): width = self.width height = self.height if width is None or height is None: return None nar = Numeric.zeros(3 * width * height, Numeric.UnsignedInt8) self.tk.call(self._w, 'makecurrent') GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1) # self.tk.call(self._w, 'swapbuffers') GL.glReadBuffer(GL.GL_BACK) _gllib.glReadPixels(0, 0, width, height, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, nar) # self.tk.call(self._w, 'swapbuffers') return nar
def reshape(self, w, h): GL.glViewport(0, 0, w, h) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() if (w <= h): GLU.gluOrtho2D(0.0, 30.0, 0.0, 30.0 * h / w) else: GLU.gluOrtho2D(0.0, 30.0 * w / h, 0.0, 30.0) GL.glMatrixMode(GL.GL_MODELVIEW)
def reshape(self, w, h): GL.glViewport( 0, 0, w, h) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() if(w <= h): GLU.gluOrtho2D( 0.0, 30.0, 0.0, 30.0 * h/w) else: GLU.gluOrtho2D( 0.0, 30.0 * w/h, 0.0, 30.0) GL.glMatrixMode( GL.GL_MODELVIEW)
def Configure(self, *dummy): """guillaume: set the OpenGL Viewport for the material editor""" if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() #print 'Configure 1' width = self.winfo_width() height = self.winfo_height() if width > height: xo = (width - height) / 2 yo = 0 size = height else: xo = 0 yo = (height - width) / 2 size = width GL.glViewport(xo, yo, size, size)
def Configure(self, *dummy): """guillaume: set the OpenGL Viewport for the material editor""" if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() #print 'Configure 1' width = self.winfo_width() height = self.winfo_height() if width > height: xo = (width-height)/2 yo = 0 size = height else: xo = 0 yo = (height-width)/2 size = width GL.glViewport(xo, yo, size, size)
def Set(self, **kw): """Set various light model parameters""" self.viewer.currentCamera.Activate() tagModified = True val = getkw(kw, 'tagModified') if val is not None: tagModified = val assert tagModified in [True, False] self._modified = tagModified ambi = getkw(kw, 'ambient') if not ambi is None: if len(ambi)==3 or len(ambi)==4: self.ambient = OneColor( ambi ) GL.glLightModelfv(GL.GL_LIGHT_MODEL_AMBIENT, self.ambient); else: raise ValueError('length of new color must be 3 or 4') localViewer = getkw(kw, 'localViewer') if not localViewer is None: if localViewer in (True,1): GL.glLightModelf(GL.GL_LIGHT_MODEL_LOCAL_VIEWER, GL.GL_TRUE); elif localViewer in (False,0): GL.glLightModelf(GL.GL_LIGHT_MODEL_LOCAL_VIEWER, GL.GL_FALSE); else: raise AttributeError('localViewer can only be True or False') self.localViewer = localViewer twoSide = getkw(kw, 'twoSide') if not twoSide is None: if twoSide in (True,1): GL.glLightModelf(GL.GL_LIGHT_MODEL_TWO_SIDE, GL.GL_TRUE); elif twoSide in (False,0): GL.glLightModelf(GL.GL_LIGHT_MODEL_TWO_SIDE, GL.GL_FALSE); else: raise AttributeError('twoSide can only be True or False') self.twoSide = twoSide self.broadcast() if len(kw): print 'WARNING8: Keyword(s) %s not used' % kw.keys()
def GetMatrix(self, root=None, instance=None, scale=True, transpose=True): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Returns the matrix by which this object is transformed scale = False: returns the rotation and translation. no scaling info included Used to save the transformed geom --> coords --> new pdb file instance is a list of integer instance indices for all parents """ if root is None: root = self.viewer.rootObject if instance is None: instance = [0] p = self.parent while p: instance.append(0) p = p.parent GL.glPushMatrix() GL.glLoadIdentity() #print 'GetMatrix', instance self.BuildMat(self, root, scale, instance) #GL.glMultMatrixf(self.instanceMatricesFortran[instanceList[0]]]) m = Numeric.array(GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)).astype('f') GL.glPopMatrix() if Numeric.alltrue(m==Numeric.zeros(16).astype('f')): # this happens when Pmv has no GUI m = Numeric.identity(4) if transpose: return Numeric.transpose(Numeric.reshape(m, (4,4))) else: return Numeric.reshape(m, (4,4))
def deleteTemplate(self): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() #print "Spheres.deleteTemplate", self.templateDSPL # it is asumed the right OpenGL context is active if GL.glGetIntegerv(GL.GL_LIST_INDEX) == [0]: assert self.templateDSPL is not None currentcontext = self.viewer.currentCamera.tk.call(self.viewer.currentCamera._w, 'contexttag') if currentcontext != self.templateDSPL[1]: import traceback;traceback.print_stack() warnings.warn('deleteTemplate failed because the current context is the wrong one') print "currentcontext != self.templateDSPL[1]", currentcontext, self.templateDSPL[1] else: #print '-%d'%self.templateDSPL[0], currentcontext, "glDeleteLists Spheres0" #print '-%d'%(self.templateDSPL[0]+1), currentcontext, "glDeleteLists Spheres1" #print '-%d'%(self.templateDSPL[0]+2), currentcontext, "glDeleteLists Spheres2" GL.glDeleteLists(self.templateDSPL[0], 3) self.templateDSPL = None
def InitColor(self, num=0): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Setup GL color (used when lighting is turned off) only sets the color if binding mode is OVERALL or PER_INSTANCE (i.e. per instance matrix) which are the 2 only colors which are not set in the display list""" prop = self.materials[GL.GL_FRONT] if prop.binding[1] == viewerConst.OVERALL: material = prop.prop[prop.diff][0] if not material.flags.contiguous: material = Numeric.array(material, copy=1) GL.glColor4fv(material.tolist()) elif prop.binding[1] == viewerConst.PER_INSTANCE: material = prop.prop[prop.diff][num] if not material.flags.contiguous: material = Numeric.array(material, copy=1) GL.glColor4fv(material.tolist())
def chooseTemplate(self): GL.glNewList(self.templateDSPL[0], GL.GL_COMPILE) #print '+%d'%self.templateDSPL[0], "glNewList Ellipsoids0" if self.invertNormals: #print "GLU_INSIDE reversed normals" #print '#%d'%(self.templateDSPL[0]+2), "glCallList Ellipsoids2" GL.glCallList(self.templateDSPL[0]+2) else: #print "GLU_OUTSIDE regular normals" #print '#%d'%(self.templateDSPL[0]+1), "glCallList Ellipsoids1" GL.glCallList(self.templateDSPL[0]+1) #print '*%d'%GL.glGetIntegerv(GL.GL_LIST_INDEX), "glEndList Ellipsoids0" GL.glEndList()
def InitColor(self, num=0): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Setup GL color (used when lighting is turned off) only sets the color if binding mode is OVERALL or PER_INSTANCE (i.e. per instance matrix) which are the 2 only colors which are not set in the display list""" prop = self.materials[GL.GL_FRONT] if prop.binding[1] == viewerConst.OVERALL: material = prop.prop[prop.diff][0] if not material.flags.contiguous: material = Numeric.array(material,copy=1) GL.glColor4fv ( material.tolist() ) elif prop.binding[1] == viewerConst.PER_INSTANCE: material = prop.prop[prop.diff][num] if not material.flags.contiguous: material = Numeric.array(material,copy=1) GL.glColor4fv ( material.tolist() )
def chooseTemplate(self): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() # make sure we are not already in a newlist if GL.glGetIntegerv(GL.GL_LIST_INDEX) == [0]: GL.glNewList(self.templateDSPL[0], GL.GL_COMPILE) #print '+%d'%self.templateDSPL[0], "glNewList Spheres0" if self.invertNormals: #print "GLU_INSIDE reversed normals" #print '#%d'%(self.templateDSPL[0]+2), "glCallList Spheres2" GL.glCallList(self.templateDSPL[0]+2) else: #print "GLU_OUTSIDE regular normals" #print '#%d'%(self.templateDSPL[0]+1), "glCallList Spheres1" GL.glCallList(self.templateDSPL[0]+1) #print '*%d'%GL.glGetIntegerv(GL.GL_LIST_INDEX), "glEndList Spheres0" GL.glEndList()
def chooseTemplate(self): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() # make sure we are not already in a newlist if GL.glGetIntegerv(GL.GL_LIST_INDEX) == [0]: GL.glNewList(self.templateDSPL[0], GL.GL_COMPILE) #print '+%d'%self.templateDSPL[0], "glNewList Spheres0" if self.invertNormals: #print "GLU_INSIDE reversed normals" #print '#%d'%(self.templateDSPL[0]+2), "glCallList Spheres2" GL.glCallList(self.templateDSPL[0] + 2) else: #print "GLU_OUTSIDE regular normals" #print '#%d'%(self.templateDSPL[0]+1), "glCallList Spheres1" GL.glCallList(self.templateDSPL[0] + 1) #print '*%d'%GL.glGetIntegerv(GL.GL_LIST_INDEX), "glEndList Spheres0" GL.glEndList()
def redoDisplayListCSG(self): if self.dpyListCSG is not None: GL.glDeleteLists(1, self.dpyListCSG) g = self.geom self.dpyListCSG = GL.glGenLists(1) GL.glNewList(self.dpyListCSG, GL.GL_COMPILE) ## if isinstance(g, Spheres): ## g.DisplayFunction() ## else: self.drawpolygons() GL.glEndList()
def deleteTemplate(self): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() #print "Spheres.deleteTemplate", self.templateDSPL # it is asumed the right OpenGL context is active if GL.glGetIntegerv(GL.GL_LIST_INDEX) == [0]: assert self.templateDSPL is not None currentcontext = self.viewer.currentCamera.tk.call( self.viewer.currentCamera._w, 'contexttag') if currentcontext != self.templateDSPL[1]: import traceback traceback.print_stack() warnings.warn( 'deleteTemplate failed because the current context is the wrong one' ) print "currentcontext != self.templateDSPL[1]", currentcontext, self.templateDSPL[ 1] else: #print '-%d'%self.templateDSPL[0], currentcontext, "glDeleteLists Spheres0" #print '-%d'%(self.templateDSPL[0]+1), currentcontext, "glDeleteLists Spheres1" #print '-%d'%(self.templateDSPL[0]+2), currentcontext, "glDeleteLists Spheres2" GL.glDeleteLists(self.templateDSPL[0], 3) self.templateDSPL = None
def getZBuffer(self, width, height): from opengltk.OpenGL import GL depthString = GL.glReadPixels(0, 0, width, height, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT) import struct zval = Numeric.array(struct.unpack('%df' % width * height, depthString)) zmax = max(zval) zmin = min(zval) zval1 = 255 * ((zval - zmin) / (zmax - zmin)) ds = zval1.astype('c').tostring() depthImage = Image.fromstring('P', (width, height), ds) return depthImage.transpose(Image.FLIP_TOP_BOTTOM)
def getHistogram(self): GL.glHistogram(GL.GL_HISTOGRAM, 256, GL.GL_RGB, GL.GL_FALSE) GL.glEnable(GL.GL_HISTOGRAM) self.redraw() values = Numeric.zeros( (256,3), Numeric.UInt16) #seg faults GL.glGetHistogram(GL.GL_HISTOGRAM, GL.GL_TRUE, GL.GL_RGB, GL.GL_UNSIGNED_SHORT, values) return values
def __init__(self, master, title, cnf={}, expand=1, **kw): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() if not kw.has_key('width'): kw['width']=150 if not kw.has_key('height'): kw['height']=150 if not kw.has_key('double'): kw['double']=1 if not kw.has_key('depth'): kw['depth']=1 # for unexplained reason anti-aliasing doesn't work # on mesa if we don't set the accumulation buffer if not kw.has_key('accum'): kw['accum'] = 1 self.width = kw['width'] self.height = kw['height'] # load the TK-OpenGL extension (Togl) loadTogl(master) # create an Tk-OpenGL widget from opengltk.exception import GLerror from Tkinter import TclError try: Tkinter.Widget.__init__(self, master, 'togl', cnf, kw) try: GL.glAccum(GL.GL_LOAD, 1.0) self.accumBuffersError = False except GLerror: self.accumBuffersError = True except TclError, e: self.accumBuffersError = True kw.pop('accum') Tkinter.Widget.__init__(self, master, 'togl', cnf, kw)
def deleteOpenglList(self): #print "Common2d3dObject.deleteOpenglList", self self.redoDspLst = 0 currentcontext = self.viewer.currentCamera.tk.call(self.viewer.currentCamera._w, 'contexttag') if self.dpyList is not None: if currentcontext != self.dpyList[1]: warnings.warn("""deleteOpenglList failed because the current context is the wrong one""") #print "currentcontext != self.dpyList[1]", currentcontext, self.dpyList[1] #import traceback;traceback.print_stack() else: #print '-%d'%self.dpyList[0], currentcontext,"glDeleteLists Common2d3dObject" GL.glDeleteLists(self.dpyList[0], 1) self.dpyList = None if self.pickDpyList is not None: if currentcontext != self.pickDpyList[1]: warnings.warn("""deleteOpenglList failed because the current context is the wrong one""") #print "currentcontext != self.pickDpyList[1]", currentcontext, self.pickDpyList[1] else: #print '-%d'%self.pickDpyList[0], currentcontext, "glDeleteLists Common2d3dObject2", GL.glDeleteLists(self.pickDpyList[0], 1) self.pickDpyList = None
def tkRedraw(self, *dummy): #if not self.winfo_ismapped(): return self.update_idletasks() self.tk.call(self._w, 'makecurrent') self.initProjection() GL.glPushMatrix() self.redraw() GL.glFlush() GL.glPopMatrix() self.tk.call(self._w, 'swapbuffers')
def makeTemplate(self): #print "Ellipsoids.makeTemplate" # it is asumed the right OpenGL context is active assert self.templateDSPL is None lFirstList = GL.glGenLists(3) #print "lFirstList Ellipsoids.makeTemplate", lFirstList, self.name lCurrentContext = self.viewer.currentCamera.tk.call(self.viewer.currentCamera._w, 'contexttag') self.templateDSPL = ( lFirstList, lCurrentContext ) GL.glNewList(lFirstList+1, GL.GL_COMPILE) #print '+%d'%(lFirstList+1), lCurrentContext, "glNewList Ellipsoids1" extractedGlutSolidSphere(1, self.slices, self.stacks, 0) #print '*%d'%GL.glGetIntegerv(GL.GL_LIST_INDEX), "glEndList Ellipsoids1" GL.glEndList() GL.glNewList(lFirstList+2, GL.GL_COMPILE) #print '+%d'%(lFirstList+2), lCurrentContext, "glNewList Ellipsoids2" extractedGlutSolidSphere(1, self.slices, self.stacks, 1) #print '*%d'%GL.glGetIntegerv(GL.GL_LIST_INDEX), "glEndList Ellipsoids2" GL.glEndList() self.chooseTemplate()
def render(self, mode='render'): # call with mode='csg' to render simple shape to setup Zbuffer for CSG # call with mode='render' to render by calling geom's draw function if self.geom: #import traceback #print traceback.print_stack() #print self.geom #print "=========================================================" root = self.geom.viewer.rootObject instance = [0] p = self.geom.parent while p: instance.append(0) p = p.parent #mat = Numeric.array(GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)).astype('f') #print 'mat OK', mat GL.glPushMatrix() GL.glLoadIdentity() self.geom.viewer.currentCamera.BuildTransformation() self.geom.BuildMat(self.geom, root, True, instance) #mat = Numeric.array(GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)).astype('f') #print 'mat PB', mat #print 'render ', mode, self.geom if mode=='csg': if self.dpyListCSG is None: self.redoDisplayListCSG() GL.glCallList(self.dpyListCSG) elif mode=='render': obj = self.geom if not obj.inheritMaterial: obj.InitMaterial(0) obj.InitColor(0) obj.DisplayFunction() GL.glPopMatrix()