Beispiel #1
0
class EM3DSliceModel(EM3DModel):
	
	def __init__(self, gl_widget, image=None):
		self.data = None
		EM3DModel.__init__(self, gl_widget)
		self.init()
		self.initialized = True
		
		self.inspector=None
	
		self.axes = []
		self.axes.append( Vec3f(1,0,0) )
		self.axes.append( Vec3f(0,1,0) )
		self.axes.append( Vec3f(0,0,1) )
		self.axes_idx = 2
		
		self.track = False
		self.bright = 0
		self.contrast = 1.0
		self.busy = True
		if image :
			self.set_data(image)
			
	def set_contrast(self,val):
		self.contrast = val
		self.generate_current_display_list()
		self.updateGL()
	def set_brightness(self,val):
		self.bright = val
		self.generate_current_display_list()
		self.updateGL()
		
#	def __del__(self):
#		print "slice died"
	
	def get_type(self):
		return "Slice Viewer"

	def init(self):
		self.data=None

		self.mmode=0
		self.cam = Camera2(self)
		
		self.vdtools = EMViewportDepthTools(self)
		
		self.cube = False
		self.inspector=None
		
		self.tex_name = 0
		self.tex_dl = 0

		self.glcontrast = 1.0
		self.glbrightness = 0.0
		
		self.rank = 1
		
		self.glflags = EMOpenGLFlagsAndTools()		# OpenGL flags - this is a singleton convenience class for testing texture support
		
	def eye_coords_dif(self,x1,y1,x2,y2,mdepth=True):
		return self.vdtools.eye_coords_dif(x1,y1,x2,y2,mdepth)
	
	def update_data(self,data):
		if data==None:
			print "Error, the data is empty"
			return
		
		if (isinstance(data,EMData) and data.get_zsize()<=1) :
			print "Error, the data is not 3D"
			return
		
#		self.data = data.copy()
#		
#		min = self.data.get_attr("minimum")
#		max = self.data.get_attr("maximum")
#		
#		self.data.add(-min)
#		self.data.mult(1/(max-min))

		self.generate_current_display_list()
		self.updateGL()
		
	def set_default_contrast_settings(self):
		min = self.data.get_attr("minimum")
		max = self.data.get_attr("maximum")
#		
#		self.data.add(-min)
#		self.data.mult(1/(max-min))
		self.bright = -min
		if max != min:	self.contrast = 1.0/(max-min)
		else: self.contrast = 1
		
	def set_data(self,data,fact=1.0):
		"""Pass in a 3D EMData object"""
		
		self.busy = True
		if data==None:
			print "Error, the data is empty"
			return
		
		if (isinstance(data,EMData) and data.get_zsize()<=1) :
			print "Error, the data is not 3D"
			self.busy = False
			return
		
		self.data = data
		
		self.set_default_contrast_settings()
		
		if not self.inspector or self.inspector ==None:
			self.inspector=EM3DSliceInspector(self)
		
		self.inspector.set_contrast_bright(self.contrast,self.bright)
		hist = self.data.calc_hist(256,0,1.0,self.bright,self.contrast)
		self.inspector.set_hist(hist,0,1.0) 
		
		self.slice = data.get_zsize()/2
		self.zslice = data.get_zsize()/2-1
		if self.zslice < 0: self.zslice = 0
		self.yslice = data.get_ysize()/2-1
		if self.yslice < 0: self.yslice = 0
		self.xslice = data.get_xsize()/2-1
		if self.xslice < 0: self.xslice = 0
		self.trackslice = self.xslice
		self.axis = 'z'
		self.inspector.set_sliceRange(0,data.get_zsize()-1)
		self.inspector.set_slice(self.zslice)
		self.generate_current_display_list()
		
		from emglobjects import EM3DGLWidget
		if isinstance(self.get_gl_widget(),EM3DGLWidget):
			self.get_gl_widget().set_camera_defaults(self.data)
			
		if ( self.tex_dl != 0 ): 
			glDeleteLists( self.tex_dl, 1)
			self.tex_dl = 0
		self.busy = False
	def get_eman_transform(self,p):
		
		if ( p[2] == 0 ):
			alt = 90
		else :
			alt = acos(p[2])*180.0/pi
		
		phi = atan2(p[0],p[1])
		phi *= 180.0/pi
		
		return [Transform({"type":"eman","alt":alt,"phi":phi}),alt,phi]
			
	def get_dimension_size(self):
		if ( self.axes_idx == 0 ):
			return self.data.get_xsize()
		elif ( self.axes_idx == 1 ):
			return self.data.get_ysize()
		elif ( self.axes_idx == 2 ):
			return self.data.get_zsize()
		else:
			#print "unsupported axis"
			# this is a hack and needs to be fixed eventually
			return self.data.get_xsize()
			#return 0
	def get_correct_dims_2d_emdata(self):
		if ( self.axes_idx == 0 ):
			return EMData(self.data.get_ysize(),self.data.get_zsize())
		elif ( self.axes_idx == 1 ):
			return EMData(self.data.get_xsize(),self.data.get_zsize())
		elif ( self.axes_idx == 2 ):
			return EMData(self.data.get_xsize(),self.data.get_ysize())
		else:
			#print "unsupported axis"
			# this is a hack and needs to be fixed eventually
			return EMData(self.data.get_xsize(),self.data.get_zsize())

	def generate_current_display_list(self):
		if self.busy: return
		if ( self.tex_dl != 0 ): glDeleteLists( self.tex_dl, 1)
		
		self.tex_dl = glGenLists(1)

		if (self.tex_dl == 0): return #OpenGL is initialized yet

		self.gen_2D_texture()
	
		
	def gen_2D_texture(self):
		glNewList(self.tex_dl,GL_COMPILE)
		
		n = self.get_dimension_size()
		v = self.axes[self.axes_idx]
		
		[t,alt,phi] = self.get_eman_transform(v)
			
		nn = float(self.slice)/float(n)
		trans = (nn-0.5)*v
		t.set_trans(n*trans)
	
		if False and EMUtil.cuda_available(): # disable for the time being - big textures won't work on CPU
			tmp = self.data.cut_slice_cuda(t)
		else:
			tmp = self.get_correct_dims_2d_emdata()
			tmp.cut_slice(self.data,t,True)
			
		tmp.add(self.bright)
		tmp.mult(self.contrast)
		
		hist = tmp.calc_hist(256,0,1.0,self.bright,self.contrast)
		self.inspector.set_hist(hist,0,1.0) 
		
		if ( self.tex_name != 0 ): glDeleteTextures(self.tex_name)
		self.tex_name = 0
		
		self.tex_name = self.glflags.gen_textureName(tmp)
		
		glEnable(GL_TEXTURE_2D)
		glBindTexture(GL_TEXTURE_2D, self.tex_name)
			
		#glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
