def main(): """Launch VisionEgg and demo the WrappedText object""" import VisionEgg VisionEgg.start_default_logging(); VisionEgg.watch_exceptions() import VisionEgg.FlowControl screen = VisionEgg.Core.get_default_screen() message="""Hello. This is a demonstration of the WrappedText object, which was created to allow users of VisionEgg to include large blocks of text in their programs. While this stimulus has many limitations, it should be useful for presenting on-screen instructions in experiments. While you are welcome to modify this file to extend its functionality, I hope you consider sharing any such modifications with the VisionEgg community. Eamon Caddigan,\nUniversity of Illinois\n15 November 2007""" wt = WrappedText(text=message, position=(50,screen.size[1]-50), size=(screen.size[0]-100, screen.size[1]-100)) viewport = VisionEgg.Core.Viewport(screen=screen, stimuli=[wt]) # Frame-based presentation duration makes it easier to use pdb p = VisionEgg.FlowControl.Presentation(viewports=[viewport], go_duration=(VisionEgg.config.VISIONEGG_MONITOR_REFRESH_HZ*30,'frames')) p.go() screen.close() # Called explicitly to behave better in interactive shells
def run(self): p = pyaudio.PyAudio() time_stamped = False stream = p.open( format=self.format, channels=self.channels, rate=self.rate, input=self.input, frames_per_buffer=self.frames_per_buffer, ) print "* recording" all = [] start_time = VisionEgg.time_func() i = 0 while (i <= self.rate / self.chunk * self.time) and ( (not time_stamped) or (VisionEgg.time_func() < end_time + 2) ): # for i in range(0, self.rate / self.chunk * self.time): data = stream.read(self.chunk) samps = numpy.fromstring(data, dtype=numpy.int16) all.append(data) loud = loudness(samps) # print str(i) + " " + str(loud) if (not time_stamped) and loud > self.sound_threshold: end_time = VisionEgg.time_func() self.q.put(start_time) self.q.put(end_time) # self.f.write("%s\t%f\t%f\t%f\t" % (self.item, end_time-start_time, start_time, end_time)) # self.f.flush() print "Crossed Threshold!" time_stamped = True i = i + 1 if not time_stamped: self.q.put(start_time) self.q.put(10000000) # self.f.write("%s\t%f\t%f\t%f\t" % (self.item, 10000000, start_time, 10000000.0)) print "* done recording" stream.close() p.terminate() # write data to WAVE file data = "".join(all) wf = wave.open(self.file_name, "wb") wf.setnchannels(self.channels) wf.setsampwidth(p.get_sample_size(self.format)) wf.setframerate(self.rate) wf.writeframes(data) wf.close()
def _draw(self): p = self.parameters side = p.side height = side * numpy.sqrt(3) / 2. center = VisionEgg._get_center(p.position, p.anchor, (side, height)) position = numpy.array(center) hh = height / 2 ll = position - (hh, hh) lr = position - (-hh, hh) u = position + (0., hh) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glDisable(gl.GL_BLEND) gl.glColor(p.color) gl.glBegin(gl.GL_TRIANGLES) self._draw_vertices(ll, lr, u) gl.glEnd() gl.glColor(p.color_edge) if p.anti_aliasing: gl.glEnable(gl.GL_LINE_SMOOTH) gl.glLineWidth(p.width) gl.glBegin(gl.GL_LINE_STRIP) self._draw_vertices(ll, lr, u, ll) gl.glEnd() gl.glDisable(gl.GL_LINE_SMOOTH)
def run(self, ID=0): self.ID = ID self.sound_fired = 0 super(RMLTrial, self).run() while not self.stopped: self.run_time = VisionEgg.time_func() - self.start_time if self.phase == 0: self.pre_experiment_time = VisionEgg.time_func() # this trial phase is ended with a enter press or TR pulse if self.ID != 0: self.phase_forward() if self.phase == 1: self.pre_stimulus_time = VisionEgg.time_func() if (self.pre_stimulus_time - self.pre_experiment_time) > self.phase_durations[1]: self.phase_forward() if self.phase == 2: self.stimulus_time = VisionEgg.time_func() if (self.stimulus_time - self.pre_stimulus_time) > self.phase_durations[2]: self.phase_forward() if self.phase == 3: self.tone_time = VisionEgg.time_func() if self.sound_fired == 0: if self.tracker != None: self.tracker.sendMessage( "trial " + str(self.ID) + " sound " + str(self.parameters["sound"]) + " at " + str(self.tone_time) ) if self.parameters["sound"] == 0: self.session.play_np_sound(self.noise_tone_array) elif self.parameters["sound"] == 1: self.session.play_sound(sound_index="reward") self.sound_fired = 1 # this trial phase is timed if (self.tone_time - self.stimulus_time) > self.phase_durations[3]: self.stopped = True # events and draw self.event() self.draw() self.stop()
def __init__(self, **kw): VisionEgg.Core.Stimulus.__init__(self,**kw) # store positions normalized around 0 so that re-sizing is ok num_dots = self.constant_parameters.num_dots # shorthand self.centers = np.random.standard_normal((3,num_dots)) self.colors = np.ones((num_dots,4)) self.colors[:self.constant_parameters.num_dark,:3] = 0 self.last_time_sec = VisionEgg.time_func() self.start_times_sec = None # setup variable, assign later
def run(self, ID = 0): self.ID = ID super(DetectTrial, self).run() while not self.stopped: self.run_time = VisionEgg.time_func() - self.start_time if self.phase == 0: self.prestimulation_time = VisionEgg.time_func() # this trial phase is ended with a space press on the first trial of a run, but timed on all other trials of a run. if ( self.prestimulation_time - self.start_time ) > self.phase_durations[1] and self.ID != 0: self.phase_forward() elif self.phase == 1: self.adaptation_time = VisionEgg.time_func() # this trial phase is timed if ( self.adaptation_time - self.prestimulation_time ) > self.phase_durations[1]: self.phase_forward() elif self.phase == 2: # this trial phase is timed self.post_adaptation_time = VisionEgg.time_func() if ( self.post_adaptation_time - self.adaptation_time ) > self.phase_durations[2]: self.session.play_sound( sound_index = 1 ) self.phase_forward() elif self.phase == 3: # this trial phase is timed self.first_test_time = VisionEgg.time_func() if ( self.first_test_time - self.post_adaptation_time ) > self.phase_durations[3]: self.phase_forward() elif self.phase == 4: # this trial phase is timed self.inter_test_time = VisionEgg.time_func() if ( self.inter_test_time - self.first_test_time ) > self.phase_durations[4]: self.session.play_sound( sound_index = 1 ) self.phase_forward() elif self.phase == 5: # this trial phase is timed self.last_test_time = VisionEgg.time_func() if ( self.last_test_time - self.inter_test_time ) > self.phase_durations[5]: self.phase_forward() elif self.phase == 6: self.answer_time = VisionEgg.time_func() - self.last_test_time elif self.phase == 7: self.post_answer_time = VisionEgg.time_func() - self.answer_time # events and draw self.event() self.draw() # we have stopped. self.stop()
def __init__(self, **kw): VisionEgg.Core.Stimulus.__init__(self,**kw) # store positions normalized between 0 and 1 so that re-sizing is ok num_dots = self.constant_parameters.num_dots # shorthand self.x_positions = RandomArray.uniform(0.0,1.0,(num_dots,)) self.y_positions = RandomArray.uniform(0.0,1.0,(num_dots,)) self.random_directions_radians = RandomArray.uniform(0.0,2*math.pi,(num_dots,)) self.last_time_sec = VisionEgg.time_func() self.start_times_sec = None # setup variable, assign later self._gave_alpha_warning = 0
def __init__(self): """We break up initialization a bit as we need to go back and forth with some information. In this case, we need screen size before specifying the stimuli""" VisionEgg.start_default_logging() VisionEgg.watch_exceptions() # get screen size for setting fullscreen resolution # comment this block out if you don't want to use full-screen. screen = pygame.display.set_mode((0, 0)) # this opens up a pygame window WIDTH, HEIGHT = screen.get_size() pygame.quit() # close this pygame window, or else it interferes w/ VE VisionEgg.config.VISIONEGG_SCREEN_W = WIDTH VisionEgg.config.VISIONEGG_SCREEN_H = HEIGHT self.screen = get_default_screen() self.keys = [] self.presses = [] self.releases = []
def __init__(self): """We break up initialization a bit as we need to go back and forth with some information. In this case, we need screen size before specifying the stimuli""" # pasted in from where it used to be at the beginning of the script # used to be outside of any methods... VisionEgg.start_default_logging() VisionEgg.watch_exceptions() # get screen size for setting fullscreen resolution # comment this block out if you don't want to use full-screen. screen = pygame.display.set_mode((0,0)) WIDTH, HEIGHT = screen.get_size() pygame.quit() VisionEgg.config.VISIONEGG_SCREEN_W = WIDTH VisionEgg.config.VISIONEGG_SCREEN_H = HEIGHT self.screen = get_default_screen() self.keys = [] self.presses = [] self.releases = []
def go(self,duration=None,prestim=None,poststim=None,RSTART=False): # pre stimulation go if prestim is not None: if RSTART: remote_start_controller = RemoteStartController() self.add_controller(None,None,remote_start_controller) self.parameters.go_duration = (prestim, 'seconds') super(FrameSweep, self).go() if RSTART: self.remove_controller(None,None,remote_start_controller) # stimulation go if duration is not None: self.parameters.go_duration = duration else: self.parameters.go_duration = ('forever','') self.add_controllers() # use VisionEgg timing function which handles platform specific problems sweep_begin = VisionEgg.true_time_func() super(FrameSweep, self).go() sweep_end = VisionEgg.true_time_func() sweep_duration = sweep_end - sweep_begin # remove all stimuli so that post presentation will show nothing. self.remove_stimuli() # the RemoveViewportController should be moved, otherwise post go will quit directly. self.remove_controller(None,None,None) # post stimulation go if poststim is not None: if RSTART: self.add_controller(None,None,RemoteStopController()) self.parameters.go_duration = (poststim, 'seconds') super(FrameSweep, self).go() if self.interrupted: self.logger.warning('Stimulation was interrupted before completion.') else: self.logger.info('Stimulation completes successfully.') self.logger.info('Actual stimulus duration: %s' %str(TimeFormat(sweep_duration)))
def event(self): for event in pygame.event.get(): super(RMLTrial, self).key_event(event) if event.type == KEYDOWN: if event.key == pygame.locals.K_ESCAPE: self.events.append([-99, VisionEgg.time_func() - self.start_time]) self.stopped = True self.session.stopped = True # it handles both numeric and lettering modes elif ( event.key == pygame.locals.K_RETURN or event.key == pygame.locals.K_t ): # press enter (or TR pulse) to start experiment self.events.append([0, VisionEgg.time_func() - self.start_time]) if self.phase == 0: self.phase_forward() elif event.key == pygame.locals.K_SPACE: if self.phase != 0: # only register space bar presses after experiment has started self.events.append( [1, VisionEgg.time_func() - self.start_time] ) # register space bar presses with '1' and save timestamp self.session.reversal_keypresses += ( 1 ) # save self.reversal_keypresses to be able to print it in the terminal later
def draw(self): # XXX This method is not speed-optimized. I just wrote it to # get the job done. (Nonetheless, it seems faster than the C # version commented out above.) p = self.parameters # shorthand now_sec = VisionEgg.time_func() if self.start_times_sec is not None: # compute extinct dots and generate new positions replace_indices = Numeric.nonzero( Numeric.greater( now_sec - self.start_times_sec, p.dot_lifespan_sec) ) Numeric.put( self.start_times_sec, replace_indices, now_sec ) new_centers = np.random.standard_normal((3,len(replace_indices))) for i in range(3): Numeric.put( self.centers[i,:], replace_indices, new_centers[i,:] ) else: # initialize dot extinction values to random (uniform) distribution self.start_times_sec = RandomArray.uniform( now_sec - p.dot_lifespan_sec, now_sec, (self.constant_parameters.num_dots,)) time_delta_sec = now_sec - self.last_time_sec self.last_time_sec = now_sec # reset for next loop self.centers = self.centers + np.array(p.signal_vec)[:,np.newaxis]*time_delta_sec xyz = self.centers*p.start_position_variance + np.array(p.start_position_mean)[:,np.newaxis] xs = xyz[0,:] ys = xyz[1,:] zs = xyz[2,:] if p.on: gl.glEnable( gl.GL_POINT_SMOOTH ) # allow max_alpha value to control blending gl.glEnable( gl.GL_BLEND ) gl.glBlendFunc( gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA ) gl.glPointSize(p.dot_size) # Clear the modeview matrix gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glDisable(gl.GL_TEXTURE_2D) draw_dots(xs,ys,zs,self.colors) gl.glDisable( gl.GL_POINT_SMOOTH ) # turn off gl.glPopMatrix()
def __init__(self, **kw): VisionEgg.Core.Stimulus.__init__(self,**kw) # store positions normalized between 0 and 1 so that re-sizing is ok num_dots = self.constant_parameters.num_dots # shorthand self.x_positions = RandomArray.uniform(0.0,1.0,(num_dots,)) self.y_positions = RandomArray.uniform(0.0,1.0,(num_dots,)) if self.parameters.mode == "wind": self.random_directions_radians = RandomArray.uniform(0.0,2*math.pi,(num_dots,)) self.velocities = RandomArray.uniform(self.parameters.velocity_max-1, self.parameters.velocity_max,(num_dots,)) elif self.parameters.mode == "Gaussian": self.random_directions_radians = numpy.random.normal(self.parameters.signal_direction_deg/180.0*math.pi, self.parameters.signal_fraction,(num_dots,)) self.velocities = RandomArray.uniform(self.parameters.velocity_min, self.parameters.velocity_max,(num_dots,)) self.last_time_sec = VisionEgg.time_func() self.start_times_sec = None # setup variable, assign later self._gave_alpha_warning = 0
def _draw(self): p = self.parameters center = VisionEgg._get_center(p.position, p.anchor, (p.radius, p.radius)) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glDisable(gl.GL_BLEND) gl.glColor(p.color) start, end = p.start, p.end if end < start: start -= 360. start, end = map(numpy.deg2rad, (start, end)) frac = (end - start) / (2 * numpy.pi) num_triangles = float(p.num_triangles) * frac angles = numpy.linspace(start, end, num_triangles) verts = numpy.zeros((num_triangles, 2)) verts[:,0] = center[0] + p.radius * numpy.cos(angles) verts[:,1] = center[1] + p.radius * numpy.sin(angles) if p.disk: gl.glBegin(gl.GL_TRIANGLE_FAN) gl.glVertex(center) self._draw_vertices(*verts) gl.glEnd() if p.anti_aliasing: gl.glEnable(gl.GL_LINE_SMOOTH) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) # Draw a second polygon in line mode, so the edges are anti-aliased gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) gl.glBegin(gl.GL_TRIANGLE_FAN) gl.glVertex(center) self._draw_vertices(*verts) gl.glEnd() gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) gl.glDisable(gl.GL_LINE_SMOOTH) if p.circle: if p.anti_aliasing: gl.glEnable(gl.GL_LINE_SMOOTH) gl.glColor(p.color_edge) gl.glLineWidth(p.circle_width) gl.glBegin(gl.GL_LINES) for i in range(verts.shape[0]-1): self._draw_vertices(verts[i], verts[i+1]) gl.glEnd() gl.glDisable(gl.GL_LINE_SMOOTH)
def draw(self): p = self.parameters # shorthand if p.on: if p.mask: gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB) if p.depth_test: gl.glEnable(gl.GL_DEPTH_TEST) else: gl.glDisable(gl.GL_DEPTH_TEST) if p.polygon_offset_enabled: gl.glEnable(gl.GL_POLYGON_OFFSET_EXT) gl.glPolygonOffset(p.polygon_offset_factor, p.polygon_offset_units) gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id) gl.glEnable(gl.GL_TEXTURE_1D) gl.glDisable(gl.GL_TEXTURE_2D) if p.bit_depth != self.cached_bit_depth: self.calculate_bit_depth_dependencies() # allow max_alpha value to control blending gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) if p.color2: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND) gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2) ## alpha is ignored because the texture base internal format is luminance else: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) if p.t0_time_sec_absolute is None and not p.ignore_time: p.t0_time_sec_absolute = VisionEgg.time_func() w = p.size[0] inc = w / float(p.num_samples) if p.ignore_time: phase = p.phase_at_t0 else: t_var = VisionEgg.time_func() - p.t0_time_sec_absolute phase = t_var * p.temporal_freq_hz * -360.0 + p.phase_at_t0 if p.recalculate_phase_tolerance is None or abs(self._last_phase - phase) > p.recalculate_phase_tolerance: self._last_phase = phase # we're re-drawing the phase at this angle floating_point_sin = ( numpy.sin( 2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float) + (phase / 180.0 * math.pi) ) * 0.5 * p.contrast + p.pedestal ) floating_point_sin = numpy.clip( floating_point_sin, 0.0, 1.0 ) # allow square wave generation if contrast > 1 texel_data = (floating_point_sin * self.max_int_val).astype(self.numpy_dtype).tostring() gl.glTexSubImage1D( gl.GL_TEXTURE_1D, # target 0, # level 0, # x offset p.num_samples, # width self.format, # format of new texel data self.gl_type, # type of new texel data texel_data, ) # new texel data # in the case of only color1, # the texel data multiplies color1 to produce a color # with color2, # the texel data linearly interpolates between color1 and color2 gl.glColor4f(p.color1[0], p.color1[1], p.color1[2], p.max_alpha) if p.mask: p.mask.draw_masked_quad_3d( 0.0, 1.0, 0.0, 1.0, p.lowerleft, p.lowerright, p.upperright, p.upperleft # for texture coordinates ) else: # draw unmasked quad gl.glBegin(gl.GL_QUADS) gl.glTexCoord2f(0.0, 0.0) gl.glVertex(*p.lowerleft) gl.glTexCoord2f(1.0, 0.0) gl.glVertex(*p.lowerright) gl.glTexCoord2f(1.0, 1.0) gl.glVertex(*p.upperright) gl.glTexCoord2f(0.0, 1.0) gl.glVertex(*p.upperleft) gl.glEnd() # GL_QUADS gl.glDisable(gl.GL_TEXTURE_1D) if p.polygon_offset_enabled: gl.glDisable(gl.GL_POLYGON_OFFSET_EXT)
def draw(self): p = self.parameters # shorthand if p.center is not None: p.anchor = 'center' p.position = p.center[0], p.center[ 1] # copy values (don't copy ref to tuple) if p.on: # calculate center center = VisionEgg._get_center(p.position, p.anchor, p.size) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glTranslate(center[0], center[1], 0.0) gl.glRotate(p.orientation, 0.0, 0.0, 1.0) if len(p.bgcolor) == 3: gl.glColor3f(*p.bgcolor) elif len(p.bgcolor) == 4: gl.glColor4f(*p.bgcolor) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) w = p.size[0] / 2.0 #grid half-size h = p.size[1] / 2.0 m = p.size[0] / p.grid[0] #cell size n = p.size[1] / p.grid[1] i = range(p.grid[0]) #grid index j = range(p.grid[1]) #draw colorful cell # vertices_list = [((-w+column*m, h-(row+1)*n, 0.0),(-w+column*m, h-row*n, 0.0),\ # (-w+(column+1)*m, h-row*n, 0.0),(-w+(column+1)*m, h-row*n, 0.0))\ # for column in j for row in i] vertices_list = [((-w+column*m, h-(row+1)*n, 0.0),(-w+column*m, h-row*n, 0.0),\ (-w+(column+1)*m, h-row*n, 0.0),(-w+(column+1)*m, h-(row+1)*n, 0.0))\ for column in j for row in i] colors_list = [ colormap(p.colorindex[row, column], color=p.cellcolor) * 4 for column in j for row in i ] #flattening the vertices and colors vertices_flat = [ num for tuple in vertices_list for vertex in tuple for num in vertex ] colors_flat = [num for tuple in colors_list for num in tuple] vertices = np.array(vertices_flat) colors = np.array(colors_flat) vertices.shape = (-1, 3) colors.shape = (-1, 3) gl.glVertexPointerd(vertices) gl.glColorPointerd(colors) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glEnableClientState(gl.GL_COLOR_ARRAY) gl.glDisable(gl.GL_LIGHTING) gl.glDrawArrays(gl.GL_QUADS, 0, p.grid[0] * p.grid[1] * 4) #draw grid lines if p.drawline: if len(p.linecolor) == 3: gl.glColor3f(*p.linecolor) elif len(p.linecolor) == 4: gl.glColor4f(*p.linecolor) row_list = [((-w, h - i * n), (w, h - i * n)) for i in range(p.grid[1] + 1)] col_list = [((-w + i * m, h), (-w + i * m, -h)) for i in range(p.grid[0] + 1)] ver_row_flat = [ num for tuple in row_list for vertex in tuple for num in vertex ] ver_col_flat = [ num for tuple in col_list for vertex in tuple for num in vertex ] vertices_row = np.array(ver_row_flat) vertices_col = np.array(ver_col_flat) vertices_row.shape = (-1, 2) vertices_col.shape = (-1, 2) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glDisableClientState(gl.GL_COLOR_ARRAY) gl.glVertexPointerd(vertices_row) gl.glDrawArrays(gl.GL_LINES, 0, (p.grid[1] + 1) * 2) gl.glVertexPointerd(vertices_col) gl.glDrawArrays(gl.GL_LINES, 0, (p.grid[0] + 1) * 2) # gl.glBegin(gl.GL_LINES); # for i in range(p.grid[1] + 1): # gl.glVertex2f(-w, h - i * n) # gl.glVertex2f(w, h - i * n) # for i in range(p.grid[0] + 1): # gl.glVertex2f(-w + i * m, h) # gl.glVertex2f(-w + i * m, -h) # gl.glEnd(); gl.glPopMatrix()
'Greek': u"Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα.", 'Thai': u"ฉันกินกระจกได้ แต่มันไม่ทำให้ฉันเจ็บ", 'Chinese': u"我能吞下玻璃而不伤身体", 'Chinese (Traditional)': u"我能吞下玻璃而不傷身體", 'Japanese': u"私はガラスを食べられます。それは私を傷つけません。", 'Korean': u"나는 유리를 먹을 수 있어요. 그래도 아프지 않아요", 'Arabic': u"أنا قادر على أكل الزجاج و هذا لا يؤلمني.", 'Hebrew': u"אני יכול לאכול זכוכית וזה לא מזיק לי.", 'Hindi': u"मैं काँच खा सकता हूँ और मुझे उससे कोई चोट नहीं पहुंचती.", } # collect above data into 2 sequences: language, phrase = zip(*[item for item in phrases.iteritems()]) import VisionEgg VisionEgg.start_default_logging(); VisionEgg.watch_exceptions() from VisionEgg.Core import * from VisionEgg.FlowControl import Presentation import VisionEgg.Text import pygame from pygame.locals import * screen = get_default_screen() screen.parameters.bgcolor = (0.0,0.0,0.2) # background blue (RGB) text=VisionEgg.Text.PangoText( color=(1.0,1.0,1.0), # alpha is ignored (set with max_alpha_param) position=(0,screen.size[1]/2), size = (screen.size[0],max(screen.size[0]/10,10)), anchor='left')
def draw(self): p = self.parameters # shorthand if p.on: # calculate center center = VisionEgg._get_center(p.position, p.anchor, p.size) if p.mask: gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB) gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id) gl.glEnable(gl.GL_TEXTURE_1D) gl.glDisable(gl.GL_TEXTURE_2D) if p.bit_depth != self.cached_bit_depth: self.calculate_bit_depth_dependencies() # Clear the modeview matrix gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() # Rotate about the center of the texture gl.glTranslate(center[0], center[1], 0) gl.glRotate(p.orientation, 0, 0, 1) if p.depth is None: gl.glDisable(gl.GL_DEPTH_TEST) depth = 0.0 else: gl.glEnable(gl.GL_DEPTH_TEST) depth = p.depth # allow max_alpha value to control blending gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) if p.color2: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND) gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2) ## alpha is ignored because the texture base internal format is luminance else: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) if p.t0_time_sec_absolute is None and not p.ignore_time: p.t0_time_sec_absolute = VisionEgg.time_func() w = p.size[0] inc = w / float(p.num_samples) if p.ignore_time: phase = p.phase_at_t0 else: t_var = VisionEgg.time_func() - p.t0_time_sec_absolute phase = t_var * p.temporal_freq_hz * -360.0 + p.phase_at_t0 if p.recalculate_phase_tolerance is None or abs(self._last_phase - phase) > p.recalculate_phase_tolerance: self._last_phase = phase # we're re-drawing the phase at this angle floating_point_sin = ( numpy.sin( 2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float) + (phase / 180.0 * math.pi) ) * 0.5 * p.contrast + p.pedestal ) floating_point_sin = numpy.clip( floating_point_sin, 0.0, 1.0 ) # allow square wave generation if contrast > 1 texel_data = (floating_point_sin * self.max_int_val).astype(self.numpy_dtype) # PyOpenGL 2.0.1.09 has a bug, so use our own wrapper _vegl.veglTexSubImage1D( gl.GL_TEXTURE_1D, # target 0, # level 0, # x offset p.num_samples, # width self.format, # format of new texel data self.gl_type, # type of new texel data texel_data, ) # new texel data if 0: compare_array = numpy.empty(texel_data.shape, dtype=texel_data.dtype) pixels = _vegl.veglGetTexImage( gl.GL_TEXTURE_1D, # target 0, # level self.format, # format self.gl_type, # type compare_array, ) assert numpy.allclose(compare_array, texel_data) h_w = p.size[0] / 2.0 h_h = p.size[1] / 2.0 l = -h_w r = h_w b = -h_h t = h_h # in the case of only color1, # the texel data multiplies color1 to produce a color # with color2, # the texel data linearly interpolates between color1 and color2 gl.glColor4f(p.color1[0], p.color1[1], p.color1[2], p.max_alpha) if p.mask: p.mask.draw_masked_quad( 0.0, 1.0, 0.0, 1.0, # l,r,b,t for texture coordinates l, r, b, t, # l,r,b,t in eye coordinates depth, ) # also in eye coordinates else: # draw unmasked quad gl.glBegin(gl.GL_QUADS) gl.glTexCoord2f(0.0, 0.0) gl.glVertex3f(l, b, depth) gl.glTexCoord2f(1.0, 0.0) gl.glVertex3f(r, b, depth) gl.glTexCoord2f(1.0, 1.0) gl.glVertex3f(r, t, depth) gl.glTexCoord2f(0.0, 1.0) gl.glVertex3f(l, t, depth) gl.glEnd() # GL_QUADS gl.glDisable(gl.GL_TEXTURE_1D) gl.glPopMatrix()
class Triangle(DisplayListStimulus): """ An equilateral triangle. Parameters ========== anti_aliasing -- (Boolean) Default: True color -- color (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (1.0, 1.0, 1.0) on -- draw? (Boolean) Default: True position -- position in eye coordinates (AnyOf(Sequence2 of Real or Sequence3 of Real or Sequence4 of Real)) Default: (320.0, 240.0) side -- side length """ parameters_and_defaults = VisionEgg.ParameterDefinition({ 'anchor': ('center', ve_types.String, 'how position parameter is used'), 'on': (True, ve_types.Boolean, 'draw?'), 'color': ((1.0, 1.0, 1.0), ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), 'color'), 'color_edge': ((1.0, 1.0, 1.0), ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), 'color for the edge'), 'anti_aliasing': (True, ve_types.Boolean), 'position': ( (320.0, 240.0), # in eye coordinates ve_types.AnyOf(ve_types.Sequence2(ve_types.Real), ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), 'position in eye coordinates'), 'side': (10., ve_types.Real, 'side length'), 'width': (1., ve_types.Real, 'line width'), }) __slots__ = VisionEgg.Core.Stimulus.__slots__ + ('_gave_alpha_warning', ) def __init__(self, **kw): DisplayListStimulus.__init__(self, **kw) self._gave_alpha_warning = 0 def _draw(self): p = self.parameters side = p.side height = side * numpy.sqrt(3) / 2. center = VisionEgg._get_center(p.position, p.anchor, (side, height)) position = numpy.array(center) hh = height / 2 ll = position - (hh, hh) lr = position - (-hh, hh) u = position + (0., hh) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glDisable(gl.GL_BLEND) gl.glColor(p.color) gl.glBegin(gl.GL_TRIANGLES) self._draw_vertices(ll, lr, u) gl.glEnd() gl.glColor(p.color_edge) if p.anti_aliasing: gl.glEnable(gl.GL_LINE_SMOOTH) gl.glLineWidth(p.width) gl.glBegin(gl.GL_LINE_STRIP) self._draw_vertices(ll, lr, u, ll) gl.glEnd() gl.glDisable(gl.GL_LINE_SMOOTH)
def run(self, ID = 0): self.ID = ID super(DetectTrial, self).run() sound_played = False while not self.stopped: self.run_time = VisionEgg.time_func() - self.start_time if self.phase == 0: self.prestimulation_time = VisionEgg.time_func() # this trial phase is ended with a space press on the first trial of a run, but timed on all other trials of a run. self.start_time = VisionEgg.time_func() elif self.phase == 1: # first delay self.delay_1_time = VisionEgg.time_func() # this trial phase is timed if ( self.delay_1_time - self.prestimulation_time ) > self.phase_durations[1] - 0.1 and sound_played == False: self.session.play_sound( sound_index = 1 ) sound_played = True if ( self.delay_1_time - self.prestimulation_time ) > self.phase_durations[1]: self.phase_forward() elif self.phase == 2: # stimulus presentation # this trial phase is timed self.test_time = VisionEgg.time_func() if ( self.test_time - self.delay_1_time ) > self.phase_durations[2]: self.phase_forward() elif self.phase == 3: # second delay # this trial phase is timed self.delay_2_time = VisionEgg.time_func() if ( self.delay_2_time - self.test_time ) > self.phase_durations[3]: self.phase_forward() elif self.phase == 4: # confidence self.confidence_time = VisionEgg.time_func() elif self.phase == 5: # third delay self.delay_3_time = VisionEgg.time_func() if ( self.delay_3_time - self.confidence_time ) > self.phase_durations[5]: self.feedback_given = False self.phase_forward() elif self.phase == 6: # feedback self.feedback_time = VisionEgg.time_func() if self.feedback_given == False and ( self.feedback_time - self.delay_3_time ) > 0.1: if self.version == 1: if self.parameters['correct'] == 1: self.session.play_sound( sound_index = 2 ) elif self.parameters['correct'] == 0: self.session.play_sound( sound_index = 0 ) if self.version == 2: if self.parameters['correct'] == 1: self.session.play_sound( sound_index = 0 ) elif self.parameters['correct'] == 0: self.session.play_sound( sound_index = 2 ) elif self.parameters['correct'] == -1: self.session.play_sound( sound_index = 3 ) self.feedback_given = True if ( self.feedback_time - self.delay_3_time ) > self.phase_durations[6]: self.phase_forward() elif self.phase == 7: # fourth delay self.delay_4_time = VisionEgg.time_func() if ( self.delay_4_time - self.feedback_time ) > self.phase_durations[7]: self.stopped = True # events and draw self.event() self.draw() # we have stopped. self.stop()
#!/usr/bin/env python #(C) Samir Menon, 27, May, 2011 # This is a sample script that loads .par stimulus presentation files and runs them. Modify and use. # It uses VisionEgg """Display text strings.""" #Import the generic VisionEgg classes import VisionEgg #VisionEgg.start_default_logging(); VisionEgg.watch_exceptions(); from VisionEgg.Core import get_default_screen, Viewport from VisionEgg.FlowControl import Presentation from VisionEgg.Text import Text #Import the custom rendering classes from CVEggStimText import * from COptSeqLoader import * #Set up an OpenGL screen screen = get_default_screen() screen.parameters.bgcolor = (0.0,0.0,0.0) # background black (RGB) #************************** #Initialize this experiment #************************** #Load the data and set the parameters data = COptSeqLoader(); data.load("stim.par");
def event(self): for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == pygame.locals.K_ESCAPE: self.events.append([-99,VisionEgg.time_func()-self.start_time]) self.parameters.update({'correct': 0}) self.stopped = True self.session.stopped = True # it handles both numeric and lettering modes elif event.key == pygame.locals.K_SPACE: self.events.append([0,VisionEgg.time_func()-self.start_time]) if self.phase in (0, 4): self.phase_forward() # else: # self.stopped = True elif event.key == pygame.locals.K_LEFT: self.events.append([1,VisionEgg.time_func()-self.start_time]) if self.version == 1: if self.phase == 2: self.parameters.update({'answer':1}) if self.parameters['target_present_in_stimulus'] == 0: self.parameters['correct']= 1 else: self.parameters['correct']= 0 if self.phase == 2: self.phase_forward() if self.version == 2: if self.phase == 2: self.parameters.update({'answer':1}) if self.parameters['target_present_in_stimulus'] == 1: self.parameters['correct']= 1 else: self.parameters['correct']= 0 if self.phase == 2: self.phase_forward() if self.phase == 0: self.nr_buttons_pressed = self.nr_buttons_pressed + 1 self.tracker.sendCommand('record_status_message "Trial %d, Buttonpress %d"'%(self.ID, self.nr_buttons_pressed)) elif event.key == pygame.locals.K_RIGHT: self.events.append([-1,VisionEgg.time_func()-self.start_time]) if self.version == 1: if self.phase == 2: self.parameters.update({'answer':-1}) if self.parameters['target_present_in_stimulus'] == 1: self.parameters['correct']= 1 else: self.parameters['correct']= 0 if self.phase == 2: self.phase_forward() if self.version == 2: if self.phase == 2: self.parameters.update({'answer':-1}) if self.parameters['target_present_in_stimulus'] == 0: self.parameters['correct']= 1 else: self.parameters['correct']= 0 if self.phase == 2: self.phase_forward() if self.phase == 0: self.nr_buttons_pressed = self.nr_buttons_pressed + 1 self.tracker.sendCommand('record_status_message "Trial %d, Buttonpress %d"'%(self.ID, self.nr_buttons_pressed)) if event.key == pygame.locals.K_c: if self.ID % 15 == 0: self.session.tracker_setup(auto_trigger_calibration = True, calibration_type = 'HV5', sample_rate = 1000) elif event.key == pygame.locals.K_a: if self.phase > 3: self.parameters['confidence'] = 0 if self.phase == 4: self.phase_forward() elif event.key == pygame.locals.K_s: if self.phase > 3: self.parameters['confidence'] = 1 if self.phase == 4: self.phase_forward() elif event.key == pygame.locals.K_d: if self.phase > 3: self.parameters['confidence'] = 2 if self.phase == 4: self.phase_forward() elif event.key == pygame.locals.K_f: if self.phase > 3: self.parameters['confidence'] = 3 if self.phase == 4: self.phase_forward() super(DetectTrial, self).key_event( event )
def draw(self): p = self.parameters # shorthand if p.on: if p.mask: gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB) if p.depth_test: gl.glEnable(gl.GL_DEPTH_TEST) else: gl.glDisable(gl.GL_DEPTH_TEST) if p.polygon_offset_enabled: gl.glEnable(gl.GL_POLYGON_OFFSET_EXT) gl.glPolygonOffset(p.polygon_offset_factor, p.polygon_offset_units) gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id) gl.glEnable(gl.GL_TEXTURE_1D) gl.glDisable(gl.GL_TEXTURE_2D) if p.bit_depth != self.cached_bit_depth: self.calculate_bit_depth_dependencies() # allow max_alpha value to control blending gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) if p.color2: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND) gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2) ## alpha is ignored because the texture base internal format is luminance else: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) if p.t0_time_sec_absolute is None and not p.ignore_time: p.t0_time_sec_absolute = VisionEgg.time_func() w = p.size[0] inc = w / float(p.num_samples) if p.ignore_time: phase = p.phase_at_t0 else: t_var = VisionEgg.time_func() - p.t0_time_sec_absolute phase = t_var * p.temporal_freq_hz * -360.0 + p.phase_at_t0 if p.recalculate_phase_tolerance is None or abs( self._last_phase - phase) > p.recalculate_phase_tolerance: self._last_phase = phase # we're re-drawing the phase at this angle floating_point_sin = numpy.sin( 2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float) + (phase / 180.0 * math.pi)) * 0.5 * p.contrast + p.pedestal floating_point_sin = numpy.clip( floating_point_sin, 0.0, 1.0) # allow square wave generation if contrast > 1 texel_data = (floating_point_sin * self.max_int_val).astype( self.numpy_dtype).tostring() gl.glTexSubImage1D( gl.GL_TEXTURE_1D, # target 0, # level 0, # x offset p.num_samples, # width self.format, # format of new texel data self.gl_type, # type of new texel data texel_data) # new texel data # in the case of only color1, # the texel data multiplies color1 to produce a color # with color2, # the texel data linearly interpolates between color1 and color2 gl.glColor4f(p.color1[0], p.color1[1], p.color1[2], p.max_alpha) if p.mask: p.mask.draw_masked_quad_3d( 0.0, 1.0, 0.0, 1.0, # for texture coordinates p.lowerleft, p.lowerright, p.upperright, p.upperleft) else: # draw unmasked quad gl.glBegin(gl.GL_QUADS) gl.glTexCoord2f(0.0, 0.0) gl.glVertex(*p.lowerleft) gl.glTexCoord2f(1.0, 0.0) gl.glVertex(*p.lowerright) gl.glTexCoord2f(1.0, 1.0) gl.glVertex(*p.upperright) gl.glTexCoord2f(0.0, 1.0) gl.glVertex(*p.upperleft) gl.glEnd() # GL_QUADS gl.glDisable(gl.GL_TEXTURE_1D) if p.polygon_offset_enabled: gl.glDisable(gl.GL_POLYGON_OFFSET_EXT)
def getState(t): global ISI, next_stim_time, direction, last_direction, arrow_scale, score global first_loop, start_time, StimCount, stimVis, fbVis, stimText global score_factor, arrowColor, leftText, rightText global left_strings, right_strings, stimulus_strings, show_array global currentTime, currentShow, currentSign, currentTR # CC added for TCPIP and detrends global tcp_dist, dist_detrend, dist_array, time_array, dist global startDetrend, detrendLag global ALPHA_MAX, ALPHA_SCALE global lumina_dev currentTime = t if (first_loop == 1) and (p.parameters.trigger_go_if_armed): first_loop = 0 start_time = VisionEgg.time_func() if TCPIP: tcp_listener.buffer="" # reset buffer if t > next_stim_time: StimCount = StimCount + 1 currentShow = int(np.abs(show_array[StimCount])) currentSign = int(np.sign(show_array[StimCount])) stimText = stimulus_strings[StimCount] leftText = left_strings[StimCount] rightText = right_strings[StimCount] next_stim_time = next_stim_time + ISI if StimCount > detrendLag: startDetrend=True #### # note: When run with SVR testing, the input values #### # will range from (-inf,inf), most likely (-5,5) if TCPIP: tcp_buffer=str(tcp_listener.buffer) #print "%s (%s)" %('tcp_data', tcp_buffer) tcp_data=tcp_buffer.replace('\000', ''); # remove null byte #print "%s (%s) (%s)" %('tcp_data', tcp_data, tcp_buffer) if tcp_data != '\000' and tcp_data != "" and \ "nan" not in tcp_data.lower(): vals=tcp_data.split(",") if len(vals) > 1: tcp_dist=float(vals[1]) else: tcp_dist=float(tcp_data) tcp_listener.buffer="" # reset buffer dist_array = dist_array + [tcp_dist] time_array = time_array + [t] if DETREND == 1: if startDetrend: dist_detrend = detrendDist(time_array, dist_array) else: dist_detrend = tcp_dist arrow_scale=dist_detrend else: arrow_scale=tcp_dist if currentShow == 9999 or FEEDBACK == 0: fbVis = 0 score = 90.0 arrowColor = 0 else: fbVis = 1 arrowColor = 1 # increment the score score = score - currentSign*arrow_scale*score_factor if score < 0: score = 0 elif score > 180: score = 180 log.write("%5.3f; STIM; %s; %s; %s; %d; %d; %5.3f; %5.3f; %5.3f\n" \ %(t, leftText, rightText, stimText, currentShow, \ currentSign, tcp_dist, arrow_scale, score)) # handle anything that comes in on the button boxes #print "About to test LUMINA", #print lumina_dev if LUMINA == 1: lumina_dev.poll_for_response() while lumina_dev.response_queue_size() > 0: response = lumina_dev.get_next_response() if response["pressed"]: print "Lumina received: %s, %d"%(response["key"],response["key"]) if response["key"] == 4: log.write("%5.3f; TR; %s\n"%(currentTime,currentTR)) currentTR=currentTR+1 else: log.write("%5.3f; LUMINA; %d\n"%(currentTime,response["key"])) #print "TESTED LUMINA" return 1
class SinGrating3D(LuminanceGratingCommon): """Sine wave grating stimulus texture mapped onto quad in 3D This is a general-purpose, realtime sine-wave luminace grating generator. This 3D version doesn't support an orientation parameter. This could be implemented, but for now should be done by orienting the quad in 3D. Parameters ========== bit_depth -- precision with which grating is calculated and sent to OpenGL (UnsignedInteger) Inherited from LuminanceGratingCommon Default: 8 color1 -- (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (1.0, 1.0, 1.0) color2 -- optional color with which to perform interpolation with color1 in RGB space (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (determined at runtime) contrast -- (Real) Default: 1.0 depth -- (Real) Default: (determined at runtime) depth_test -- perform depth test? (Boolean) Default: True ignore_time -- (Boolean) Default: False lowerleft -- vertex position (units: eye coordinates) (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (0.0, 0.0, -1.0) lowerright -- vertex position (units: eye coordinates) (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (1.0, 0.0, -1.0) mask -- optional masking function (Instance of <class 'VisionEgg.Textures.Mask2D'>) Default: (determined at runtime) max_alpha -- (Real) Default: 1.0 num_samples -- (UnsignedInteger) Default: 512 on -- draw stimulus? (Boolean) Default: True pedestal -- (Real) Default: 0.5 phase_at_t0 -- (Real) Default: 0.0 recalculate_phase_tolerance -- (Real) Default: (determined at runtime) size -- defines coordinate size of grating (in eye coordinates) (Sequence2 of Real) Default: (1.0, 1.0) spatial_freq -- frequency defined relative to coordinates defined in size parameter (units; cycles/eye_coord_unit) (Real) Default: 4.0 t0_time_sec_absolute -- (Real) Default: (determined at runtime) temporal_freq_hz -- (Real) Default: 5.0 upperleft -- vertex position (units: eye coordinates) (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (0.0, 1.0, -1.0) upperright -- vertex position (units: eye coordinates) (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (1.0, 1.0, -1.0) """ parameters_and_defaults = VisionEgg.ParameterDefinition({ 'on': (True, ve_types.Boolean, "draw stimulus?"), 'mask': ( None, # allows window onto otherwise (tilted) rectangular grating ve_types.Instance(VisionEgg.Textures.Mask2D), "optional masking function"), 'contrast': (1.0, ve_types.Real), 'pedestal': (0.5, ve_types.Real), 'depth': ( None, # if not None, turns on depth testing and allows for occlusion ve_types.Real), 'size': ( (1.0, 1.0), # in eye coordinates ve_types.Sequence2(ve_types.Real), "defines coordinate size of grating (in eye coordinates)"), 'spatial_freq': ( 4.0, # cycles/eye coord units ve_types.Real, "frequency defined relative to coordinates defined in size parameter (units; cycles/eye_coord_unit)" ), 'temporal_freq_hz': ( 5.0, # hz ve_types.Real), 't0_time_sec_absolute': ( None, # Will be assigned during first call to draw() ve_types.Real), 'ignore_time': ( False, # ignore temporal frequency variable - allow control purely with phase_at_t0 ve_types.Boolean), 'phase_at_t0': ( 0.0, # degrees [0.0-360.0] ve_types.Real), 'num_samples': ( 512, # number of spatial samples, should be a power of 2 ve_types.UnsignedInteger), 'max_alpha': ( 1.0, # controls "opacity": 1.0 = completely opaque, 0.0 = completely transparent ve_types.Real), 'color1': ( (1.0, 1.0, 1.0), # alpha is ignored (if given) -- use max_alpha parameter ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real))), 'color2': ( None, # perform interpolation with color1 in RGB space. ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), "optional color with which to perform interpolation with color1 in RGB space" ), 'recalculate_phase_tolerance': ( None, # only recalculate texture when phase is changed by more than this amount, None for always recalculate. (Saves time.) ve_types.Real), 'depth_test': (True, ve_types.Boolean, "perform depth test?"), 'lowerleft': ( (0.0, 0.0, -1.0), # in eye coordinates ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), "vertex position (units: eye coordinates)"), 'lowerright': ( (1.0, 0.0, -1.0), # in eye coordinates ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), "vertex position (units: eye coordinates)"), 'upperleft': ( (0.0, 1.0, -1.0), # in eye coordinates ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), "vertex position (units: eye coordinates)"), 'upperright': ( (1.0, 1.0, -1.0), # in eye coordinates ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), "vertex position (units: eye coordinates)"), 'polygon_offset_enabled': (False, ve_types.Boolean, "perform polygon offset?"), 'polygon_offset_factor': (1.0, ve_types.Real, "polygon factor"), 'polygon_offset_units': (1.0, ve_types.Real, "polygon units"), }) __slots__ = ( '_texture_object_id', '_last_phase', ) def __init__(self, **kw): LuminanceGratingCommon.__init__(self, **kw) p = self.parameters # shorthand self._texture_object_id = gl.glGenTextures(1) if p.mask: gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB) gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id) # Do error-checking on texture to make sure it will load max_dim = gl.glGetIntegerv(gl.GL_MAX_TEXTURE_SIZE) if p.num_samples > max_dim: raise NumSamplesTooLargeError( "Grating num_samples too large for video system.\nOpenGL reports maximum size of %d" % (max_dim, )) self.calculate_bit_depth_dependencies() w = p.size[0] inc = w / float(p.num_samples) phase = 0.0 # this data won't get used - don't care about phase self._last_phase = phase floating_point_sin = numpy.sin( 2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float) + (phase / 180.0 * math.pi)) * 0.5 * p.contrast + p.pedestal floating_point_sin = numpy.clip( floating_point_sin, 0.0, 1.0) # allow square wave generation if contrast > 1 texel_data = (floating_point_sin * self.max_int_val).astype( self.numpy_dtype).tostring() # Because the MAX_TEXTURE_SIZE method is insensitive to the current # state of the video system, another check must be done using # "proxy textures". gl.glTexImage1D( gl.GL_PROXY_TEXTURE_1D, # target 0, # level self.gl_internal_format, # video RAM internal format p.num_samples, # width 0, # border self.format, # format of texel data self.gl_type, # type of texel data texel_data) # texel data (irrelevant for proxy) if gl.glGetTexLevelParameteriv( gl.GL_PROXY_TEXTURE_1D, # Need PyOpenGL >= 2.0 0, gl.GL_TEXTURE_WIDTH) == 0: raise NumSamplesTooLargeError( "Grating num_samples is too wide for your video system!") # If we got here, it worked and we can load the texture for real. gl.glTexImage1D( gl.GL_TEXTURE_1D, # target 0, # level self.gl_internal_format, # video RAM internal format p.num_samples, # width 0, # border self.format, # format of texel data self.gl_type, # type of texel data texel_data) # texel data # Set texture object defaults gl.glTexParameteri(gl.GL_TEXTURE_1D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_1D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_1D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_1D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) if p.color2 is not None: if VisionEgg.Core.gl_renderer == 'ATi Rage 128 Pro OpenGL Engine' and VisionEgg.Core.gl_version == '1.1 ATI-1.2.22': logger = logging.getLogger('VisionEgg.Gratings') logger.warning("Your video card and driver have known " "bugs which prevent them from rendering " "color gratings properly.") def __del__(self): gl.glDeleteTextures([self._texture_object_id]) def draw(self): p = self.parameters # shorthand if p.on: if p.mask: gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB) if p.depth_test: gl.glEnable(gl.GL_DEPTH_TEST) else: gl.glDisable(gl.GL_DEPTH_TEST) if p.polygon_offset_enabled: gl.glEnable(gl.GL_POLYGON_OFFSET_EXT) gl.glPolygonOffset(p.polygon_offset_factor, p.polygon_offset_units) gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id) gl.glEnable(gl.GL_TEXTURE_1D) gl.glDisable(gl.GL_TEXTURE_2D) if p.bit_depth != self.cached_bit_depth: self.calculate_bit_depth_dependencies() # allow max_alpha value to control blending gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) if p.color2: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND) gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2) ## alpha is ignored because the texture base internal format is luminance else: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) if p.t0_time_sec_absolute is None and not p.ignore_time: p.t0_time_sec_absolute = VisionEgg.time_func() w = p.size[0] inc = w / float(p.num_samples) if p.ignore_time: phase = p.phase_at_t0 else: t_var = VisionEgg.time_func() - p.t0_time_sec_absolute phase = t_var * p.temporal_freq_hz * -360.0 + p.phase_at_t0 if p.recalculate_phase_tolerance is None or abs( self._last_phase - phase) > p.recalculate_phase_tolerance: self._last_phase = phase # we're re-drawing the phase at this angle floating_point_sin = numpy.sin( 2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float) + (phase / 180.0 * math.pi)) * 0.5 * p.contrast + p.pedestal floating_point_sin = numpy.clip( floating_point_sin, 0.0, 1.0) # allow square wave generation if contrast > 1 texel_data = (floating_point_sin * self.max_int_val).astype( self.numpy_dtype).tostring() gl.glTexSubImage1D( gl.GL_TEXTURE_1D, # target 0, # level 0, # x offset p.num_samples, # width self.format, # format of new texel data self.gl_type, # type of new texel data texel_data) # new texel data # in the case of only color1, # the texel data multiplies color1 to produce a color # with color2, # the texel data linearly interpolates between color1 and color2 gl.glColor4f(p.color1[0], p.color1[1], p.color1[2], p.max_alpha) if p.mask: p.mask.draw_masked_quad_3d( 0.0, 1.0, 0.0, 1.0, # for texture coordinates p.lowerleft, p.lowerright, p.upperright, p.upperleft) else: # draw unmasked quad gl.glBegin(gl.GL_QUADS) gl.glTexCoord2f(0.0, 0.0) gl.glVertex(*p.lowerleft) gl.glTexCoord2f(1.0, 0.0) gl.glVertex(*p.lowerright) gl.glTexCoord2f(1.0, 1.0) gl.glVertex(*p.upperright) gl.glTexCoord2f(0.0, 1.0) gl.glVertex(*p.upperleft) gl.glEnd() # GL_QUADS gl.glDisable(gl.GL_TEXTURE_1D) if p.polygon_offset_enabled: gl.glDisable(gl.GL_POLYGON_OFFSET_EXT)
def draw(self): p = self.parameters # shorthand if p.on: # calculate center center = VisionEgg._get_center(p.position, p.anchor, p.size) if p.mask: gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB) gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id) gl.glEnable(gl.GL_TEXTURE_1D) gl.glDisable(gl.GL_TEXTURE_2D) if p.bit_depth != self.cached_bit_depth: self.calculate_bit_depth_dependencies() # Clear the modeview matrix gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() # Rotate about the center of the texture gl.glTranslate(center[0], center[1], 0) gl.glRotate(p.orientation, 0, 0, 1) if p.depth is None: gl.glDisable(gl.GL_DEPTH_TEST) depth = 0.0 else: gl.glEnable(gl.GL_DEPTH_TEST) depth = p.depth # allow max_alpha value to control blending gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) if p.color2: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND) gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2) ## alpha is ignored because the texture base internal format is luminance else: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) if p.t0_time_sec_absolute is None and not p.ignore_time: p.t0_time_sec_absolute = VisionEgg.time_func() w = p.size[0] inc = w / float(p.num_samples) if p.ignore_time: phase = p.phase_at_t0 else: t_var = VisionEgg.time_func() - p.t0_time_sec_absolute phase = t_var * p.temporal_freq_hz * -360.0 + p.phase_at_t0 if p.recalculate_phase_tolerance is None or abs( self._last_phase - phase) > p.recalculate_phase_tolerance: self._last_phase = phase # we're re-drawing the phase at this angle floating_point_sin = numpy.sin( 2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float) + (phase / 180.0 * math.pi)) * 0.5 * p.contrast + p.pedestal floating_point_sin = numpy.clip( floating_point_sin, 0.0, 1.0) # allow square wave generation if contrast > 1 texel_data = (floating_point_sin * self.max_int_val).astype( self.numpy_dtype) # PyOpenGL 2.0.1.09 has a bug, so use our own wrapper _vegl.veglTexSubImage1D( gl.GL_TEXTURE_1D, # target 0, # level 0, # x offset p.num_samples, # width self.format, # format of new texel data self.gl_type, # type of new texel data texel_data) # new texel data if 0: compare_array = numpy.empty(texel_data.shape, dtype=texel_data.dtype) pixels = _vegl.veglGetTexImage( gl.GL_TEXTURE_1D, # target 0, # level self.format, # format self.gl_type, # type compare_array) assert numpy.allclose(compare_array, texel_data) h_w = p.size[0] / 2.0 h_h = p.size[1] / 2.0 l = -h_w r = h_w b = -h_h t = h_h # in the case of only color1, # the texel data multiplies color1 to produce a color # with color2, # the texel data linearly interpolates between color1 and color2 gl.glColor4f(p.color1[0], p.color1[1], p.color1[2], p.max_alpha) if p.mask: p.mask.draw_masked_quad( 0.0, 1.0, 0.0, 1.0, # l,r,b,t for texture coordinates l, r, b, t, # l,r,b,t in eye coordinates depth) # also in eye coordinates else: # draw unmasked quad gl.glBegin(gl.GL_QUADS) gl.glTexCoord2f(0.0, 0.0) gl.glVertex3f(l, b, depth) gl.glTexCoord2f(1.0, 0.0) gl.glVertex3f(r, b, depth) gl.glTexCoord2f(1.0, 1.0) gl.glVertex3f(r, t, depth) gl.glTexCoord2f(0.0, 1.0) gl.glVertex3f(l, t, depth) gl.glEnd() # GL_QUADS gl.glDisable(gl.GL_TEXTURE_1D) gl.glPopMatrix()
class SinGrating2D(LuminanceGratingCommon): """Sine wave grating stimulus This is a general-purpose, realtime sine-wave luminace grating generator. To acheive an arbitrary orientation, this class rotates a textured quad. To draw a grating with sides that always remain horizontal and vertical, draw a large grating in a small viewport. (The viewport will clip anything beyond its edges.) Parameters ========== anchor -- specifies how position parameter is interpreted (String) Default: center bit_depth -- precision with which grating is calculated and sent to OpenGL (UnsignedInteger) Inherited from LuminanceGratingCommon Default: 8 color1 -- (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (1.0, 1.0, 1.0) color2 -- optional color with which to perform interpolation with color1 in RGB space (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (determined at runtime) contrast -- (Real) Default: 1.0 depth -- (Real) Default: (determined at runtime) ignore_time -- (Boolean) Default: False mask -- optional masking function (Instance of <class 'VisionEgg.Textures.Mask2D'>) Default: (determined at runtime) max_alpha -- (Real) Default: 1.0 num_samples -- (UnsignedInteger) Default: 512 on -- draw stimulus? (Boolean) Default: True orientation -- (Real) Default: 0.0 pedestal -- (Real) Default: 0.5 phase_at_t0 -- (Real) Default: 0.0 position -- (units: eye coordinates) (Sequence2 of Real) Default: (320.0, 240.0) recalculate_phase_tolerance -- (Real) Default: (determined at runtime) size -- defines coordinate size of grating (in eye coordinates) (Sequence2 of Real) Default: (640.0, 480.0) spatial_freq -- frequency defined relative to coordinates defined in size parameter (units: cycles/eye_coord_unit) (Real) Default: 0.0078125 t0_time_sec_absolute -- (Real) Default: (determined at runtime) temporal_freq_hz -- (Real) Default: 5.0 """ parameters_and_defaults = VisionEgg.ParameterDefinition({ 'on': (True, ve_types.Boolean, "draw stimulus?"), 'mask': ( None, # allows window onto otherwise (tilted) rectangular grating ve_types.Instance(VisionEgg.Textures.Mask2D), "optional masking function"), 'contrast': (1.0, ve_types.Real), 'pedestal': (0.5, ve_types.Real), 'position': ( (320.0, 240.0), # in eye coordinates ve_types.Sequence2(ve_types.Real), "(units: eye coordinates)"), 'anchor': ('center', ve_types.String, "specifies how position parameter is interpreted"), 'depth': ( None, # if not None, turns on depth testing and allows for occlusion ve_types.Real), 'size': ( (640.0, 480.0), ve_types.Sequence2(ve_types.Real), "defines coordinate size of grating (in eye coordinates)", ), 'spatial_freq': ( 1.0 / 128.0, # cycles/eye coord units ve_types.Real, "frequency defined relative to coordinates defined in size parameter (units: cycles/eye_coord_unit)", ), 'temporal_freq_hz': ( 5.0, # hz ve_types.Real), 't0_time_sec_absolute': ( None, # Will be assigned during first call to draw() ve_types.Real), 'ignore_time': ( False, # ignore temporal frequency variable - allow control purely with phase_at_t0 ve_types.Boolean), 'phase_at_t0': ( 0.0, # degrees [0.0-360.0] ve_types.Real), 'orientation': ( 0.0, # 0=right, 90=up ve_types.Real), 'num_samples': ( 512, # number of spatial samples, should be a power of 2 ve_types.UnsignedInteger), 'max_alpha': ( 1.0, # controls "opacity": 1.0 = completely opaque, 0.0 = completely transparent ve_types.Real), 'color1': ( (1.0, 1.0, 1.0), # alpha is ignored (if given) -- use max_alpha parameter ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real))), 'color2': ( None, # perform interpolation with color1 in RGB space. ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), "optional color with which to perform interpolation with color1 in RGB space" ), 'recalculate_phase_tolerance': ( None, # only recalculate texture when phase is changed by more than this amount, None for always recalculate. (Saves time.) ve_types.Real), }) __slots__ = ( '_texture_object_id', '_last_phase', ) def __init__(self, **kw): LuminanceGratingCommon.__init__(self, **kw) p = self.parameters # shorthand self._texture_object_id = gl.glGenTextures(1) if p.mask: gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB) gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id) # Do error-checking on texture to make sure it will load max_dim = gl.glGetIntegerv(gl.GL_MAX_TEXTURE_SIZE) if p.num_samples > max_dim: raise NumSamplesTooLargeError( "Grating num_samples too large for video system.\nOpenGL reports maximum size of %d" % (max_dim, )) self.calculate_bit_depth_dependencies() w = p.size[0] inc = w / float(p.num_samples) phase = 0.0 # this data won't get used - don't care about phase self._last_phase = phase floating_point_sin = numpy.sin( 2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float) + (phase / 180.0 * math.pi)) * 0.5 * p.contrast + p.pedestal floating_point_sin = numpy.clip( floating_point_sin, 0.0, 1.0) # allow square wave generation if contrast > 1 texel_data = (floating_point_sin * self.max_int_val).astype( self.numpy_dtype).tostring() # Because the MAX_TEXTURE_SIZE method is insensitive to the current # state of the video system, another check must be done using # "proxy textures". gl.glTexImage1D( gl.GL_PROXY_TEXTURE_1D, # target 0, # level self.gl_internal_format, # video RAM internal format p.num_samples, # width 0, # border self.format, # format of texel data self.gl_type, # type of texel data texel_data) # texel data (irrelevant for proxy) if gl.glGetTexLevelParameteriv( gl.GL_PROXY_TEXTURE_1D, # Need PyOpenGL >= 2.0 0, gl.GL_TEXTURE_WIDTH) == 0: raise NumSamplesTooLargeError( "Grating num_samples is too wide for your video system!") # If we got here, it worked and we can load the texture for real. gl.glTexImage1D( gl.GL_TEXTURE_1D, # target 0, # level self.gl_internal_format, # video RAM internal format p.num_samples, # width 0, # border self.format, # format of texel data self.gl_type, # type of texel data texel_data) # texel data # Set texture object defaults gl.glTexParameteri(gl.GL_TEXTURE_1D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_1D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_1D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_1D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) if p.color2 is not None: if VisionEgg.Core.gl_renderer == 'ATi Rage 128 Pro OpenGL Engine' and VisionEgg.Core.gl_version == '1.1 ATI-1.2.22': logger = logging.getLogger('VisionEgg.Gratings') logger.warning("Your video card and driver have known " "bugs which prevent them from rendering " "color gratings properly.") def __del__(self): gl.glDeleteTextures([self._texture_object_id]) def draw(self): p = self.parameters # shorthand if p.on: # calculate center center = VisionEgg._get_center(p.position, p.anchor, p.size) if p.mask: gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB) gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id) gl.glEnable(gl.GL_TEXTURE_1D) gl.glDisable(gl.GL_TEXTURE_2D) if p.bit_depth != self.cached_bit_depth: self.calculate_bit_depth_dependencies() # Clear the modeview matrix gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() # Rotate about the center of the texture gl.glTranslate(center[0], center[1], 0) gl.glRotate(p.orientation, 0, 0, 1) if p.depth is None: gl.glDisable(gl.GL_DEPTH_TEST) depth = 0.0 else: gl.glEnable(gl.GL_DEPTH_TEST) depth = p.depth # allow max_alpha value to control blending gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) if p.color2: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND) gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2) ## alpha is ignored because the texture base internal format is luminance else: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) if p.t0_time_sec_absolute is None and not p.ignore_time: p.t0_time_sec_absolute = VisionEgg.time_func() w = p.size[0] inc = w / float(p.num_samples) if p.ignore_time: phase = p.phase_at_t0 else: t_var = VisionEgg.time_func() - p.t0_time_sec_absolute phase = t_var * p.temporal_freq_hz * -360.0 + p.phase_at_t0 if p.recalculate_phase_tolerance is None or abs( self._last_phase - phase) > p.recalculate_phase_tolerance: self._last_phase = phase # we're re-drawing the phase at this angle floating_point_sin = numpy.sin( 2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float) + (phase / 180.0 * math.pi)) * 0.5 * p.contrast + p.pedestal floating_point_sin = numpy.clip( floating_point_sin, 0.0, 1.0) # allow square wave generation if contrast > 1 texel_data = (floating_point_sin * self.max_int_val).astype( self.numpy_dtype) # PyOpenGL 2.0.1.09 has a bug, so use our own wrapper _vegl.veglTexSubImage1D( gl.GL_TEXTURE_1D, # target 0, # level 0, # x offset p.num_samples, # width self.format, # format of new texel data self.gl_type, # type of new texel data texel_data) # new texel data if 0: compare_array = numpy.empty(texel_data.shape, dtype=texel_data.dtype) pixels = _vegl.veglGetTexImage( gl.GL_TEXTURE_1D, # target 0, # level self.format, # format self.gl_type, # type compare_array) assert numpy.allclose(compare_array, texel_data) h_w = p.size[0] / 2.0 h_h = p.size[1] / 2.0 l = -h_w r = h_w b = -h_h t = h_h # in the case of only color1, # the texel data multiplies color1 to produce a color # with color2, # the texel data linearly interpolates between color1 and color2 gl.glColor4f(p.color1[0], p.color1[1], p.color1[2], p.max_alpha) if p.mask: p.mask.draw_masked_quad( 0.0, 1.0, 0.0, 1.0, # l,r,b,t for texture coordinates l, r, b, t, # l,r,b,t in eye coordinates depth) # also in eye coordinates else: # draw unmasked quad gl.glBegin(gl.GL_QUADS) gl.glTexCoord2f(0.0, 0.0) gl.glVertex3f(l, b, depth) gl.glTexCoord2f(1.0, 0.0) gl.glVertex3f(r, b, depth) gl.glTexCoord2f(1.0, 1.0) gl.glVertex3f(r, t, depth) gl.glTexCoord2f(0.0, 1.0) gl.glVertex3f(l, t, depth) gl.glEnd() # GL_QUADS gl.glDisable(gl.GL_TEXTURE_1D) gl.glPopMatrix()
class CheckBoard(Stimulus): """A checkboard stimulus, typically used as a aux stimulus for whitenoise. Parameters ========== anchor -- how position parameter is used (String) Default: center color -- color (256 jet colormap ) Default: 0(gray) on -- draw? (Boolean) Default: True position -- position in eye coordinates (AnyOf(Sequence2 of Real or Sequence3 of Real or Sequence4 of Real)) Default: (320.0, 240.0) size -- size in eye coordinates (Sequence2 of Real) Default: (4.0, 4.0) """ parameters_and_defaults = VisionEgg.ParameterDefinition({ 'on': (True, ve_types.Boolean, 'draw?'), 'bgcolor': ((0.5, 0.5, 0.5), ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), 'backgroud color'), 'linecolor': ((0.5, 0.0, 0.0), ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), 'grid line color'), 'cellcolor': ('gbr', ve_types.String, 'color map for the range [0.0,1.0]'), 'colorindex': (None, ve_types.Sequence(ve_types.Integer), 'color index in jet colormap'), 'drawline': (False, ve_types.Boolean, 'draw line?'), 'orientation': (0.0, ve_types.Real), 'position': ( (320.0, 240.0), # in eye coordinates ve_types.AnyOf(ve_types.Sequence2(ve_types.Real), ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), 'position in eye coordinates'), 'anchor': ('center', ve_types.String, 'how position parameter is used'), 'size': ( (100.0, 100.0), # horiz and vertical size ve_types.Sequence2(ve_types.Real), 'size in eye coordinates'), 'grid': ( (8, 8), # grid dimension of the checkboard ve_types.Sequence2(ve_types.Integer), 'grid dimension'), 'center': ( None, # DEPRECATED -- don't use ve_types.Sequence2(ve_types.Real), 'position in eye coordinates', VisionEgg.ParameterDefinition.DEPRECATED), }) def __init__(self, **kw): Stimulus.__init__(self, **kw) self.parameters.colorindex = np.zeros(self.parameters.grid) self.parameters.colorindex.fill(0.5) def draw(self): p = self.parameters # shorthand if p.center is not None: p.anchor = 'center' p.position = p.center[0], p.center[ 1] # copy values (don't copy ref to tuple) if p.on: # calculate center center = VisionEgg._get_center(p.position, p.anchor, p.size) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glTranslate(center[0], center[1], 0.0) gl.glRotate(p.orientation, 0.0, 0.0, 1.0) if len(p.bgcolor) == 3: gl.glColor3f(*p.bgcolor) elif len(p.bgcolor) == 4: gl.glColor4f(*p.bgcolor) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) w = p.size[0] / 2.0 #grid half-size h = p.size[1] / 2.0 m = p.size[0] / p.grid[0] #cell size n = p.size[1] / p.grid[1] i = range(p.grid[0]) #grid index j = range(p.grid[1]) #draw colorful cell # vertices_list = [((-w+column*m, h-(row+1)*n, 0.0),(-w+column*m, h-row*n, 0.0),\ # (-w+(column+1)*m, h-row*n, 0.0),(-w+(column+1)*m, h-row*n, 0.0))\ # for column in j for row in i] vertices_list = [((-w+column*m, h-(row+1)*n, 0.0),(-w+column*m, h-row*n, 0.0),\ (-w+(column+1)*m, h-row*n, 0.0),(-w+(column+1)*m, h-(row+1)*n, 0.0))\ for column in j for row in i] colors_list = [ colormap(p.colorindex[row, column], color=p.cellcolor) * 4 for column in j for row in i ] #flattening the vertices and colors vertices_flat = [ num for tuple in vertices_list for vertex in tuple for num in vertex ] colors_flat = [num for tuple in colors_list for num in tuple] vertices = np.array(vertices_flat) colors = np.array(colors_flat) vertices.shape = (-1, 3) colors.shape = (-1, 3) gl.glVertexPointerd(vertices) gl.glColorPointerd(colors) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glEnableClientState(gl.GL_COLOR_ARRAY) gl.glDisable(gl.GL_LIGHTING) gl.glDrawArrays(gl.GL_QUADS, 0, p.grid[0] * p.grid[1] * 4) #draw grid lines if p.drawline: if len(p.linecolor) == 3: gl.glColor3f(*p.linecolor) elif len(p.linecolor) == 4: gl.glColor4f(*p.linecolor) row_list = [((-w, h - i * n), (w, h - i * n)) for i in range(p.grid[1] + 1)] col_list = [((-w + i * m, h), (-w + i * m, -h)) for i in range(p.grid[0] + 1)] ver_row_flat = [ num for tuple in row_list for vertex in tuple for num in vertex ] ver_col_flat = [ num for tuple in col_list for vertex in tuple for num in vertex ] vertices_row = np.array(ver_row_flat) vertices_col = np.array(ver_col_flat) vertices_row.shape = (-1, 2) vertices_col.shape = (-1, 2) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glDisableClientState(gl.GL_COLOR_ARRAY) gl.glVertexPointerd(vertices_row) gl.glDrawArrays(gl.GL_LINES, 0, (p.grid[1] + 1) * 2) gl.glVertexPointerd(vertices_col) gl.glDrawArrays(gl.GL_LINES, 0, (p.grid[0] + 1) * 2) # gl.glBegin(gl.GL_LINES); # for i in range(p.grid[1] + 1): # gl.glVertex2f(-w, h - i * n) # gl.glVertex2f(w, h - i * n) # for i in range(p.grid[0] + 1): # gl.glVertex2f(-w + i * m, h) # gl.glVertex2f(-w + i * m, -h) # gl.glEnd(); gl.glPopMatrix() #save checkboard to file def save(self): import time, os (year, month, day, hour24, min, sec) = time.localtime(time.time())[:6] trial_time_str = "%04d%02d%02d_%02d%02d%02d" % (year, month, day, hour24, min, sec) dummy_filename = os.path.abspath(os.curdir)+ os.path.sep + 'screenshoot' + \ os.path.sep + 'checkboard' + trial_time_str + '.jpg'
#!/usr/bin/env python """ Textures with alpha (transparency). """ import VisionEgg as ve ve.start_default_logging(); ve.watch_exceptions() import VisionEgg.Core as vec from VisionEgg.FlowControl import Presentation import VisionEgg.Textures as vet import Image, ImageDraw # Python Imaging Library (PIL) import OpenGL.GL as gl # PyOpenGL import os import numpy # Numeric screen = vec.get_default_screen() texel_scale = 5 # create background texture from image file bg_filename = os.path.join(ve.config.VISIONEGG_SYSTEM_DIR,"data","panorama.jpg") bg_texture = vet.Texture(bg_filename) bg = vet.TextureStimulus(texture = bg_texture, size = bg_texture.size, shrink_texture_ok=False, mipmaps_enabled=False, )
#!/usr/bin/env python """Very simple driving simulator""" # $Id: driving.py 737 2012-01-20 03:32:04Z stepp $ import random import numpy import Image, ImageDraw, ImagePath import VisionEgg VisionEgg.start_default_logging() VisionEgg.watch_exceptions() from VisionEgg.Core import * import Simulation doEyetrack = False trialDuration = 60.0 VisionEgg.config.VISIONEGG_FULLSCREEN = 1 VisionEgg.config.VISIONEGG_SCREEN_W = 1024 VisionEgg.config.VISIONEGG_SCREEN_H = 768 screen = get_default_screen() sim = Simulation.Simulation(screen) practiceTrials = [(0, 0), (0, 0), (0, 0)] trials = [(1, 0.05), (2, 0.10), (3, 0.15), (4, 0.20), (5, 0.25), (6, 0.30), (7, 0.35), (8, 0.40), (9, 0.45), (10, 0.50), (11, 0.55), (12, 0.60),
def test_ClassWithParameters_pickle_ability(self): self.pickle_test(VisionEgg.ClassWithParameters())
def run(self, ID = 0): self.ID = ID super(DetectTrial, self).run() sound_played = False # self.start_time = VisionEgg.time_func() while not self.stopped: self.run_time = VisionEgg.time_func() - self.start_time if self.phase == 0: self.prestimulation_time = VisionEgg.time_func() if self.ID % 15 != 0: if ( self.prestimulation_time - self.start_time ) > self.phase_durations[0]: self.phase_forward() # this trial phase is ended with a space press on the first trial of a run, but timed on all other trials of a run. elif self.phase == 1: # first delay self.delay_1_time = VisionEgg.time_func() # this trial phase is timed if ( self.delay_1_time - self.prestimulation_time ) > self.phase_durations[1] - 0.1 and sound_played == False: self.session.play_sound( sound_index = 1 ) sound_played = True if ( self.delay_1_time - self.prestimulation_time ) > self.phase_durations[1]: self.phase_forward() elif self.phase == 2: # stimulus presentation # this trial phase is timed self.test_time = VisionEgg.time_func() if ( self.test_time - self.delay_1_time ) > self.phase_durations[2]: self.phase_forward() elif self.phase == 3: # second delay # this trial phase is timed self.delay_2_time = VisionEgg.time_func() if ( self.delay_2_time - self.test_time ) > self.phase_durations[3]: this_prob = np.random.rand() # print this_prob, self.ID if (this_prob < 0.1 or self.parameters['correct'] == -1) and not hasattr(self, 'has_been_extended'): self.phase_durations[3] = self.phase_durations[3] + 2.0 self.has_been_extended = True else: self.stopped = True return if this_prob < 0.1: if self.version == 1: if self.parameters['correct'] == 1: self.session.play_sound( sound_index = 2 ) elif self.parameters['correct'] == 0: self.session.play_sound( sound_index = 0 ) if self.version == 2: if self.parameters['correct'] == 1: self.session.play_sound( sound_index = 0 ) elif self.parameters['correct'] == 0: self.session.play_sound( sound_index = 2 ) if self.parameters['correct'] == -1: self.session.play_sound( sound_index = 3 ) # elif self.phase == 4: # confidence # self.confidence_time = VisionEgg.time_func() # elif self.phase == 5: # third delay # self.delay_3_time = VisionEgg.time_func() # if ( self.delay_3_time - self.confidence_time ) > self.phase_durations[5]: # self.feedback_given = False # self.phase_forward() # elif self.phase == 6: # feedback # self.feedback_time = VisionEgg.time_func() # if self.feedback_given == False and ( self.feedback_time - self.delay_3_time ) > 0.1: # if self.version == 1: # if self.parameters['correct'] == 1: # self.session.play_sound( sound_index = 2 ) # elif self.parameters['correct'] == 0: # self.session.play_sound( sound_index = 0 ) # if self.version == 2: # if self.parameters['correct'] == 1: # self.session.play_sound( sound_index = 0 ) # elif self.parameters['correct'] == 0: # self.session.play_sound( sound_index = 2 ) # elif self.parameters['correct'] == -1: # self.session.play_sound( sound_index = 3 ) # self.feedback_given = True # if ( self.feedback_time - self.delay_3_time ) > self.phase_durations[6]: # self.phase_forward() # elif self.phase == 7: # fourth delay # self.delay_4_time = VisionEgg.time_func() # if ( self.delay_4_time - self.feedback_time ) > self.phase_durations[7]: # self.stopped = True # events and draw self.event() self.draw() # we have stopped. self.stop()
def draw(self): p = self.parameters # shorthand if p.on: # calculate center center = VisionEgg._get_center(p.position,p.anchor,(p.radius, p.radius)) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glDisable(gl.GL_BLEND) if len(p.color)==3: gl.glColor3f(*p.color) elif len(p.color)==4: gl.glColor4f(*p.color) # Build filled circle from points # gl.glBegin(gl.GL_POINTS) # radius = int(math.ceil(p.radius)) # for i in range(-radius, radius): # for j in range(-radius, radius): # if(i * i + j * j < radius * radius): # gl.glVertex3f(p.position[0] + i, p.position[1] + j, 0.0) # gl.glEnd() # GL_POINTS # Build filled circle from triangles (this is typically faster # then the commented code above with the points) gl.glBegin(gl.GL_TRIANGLE_FAN) gl.glVertex3f(p.position[0], p.position[1], 0.0) angles = Numeric.arange(p.num_triangles)/float(p.num_triangles)*2.0*math.pi verts = Numeric.zeros( (p.num_triangles,2), Numeric.Float ) verts[:,0] = p.position[0] + p.radius * Numeric.cos(angles) verts[:,1] = p.position[1] + p.radius * Numeric.sin(angles) for i in range(verts.shape[0]): gl.glVertex2fv(verts[i]) gl.glVertex2fv(verts[0]) gl.glEnd() # GL_TRIANGLE_FAN if p.anti_aliasing: if not self._gave_alpha_warning: if len(p.color) > 3 and p.color[3] != 1.0: logger = logging.getLogger('VisionEgg.Arrow') logger.warning("The parameter anti_aliasing is " "set to true in the Arrow " "stimulus class, but the color " "parameter specifies an alpha " "value other than 1.0. To " "acheive anti-aliasing, ensure " "that the alpha value for the " "color parameter is 1.0.") self._gave_alpha_warning = 1 # We've already drawn a filled polygon (aliased), now redraw # the outline of the polygon (with anti-aliasing). (Using # GL_POLYGON_SMOOTH results in artifactual lines where # triangles were joined to create quad, at least on some OpenGL # implementations.) # Calculate coverage value for each pixel of outline # and store as alpha gl.glEnable(gl.GL_LINE_SMOOTH) # Now specify how to use the alpha value gl.glBlendFunc(gl.GL_SRC_ALPHA,gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) # Draw a second polygon in line mode, so the edges are anti-aliased gl.glPolygonMode(gl.GL_FRONT_AND_BACK,gl.GL_LINE) gl.glBegin(gl.GL_TRIANGLE_FAN) gl.glVertex3f(p.position[0], p.position[1], 0.0) angles = Numeric.arange(p.num_triangles)/float(p.num_triangles)*2.0*math.pi verts = Numeric.zeros( (p.num_triangles,2), Numeric.Float ) verts[:,0] = p.position[0] + p.radius * Numeric.cos(angles) verts[:,1] = p.position[1] + p.radius * Numeric.sin(angles) for i in range(verts.shape[0]): gl.glVertex2fv(verts[i]) gl.glVertex2fv(verts[0]) gl.glEnd() # GL_TRIANGLE_FAN # Set the polygon mode back to fill mode gl.glPolygonMode(gl.GL_FRONT_AND_BACK,gl.GL_FILL) gl.glDisable(gl.GL_LINE_SMOOTH)
#!/usr/bin/env python """ Textures with alpha (transparency). """ import VisionEgg as ve ve.start_default_logging() ve.watch_exceptions() import VisionEgg.Core as vec from VisionEgg.FlowControl import Presentation import VisionEgg.Textures as vet import Image, ImageDraw # Python Imaging Library (PIL) import OpenGL.GL as gl # PyOpenGL import os import numpy # Numeric screen = vec.get_default_screen() texel_scale = 5 # create background texture from image file bg_filename = os.path.join(ve.config.VISIONEGG_SYSTEM_DIR, "data", "panorama.jpg") bg_texture = vet.Texture(bg_filename) bg = vet.TextureStimulus( texture=bg_texture, size=bg_texture.size,
def event(self): for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == pygame.locals.K_ESCAPE: self.events.append([-99,VisionEgg.time_func()-self.start_time]) self.parameters.update({'correct': 0}) self.stopped = True self.session.stopped = True # it handles both numeric and lettering modes elif event.key == pygame.locals.K_SPACE: self.events.append([0,VisionEgg.time_func()-self.start_time]) if self.phase in (0, 4): self.phase_forward() # else: # self.stopped = True elif event.key == pygame.locals.K_LEFT: self.events.append([1,VisionEgg.time_func()-self.start_time]) if self.version == 1: if self.phase == 2: self.parameters.update({'answer':1}) if self.parameters['target_present_in_stimulus'] == 0: self.parameters['correct']= 1 else: self.parameters['correct']= 0 if self.phase == 2: self.phase_forward() if self.version == 2: if self.phase == 2: self.parameters.update({'answer':1}) if self.parameters['target_present_in_stimulus'] == 1: self.parameters['correct']= 1 else: self.parameters['correct']= 0 if self.phase == 2: self.phase_forward() elif event.key == pygame.locals.K_RIGHT: self.events.append([-1,VisionEgg.time_func()-self.start_time]) if self.version == 1: if self.phase == 2: self.parameters.update({'answer':-1}) if self.parameters['target_present_in_stimulus'] == 1: self.parameters['correct']= 1 else: self.parameters['correct']= 0 if self.phase == 2: self.phase_forward() if self.version == 2: if self.phase == 2: self.parameters.update({'answer':-1}) if self.parameters['target_present_in_stimulus'] == 0: self.parameters['correct']= 1 else: self.parameters['correct']= 0 if self.phase == 2: self.phase_forward() elif event.key == pygame.locals.K_a: if self.phase > 3: self.parameters['confidence'] = 0 if self.phase == 4: self.phase_forward() elif event.key == pygame.locals.K_s: if self.phase > 3: self.parameters['confidence'] = 1 if self.phase == 4: self.phase_forward() elif event.key == pygame.locals.K_d: if self.phase > 3: self.parameters['confidence'] = 2 if self.phase == 4: self.phase_forward() elif event.key == pygame.locals.K_f: if self.phase > 3: self.parameters['confidence'] = 3 if self.phase == 4: self.phase_forward() super(DetectTrial, self).key_event( event )
def draw(self): p = self.parameters # Shorthand if p.on: # Calculate center center = VisionEgg._get_center(p.position,p.anchor,p.size) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glTranslate(center[0],center[1],0.0) gl.glRotate(-p.orientation,0.0,0.0,1.0) if len(p.color)==3: gl.glColor3f(*p.color) elif len(p.color)==4: gl.glColor4f(*p.color) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glBlendFunc(gl.GL_SRC_ALPHA,gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) w = p.size[0]/2.0 h = p.size[1]/2.0 gl.glBegin(gl.GL_QUADS) # Draw Rectangle gl.glVertex3f( 0.25*w, h, 0.0) gl.glVertex3f(-w, h, 0.0) gl.glVertex3f(-w,-h, 0.0) gl.glVertex3f( 0.25*w, -h, 0.0) gl.glEnd() # GL_QUADS gl.glBegin(gl.GL_TRIANGLES) # Draw Triangle gl.glVertex3f( 1.00*w, 0.0*h, 0.0) # Top gl.glVertex3f( 0.25*w,-3.0*h, 0.0) gl.glVertex3f( 0.25*w, 3.0*h, 0.0) gl.glEnd() # GL_QUADS if p.anti_aliasing: if not self._gave_alpha_warning: if len(p.color) > 3 and p.color[3] != 1.0: logger = logging.getLogger('VisionEgg.Arrow') logger.warning("The parameter anti_aliasing is " "set to true in the Arrow " "stimulus class, but the color " "parameter specifies an alpha " "value other than 1.0. To " "acheive anti-aliasing, ensure " "that the alpha value for the " "color parameter is 1.0.") self._gave_alpha_warning = 1 # We've already drawn a filled polygon (aliased), now redraw # the outline of the polygon (with anti-aliasing). (Using # GL_POLYGON_SMOOTH results in artifactual lines where # triangles were joined to create quad, at least on some OpenGL # implementations.) # Calculate coverage value for each pixel of outline # and store as alpha gl.glEnable(gl.GL_LINE_SMOOTH) # Now specify how to use the alpha value gl.glBlendFunc(gl.GL_SRC_ALPHA,gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) # Draw a second polygon in line mode, so the edges are anti-aliased gl.glPolygonMode(gl.GL_FRONT_AND_BACK,gl.GL_LINE) gl.glBegin(gl.GL_QUADS) gl.glVertex3f( 0.25*w, h, 0.0) # Draw Rectangle gl.glVertex3f(-w, h, 0.0) gl.glVertex3f(-w,-h, 0.0) gl.glVertex3f( 0.25*w, -h, 0.0) gl.glVertex3f( 1.00*w, 0.0*h, 0.0) # Draw Triangle gl.glVertex3f( 0.25*w,-3.0*h, 0.0) gl.glVertex3f( 0.25*w, 3.0*h, 0.0) gl.glEnd() # GL_QUADS # Set the polygon mode back to fill mode gl.glPolygonMode(gl.GL_FRONT_AND_BACK,gl.GL_FILL) gl.glDisable(gl.GL_LINE_SMOOTH) gl.glPopMatrix()
def draw(self): # XXX This method is not speed-optimized. I just wrote it to # get the job done. (Nonetheless, it seems faster than the C # version commented out above.) p = self.parameters # shorthand if p.center is not None: if not hasattr(VisionEgg.config,"_GAVE_CENTER_DEPRECATION"): logger = logging.getLogger('VisionEgg.Dots') logger.warning("Specifying DotArea2D by deprecated " "'center' parameter deprecated. Use " "'position' parameter instead. (Allows " "use of 'anchor' parameter to set to " "other values.)") VisionEgg.config._GAVE_CENTER_DEPRECATION = 1 p.anchor = 'center' p.position = p.center[0], p.center[1] # copy values (don't copy ref to tuple) if p.on: # calculate center center = VisionEgg._get_center(p.position,p.anchor,p.size) if p.anti_aliasing: if len(p.color) == 4 and not self._gave_alpha_warning: if p.color[3] != 1.0: logger = logging.getLogger('VisionEgg.Dots') logger.warning("The parameter anti_aliasing is " "set to true in the DotArea2D " "stimulus class, but the color " "parameter specifies an alpha " "value other than 1.0. To " "acheive the best anti-aliasing, " "ensure that the alpha value for " "the color parameter is 1.0.") self._gave_alpha_warning = 1 gl.glEnable( gl.GL_POINT_SMOOTH ) # allow max_alpha value to control blending gl.glEnable( gl.GL_BLEND ) gl.glBlendFunc( gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA ) else: gl.glDisable( gl.GL_BLEND ) now_sec = VisionEgg.time_func() if self.start_times_sec is not None: # compute extinct dots and generate new positions replace_indices = Numeric.nonzero( Numeric.greater( now_sec - self.start_times_sec, p.dot_lifespan_sec) ) Numeric.put( self.start_times_sec, replace_indices, now_sec ) new_x_positions = RandomArray.uniform(0.0,1.0, (len(replace_indices),)) Numeric.put( self.x_positions, replace_indices, new_x_positions ) new_y_positions = RandomArray.uniform(0.0,1.0, (len(replace_indices),)) Numeric.put( self.y_positions, replace_indices, new_y_positions ) new_random_directions_radians = RandomArray.uniform(0.0,2*math.pi, (len(replace_indices),)) Numeric.put( self.random_directions_radians, replace_indices, new_random_directions_radians ) else: # initialize dot extinction values to random (uniform) distribution self.start_times_sec = RandomArray.uniform( now_sec - p.dot_lifespan_sec, now_sec, (self.constant_parameters.num_dots,)) signal_num_dots = int(round(p.signal_fraction * self.constant_parameters.num_dots)) time_delta_sec = now_sec - self.last_time_sec self.last_time_sec = now_sec # reset for next loop x_increment_normalized = math.cos(p.signal_direction_deg/180.0*math.pi) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec y_increment_normalized = -math.sin(p.signal_direction_deg/180.0*math.pi) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec self.x_positions[:signal_num_dots] += x_increment_normalized self.y_positions[:signal_num_dots] += y_increment_normalized num_random_dots = self.constant_parameters.num_dots - signal_num_dots random_x_increment_normalized = Numeric.cos(self.random_directions_radians[signal_num_dots:]) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec random_y_increment_normalized = -Numeric.sin(self.random_directions_radians[signal_num_dots:]) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec self.x_positions[signal_num_dots:] += random_x_increment_normalized self.y_positions[signal_num_dots:] += random_y_increment_normalized self.x_positions = Numeric.fmod( self.x_positions, 1.0 ) # wrap self.y_positions = Numeric.fmod( self.y_positions, 1.0 ) self.x_positions = Numeric.fmod( self.x_positions+1, 1.0 ) # wrap again for values < 1 self.y_positions = Numeric.fmod( self.y_positions+1, 1.0 ) xs = (self.x_positions - 0.5) * p.size[0] + center[0] ys = (self.y_positions - 0.5) * p.size[1] + center[1] if len(p.color)==3: gl.glColor3f(*p.color) elif len(p.color)==4: gl.glColor4f(*p.color) gl.glPointSize(p.dot_size) # Clear the modeview matrix gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glDisable(gl.GL_TEXTURE_2D) if p.depth is None: depth = 0.0 else: gl.glEnable(gl.GL_DEPTH_TEST) depth = p.depth zs = (depth,)*len(xs) # make N tuple with repeat value of depth draw_dots(xs,ys,zs) if p.anti_aliasing: gl.glDisable( gl.GL_POINT_SMOOTH ) # turn off gl.glPopMatrix()
def draw(self): p = self.parameters # shorthand if p.center is not None: if not hasattr(VisionEgg.config,"_GAVE_CENTER_DEPRECATION"): logger = logging.getLogger('VisionEgg.MoreStimuli') logger.warning("Specifying Target2D by deprecated " "'center' parameter deprecated. Use " "'position' parameter instead. (Allows " "use of 'anchor' parameter to set to " "other values.)") VisionEgg.config._GAVE_CENTER_DEPRECATION = 1 p.anchor = 'center' p.position = p.center[0], p.center[1] # copy values (don't copy ref to tuple) if p.on: # calculate center center = VisionEgg._get_center(p.position,p.anchor,p.size) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glTranslate(center[0],center[1],0.0) gl.glRotate(p.orientation,0.0,0.0,1.0) if len(p.color)==3: gl.glColor3f(*p.color) elif len(p.color)==4: gl.glColor4f(*p.color) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glBlendFunc(gl.GL_SRC_ALPHA,gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) w = p.size[0]/2.0 h = p.size[1]/2.0 gl.glBegin(gl.GL_QUADS) gl.glVertex3f(-w,-h, 0.0) gl.glVertex3f( w,-h, 0.0) gl.glVertex3f( w, h, 0.0) gl.glVertex3f(-w, h, 0.0) gl.glEnd() # GL_QUADS if p.anti_aliasing: if not self._gave_alpha_warning: if len(p.color) > 3 and p.color[3] != 1.0: logger = logging.getLogger('VisionEgg.MoreStimuli') logger.warning("The parameter anti_aliasing is " "set to true in the Target2D " "stimulus class, but the color " "parameter specifies an alpha " "value other than 1.0. To " "acheive anti-aliasing, ensure " "that the alpha value for the " "color parameter is 1.0.") self._gave_alpha_warning = 1 # We've already drawn a filled polygon (aliased), now # redraw the outline of the polygon (with # anti-aliasing). (Using GL_POLYGON_SMOOTH results in # artifactual lines where triangles were joined to # create quad, at least on some OpenGL # implementations.) # Calculate coverage value for each pixel of outline # and store as alpha gl.glEnable(gl.GL_LINE_SMOOTH) # Now specify how to use the alpha value gl.glBlendFunc(gl.GL_SRC_ALPHA,gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) # Draw a second polygon in line mode, so the edges are anti-aliased gl.glPolygonMode(gl.GL_FRONT_AND_BACK,gl.GL_LINE) gl.glBegin(gl.GL_QUADS) gl.glVertex3f(-w,-h, 0.0); gl.glVertex3f( w,-h, 0.0); gl.glVertex3f( w, h, 0.0); gl.glVertex3f(-w, h, 0.0); gl.glEnd() # GL_QUADS # Set the polygon mode back to fill mode gl.glPolygonMode(gl.GL_FRONT_AND_BACK,gl.GL_FILL) gl.glDisable(gl.GL_LINE_SMOOTH) gl.glPopMatrix()
#!/usr/bin/env python """ multiple stimulus demo """ ############################ # Import various modules # ############################ import VisionEgg VisionEgg.start_default_logging() VisionEgg.watch_exceptions() from VisionEgg.Core import * from VisionEgg.Dots import DotArea2D from VisionEgg.Gratings import SinGrating2D from VisionEgg.MoreStimuli import Target2D from VisionEgg.Textures import Mask2D, Texture, SpinningDrum, TextureStimulus from VisionEgg.Textures import TextureTooLargeError from VisionEgg.Text import Text from math import sin, pi import math from pygame.locals import QUIT, KEYDOWN, MOUSEBUTTONDOWN import numpy ##################################### # Initialize OpenGL window/screen # #####################################
def draw(self): p = self.parameters # Shorthand if p.on: # Calculate center center = VisionEgg._get_center(p.position, p.anchor, p.size) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glTranslate(center[0], center[1], 0.0) gl.glRotate(-p.orientation, 0.0, 0.0, 1.0) if len(p.color) == 3: gl.glColor3f(*p.color) elif len(p.color) == 4: gl.glColor4f(*p.color) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) w = p.size[0] / 2.0 h = p.size[1] / 2.0 gl.glBegin(gl.GL_QUADS) # Draw Rectangle gl.glVertex3f(0.25 * w, h, 0.0) gl.glVertex3f(-w, h, 0.0) gl.glVertex3f(-w, -h, 0.0) gl.glVertex3f(0.25 * w, -h, 0.0) gl.glEnd() # GL_QUADS gl.glBegin(gl.GL_TRIANGLES) # Draw Triangle gl.glVertex3f(1.00 * w, 0.0 * h, 0.0) # Top gl.glVertex3f(0.25 * w, -3.0 * h, 0.0) gl.glVertex3f(0.25 * w, 3.0 * h, 0.0) gl.glEnd() # GL_QUADS if p.anti_aliasing: if not self._gave_alpha_warning: if len(p.color) > 3 and p.color[3] != 1.0: logger = logging.getLogger('VisionEgg.Arrow') logger.warning("The parameter anti_aliasing is " "set to true in the Arrow " "stimulus class, but the color " "parameter specifies an alpha " "value other than 1.0. To " "acheive anti-aliasing, ensure " "that the alpha value for the " "color parameter is 1.0.") self._gave_alpha_warning = 1 # We've already drawn a filled polygon (aliased), now redraw # the outline of the polygon (with anti-aliasing). (Using # GL_POLYGON_SMOOTH results in artifactual lines where # triangles were joined to create quad, at least on some OpenGL # implementations.) # Calculate coverage value for each pixel of outline # and store as alpha gl.glEnable(gl.GL_LINE_SMOOTH) # Now specify how to use the alpha value gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) # Draw a second polygon in line mode, so the edges are anti-aliased gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) gl.glBegin(gl.GL_QUADS) gl.glVertex3f(0.25 * w, h, 0.0) # Draw Rectangle gl.glVertex3f(-w, h, 0.0) gl.glVertex3f(-w, -h, 0.0) gl.glVertex3f(0.25 * w, -h, 0.0) gl.glVertex3f(1.00 * w, 0.0 * h, 0.0) # Draw Triangle gl.glVertex3f(0.25 * w, -3.0 * h, 0.0) gl.glVertex3f(0.25 * w, 3.0 * h, 0.0) gl.glEnd() # GL_QUADS # Set the polygon mode back to fill mode gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) gl.glDisable(gl.GL_LINE_SMOOTH) gl.glPopMatrix()
def get_str(xx, const=0): class_by_key = {} done_parameters_and_defaults = [] classes = VisionEgg.recursive_base_class_finder(xx) # Fill self.parameters with parameter names and set to default values for klass in classes: if klass == object: continue # base class of new style classes - ignore if const: pd = klass.constant_parameters_and_defaults else: pd = klass.parameters_and_defaults if pd not in done_parameters_and_defaults: for parameter_name in pd.keys(): class_by_key[parameter_name] = klass done_parameters_and_defaults.append(pd) ks = class_by_key.keys() ks.sort() if len(ks): out_strs = [] if not const: out_strs.append("Parameters\n") out_strs.append("==========\n") else: out_strs.append("Constant Parameters\n") out_strs.append("===================\n") # pass 1: max_len = 0 for param_name in ks: max_len = max(max_len, len(param_name)) for param_name in ks: klass = class_by_key[param_name] if const: p = klass.constant_parameters_and_defaults else: p = klass.parameters_and_defaults if len(p[param_name]) > 3: if p[param_name][3] == VisionEgg.ParameterDefinition.DEPRECATED: continue type_str = param_name default = p[param_name][0] ve_type = p[param_name][1] if len(p[param_name]) > 2: description = p[param_name][2] + " " else: description = "" out_strs.append("%s -- %s(%s)\n" % (param_name.ljust(max_len), description, str(ve_type))) if xx != klass: if klass.__module__ != xx.__module__: mod_name = "%s." % klass.__module__ else: mod_name = "" out_strs.append(" " * (max_len + 4) + "Inherited from %s%s\n" % (mod_name, klass.__name__)) tmp = str(default).split("\n") if default is None: tmp = ["(determined at runtime)"] if len(p[param_name]) > 3: if p[param_name][3] == VisionEgg.ParameterDefinition.OPENGL_ENUM: if default is None: gl_name = "(GL enum determined at runtime)" else: gl_name = str(default) tmp = [gl_name] out_strs.append(" " * (max_len + 4) + "Default: " + tmp[0] + "\n") if len(tmp) > 1: for i in range(1, len(tmp)): out_strs.append(" " * (max_len + 13) + tmp[i] + "\n") return out_strs
#!/usr/bin/env python """Draw dots and save movie using your own event loop. This bypasses the VisionEgg.FlowControl.Presentation class. It may be easier to create simple scripts this way.""" import VisionEgg VisionEgg.start_default_logging(); VisionEgg.watch_exceptions() from VisionEgg.Core import * import pygame from pygame.locals import * from VisionEgg.Text import * from VisionEgg.Dots import * screen = get_default_screen() screen.parameters.bgcolor = (0.0,0.0,0.0,0.0) # black (RGBA) dots = DotArea2D( position = ( screen.size[0]/2.0, screen.size[1]/2.0 ), size = ( 300.0 , 300.0 ), signal_fraction = 0.1, signal_direction_deg = 180.0, velocity_pixels_per_sec = 10.0, dot_lifespan_sec = 5.0, dot_size = 3.0, num_dots = 100) text = Text( text = "Vision Egg makeMovie2 demo.", position = (screen.size[0]/2,2), anchor = 'bottom',
class FilledCircle(VisionEgg.Core.Stimulus): """ A circular stimulus, typically used as a fixation point. (Note, this implementation almost certainly could be made faster using display lists.) Parameters ========== anchor -- how position parameter is used (String) Default: center anti_aliasing -- (Boolean) Default: True color -- color (AnyOf(Sequence3 of Real or Sequence4 of Real)) Default: (1.0, 1.0, 1.0) num_triangles -- number of triangles used to draw circle (Integer) Default: 51 on -- draw? (Boolean) Default: True position -- position in eye coordinates (AnyOf(Sequence2 of Real or Sequence3 of Real or Sequence4 of Real)) Default: (320.0, 240.0) radius -- radius in eye coordinates (Real) Default: 2.0 """ parameters_and_defaults = VisionEgg.ParameterDefinition({ 'on': (True, ve_types.Boolean, 'draw?'), 'color': ((1.0, 1.0, 1.0), ve_types.AnyOf(ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), 'color'), 'anti_aliasing': (True, ve_types.Boolean), 'position': ( (320.0, 240.0), # in eye coordinates ve_types.AnyOf(ve_types.Sequence2(ve_types.Real), ve_types.Sequence3(ve_types.Real), ve_types.Sequence4(ve_types.Real)), 'position in eye coordinates'), 'anchor': ('center', ve_types.String, 'how position parameter is used'), 'radius': (2.0, ve_types.Real, 'radius in eye coordinates'), 'num_triangles': (51, ve_types.Integer, 'number of triangles used to draw circle'), }) __slots__ = VisionEgg.Core.Stimulus.__slots__ + ('_gave_alpha_warning', ) def __init__(self, **kw): VisionEgg.Core.Stimulus.__init__(self, **kw) self._gave_alpha_warning = 0 def draw(self): p = self.parameters # shorthand if p.on: # calculate center center = VisionEgg._get_center(p.position, p.anchor, (p.radius, p.radius)) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glDisable(gl.GL_BLEND) if len(p.color) == 3: gl.glColor3f(*p.color) elif len(p.color) == 4: gl.glColor4f(*p.color) # Build filled circle from points # gl.glBegin(gl.GL_POINTS) # radius = int(math.ceil(p.radius)) # for i in range(-radius, radius): # for j in range(-radius, radius): # if(i * i + j * j < radius * radius): # gl.glVertex3f(p.position[0] + i, p.position[1] + j, 0.0) # gl.glEnd() # GL_POINTS # Build filled circle from triangles (this is typically faster # then the commented code above with the points) gl.glBegin(gl.GL_TRIANGLE_FAN) gl.glVertex3f(p.position[0], p.position[1], 0.0) angles = Numeric.arange(p.num_triangles) / float( p.num_triangles) * 2.0 * math.pi verts = Numeric.zeros((p.num_triangles, 2), Numeric.Float) verts[:, 0] = p.position[0] + p.radius * Numeric.cos(angles) verts[:, 1] = p.position[1] + p.radius * Numeric.sin(angles) for i in range(verts.shape[0]): gl.glVertex2fv(verts[i]) gl.glVertex2fv(verts[0]) gl.glEnd() # GL_TRIANGLE_FAN if p.anti_aliasing: if not self._gave_alpha_warning: if len(p.color) > 3 and p.color[3] != 1.0: logger = logging.getLogger('VisionEgg.Arrow') logger.warning("The parameter anti_aliasing is " "set to true in the Arrow " "stimulus class, but the color " "parameter specifies an alpha " "value other than 1.0. To " "acheive anti-aliasing, ensure " "that the alpha value for the " "color parameter is 1.0.") self._gave_alpha_warning = 1 # We've already drawn a filled polygon (aliased), now redraw # the outline of the polygon (with anti-aliasing). (Using # GL_POLYGON_SMOOTH results in artifactual lines where # triangles were joined to create quad, at least on some OpenGL # implementations.) # Calculate coverage value for each pixel of outline # and store as alpha gl.glEnable(gl.GL_LINE_SMOOTH) # Now specify how to use the alpha value gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) # Draw a second polygon in line mode, so the edges are anti-aliased gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) gl.glBegin(gl.GL_TRIANGLE_FAN) gl.glVertex3f(p.position[0], p.position[1], 0.0) angles = Numeric.arange(p.num_triangles) / float( p.num_triangles) * 2.0 * math.pi verts = Numeric.zeros((p.num_triangles, 2), Numeric.Float) verts[:, 0] = p.position[0] + p.radius * Numeric.cos(angles) verts[:, 1] = p.position[1] + p.radius * Numeric.sin(angles) for i in range(verts.shape[0]): gl.glVertex2fv(verts[i]) gl.glVertex2fv(verts[0]) gl.glEnd() # GL_TRIANGLE_FAN # Set the polygon mode back to fill mode gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) gl.glDisable(gl.GL_LINE_SMOOTH)
def draw(self): p = self.parameters # shorthand if p.on: # calculate center center = VisionEgg._get_center(p.position, p.anchor, (p.radius, p.radius)) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glDisable(gl.GL_BLEND) if len(p.color) == 3: gl.glColor3f(*p.color) elif len(p.color) == 4: gl.glColor4f(*p.color) # Build filled circle from points # gl.glBegin(gl.GL_POINTS) # radius = int(math.ceil(p.radius)) # for i in range(-radius, radius): # for j in range(-radius, radius): # if(i * i + j * j < radius * radius): # gl.glVertex3f(p.position[0] + i, p.position[1] + j, 0.0) # gl.glEnd() # GL_POINTS # Build filled circle from triangles (this is typically faster # then the commented code above with the points) gl.glBegin(gl.GL_TRIANGLE_FAN) gl.glVertex3f(p.position[0], p.position[1], 0.0) angles = Numeric.arange(p.num_triangles) / float( p.num_triangles) * 2.0 * math.pi verts = Numeric.zeros((p.num_triangles, 2), Numeric.Float) verts[:, 0] = p.position[0] + p.radius * Numeric.cos(angles) verts[:, 1] = p.position[1] + p.radius * Numeric.sin(angles) for i in range(verts.shape[0]): gl.glVertex2fv(verts[i]) gl.glVertex2fv(verts[0]) gl.glEnd() # GL_TRIANGLE_FAN if p.anti_aliasing: if not self._gave_alpha_warning: if len(p.color) > 3 and p.color[3] != 1.0: logger = logging.getLogger('VisionEgg.Arrow') logger.warning("The parameter anti_aliasing is " "set to true in the Arrow " "stimulus class, but the color " "parameter specifies an alpha " "value other than 1.0. To " "acheive anti-aliasing, ensure " "that the alpha value for the " "color parameter is 1.0.") self._gave_alpha_warning = 1 # We've already drawn a filled polygon (aliased), now redraw # the outline of the polygon (with anti-aliasing). (Using # GL_POLYGON_SMOOTH results in artifactual lines where # triangles were joined to create quad, at least on some OpenGL # implementations.) # Calculate coverage value for each pixel of outline # and store as alpha gl.glEnable(gl.GL_LINE_SMOOTH) # Now specify how to use the alpha value gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) # Draw a second polygon in line mode, so the edges are anti-aliased gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) gl.glBegin(gl.GL_TRIANGLE_FAN) gl.glVertex3f(p.position[0], p.position[1], 0.0) angles = Numeric.arange(p.num_triangles) / float( p.num_triangles) * 2.0 * math.pi verts = Numeric.zeros((p.num_triangles, 2), Numeric.Float) verts[:, 0] = p.position[0] + p.radius * Numeric.cos(angles) verts[:, 1] = p.position[1] + p.radius * Numeric.sin(angles) for i in range(verts.shape[0]): gl.glVertex2fv(verts[i]) gl.glVertex2fv(verts[0]) gl.glEnd() # GL_TRIANGLE_FAN # Set the polygon mode back to fill mode gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) gl.glDisable(gl.GL_LINE_SMOOTH)
def draw(self): p = self.parameters # shorthand if p.center is not None: if not hasattr(VisionEgg.config, "_GAVE_CENTER_DEPRECATION"): logger = logging.getLogger('VisionEgg.MoreStimuli') logger.warning("Specifying Target2D by deprecated " "'center' parameter deprecated. Use " "'position' parameter instead. (Allows " "use of 'anchor' parameter to set to " "other values.)") VisionEgg.config._GAVE_CENTER_DEPRECATION = 1 p.anchor = 'center' p.position = p.center[0], p.center[ 1] # copy values (don't copy ref to tuple) if p.on: # calculate center center = VisionEgg._get_center(p.position, p.anchor, p.size) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glTranslate(center[0], center[1], 0.0) gl.glRotate(p.orientation, 0.0, 0.0, 1.0) if len(p.color) == 3: gl.glColor3f(*p.color) elif len(p.color) == 4: gl.glColor4f(*p.color) gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_TEXTURE_2D) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) w = p.size[0] / 2.0 h = p.size[1] / 2.0 gl.glBegin(gl.GL_QUADS) gl.glVertex3f(-w, -h, 0.0) gl.glVertex3f(w, -h, 0.0) gl.glVertex3f(w, h, 0.0) gl.glVertex3f(-w, h, 0.0) gl.glEnd() # GL_QUADS if p.anti_aliasing: if not self._gave_alpha_warning: if len(p.color) > 3 and p.color[3] != 1.0: logger = logging.getLogger('VisionEgg.MoreStimuli') logger.warning("The parameter anti_aliasing is " "set to true in the Target2D " "stimulus class, but the color " "parameter specifies an alpha " "value other than 1.0. To " "acheive anti-aliasing, ensure " "that the alpha value for the " "color parameter is 1.0.") self._gave_alpha_warning = 1 # We've already drawn a filled polygon (aliased), now # redraw the outline of the polygon (with # anti-aliasing). (Using GL_POLYGON_SMOOTH results in # artifactual lines where triangles were joined to # create quad, at least on some OpenGL # implementations.) # Calculate coverage value for each pixel of outline # and store as alpha gl.glEnable(gl.GL_LINE_SMOOTH) # Now specify how to use the alpha value gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) # Draw a second polygon in line mode, so the edges are anti-aliased gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) gl.glBegin(gl.GL_QUADS) gl.glVertex3f(-w, -h, 0.0) gl.glVertex3f(w, -h, 0.0) gl.glVertex3f(w, h, 0.0) gl.glVertex3f(-w, h, 0.0) gl.glEnd() # GL_QUADS # Set the polygon mode back to fill mode gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) gl.glDisable(gl.GL_LINE_SMOOTH) gl.glPopMatrix()
#!/usr/bin/env python """Sinusoidal grating calculated in realtime.""" ############################ # Import various modules # ############################ import VisionEgg VisionEgg.start_default_logging(); VisionEgg.watch_exceptions() from VisionEgg.Core import * from VisionEgg.FlowControl import Presentation from VisionEgg.Gratings import * ##################################### # Initialize OpenGL window/screen # ##################################### screen = get_default_screen() ###################################### # Create sinusoidal grating object # ###################################### stimulus = SinGrating2D(position = ( screen.size[0]/2.0, screen.size[1]/2.0 ), anchor = 'center', size = ( 300.0 , 300.0 ), spatial_freq = 10.0 / screen.size[0], # units of cycles/pixel temporal_freq_hz = 1.0, orientation = 45.0 )
def get_str(xx, const=0): class_by_key = {} done_parameters_and_defaults = [] classes = VisionEgg.recursive_base_class_finder(xx) # Fill self.parameters with parameter names and set to default values for klass in classes: if klass == object: continue # base class of new style classes - ignore if const: pd = klass.constant_parameters_and_defaults else: pd = klass.parameters_and_defaults if pd not in done_parameters_and_defaults: for parameter_name in pd.keys(): class_by_key[parameter_name] = klass done_parameters_and_defaults.append(pd) ks = class_by_key.keys() ks.sort() if len(ks): out_strs = [] if not const: out_strs.append('Parameters\n') out_strs.append('==========\n') else: out_strs.append('Constant Parameters\n') out_strs.append('===================\n') # pass 1: max_len = 0 for param_name in ks: max_len = max(max_len, len(param_name)) for param_name in ks: klass = class_by_key[param_name] if const: p = klass.constant_parameters_and_defaults else: p = klass.parameters_and_defaults if len(p[param_name]) > 3: if p[param_name][ 3] == VisionEgg.ParameterDefinition.DEPRECATED: continue type_str = param_name default = p[param_name][0] ve_type = p[param_name][1] if len(p[param_name]) > 2: description = p[param_name][2] + ' ' else: description = '' out_strs.append( '%s -- %s(%s)\n' % (param_name.ljust(max_len), description, str(ve_type))) if xx != klass: if klass.__module__ != xx.__module__: mod_name = '%s.' % klass.__module__ else: mod_name = '' out_strs.append(' ' * (max_len + 4) + 'Inherited from %s%s\n' % ( mod_name, klass.__name__, )) tmp = str(default).split('\n') if default is None: tmp = ['(determined at runtime)'] if len(p[param_name]) > 3: if p[param_name][ 3] == VisionEgg.ParameterDefinition.OPENGL_ENUM: if default is None: gl_name = '(GL enum determined at runtime)' else: gl_name = str(default) tmp = [gl_name] out_strs.append(' ' * (max_len + 4) + 'Default: ' + tmp[0] + '\n') if len(tmp) > 1: for i in range(1, len(tmp)): out_strs.append(' ' * (max_len + 13) + tmp[i] + '\n') return out_strs