#		if ( not data_dims_power_of(self.data,2) and self.glflags.npt_textures_unsupported()):
#			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
#		else:
#			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
		
			
		glPushMatrix()
		glTranslate(trans[0]+0.5,trans[1]+0.5,trans[2]+0.5)
		glRotatef(-phi,0,0,1)
		glRotatef(-alt,1,0,0)
		glBegin(GL_QUADS)
		glTexCoord2f(0,0)
		glVertex2f(-0.5,-0.5)
		
		glTexCoord2f(1,0)
		glVertex2f( 0.5,-0.5)
		
		glTexCoord2f(1,1)
		glVertex2f( 0.5, 0.5)
		
		glTexCoord2f(0,1)
		glVertex2f(-0.5, 0.5)
		glEnd()
		glPopMatrix()
		
		glDisable(GL_TEXTURE_2D)
		glEndList()
		
	def render(self):
		if self.busy: return
		lighting = glIsEnabled(GL_LIGHTING)
		cull = glIsEnabled(GL_CULL_FACE)
		polygonmode = glGetIntegerv(GL_POLYGON_MODE)
		glDisable(GL_LIGHTING)
		glDisable(GL_CULL_FACE)
		
		glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
		
		glPushMatrix()
		self.cam.position(True)
		# the ones are dummy variables atm... they don't do anything
		self.vdtools.update(1,1)
		glPopMatrix()
		
		self.cam.position()
		self.vdtools.store_model()
		
		if ( self.track ):
			self.loadTrackAxis()
			self.generate_current_display_list()
		
		if ( self.tex_dl == 0 ):
			self.generate_current_display_list()
		
		glStencilFunc(GL_EQUAL,self.rank,0)
		glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE)
		glPushMatrix()
		glTranslate(-self.data.get_xsize()/2.0,-self.data.get_ysize()/2.0,-self.data.get_zsize()/2.0)
		glScalef(self.data.get_xsize(),self.data.get_ysize(),self.data.get_zsize())
		glCallList(self.tex_dl)
		glPopMatrix()
		
		#breaks in desktop!
		#glStencilFunc(GL_EQUAL,self.rank,self.rank)
		#glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP)
		#glPushMatrix()
		##glLoadIdentity()
		#[width,height] = self.parent.get_near_plane_dims()
		#z = self.parent.get_start_z()
		#glTranslate(-width/2.0,-height/2.0,-z-0.01)
		#glScalef(width,height,1.0)
		self.draw_bc_screen()
		#glPopMatrix()
		
		glStencilFunc(GL_ALWAYS,1,1)
		glColor3f(1,1,1)
		if self.cube:
			glPushMatrix()
			self.draw_volume_bounds()
			glPopMatrix()
			
		if ( lighting ): glEnable(GL_LIGHTING)
		if ( cull ): glEnable(GL_CULL_FACE)
		
		if ( polygonmode[0] == GL_LINE ): glPolygonMode(GL_FRONT, GL_LINE)
		if ( polygonmode[1] == GL_LINE ): glPolygonMode(GL_BACK, GL_LINE)
	
	def set_slice(self,val):
		self.slice = val
		if self.axis == 'z':
			self.zslice = val
		elif self.axis == 'y':
			self.yslice = val
		elif self.axis == 'x':
			self.xslice = val
		else:
			self.trackslice = val
		
		self.generate_current_display_list()
		self.updateGL()
		
	def setAxis(self,val):
		self.axis = str(val).strip()
		
		if (self.inspector != None):
			if self.axis == 'z':
				self.inspector.set_sliceRange(0,self.data.get_zsize()-1)
				self.inspector.set_slice(self.zslice)
				self.axes_idx = 2
				self.track = False
			elif self.axis == 'y':
				self.inspector.set_sliceRange(0,self.data.get_ysize()-1)
				self.inspector.set_slice(self.yslice)
				self.axes_idx = 1
				self.track = False
			elif self.axis == 'x':
				self.inspector.set_sliceRange(0,self.data.get_xsize()-1)
				self.inspector.set_slice(self.xslice)
				self.axes_idx = 0
				self.track = False
			elif self.axis == 'track':
				self.track = True
				self.inspector.set_sliceRange(0,self.data.get_xsize()-1)
				self.inspector.set_slice(self.trackslice)
				self.axes_idx = 3
				
				self.loadTrackAxis()
			else:
				print "Error, unknown axis", self.axis, val
		
		self.generate_current_display_list()
		self.updateGL()

	def update_inspector(self,t3d):
		if not self.inspector or self.inspector ==None:
			self.inspector=EM3DSliceInspector(self)
		self.inspector.update_rotations(t3d)
	
	def get_inspector(self):
		if not self.inspector : self.inspector=EM3DSliceInspector(self)
		return self.inspector

	def loadTrackAxis(self):
		t3d = self.vdtools.getEmanMatrix()
		#at3d = self.cam.t3d_stack[len(self.cam.t3d_stack)-1]
		
		point = Vec3f(0,0,1)
		
		point *= 1.0/self.vdtools.getCurrentScale()
		
		point = point*t3d
		
		#if ( point[2] != 0 ): point[2] = -point[2]
		
		if len(self.axes) == 3 :
			self.axes.append(point)
		else:
			self.axes[3] = point

	def resize(self):
		self.vdtools.set_update_P_inv()
Beispiel #2
0
class EMImage3DWidget(EMGLWidget, EMLightsDrawer, EMGLProjectionViewMatrices):
	""" 
	A QT widget for rendering 3D EMData objects
	"""
	allim=weakref.WeakKeyDictionary()
	def add_model(self,model,num=0):
		model.set_gl_widget(self)
		model.set_dont_delete_parent() # stops a RunTimeError
		
		if self.viewables: 
			#TODO: find a better way to work with cameras
			model.cam.scale = self.viewables[0].cam.scale #Make the new model have the same scale as the first "viewable"
			model.cam.t3d_stack = self.viewables[0].cam.t3d_stack[:] #Make the new model have the same orientation and position as the first "viewable"
			model.get_inspector().update_rotations(model.cam.t3d_stack[-1])
			model.get_inspector().set_xyz_trans(model.cam.cam_x,model.cam.cam_y,model.cam.cam_z)
			model.get_inspector().set_scale(model.cam.scale)
		
		self.viewables.append(model)
		name = model.get_type()+" " + str(num)
		self.viewables[-1].set_name(name)
		self.viewables[-1].set_rank(len(self.viewables))
		self.currentselection = len(self.viewables)-1
		self.updateGL()
		
	def __init__(self, parent=None, image=None,application=None,winid=None):
		EMImage3DWidget.allim[self] = 0
		EMGLWidget.__init__(self,parent)
		EMLightsDrawer.__init__(self)
		EMGLProjectionViewMatrices.__init__(self)
		
		fmt=QtOpenGL.QGLFormat()
		fmt.setDoubleBuffer(True)
		fmt.setDepth(True)
		fmt.setStencil(True)
		fmt.setSampleBuffers(True)
		self.setFormat(fmt)
		
		self.aspect=1.0
		self.fov = 50 # field of view angle used by gluPerspective
		self.d = 0
		self.zwidth = 0
		self.yheight = None
		
		self.data = None # should eventually be an EMData object

#		self.cam = Camera()
		self.cam = Camera2(self)
		self.cam.cam_z = -250
		
		self.resize(480,480)
		self.startz = 1
		self.endz = 500
		
		self.currentselection = -1
		self.inspector = None
		
		self.viewables = []
		self.num_iso = 0
		self.num_vol = 0
		self.num_sli = 0
		self.num_sym = 0

		self.vdtools = EMViewportDepthTools(self)
		
		self.last_window_width = -1 # used for automatic resizing from the desktop
		self.last_window_height = -1 # used for automatic resizing from the desktop
		
		self.file_name = None		
		self.emit_events = False		
		self.perspective = False

		if image != None: 
			self.set_data(image)
		
		#From get_qt_widget...
		if isinstance(self.data,EMData):
			self.set_cam_z_from_fov_image(self.get_fov(),self.data)
		
		self.qt_parent.setWindowIcon(QtGui.QIcon(get_image_directory() +"single_image_3d.png"))
		#End from get_qt_widget
		
		self.updateGL() #Solves "error, OpenGL seems not to be initialized" message
		
	def __set_model_contexts(self):
		for v in self.viewables:
			v.set_gl_widget(self)
	def add_isosurface(self):
		model = EMIsosurfaceModel(self, self.data, False)
		self.num_iso += 1
		self.add_model(model,self.num_iso)
	def add_slice_viewer(self):
		model = EM3DSliceModel(self, self.data)
		self.num_sli += 1
		self.add_model(model,self.num_sli)
	def add_sym(self):
		# the difference between the EMEulerExplorer and the EM3DSymModel
		# is only that the EMEulerExplorer will look in the current directory for refinement directories and
		# display related information. Simply change from one to the other if you don't like it
		model = EMEulerExplorer(self,True,False)
		#model = EM3DSymModel(self)
		model.set_radius(self.radius)
		self.num_sym += 1
		self.add_model(model,self.num_sym)
	def add_volume(self):
		model = EMVolumeModel(self, self.data)
		self.num_vol += 1
		self.add_model(model,self.num_vol)
	def delete_current(self, val):
		if ( len(self.viewables) == 0 ): return
		
		v = self.viewables.pop(val)
		
		
		#self.application.deregister_qt_emitter(v)
		if (len(self.viewables) == 0 ) : 
			self.currentselection = -1
		elif ( len(self.viewables) == 1):
			self.currentselection = 0
		elif ( val == 0):
			pass
		else:
			self.currentselection = val - 1
		
		
		# Need to set the rank appropriately
		for i in range(0,len(self.viewables)):
			self.viewables[i].set_rank(i+1)
	def enable_emit_events(self,val=True):
		for v in self.viewables: v.enable_emit_events(val)
		self.emit_events = val
		self.cam.enable_emit_events(val)
	def eye_coords_dif(self,x1,y1,x2,y2,mdepth=True):
		return self.vdtools.eye_coords_dif(x1,y1,x2,y2,mdepth)
	def get_current_idx(self):
		return self.currentselection
	def get_current_inspector(self):
		if self.currentselection == -1 : return None
		elif self.currentselection >= len(self.viewables):
			print "error, current selection too large", self.currentselection,len(self.viewables)
			return None
		return self.viewables[self.currentselection].get_inspector()		
	def get_current_name(self):
		if self.currentselection == -1 : return ""
		elif self.currentselection >= len(self.viewables):
			print "error, current selection too large", self.currentselection,len(self.viewables)
			return ""
		return self.viewables[self.currentselection].get_name()
	def get_current_transform(self):
		size = len(self.cam.t3d_stack)
		return self.cam.t3d_stack[size-1]
	def get_data_dims(self):
		if self.data != None:
			return [self.data.get_xsize(),self.data.get_ysize(),self.data.get_zsize()]
		else: return [0,0,0]
	def get_emit_signals_and_connections(self):
		ret = {}
		for v in self.viewables: ret.update(v.get_emit_signals_and_connections())
		ret.update(self.cam.get_emit_signals_and_connections())
		ret.update({"set_perspective":self.set_perspective})
		
		return ret
	def get_fov(self):
		return self.fov
	def get_inspector(self):
		if not self.inspector :  self.inspector=EMImageInspector3D(self)
		return self.inspector
	def get_near_plane_dims(self):
		if self.perspective:
			height = 2.0*self.startz * tan(self.fov/2.0*pi/180.0)
			width = self.aspect * height
			return [width,height]
		else:
			return [self.xwidth,self.yheight]
	def get_render_dims_at_depth(self, depth):
		# This function returns the width and height of the renderable 
		# area at the origin of the data volume
		height = -2*tan(self.fov/2.0*pi/180.0)*(depth)
		width = self.aspect*height
		return [width,height]
	def get_start_z(self):
		return self.startz
	def get_sundry_inspector(self):
		return self.viewables[self.currentselection].get_inspector()
	def initializeGL(self):
		glEnable(GL_LIGHTING)
		glEnable(GL_LIGHT0)
		#glEnable(GL_LIGHT1)
		glEnable(GL_DEPTH_TEST)
		glLightfv(GL_LIGHT0, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT0, GL_DIFFUSE, [1.0,1.0,1.0, 1.0])
		glLightfv(GL_LIGHT0, GL_SPECULAR, [1.0, 1.0, 1.0, 1.0])
		glLightfv(GL_LIGHT0, GL_POSITION, [0.1,.1,1.,0.])
		
		glLightfv(GL_LIGHT1, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT1, GL_DIFFUSE, [0.5,0.5,0.5, 1.0])
		glLightfv(GL_LIGHT1, GL_SPECULAR, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT1, GL_POSITION, [0,0,1,1]) # set the is self.radius when it's known
		glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, [0,0,-1])
		glLightfv(GL_LIGHT1, GL_QUADRATIC_ATTENUATION,0.0037)
		
		glLightfv(GL_LIGHT2, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT2, GL_DIFFUSE, [0.5,0.5,0.5, 1.0])
		glLightfv(GL_LIGHT2, GL_SPECULAR, [0.0, 1.0, 0.0, 1.0])
		glLightfv(GL_LIGHT2, GL_POSITION, [0.1,.1,1.,0.])
		
		glLightfv(GL_LIGHT3, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT3, GL_DIFFUSE, [0.5,0.5,0.5, 1.0])
		glLightfv(GL_LIGHT3, GL_SPECULAR, [0.0, 1.0, 0.0, 1.0])
		glLightfv(GL_LIGHT3, GL_POSITION, [0.1,.1,1.,0.])
		#GL_SPOT_DIRECTION,GL_SPOT_CUTOFF,GL_QUADRATIC_ATTENUATION
		
		
		GL.glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
		glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE)
		glShadeModel(GL_SMOOTH)
		#glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [0.1,0.1,0.1,1.0]);
		
		glClearStencil(0)
		glEnable(GL_STENCIL_TEST)
		GL.glClearColor(0,0,0,0)
		
		
		glEnable(GL_NORMALIZE)
	def is_emitting(self): return self.emit_events
	def load_last_viewable_camera(self):
		return
		size = len(self.viewables)
		if ( size <= 1 ): return
		self.viewables[size-1].set_camera(self.viewables[0].get_current_camera())
	def load_orthographic(self):
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		
		if self.yheight == None: self.yheight = self.height()
		
		self.aspect = float(self.width())/float(self.height())
		self.xwidth = self.aspect*self.yheight
		if self.xwidth == 0 or self.yheight == 0: return # probably startup
		
		glOrtho(-self.xwidth/2.0,self.xwidth/2.0,-self.yheight/2.0,self.yheight/2.0,self.startz,self.endz)
		glMatrixMode(GL_MODELVIEW)
	def load_perspective(self):
		self.aspect = float(self.width())/float(self.height())
		
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		if self.startz < 0: self.startz = 1
		gluPerspective(self.fov,self.aspect,self.startz,self.endz)
		glMatrixMode(GL_MODELVIEW)
	def load_rotation(self,t3d):
		self.cam.load_rotation(t3d)
		self.updateGL()
	def mouseMoveEvent(self, event):
		if self.current_mouse_mode:
			EMLightsDrawer.mouseMoveEvent(self, event)
		else:
			for model in self.viewables:
				try:
					model.mouseMoveEvent(event)
				except AttributeError, e:
					pass
		self.updateGL()
Beispiel #3
0
class EMImage3DWidget(EMGLWidget, EMLightsDrawer, EMGLProjectionViewMatrices):
	""" 
	A QT widget for rendering 3D EMData objects
	"""
	allim=weakref.WeakKeyDictionary()
	def add_model(self,model,num=0):
		model.set_gl_widget(self)
		model.set_dont_delete_parent() # stops a RunTimeError
		
		if self.viewables: 
			#TODO: find a better way to work with cameras
			model.cam.scale = self.viewables[0].cam.scale #Make the new model have the same scale as the first "viewable"
			model.cam.t3d_stack = self.viewables[0].cam.t3d_stack[:] #Make the new model have the same orientation and position as the first "viewable"
			model.get_inspector().update_rotations(model.cam.t3d_stack[-1])
			model.get_inspector().set_xyz_trans(model.cam.cam_x,model.cam.cam_y,model.cam.cam_z)
			model.get_inspector().set_scale(model.cam.scale)
		
		self.viewables.append(model)
		name = model.get_type()+" " + str(num)
		self.viewables[-1].set_name(name)
		self.viewables[-1].set_rank(len(self.viewables))
		self.currentselection = len(self.viewables)-1
		self.updateGL()
		
	def __init__(self, parent=None, image=None,application=None,winid=None):
		EMImage3DWidget.allim[self] = 0
		EMGLWidget.__init__(self,parent)
		EMLightsDrawer.__init__(self)
		EMGLProjectionViewMatrices.__init__(self)
		
		fmt=QtOpenGL.QGLFormat()
		fmt.setDoubleBuffer(True)
		fmt.setDepth(True)
		fmt.setStencil(True)
		fmt.setSampleBuffers(True)
		self.setFormat(fmt)
		
		self.aspect=1.0
		self.fov = 50 # field of view angle used by gluPerspective
		self.d = 0
		self.zwidth = 0
		self.yheight = None
		
		self.data = None # should eventually be an EMData object

#		self.cam = Camera()
		self.cam = Camera2(self)
		self.cam.cam_z = -250
		
		self.resize(480,480)
		self.startz = 1
		self.endz = 500
		
		self.currentselection = -1
		self.inspector = None
		
		self.viewables = []
		self.num_iso = 0
		self.num_vol = 0
		self.num_sli = 0
		self.num_sym = 0

		self.vdtools = EMViewportDepthTools(self)
		
		self.last_window_width = -1 # used for automatic resizing from the desktop
		self.last_window_height = -1 # used for automatic resizing from the desktop
		
		self.file_name = None		
		self.emit_events = False		
		self.perspective = False

		if image != None: 
			self.set_data(image)
		
		#From get_qt_widget...
		if isinstance(self.data,EMData):
			self.set_cam_z_from_fov_image(self.get_fov(),self.data)
		
		self.qt_parent.setWindowIcon(QtGui.QIcon(get_image_directory() +"single_image_3d.png"))
		#End from get_qt_widget
		
		self.updateGL() #Solves "error, OpenGL seems not to be initialized" message
		
	def __set_model_contexts(self):
		for v in self.viewables:
			v.set_gl_widget(self)
	def add_isosurface(self):
		model = EMIsosurfaceModel(self, self.data, False)
		self.num_iso += 1
		self.add_model(model,self.num_iso)
	def add_slice_viewer(self):
		model = EM3DSliceModel(self, self.data)
		self.num_sli += 1
		self.add_model(model,self.num_sli)
	def add_sym(self):
		# the difference between the EMEulerExplorer and the EM3DSymModel
		# is only that the EMEulerExplorer will look in the current directory for refinement directories and
		# display related information. Simply change from one to the other if you don't like it
		model = EMEulerExplorer(self,True,False)
		#model = EM3DSymModel(self)
		model.set_radius(self.radius)
		self.num_sym += 1
		self.add_model(model,self.num_sym)
	def add_volume(self):
		model = EMVolumeModel(self, self.data)
		self.num_vol += 1
		self.add_model(model,self.num_vol)
	def delete_current(self, val):
		if ( len(self.viewables) == 0 ): return
		
		v = self.viewables.pop(val)
		
		
		#self.application.deregister_qt_emitter(v)
		if (len(self.viewables) == 0 ) : 
			self.currentselection = -1
		elif ( len(self.viewables) == 1):
			self.currentselection = 0
		elif ( val == 0):
			pass
		else:
			self.currentselection = val - 1
		
		
		# Need to set the rank appropriately
		for i in range(0,len(self.viewables)):
			self.viewables[i].set_rank(i+1)
	def enable_emit_events(self,val=True):
		for v in self.viewables: v.enable_emit_events(val)
		self.emit_events = val
		self.cam.enable_emit_events(val)
	def eye_coords_dif(self,x1,y1,x2,y2,mdepth=True):
		return self.vdtools.eye_coords_dif(x1,y1,x2,y2,mdepth)
	def get_current_idx(self):
		return self.currentselection
	def get_current_inspector(self):
		if self.currentselection == -1 : return None
		elif self.currentselection >= len(self.viewables):
			print "error, current selection too large", self.currentselection,len(self.viewables)
			return None
		return self.viewables[self.currentselection].get_inspector()		
	def get_current_name(self):
		if self.currentselection == -1 : return ""
		elif self.currentselection >= len(self.viewables):
			print "error, current selection too large", self.currentselection,len(self.viewables)
			return ""
		return self.viewables[self.currentselection].get_name()
	def get_current_transform(self):
		size = len(self.cam.t3d_stack)
		return self.cam.t3d_stack[size-1]
	def get_data_dims(self):
		if self.data != None:
			return [self.data.get_xsize(),self.data.get_ysize(),self.data.get_zsize()]
		else: return [0,0,0]
	def get_emit_signals_and_connections(self):
		ret = {}
		for v in self.viewables: ret.update(v.get_emit_signals_and_connections())
		ret.update(self.cam.get_emit_signals_and_connections())
		ret.update({"set_perspective":self.set_perspective})
		
		return ret
	def get_fov(self):
		return self.fov
	def get_inspector(self):
		if not self.inspector :  self.inspector=EMImageInspector3D(self)
		return self.inspector
	def get_near_plane_dims(self):
		if self.perspective:
			height = 2.0*self.startz * tan(self.fov/2.0*pi/180.0)
			width = self.aspect * height
			return [width,height]
		else:
			return [self.xwidth,self.yheight]
	def get_render_dims_at_depth(self, depth):
		# This function returns the width and height of the renderable 
		# area at the origin of the data volume
		height = -2*tan(self.fov/2.0*pi/180.0)*(depth)
		width = self.aspect*height
		return [width,height]
	def get_start_z(self):
		return self.startz
	def get_sundry_inspector(self):
		return self.viewables[self.currentselection].get_inspector()
	def initializeGL(self):
		glEnable(GL_LIGHTING)
		glEnable(GL_LIGHT0)
		#glEnable(GL_LIGHT1)
		glEnable(GL_DEPTH_TEST)
		glLightfv(GL_LIGHT0, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT0, GL_DIFFUSE, [1.0,1.0,1.0, 1.0])
		glLightfv(GL_LIGHT0, GL_SPECULAR, [1.0, 1.0, 1.0, 1.0])
		glLightfv(GL_LIGHT0, GL_POSITION, [0.1,.1,1.,0.])
		
		glLightfv(GL_LIGHT1, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT1, GL_DIFFUSE, [0.5,0.5,0.5, 1.0])
		glLightfv(GL_LIGHT1, GL_SPECULAR, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT1, GL_POSITION, [0,0,1,1]) # set the is self.radius when it's known
		glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, [0,0,-1])
		glLightfv(GL_LIGHT1, GL_QUADRATIC_ATTENUATION,0.0037)
		
		glLightfv(GL_LIGHT2, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT2, GL_DIFFUSE, [0.5,0.5,0.5, 1.0])
		glLightfv(GL_LIGHT2, GL_SPECULAR, [0.0, 1.0, 0.0, 1.0])
		glLightfv(GL_LIGHT2, GL_POSITION, [0.1,.1,1.,0.])
		
		glLightfv(GL_LIGHT3, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])
		glLightfv(GL_LIGHT3, GL_DIFFUSE, [0.5,0.5,0.5, 1.0])
		glLightfv(GL_LIGHT3, GL_SPECULAR, [0.0, 1.0, 0.0, 1.0])
		glLightfv(GL_LIGHT3, GL_POSITION, [0.1,.1,1.,0.])
		#GL_SPOT_DIRECTION,GL_SPOT_CUTOFF,GL_QUADRATIC_ATTENUATION
		
		
		GL.glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
		glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE)
		glShadeModel(GL_SMOOTH)
		#glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [0.1,0.1,0.1,1.0]);
		
		glClearStencil(0)
		glEnable(GL_STENCIL_TEST)
		GL.glClearColor(0,0,0,0)
		
		
		glEnable(GL_NORMALIZE)
	def is_emitting(self): return self.emit_events
	def load_last_viewable_camera(self):
		return
		size = len(self.viewables)
		if ( size <= 1 ): return
		self.viewables[size-1].set_camera(self.viewables[0].get_current_camera())
	def load_orthographic(self):
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		
		if self.yheight == None: self.yheight = self.height()
		
		self.aspect = float(self.width())/float(self.height())
		self.xwidth = self.aspect*self.yheight
		if self.xwidth == 0 or self.yheight == 0: return # probably startup
		
		glOrtho(-self.xwidth/2.0,self.xwidth/2.0,-self.yheight/2.0,self.yheight/2.0,self.startz,self.endz)
		glMatrixMode(GL_MODELVIEW)
	def load_perspective(self):
		self.aspect = float(self.width())/float(self.height())
		
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		if self.startz < 0: self.startz = 1
		gluPerspective(self.fov,self.aspect,self.startz,self.endz)
		glMatrixMode(GL_MODELVIEW)
	def load_rotation(self,t3d):
		self.cam.load_rotation(t3d)
		self.updateGL()
	def mouseMoveEvent(self, event):
		if self.current_mouse_mode:
			EMLightsDrawer.mouseMoveEvent(self, event)
		else:
			for model in self.viewables:
				try:
					model.mouseMoveEvent(event)
				except AttributeError, e:
					pass
		self.updateGL()
Beispiel #4
0
class EM3DSliceModel(EM3DModel):
    def __init__(self, gl_widget, image=None):
        self.data = None
        EM3DModel.__init__(self, gl_widget)
        self.init()
        self.initialized = True

        self.inspector = None

        self.axes = []
        self.axes.append(Vec3f(1, 0, 0))
        self.axes.append(Vec3f(0, 1, 0))
        self.axes.append(Vec3f(0, 0, 1))
        self.axes_idx = 2

        self.track = False
        self.bright = 0
        self.contrast = 1.0
        self.busy = True
        if image:
            self.set_data(image)

    def set_contrast(self, val):
        self.contrast = val
        self.generate_current_display_list()
        self.updateGL()

    def set_brightness(self, val):
        self.bright = val
        self.generate_current_display_list()
        self.updateGL()

#	def __del__(self):
#		print "slice died"

    def get_type(self):
        return "Slice Viewer"

    def init(self):
        self.data = None

        self.mmode = 0
        self.cam = Camera2(self)

        self.vdtools = EMViewportDepthTools(self)

        self.cube = False
        self.inspector = None

        self.tex_name = 0
        self.tex_dl = 0

        self.glcontrast = 1.0
        self.glbrightness = 0.0

        self.rank = 1

        self.glflags = EMOpenGLFlagsAndTools(
        )  # OpenGL flags - this is a singleton convenience class for testing texture support

    def eye_coords_dif(self, x1, y1, x2, y2, mdepth=True):
        return self.vdtools.eye_coords_dif(x1, y1, x2, y2, mdepth)

    def update_data(self, data):
        if data == None:
            print("Error, the data is empty")
            return

        if (isinstance(data, EMData) and data.get_zsize() <= 1):
            print("Error, the data is not 3D")
            return


#		self.data = data.copy()
#
#		min = self.data.get_attr("minimum")
#		max = self.data.get_attr("maximum")
#
#		self.data.add(-min)
#		self.data.mult(1/(max-min))

        self.generate_current_display_list()
        self.updateGL()

    def set_default_contrast_settings(self):
        min = self.data.get_attr("minimum")
        max = self.data.get_attr("maximum")
        #
        #		self.data.add(-min)
        #		self.data.mult(1/(max-min))
        self.bright = -min
        if max != min: self.contrast = 1.0 / (max - min)
        else: self.contrast = 1

    def set_data(self, data, fact=1.0):
        """Pass in a 3D EMData object"""

        self.busy = True
        if data == None:
            print("Error, the data is empty")
            return

        if (isinstance(data, EMData) and data.get_zsize() <= 1):
            print("Error, the data is not 3D")
            self.busy = False
            return

        self.data = data

        self.set_default_contrast_settings()

        if not self.inspector or self.inspector == None:
            self.inspector = EM3DSliceInspector(self)

        self.inspector.set_contrast_bright(self.contrast, self.bright)
        hist = self.data.calc_hist(256, 0, 1.0, self.bright, self.contrast)
        self.inspector.set_hist(hist, 0, 1.0)

        self.slice = data.get_zsize() / 2
        self.zslice = data.get_zsize() / 2 - 1
        if self.zslice < 0: self.zslice = 0
        self.yslice = data.get_ysize() / 2 - 1
        if self.yslice < 0: self.yslice = 0
        self.xslice = data.get_xsize() / 2 - 1
        if self.xslice < 0: self.xslice = 0
        self.trackslice = self.xslice
        self.axis = 'z'
        self.inspector.set_sliceRange(0, data.get_zsize() - 1)
        self.inspector.set_slice(self.zslice)
        self.generate_current_display_list()

        from emglobjects import EM3DGLWidget
        if isinstance(self.get_gl_widget(), EM3DGLWidget):
            self.get_gl_widget().set_camera_defaults(self.data)

        if (self.tex_dl != 0):
            glDeleteLists(self.tex_dl, 1)
            self.tex_dl = 0
        self.busy = False

    def get_eman_transform(self, p):

        if (p[2] == 0):
            alt = 90
        else:
            alt = acos(p[2]) * 180.0 / pi

        phi = atan2(p[0], p[1])
        phi *= 180.0 / pi

        return [Transform({"type": "eman", "alt": alt, "phi": phi}), alt, phi]

    def get_dimension_size(self):
        if (self.axes_idx == 0):
            return self.data.get_xsize()
        elif (self.axes_idx == 1):
            return self.data.get_ysize()
        elif (self.axes_idx == 2):
            return self.data.get_zsize()
        else:
            #print "unsupported axis"
            # this is a hack and needs to be fixed eventually
            return self.data.get_xsize()
            #return 0
    def get_correct_dims_2d_emdata(self):
        if (self.axes_idx == 0):
            return EMData(self.data.get_ysize(), self.data.get_zsize())
        elif (self.axes_idx == 1):
            return EMData(self.data.get_xsize(), self.data.get_zsize())
        elif (self.axes_idx == 2):
            return EMData(self.data.get_xsize(), self.data.get_ysize())
        else:
            #print "unsupported axis"
            # this is a hack and needs to be fixed eventually
            return EMData(self.data.get_xsize(), self.data.get_zsize())

    def generate_current_display_list(self):
        if self.busy: return
        if (self.tex_dl != 0): glDeleteLists(self.tex_dl, 1)

        self.tex_dl = glGenLists(1)

        if (self.tex_dl == 0): return  #OpenGL is initialized yet

        self.gen_2D_texture()

    def gen_2D_texture(self):
        glNewList(self.tex_dl, GL_COMPILE)

        n = self.get_dimension_size()
        v = self.axes[self.axes_idx]

        [t, alt, phi] = self.get_eman_transform(v)

        nn = float(self.slice) / float(n)
        trans = (nn - 0.5) * v
        t.set_trans(n * trans)

        if False and EMUtil.cuda_available(
        ):  # disable for the time being - big textures won't work on CPU
            tmp = self.data.cut_slice_cuda(t)
        else:
            tmp = self.get_correct_dims_2d_emdata()
            tmp.cut_slice(self.data, t, True)

        tmp.add(self.bright)
        tmp.mult(self.contrast)

        hist = tmp.calc_hist(256, 0, 1.0, self.bright, self.contrast)
        self.inspector.set_hist(hist, 0, 1.0)

        if (self.tex_name != 0): glDeleteTextures(self.tex_name)
        self.tex_name = 0

        self.tex_name = self.glflags.gen_textureName(tmp)

        glEnable(GL_TEXTURE_2D)
        glBindTexture(GL_TEXTURE_2D, self.tex_name)

        #glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        #		if ( not data_dims_power_of(self.data,2) and self.glflags.npt_textures_unsupported()):
        #			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        #		else:
        #			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)

        glPushMatrix()
        glTranslate(trans[0] + 0.5, trans[1] + 0.5, trans[2] + 0.5)
        glRotatef(-phi, 0, 0, 1)
        glRotatef(-alt, 1, 0, 0)
        glBegin(GL_QUADS)
        glTexCoord2f(0, 0)
        glVertex2f(-0.5, -0.5)

        glTexCoord2f(1, 0)
        glVertex2f(0.5, -0.5)

        glTexCoord2f(1, 1)
        glVertex2f(0.5, 0.5)

        glTexCoord2f(0, 1)
        glVertex2f(-0.5, 0.5)
        glEnd()
        glPopMatrix()

        glDisable(GL_TEXTURE_2D)
        glEndList()

    def render(self):
        if self.busy: return
        lighting = glIsEnabled(GL_LIGHTING)
        cull = glIsEnabled(GL_CULL_FACE)
        polygonmode = glGetIntegerv(GL_POLYGON_MODE)
        glDisable(GL_LIGHTING)
        glDisable(GL_CULL_FACE)

        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

        glPushMatrix()
        self.cam.position(True)
        # the ones are dummy variables atm... they don't do anything
        self.vdtools.update(1, 1)
        glPopMatrix()

        self.cam.position()
        self.vdtools.store_model()

        if (self.track):
            self.loadTrackAxis()
            self.generate_current_display_list()

        if (self.tex_dl == 0):
            self.generate_current_display_list()

        glStencilFunc(GL_EQUAL, self.rank, 0)
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)
        glPushMatrix()
        glTranslate(-self.data.get_xsize() / 2.0, -self.data.get_ysize() / 2.0,
                    -self.data.get_zsize() / 2.0)
        glScalef(self.data.get_xsize(), self.data.get_ysize(),
                 self.data.get_zsize())
        glCallList(self.tex_dl)
        glPopMatrix()

        #breaks in desktop!
        #glStencilFunc(GL_EQUAL,self.rank,self.rank)
        #glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP)
        #glPushMatrix()
        ##glLoadIdentity()
        #[width,height] = self.parent.get_near_plane_dims()
        #z = self.parent.get_start_z()
        #glTranslate(-width/2.0,-height/2.0,-z-0.01)
        #glScalef(width,height,1.0)
        self.draw_bc_screen()
        #glPopMatrix()

        glStencilFunc(GL_ALWAYS, 1, 1)
        glColor3f(1, 1, 1)
        if self.cube:
            glPushMatrix()
            self.draw_volume_bounds()
            glPopMatrix()

        if (lighting): glEnable(GL_LIGHTING)
        if (cull): glEnable(GL_CULL_FACE)

        if (polygonmode[0] == GL_LINE): glPolygonMode(GL_FRONT, GL_LINE)
        if (polygonmode[1] == GL_LINE): glPolygonMode(GL_BACK, GL_LINE)

    def set_slice(self, val):
        self.slice = val
        if self.axis == 'z':
            self.zslice = val
        elif self.axis == 'y':
            self.yslice = val
        elif self.axis == 'x':
            self.xslice = val
        else:
            self.trackslice = val

        self.generate_current_display_list()
        self.updateGL()

    def setAxis(self, val):
        self.axis = str(val).strip()

        if (self.inspector != None):
            if self.axis == 'z':
                self.inspector.set_sliceRange(0, self.data.get_zsize() - 1)
                self.inspector.set_slice(self.zslice)
                self.axes_idx = 2
                self.track = False
            elif self.axis == 'y':
                self.inspector.set_sliceRange(0, self.data.get_ysize() - 1)
                self.inspector.set_slice(self.yslice)
                self.axes_idx = 1
                self.track = False
            elif self.axis == 'x':
                self.inspector.set_sliceRange(0, self.data.get_xsize() - 1)
                self.inspector.set_slice(self.xslice)
                self.axes_idx = 0
                self.track = False
            elif self.axis == 'track':
                self.track = True
                self.inspector.set_sliceRange(0, self.data.get_xsize() - 1)
                self.inspector.set_slice(self.trackslice)
                self.axes_idx = 3

                self.loadTrackAxis()
            else:
                print("Error, unknown axis", self.axis, val)

        self.generate_current_display_list()
        self.updateGL()

    def update_inspector(self, t3d):
        if not self.inspector or self.inspector == None:
            self.inspector = EM3DSliceInspector(self)
        self.inspector.update_rotations(t3d)

    def get_inspector(self):
        if not self.inspector: self.inspector = EM3DSliceInspector(self)
        return self.inspector

    def loadTrackAxis(self):
        t3d = self.vdtools.getEmanMatrix()
        #at3d = self.cam.t3d_stack[len(self.cam.t3d_stack)-1]

        point = Vec3f(0, 0, 1)

        point *= 1.0 / self.vdtools.getCurrentScale()

        point = point * t3d

        #if ( point[2] != 0 ): point[2] = -point[2]

        if len(self.axes) == 3:
            self.axes.append(point)
        else:
            self.axes[3] = point

    def resize(self):
        self.vdtools.set_update_P_inv()
Beispiel #5
0
class EM3DFontModel(EMLightsDrawer,EM3DModel,DynamicFonts):
	def __init__(self, gl_widget):
		EM3DModel.__init__(self, gl_widget)
		DynamicFonts.__init__(self)

		self.init()
		self.initialized = True
		self.load_colors()
		self.cam=Camera2(self)
		self.cam.basicmapping = True #Ross's experiment... fixes translation

		self.brightness = 0
		self.contrast = 10
		self.glcontrast = 1.0
		self.glbrightness = 0.0
		self.rank = 1
		self.inspector=None
		self.bgR = .85
		self.bgG = .85
		self.bgB = 1.0
		self.bg_a = 1
		self.lspacing = 75
#		self.get_gl_widget().cam.default_z = -25	# this is me hacking
#		self.get_gl_widget().cam.cam_z = -25 		# this is me hacking
		self.vdtools = EMViewportDepthTools(self)
		self.font_renderer = get_3d_font_renderer()
		self.font_renderer.set_font_mode(FTGLFontMode.EXTRUDE)
		self.font_renderer.set_depth(75)
		self.render_string = "hello world"

		EMLightsDrawer.__init__(self)
		self.setInit()

	def set_render_string(self,string):
		self.render_string = string
	def set_bg_r(self,bgR):
		self.bgR = bgR
	def set_bg_g(self,bgG):
		self.bgG = bgG
	def set_bg_b(self,bgB):
		self.bgB = bgB
	def set_bg_a(self,bg_a):
		self.bg_a = bg_a
	def set_lspacing(self,lspacing):
		self.lspacing = lspacing

	def render(self):
		#if (not isinstance(self.data,EMData)): return
	
		glEnable(GL_NORMALIZE)
		lighting = glIsEnabled(GL_LIGHTING)
		cull = glIsEnabled(GL_CULL_FACE)
		depth = glIsEnabled(GL_DEPTH_TEST)
		polygonmode = glGetIntegerv(GL_POLYGON_MODE)

		glDisable(GL_CULL_FACE)
		glEnable(GL_DEPTH_TEST)

		if ( self.wire ):
			glPolygonMode(GL_FRONT_AND_BACK,GL_LINE)
		else:
			glPolygonMode(GL_FRONT_AND_BACK,GL_FILL)

		if self.light:
			glEnable(GL_LIGHTING)
		else:
			glDisable(GL_LIGHTING)

		glPushMatrix()
		self.cam.position(True)
		# the ones are dummy variables atm... they don't do anything
		self.vdtools.update(1,1)
		glPopMatrix()

		glPushMatrix()
		self.cam.position()
	
		glPushMatrix()
		self.cam.position(True)
		# the ones are dummy variables atm... they don't do anything
		self.vdtools.update(1,1)
		glPopMatrix()

		glShadeModel(GL_SMOOTH)

		glStencilFunc(GL_EQUAL,self.rank,0)
		glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE)
		glMaterial(GL_FRONT, GL_AMBIENT, self.colors[self.currentcolor]["ambient"])
		glMaterial(GL_FRONT, GL_DIFFUSE, self.colors[self.currentcolor]["diffuse"])
		glMaterial(GL_FRONT, GL_SPECULAR, self.colors[self.currentcolor]["specular"])
		glMaterial(GL_FRONT, GL_SHININESS, self.colors[self.currentcolor]["shininess"])
		glColor(self.colors[self.currentcolor]["diffuse"])

		glClearColor(self.bgR,self.bgG,self.bgB,self.bg_a)

		glEnable(GL_NORMALIZE)
		#HERE
		glPushMatrix()
		glNormal(0,0,1)
		glEnable(GL_TEXTURE_2D)

		i = 0
		self.ifevalstr = self.render_string.split("\n")
		ifevalref = len(self.ifevalstr)-1
		spfac_i = -1*int((ifevalref+1)/2)
		spfac_f = int((ifevalref+1)/2)
		spfac = [-1*int((ifevalref+1)/2)]
		while spfac_i<spfac_f:
			spfac_i = spfac_i+1
			spfac.append(spfac_i)
		if ifevalref%2!=0:
			spfac.remove(0)
			while i<len(spfac)/2:
				i = i+1
				spfac[i-1]=spfac[i-1]+0.5
			while (i<len(spfac)):
				i = i+1
				spfac[i-1]=spfac[i-1]-0.5
		i = 0
		while i<=ifevalref:
			i = i+1
			tvar = str("bbox"+str(i))
			tvar = self.font_renderer.bounding_box(self.ifevalstr[i-1])
			glPushMatrix()
			glTranslate((tvar[0]-tvar[3])/2,(tvar[1]-tvar[4]-(((spfac[i-1])*self.lspacing)-0))/2,-(tvar[2]-tvar[5])/2)
			self.font_renderer.render_string(self.ifevalstr[i-1]);
			glPopMatrix()	

		glPopMatrix()

		glPopMatrix()
		glStencilFunc(GL_EQUAL,self.rank,self.rank)
		glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP)
		glPushMatrix()
		glLoadIdentity()
		glScalef(10,10,1)
		glTranslate(-90.5,-90.5,-91)
		self.draw_bc_screen()
		glPopMatrix()

		EMLightsDrawer.draw(self)		
		glStencilFunc(GL_ALWAYS,1,1)

		if ( lighting ): glEnable(GL_LIGHTING)
		else: glDisable(GL_LIGHTING)
		if ( cull ): glEnable(GL_CULL_FACE)
		else: glDisable(GL_CULL_FACE)
		if ( depth ): glEnable(GL_DEPTH_TEST)
		else : glDisable(GL_DEPTH_TEST)

		if ( polygonmode[0] == GL_LINE ): glPolygonMode(GL_FRONT, GL_LINE)
		else: glPolygonMode(GL_FRONT, GL_FILL)
		if ( polygonmode[1] == GL_LINE ): glPolygonMode(GL_BACK, GL_LINE)
		else: glPolygonMode(GL_BACK, GL_FILL)

	def init(self):
		self.mmode = 0
		self.wire = False
		self.light = True

	def setInit(self):
		self.cam.default_z = 0
		self.cam.cam_z = -10*32
		if not self.inspector or self.inspector ==None:
			self.inspector=EMFontInspector(self)
		self.inspector.setColors(self.colors,self.currentcolor)

	def load_colors(self):
		self.colors = get_default_gl_colors()
		self.currentcolor = "ruby"
	def mouseDoubleClickEvent(self, event):
		if self.current_mouse_mode:
			EMLightsDrawer.mouseDoubleClickEvent(self, event)
		else:
			EM3DModel.mouseDoubleClickEvent(self, event)
	def mouseMoveEvent(self, event):
		if self.current_mouse_mode:
			EMLightsDrawer.mouseMoveEvent(self, event)
		else:
			EM3DModel.mouseMoveEvent(self, event)
	def mousePressEvent(self, event):
		if self.current_mouse_mode:
			EMLightsDrawer.mousePressEvent(self, event)
		else:
			EM3DModel.mousePressEvent(self, event)
	def mouseReleaseEvent(self, event):
		if self.current_mouse_mode:
			EMLightsDrawer.mouseReleaseEvent(self, event)
		else:
			EM3DModel.mouseReleaseEvent(self, event)
	def setColor(self,val):
		self.currentcolor = str(val)
		self.updateGL()

	def toggle_wire(self,val):
		self.wire = not self.wire
		self.updateGL()

	def toggle_light(self,val):
		self.light = not self.light
		self.updateGL()

	def update_inspector(self,t3d):
		if not self.inspector or self.inspector ==None:
			self.inspector=EMFontInspector(self)
		self.inspector.update_rotations(t3d)

	def get_inspector(self):
		if not self.inspector : self.inspector=EMFontInspector(self)
		return self.inspector
	
	def eye_coords_dif(self,x1,y1,x2,y2,mdepth=True):
		return self.vdtools.eye_coords_dif(x1,y1,x2,y2,mdepth)

#	def resize(self):
#		self.vdtools.set_update_P_inv()
	def get_type(self):
		return "EM3DFontModel"
Beispiel #6
0
class EM3DFontModel(EMLightsDrawer, EM3DModel, DynamicFonts):
    def __init__(self, gl_widget):
        EM3DModel.__init__(self, gl_widget)
        DynamicFonts.__init__(self)

        self.init()
        self.initialized = True
        self.load_colors()
        self.cam = Camera2(self)
        self.cam.basicmapping = True  #Ross's experiment... fixes translation

        self.brightness = 0
        self.contrast = 10
        self.glcontrast = 1.0
        self.glbrightness = 0.0
        self.rank = 1
        self.inspector = None
        self.bgR = .85
        self.bgG = .85
        self.bgB = 1.0
        self.bg_a = 1
        self.lspacing = 75
        #		self.get_gl_widget().cam.default_z = -25	# this is me hacking
        #		self.get_gl_widget().cam.cam_z = -25 		# this is me hacking
        self.vdtools = EMViewportDepthTools(self)
        self.font_renderer = get_3d_font_renderer()
        self.font_renderer.set_font_mode(FTGLFontMode.EXTRUDE)
        self.font_renderer.set_depth(75)
        self.render_string = "hello world"

        EMLightsDrawer.__init__(self)
        self.setInit()

    def set_render_string(self, string):
        self.render_string = string

    def set_bg_r(self, bgR):
        self.bgR = bgR

    def set_bg_g(self, bgG):
        self.bgG = bgG

    def set_bg_b(self, bgB):
        self.bgB = bgB

    def set_bg_a(self, bg_a):
        self.bg_a = bg_a

    def set_lspacing(self, lspacing):
        self.lspacing = lspacing

    def render(self):
        #if (not isinstance(self.data,EMData)): return

        glEnable(GL_NORMALIZE)
        lighting = glIsEnabled(GL_LIGHTING)
        cull = glIsEnabled(GL_CULL_FACE)
        depth = glIsEnabled(GL_DEPTH_TEST)
        polygonmode = glGetIntegerv(GL_POLYGON_MODE)

        glDisable(GL_CULL_FACE)
        glEnable(GL_DEPTH_TEST)

        if (self.wire):
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
        else:
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

        if self.light:
            glEnable(GL_LIGHTING)
        else:
            glDisable(GL_LIGHTING)

        glPushMatrix()
        self.cam.position(True)
        # the ones are dummy variables atm... they don't do anything
        self.vdtools.update(1, 1)
        glPopMatrix()

        glPushMatrix()
        self.cam.position()

        glPushMatrix()
        self.cam.position(True)
        # the ones are dummy variables atm... they don't do anything
        self.vdtools.update(1, 1)
        glPopMatrix()

        glShadeModel(GL_SMOOTH)

        glStencilFunc(GL_EQUAL, self.rank, 0)
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)
        glMaterial(GL_FRONT, GL_AMBIENT,
                   self.colors[self.currentcolor]["ambient"])
        glMaterial(GL_FRONT, GL_DIFFUSE,
                   self.colors[self.currentcolor]["diffuse"])
        glMaterial(GL_FRONT, GL_SPECULAR,
                   self.colors[self.currentcolor]["specular"])
        glMaterial(GL_FRONT, GL_SHININESS,
                   self.colors[self.currentcolor]["shininess"])
        glColor(self.colors[self.currentcolor]["diffuse"])

        glClearColor(self.bgR, self.bgG, self.bgB, self.bg_a)

        glEnable(GL_NORMALIZE)
        #HERE
        glPushMatrix()
        glNormal(0, 0, 1)
        glEnable(GL_TEXTURE_2D)

        i = 0
        self.ifevalstr = self.render_string.split("\n")
        ifevalref = len(self.ifevalstr) - 1
        spfac_i = -1 * int((ifevalref + 1) / 2)
        spfac_f = int((ifevalref + 1) / 2)
        spfac = [-1 * int((ifevalref + 1) / 2)]
        while spfac_i < spfac_f:
            spfac_i = spfac_i + 1
            spfac.append(spfac_i)
        if ifevalref % 2 != 0:
            spfac.remove(0)
            while i < len(spfac) / 2:
                i = i + 1
                spfac[i - 1] = spfac[i - 1] + 0.5
            while (i < len(spfac)):
                i = i + 1
                spfac[i - 1] = spfac[i - 1] - 0.5
        i = 0
        while i <= ifevalref:
            i = i + 1
            tvar = str("bbox" + str(i))
            tvar = self.font_renderer.bounding_box(self.ifevalstr[i - 1])
            glPushMatrix()
            glTranslate((tvar[0] - tvar[3]) / 2,
                        (tvar[1] - tvar[4] -
                         (((spfac[i - 1]) * self.lspacing) - 0)) / 2,
                        -(tvar[2] - tvar[5]) / 2)
            self.font_renderer.render_string(self.ifevalstr[i - 1])
            glPopMatrix()

        glPopMatrix()

        glPopMatrix()
        glStencilFunc(GL_EQUAL, self.rank, self.rank)
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP)
        glPushMatrix()
        glLoadIdentity()
        glScalef(10, 10, 1)
        glTranslate(-90.5, -90.5, -91)
        self.draw_bc_screen()
        glPopMatrix()

        EMLightsDrawer.draw(self)
        glStencilFunc(GL_ALWAYS, 1, 1)

        if (lighting): glEnable(GL_LIGHTING)
        else: glDisable(GL_LIGHTING)
        if (cull): glEnable(GL_CULL_FACE)
        else: glDisable(GL_CULL_FACE)
        if (depth): glEnable(GL_DEPTH_TEST)
        else: glDisable(GL_DEPTH_TEST)

        if (polygonmode[0] == GL_LINE): glPolygonMode(GL_FRONT, GL_LINE)
        else: glPolygonMode(GL_FRONT, GL_FILL)
        if (polygonmode[1] == GL_LINE): glPolygonMode(GL_BACK, GL_LINE)
        else: glPolygonMode(GL_BACK, GL_FILL)

    def init(self):
        self.mmode = 0
        self.wire = False
        self.light = True

    def setInit(self):
        self.cam.default_z = 0
        self.cam.cam_z = -10 * 32
        if not self.inspector or self.inspector == None:
            self.inspector = EMFontInspector(self)
        self.inspector.setColors(self.colors, self.currentcolor)

    def load_colors(self):
        self.colors = get_default_gl_colors()
        self.currentcolor = "ruby"

    def mouseDoubleClickEvent(self, event):
        if self.current_mouse_mode:
            EMLightsDrawer.mouseDoubleClickEvent(self, event)
        else:
            EM3DModel.mouseDoubleClickEvent(self, event)

    def mouseMoveEvent(self, event):
        if self.current_mouse_mode:
            EMLightsDrawer.mouseMoveEvent(self, event)
        else:
            EM3DModel.mouseMoveEvent(self, event)

    def mousePressEvent(self, event):
        if self.current_mouse_mode:
            EMLightsDrawer.mousePressEvent(self, event)
        else:
            EM3DModel.mousePressEvent(self, event)

    def mouseReleaseEvent(self, event):
        if self.current_mouse_mode:
            EMLightsDrawer.mouseReleaseEvent(self, event)
        else:
            EM3DModel.mouseReleaseEvent(self, event)

    def setColor(self, val):
        self.currentcolor = str(val)
        self.updateGL()

    def toggle_wire(self, val):
        self.wire = not self.wire
        self.updateGL()

    def toggle_light(self, val):
        self.light = not self.light
        self.updateGL()

    def update_inspector(self, t3d):
        if not self.inspector or self.inspector == None:
            self.inspector = EMFontInspector(self)
        self.inspector.update_rotations(t3d)

    def get_inspector(self):
        if not self.inspector: self.inspector = EMFontInspector(self)
        return self.inspector

    def eye_coords_dif(self, x1, y1, x2, y2, mdepth=True):
        return self.vdtools.eye_coords_dif(x1, y1, x2, y2, mdepth)


#	def resize(self):
#		self.vdtools.set_update_P_inv()

    def get_type(self):
        return "EM3DFontModel"
class EM3DModule(EMImage3DGUIModule):
	
	def get_qt_widget(self):
		if self.qt_context_parent == None:	
			from emimageutil import EMParentWin
			from emimage3d import EMImage3DWidget
			self.under_qt_control = True
			self.gl_context_parent = EMImage3DWidget(self)
			self.qt_context_parent = EMParentWin(self.gl_context_parent)
			self.gl_widget = self.gl_context_parent			
			self.qt_context_parent.setWindowIcon(QtGui.QIcon(get_image_directory() +"single_image_3d.png"))
		
		return self.qt_context_parent
	
	def get_gl_widget(self,qt_context_parent,gl_context_parent):
		self.under_qt_control = False
		ret = EMImage3DGUIModule.get_gl_widget(self,qt_context_parent,gl_context_parent)
		self.gl_widget.setWindowTitle(remove_directories_from_name(self.file_name))
		self.__set_module_contexts()
		return ret
	
	def get_desktop_hint(self):
		return "image"

	def __init__(self,application=None,ensure_gl_context=True,application_control=True):
		EMImage3DGUIModule.__init__(self,application,ensure_gl_context=ensure_gl_context,application_control=application_control)
		#EMLightsDrawer.__init__(self)
		self.cam = Camera2(self)
		self.vdtools = EMViewportDepthTools(self)
		self.perspective = False
		self.colors = get_default_gl_colors()
		self.perspective = True
		
		# basic shapes will be stored in these lists
		self.gq = None # will be a glu quadric
		self.cylinderdl = 0 # will be a cylinder with no caps
		self.diskdl = 0 # this will be a flat disk
		self.spheredl = 0 # this will be a low resolution sphere
		self.highresspheredl = 0 # high resolution sphere
		self.cappedcylinderdl = 0 # a capped cylinder
		self.first_render_flag = True # this is used to catch the first call to the render function - so you can do an GL context sensitive initialization when you know there is a valid context
	
		self.inspector = None # will be the inspector, i.e. an instance of an EM3DInspector
		self.radius = 100
		
		self.font_renderer = None # will be a 3D fonts renderer
		
		
	def __del__(self):
		if self.under_qt_control and not self.dont_delete_parent:
			self.qt_context_parent.deleteLater()
		self.core_object.deleteLater()

	def width(self):
		try: return self.gl_widget.width()
		except: return 0
		
	def height(self):
		try: return self.gl_widget.height()
		except: return 0
	
	def initializeGL(self):
		# put your own initialization things in here
		glEnable(GL_LIGHTING)
		glEnable(GL_NORMALIZE)
		
	def load_gl_color(self,name):
		color = self.colors[name]
		glColor(color["ambient"])
		glMaterial(GL_FRONT,GL_AMBIENT,color["ambient"])
		glMaterial(GL_FRONT,GL_DIFFUSE,color["diffuse"])
		glMaterial(GL_FRONT,GL_SPECULAR,color["specular"])
		glMaterial(GL_FRONT,GL_EMISSION,color["emission"])
		glMaterial(GL_FRONT,GL_SHININESS,color["shininess"])
	
	
	def render(self):
		if self.first_render_flag:
#			self.initializeGL()
#			self.init_basic_shapes() # only does something the first time you call it
#			self.init_font_renderer()
			if not self.perspective:self.gl_context_parent.load_orthographic()
			else: self.gl_context_parent.load_perspective()
			self.first_render_flag = False
					
		#self.vdtools.set_update_P_inv()
		glPushMatrix()
		self.cam.position(True)
		# the ones are dummy variables atm... they don't do anything
		self.vdtools.update(1,1)
		glPopMatrix()
		
		glPushMatrix()
		self.cam.position()
	
		self.draw_objects()
		
		glPopMatrix()
		
#		glPushMatrix()
#		self.cam.translate_only()
#		EMLightsDrawer.draw(self)
#		glPopMatrix()
		
	
	def draw_objects(self):
#		glPushMatrix()
#		glScale(50,50,50)
#		self.load_gl_color("red")
#		glCallList(self.highresspheredl)
#		glPopMatrix()
		
		glPushMatrix()
		glTranslate(100,0,0)
		glScale(50,50,50)
		self.load_gl_color("blue")
		glCallList(self.spheredl)
		glPopMatrix()
		
		glPushMatrix()
		glTranslate(0,100,0)
		glScale(50,10,10)
		glTranslate(-0.5,0,0)
		glRotate(90,0,1,0)
		self.load_gl_color("emerald")
		glCallList(self.cylinderdl)
		glPopMatrix()
		
		glPushMatrix()
		glTranslate(-100,25,0)
		glScale(10,50,10)
		glTranslate(-0.5,0,0)
		glRotate(90,1,0,0)
		self.load_gl_color("gold")
		glCallList(self.cappedcylinderdl)
		glPopMatrix()
		
		glPushMatrix()
		glTranslate(0,-100,0)
		glScale(15,15,15)
		self.load_gl_color("copper")
		glCallList(self.diskdl)
		glPopMatrix()
		
		glPushMatrix()
		glTranslate(0,-100,-10)
		glScale(15,15,15)
		glRotate(180,0,1,0)
		self.load_gl_color("silver")
		glCallList(self.diskdl)
		glPopMatrix()
		
		glPushMatrix()
		glTranslate(0,0,50)
		s = "bdb:EMAN2"
		
		bbox = self.font_renderer.bounding_box(s)
		glTranslate(-(bbox[3]-bbox[0])/2, -(bbox[4]-bbox[1])/2,-(bbox[5]-bbox[02])/2)
		self.font_renderer.render_string(s)
		glPopMatrix()
		
		
		glPushMatrix()
		glTranslate(0,-50,-50)
		s = "=^_^="
		bbox = self.font_renderer.bounding_box(s)
		glTranslate(-(bbox[3]-bbox[0])/2, -(bbox[4]-bbox[1])/2,-(bbox[5]-bbox[02])/2)
		self.font_renderer.render_string(s)
		glPopMatrix()
	
	
	def init_font_renderer(self):
		if self.font_renderer == None:
			self.font_renderer = get_3d_font_renderer()
			self.font_renderer.set_face_size(20)
			self.font_renderer.set_depth(12)
			self.font_renderer.set_font_mode(FTGLFontMode.EXTRUDE)
		
		
	def init_basic_shapes(self):
		#self.gl_context_parent.makeCurrent()
		if self.gq == None:
			
			self.gq=gluNewQuadric() # a quadric for general use
			gluQuadricDrawStyle(self.gq,GLU_FILL)
			gluQuadricNormals(self.gq,GLU_SMOOTH)
			gluQuadricOrientation(self.gq,GLU_OUTSIDE)
			gluQuadricTexture(self.gq,GL_FALSE)
		
		if ( self.cylinderdl == 0 ):
			self.cylinderdl=glGenLists(1)
				
			glNewList(self.cylinderdl,GL_COMPILE)
			glPushMatrix()
			gluCylinder(self.gq,1.0,1.0,1.0,12,2)
			glPopMatrix()
				
			glEndList()
		
		if self.diskdl == 0:
			self.diskdl=glGenLists(1)
				
			glNewList(self.diskdl,GL_COMPILE)
			gluDisk(self.gq,0,1,12,2)
			glEndList()
		
		if self.spheredl == 0:
			self.spheredl=glGenLists(1)
				
			glNewList(self.spheredl,GL_COMPILE)
			gluSphere(self.gq,.5,4,2)
			glEndList()

		
		if self.highresspheredl == 0:
			self.highresspheredl=glGenLists(1)
				
			glNewList(self.highresspheredl,GL_COMPILE)
			gluSphere(self.gq,.5,16,16)
			glEndList()
			
		if ( self.cappedcylinderdl == 0 ):
			self.cappedcylinderdl=glGenLists(1)
			glNewList(self.cappedcylinderdl,GL_COMPILE)
			glCallList(self.cylinderdl)
			glPushMatrix()
			glTranslate(0,0,1)
			glCallList(self.diskdl)
			glPopMatrix()
			glPushMatrix()
			glRotate(180,0,1,0)
			glCallList(self.diskdl)
			glPopMatrix()
			glEndList()
			
	def eye_coords_dif(self,x1,y1,x2,y2,mdepth=True):
		return self.vdtools.eye_coords_dif(x1,y1,x2,y2,mdepth)
	
	def resizeEvent(self, width, height):
		for i in self.viewables:
			i.resizeEvent()
	
	def get_inspector(self):
		if self.inspector == None:
			self.inspector = EM3DInspector(self)
		return self.inspector

	def set_cam_z(self,z):
		self.cam.set_cam_z( z )
		self.updateGL()
		
	def set_cam_y(self,y):
		self.cam.set_cam_y( y )
		self.updateGL()
		
	def set_cam_x(self,x):
		self.cam.set_cam_x( x )
		self.updateGL()
	
	def set_scale(self,val):
		self.cam.scale = val
		self.updateGL()	

	def resizeEvent(self,width=0,height=0):
		self.vdtools.set_update_P_inv()
	
	def load_rotation(self,t3d):
		self.cam.load_rotation(t3d)
		self.updateGL()

	def get_start_z(self):
		return self.gl_context_parent.get_start_z()
	
	def get_near_plane_dims(self):
		return self.gl_context_parent.get_near_plane_dims()
	
	def set_perspective(self,bool):
		self.perspective = bool
		
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		if not self.perspective:self.gl_context_parent.load_orthographic()
		else: self.gl_context_parent.load_perspective()
		glMatrixMode(GL_MODELVIEW)
		
		self.updateGL()