Jeremy Gray | 28 Feb 18:31 2015
Picon

pyglet 1.2.1: pyglet.font.load error on travis-ci (linux)

Congrats on the recent release of 1.2! Thats a huge milestone. It will be a great help to me going forward to have this available.

Mostly the transition has been smooth for me, but I get an unexpected error when testing code on travis-ci that I don't get when testing on Mac OS 10.9, or on travis with pyglet 1.1.4. My code, typically called with font = '"" but I also tried "Helvetica"

    self._font = pyglet.font.load(font, int(self._heightPix), dpi=72, italic=self.italic, bold=self.bold)

leads down into pyglet, eventually to:

    def _add_to_search_cache(self, search_pattern, result_pattern):
        self._search_cache[(search_pattern.name,  
                                     search_pattern.size, 
                                     search_pattern.bold, 
                                     search_pattern.italic)] = result_pattern
        if len(self._search_cache) > self._cache_size:
            self._search_cache.popitem(last=False).dispose()

AttributeError: 'tuple' object has no attribute 'dispose'

Any ideas how I can fix this? Thanks.

--Jeremy

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
Garo Atberger | 25 Feb 21:20 2015
Picon

Setting an irregular image grid or drawing a specific sprite from a spritesheet

Hello there, I've started using Pyglet a few months ago in an effort to make a small shoot 'em up game. So far the simple things haven't proven an issue to me, until recently when I wanted to draw something from a specific spritesheet. The docs pointed me to image grids, but I was unsure.

The sprite sheet has multiple sprites with various sizes, and I've had trouble finding a solution to draw a specific one from the lot. Is there an efficient way to do that?

- Garo

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
Shane Kerr | 25 Feb 17:33 2015
Picon

www.pyglet.org for 1.2.1 release

Hello,

Congratulations on the recent release!

I was about to dig into the documentation, and noticed that it still refers to 1.1.4 as the current release and 1.2 as the development release:

http://www.pyglet.org/documentation.html

Probably this should be updated to refer to 1.2.1 as the current release, and 1.3 as the development release. Perhaps it makes sense to also include a link to the 1.1.4 documentation since 1.2 is quite fresh. ;)

Other minor changes:
  • The "news" section should probably have an entry for the 1.2.1 release too:
    http://www.pyglet.org/news.html
  • The "download" page should be updated to 1.2.1 as well:
    http://www.pyglet.org/download.html
Anyway, congratulations again. I hope to have time to play with the new release soon. :)

Cheers,

--
Shane

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
Da, Jose Luis | 25 Feb 17:33 2015

Help with getting mouse input

Hi all, 

I am using pyglet to develop a series of visual stimuli. I have some problems with my code, could you help me understand what I am doing wrong?

I have attached a part of the code I am using, the main file is called "150121_Plaid_v19", and "rlabs_libutils" is a library of some functions, one of which I will explain next.
In lines 190 - 258 I have the stimulus loop (or game loop) and for each iteration I need to retrieve the subject's input and save it in an array. In order to do that, I use the function 'my_dispatch_events', which I call in line 204 with the pyglet window and an instance of a class called LastEvent() that I defined.

With this method, I lose some of the data. Could you help me understand what would be a good method of retrieving input events and saving them for each iteration of the game loop, while using as few global variables as possible (I would like to keep the pyglet window instance as a local variable)?.

Thank you very much for your attention,
jl

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
import os, sys

lib_path = os.path.abspath(os.path.join('..','_Libraries'))
sys.path.append(lib_path)

from rlabs_libtobii import EyetrackerBrowser, MyTobiiController             # this is OUR library for the tobii eyetracker
from rlabs_libutils import *

from pyglet.window import Window
from pyglet.gl import *                                                     # to change the color of the background
from pyglet import clock

import time                                                                 # for the while loop
from numpy.random import permutation as np_permutation                      # for random trials

def main(ExpName = 'Plaid_v19', subjectname = ''):
    ######################################################
    ## Load parameters
    ######################################################
    if getattr(sys, 'frozen', False):                                       # path is different
        application_path = os.path.dirname(sys.executable)                  # if its an executable
    elif __file__:                                                          # or a Python script,
        application_path = os.path.dirname(__file__)                        # look for it

    # config_name = "config_file"                                             # Name of the config file
    # trials_name = "trials_file"                                             # Name of the trials file
    
    # config_name_full = os.path.join(application_path, config_name)  # Full path name of the config file
    # trials_name_full = os.path.join(application_path, trials_name)  # Full path name of the trials file

    from config_file import (aperture_color,numTheta,apertureDiv,               # import config parameters
        red_color, cyan_color, stereo1, stereo2, fixp_color, surrp_color, 
        time_fixp, framerate, FPsize, fg_color, aperture_switch, forced,aperture_radius,
        testing_with_eyetracker, randomize_trials, fixYN)

    from trials_file import (numtrials,mylambda1, duty_cycle1, orientation1,    # import trials parameters
        speed1, mylambda2, duty_cycle2, orientation2, speed2, timeCurrentTrial)

    if forced:                                                                  # read forced transitions file
        transfilename = 'datatestN_NR_5_trans.txt'
        # transfilename_full = os.path.join(application_path, transfilename)      # Full path name of the
transition file
        # transTimeL, transTimeR = read_forced_transitions(transfilename)
        transTimeL, transTimeR = read_forced_transitions(transfilename=transfilename)
        timeRamp = 0.5
    else:
        deltaX1 = 0
        deltaX2 = 0

    ## randomize trials ?
    if randomize_trials:
        trials_array = np_permutation(numtrials) # goes from 0 to numtrials in random order
    else:
        trials_array = range(numtrials) # no random


    ######################################################  
    ## Create Pyglet Window
    ######################################################
    screens = pyglet.window.get_platform().get_default_display().get_screens()
    if aperture_switch:
        allowstencil = pyglet.gl.Config(stencil_size = 8,double_buffer=True)
        MyWin = Window(config=allowstencil,fullscreen=True,screen=screens[0], visible = 0) # Create window
(not visible for now)
    else:
        MyWin = Window(fullscreen=True,screen=screens[0], visible = 0)

    xcenter = MyWin.width/2
    ycenter = MyWin.height/2

    clock.set_fps_limit(framerate)                                          # set limit for frames per second
    frameMs = 1000.0/framerate                                              # manual frame rate control: frameMs is the time in ms a frame will be displayed
    
    ######################################################  
    ## Initialize variables for data file
    ######################################################
    
    # Name of the data files
    filename_fordata   = os.path.join('data',("Plaid_v19" + "-" + time.strftime("%y.%m.%d_%H.%M",
time.localtime()) + "_" + subjectname + "_" + "data" + ".txt"))
    filename_rawdata   = os.path.join('data',("Plaid_v19" + "-" + time.strftime("%y.%m.%d_%H.%M",
time.localtime()) + "_" + subjectname + "_" + "rawd" + ".txt"))
    eyetrackeroutput   = os.path.join('data',("Plaid_v19" + "-" + time.strftime("%y.%m.%d_%H.%M",
time.localtime()) + "_" + subjectname + "_" + "eyet" + ".txt"))
    eyetrackeroutput2  = os.path.join('data',("Plaid_v19" + "-" + time.strftime("%y.%m.%d_%H.%M",
time.localtime()) + "_" + subjectname + "_" + "etvg" + ".txt"))
    
    right_keys  = [4, 109, 110, 106] # right click, M, N, J                 # array with ascii codes for right keys
    left_keys   = [1, 122, 120, 115] # left click, Z, X, S                  # array with ascii codes for left keys
    
    lastevent = LastEvent()                                                 # LastEvent() is defined in rlabs_libutils
    data_struct = DataStruct()                                              # DataStruct() is defined in rlabs_libutils

    # 3.4 - Initialize text to be shown at startup (not whown right now)
    textInstruc = "Continually report the motion of the grating in front.\nPress the left mouse button for
left-ward motion.\nPress the right mouse button for right-ward motion\n\nClick mouse-wheel to start"
    # Use the mouse buttons to indicate the direction of the plaid in front.\n\nClick mouse-wheel to start"
    # textInstruc = "Use the mouse buttons to indicate the direction of the plaid in front.\n\nClick
mouse-wheel to start"
    lbl_instr = pyglet.text.Label(text=textInstruc, font_name=None, font_size=36, bold=False,
italic=False, 
        color=(0, 0, 0, 255), x = 100, y = MyWin.height/1.5, width=1400, height=None, 
        anchor_x='left', anchor_y='baseline', halign='left', multiline=True, dpi=None, batch=None, group=None)

    textInstruc2 = "Click mouse-wheel for next trial"
    lbl_instr2 = pyglet.text.Label(text=textInstruc2, font_name=None, font_size=24, bold=False,
italic=False, 
        color=(0, 0, 0, 255), x = MyWin.width/2 - 200, y = MyWin.height/2.4, width=1400, height=None, 
        anchor_x='left', anchor_y='baseline', halign='left', multiline=True, dpi=None, batch=None, group=None)


    if testing_with_eyetracker:
        ######################################################
        ## Create an EyetrackerBrowser and display it
        ###################################################### 
        eb = EyetrackerBrowser()
        eb.main()

        ######################################################  
        ## Initialize controller (MyTobiiController)
        ######################################################
        controller = MyTobiiController(datafilename=eyetrackeroutput, vergdfn = eyetrackeroutput2)       #
create controller
        controller.waitForFindEyeTracker()                                  # wait to find eyetracker
        controller.activate(controller.eyetrackers.keys()[0])               # activate eyetracker
    

    ######################################################  
    ## Start trials
    ######################################################

    if testing_with_eyetracker:
        controller.startTracking()                                                              # start the eye tracking recording
        time.sleep(0.2)                                                                         # wait for the eytracker to warm up
        controller.recordEvent("{0}\t{1}\t{2}".format('InfoEvent','ExpName',ExpName))           # write event to
eyetracker data file: expname
        controller.recordEvent("{0}\t{1}\t{2}".format('InfoEvent','SubjectName',subjectname))   #
write event to eyetracker data file: subjectname

    MyWin.set_visible(True)                                                 # set window to visible
    MyWin.set_mouse_visible(False)                                          # set mouse to not visible
    timeStart_general = time.time()                                         # get general start time
    
    for trial_counter in range(numtrials):                                  # for each trial 

        ######################################################  
        ## Prepare variables before stimulus loop
        ######################################################
        
        trial = trials_array[trial_counter]

        # read from trials

        apertRad_pix = MyWin.height / apertureDiv
        
        grating11 = Grating(MyWin, mycoords(0,0, MyWin).x + stereo1, mycoords(0,0, MyWin).y, red_color,
orientation1[trial], mylambda1[trial], duty_cycle1, apertRad_pix, speed1)
        grating12 = Grating(MyWin, mycoords(0,0, MyWin).x - stereo1, mycoords(0,0, MyWin).y, cyan_color,
orientation1[trial], mylambda1[trial], duty_cycle1, apertRad_pix, speed1)
        grating21 = Grating(MyWin, mycoords(0,0, MyWin).x + stereo2, mycoords(0,0, MyWin).y, red_color,
orientation2[trial], mylambda2[trial], duty_cycle2, apertRad_pix, speed2)
        grating22 = Grating(MyWin, mycoords(0,0, MyWin).x - stereo2, mycoords(0,0, MyWin).y, cyan_color,
orientation2[trial], mylambda2[trial], duty_cycle2, apertRad_pix, speed2)
        
        # grating11 = GratingHORIZONTAL(MyWin, mycoords(0,0, MyWin).x + stereo1, mycoords(0,0, MyWin).y,
red_color, orientation1[trial], mylambda1[trial], duty_cycle1, apertRad_pix, speed1)
        # grating12 = GratingHORIZONTAL(MyWin, mycoords(0,0, MyWin).x - stereo1, mycoords(0,0, MyWin).y,
cyan_color, orientation1[trial], mylambda1[trial], duty_cycle1, apertRad_pix, speed1)

        ######################################################  
        ## Wait for go Loop
        ######################################################
        while not wait_for_go_function(MyWin,lastevent) and not MyWin.has_exit:
            glClearColor(fg_color[0],fg_color[1],fg_color[2],1)             # set background color
            MyWin.clear()                                                   # clear window
            
            if trial_counter == 0:                                          # if first trial,
                lbl_instr.draw()                                            # show instructions
            
            else:                                                           # for the rest show fixation point
                lbl_instr2.draw()                                            # show instructions
                drawCircle(xcenter, ycenter, numTheta, FPsize * 4, surrp_color)
                drawCircle(xcenter, ycenter, numTheta, FPsize, fixp_color)
                


            
            MyWin.flip()                                                    # flip window


        ######################################################  
        ## Start stimulus loop
        ######################################################

        # Initialize forced variables
        if forced:
            i_R = 0
            i_L = 0
            Ron = 0
            Lon = 0
            timeTransR = transTimeL[0]
            timeTransL = transTimeR[0]
            deltaXaux1 = 0
            deltaXaux2 = 0


        timeStart = time.time()                                             # get trial start time
        
        if testing_with_eyetracker:                                         # write START trial to log file
            controller.recordEvent("{0}\t{1}\t{2}".format('TrialEvent',trial,'START'))     # write event to
eyetracker data file

        while (time.time() - timeStart) < timeCurrentTrial and not MyWin.has_exit:
            
            timeNow = time.time()                                           # get current time

            startMs = clock.tick()                                          # manual frame rate control: time point when frame starts. Also needed to show fps

            glClearColor(fg_color[0],fg_color[1],fg_color[2],1)             # set background color
            MyWin.clear()                                                   # clear window
            MyWin.dispatch_events()                                         # dispatch window events (very important call)

            ######################################################  
            ## Retrieve subject input and save it to data arrays
            ######################################################
            # MyWin.dispatch_events()
            lastevent = my_dispatch_events(MyWin, lastevent)                # my_dispatch_events is defined in rlabs_libutils
                                                                            # last event subject has triggered, will remain the same until subject triggers another event
            # write last event to data arrays
            if lastevent.type != []:                                        # if there's an event, save it

                save_data_to_arrays(lastevent, data_struct, trial, timeNow) # save_data_to_arrays is defined in rlabs_libutils
                
                if testing_with_eyetracker: 
                    controller.recordEvent("{0}\t{1}\t{2}".format('InputEvent', lastevent.type, lastevent.id))     #
write event to eyetracker data file

                lastevent.reset_values()                                    # reset values of event
                

            ######################################################  
            ## Update position of objects
            ######################################################

            if forced:
                stereo1, stereo2, i_R, i_L, Ron, Lon, timeTransR, timeTransL, deltaXaux1, deltaXaux2 =
compute_forced_values(i_R, i_L, Ron, Lon, timeTransR, timeTransL, deltaXaux1, deltaXaux2,
timeRamp, timeStart, timeNow, transTimeL, transTimeR)
            else:
                stereo1 = stereo1
                stereo2 = stereo2

            grating11.update_position(timeStart, stereo1)
            grating12.update_position(timeStart, stereo2)
            grating21.update_position(timeStart, stereo2)
            grating22.update_position(timeStart, stereo1)
            
        
            ######################################################  
            ## Draw objects
            ######################################################
            glEnable(GL_BLEND)
            
            drawAperture(xcenter, ycenter, apertRad_pix, aperture_color, numTheta)

            grating11.draw()
            grating12.draw()
            grating21.draw()
            grating22.draw()
            
            glDisable(GL_BLEND)
            if fixYN:
                drawCircle(xcenter, ycenter, numTheta, FPsize * 4, surrp_color)
                drawCircle(xcenter, ycenter, numTheta, FPsize, fixp_color)

            fps.draw()


            ######################################################  
            ## Flip the window
            ######################################################
            MyWin.flip()                                                    # flip window

            endMs = clock.tick() # manual frame rate control: time point when frame ends.
            # delaytime = frameMs - (endMs-startMs) # manual frame rate control: time time frame must be frozen.


        if testing_with_eyetracker:                                         # write END trial to log file
            controller.recordEvent("{0}\t{1}\t{2}".format('TrialEvent',trial,'END'))     # write event to
eyetracker data file

        if MyWin.has_exit:                                                  # This breaks the For stimulus loop. 
            break                                                           # Data is not lost, it has already been saved in the arrays.


    ###############################################################  
    ## Stop eyetracker processes, save data and close pyglet window
    ###############################################################
    if testing_with_eyetracker:
        controller.stopTracking()                                           # stop eye tracking and write output file
        controller.destroy()                                                # destroy controller

    save_raw_data(filename_rawdata, data_struct)                            # save raw data
    save_data_formatted(filename_fordata,data_struct,right_keys,left_keys)  # save formatted data

    MyWin.close()                                                           # close pyglet window


    ######################################################  
    ## 
    ######################################################

if __name__ == '__main__':
    print 'running 150121_Plaid_v19'

    if len(sys.argv) > 1:                           # optional: add a subject name
        subjectname = sys.argv[1]                   # run as python Plaid_v19 subjectname
    else:
        subjectname = 'defaultsubjectname'

    fps = pyglet.clock.ClockDisplay(color=(1,1,1,1)) # show frames per second
    main(subjectname = subjectname)
    
import math 						# for the circle
from pyglet.gl import *				# for the circle
import time 						# for the update method of the gratings
import csv          				# for reading the forced transition file
import os, stat                     # to create read-only file
########################################
## Data management functions and classes
########################################

class DataStruct(object):
    
    def __init__(self):

        self.eventsCounter       = [0]
        self.event_counter_array = []
        self.time_array          = []
        self.event_type_array    = []
        self.ID_array            = []
        self.trial_index_array   = []

class LastEvent():
	def __init__(self):
		self.type 	 = []
		self.id 	 = []
		self.counter = []

	def reset_values(self):
		self.type 	 = []
		self.id 	 = []
		self.counter = []

def save_data_to_arrays(lastevent, data_struct, trial, timeNow):
	"""
	Appends each new event of an instance of the class 
	LastEvent() to the correspondent array of an instance 
	of the the class LastEvent()
	
	arguments
		- lastevent: 	instance of LastEvent class
		- data_struct: 	instance of DataStruct class
		- trial:		number of the current trial
		- timeNow:		call to time.time() 
		
	returns
		Nothing -- data_struct will be updated

	"""
    # add event data to arrays
	data_struct.eventsCounter[0] += 1
	data_struct.event_counter_array.append(data_struct.eventsCounter[0])
	data_struct.time_array.append(timeNow)
	data_struct.event_type_array.append(lastevent.type) 
	data_struct.ID_array.append(lastevent.id)
	data_struct.trial_index_array.append(trial)        

def save_raw_data(rawdata_filename, data_struct):
	# """
	# Save contents of data_struct to output file
	# arguments
	# 	- rawdata_filename: name of output file
	# 	- data_struct: 		instance of DataStruct class
		
	# returns
	# 	Nothing --
    #"""
    timeStampStart = 0#data_struct.time_array[0]



    length = len(data_struct.event_counter_array)
    with open(rawdata_filename, 'w' ) as txtfile:
        for i in range(length):
            txtfile.write(str(data_struct.event_counter_array[i]) +'\t'+
str(data_struct.trial_index_array[i]) +'\t'+
str((data_struct.time_array[i]-timeStampStart)) +'\t'+ str(data_struct.event_type_array[i]) +'\t'+str(data_struct.ID_array[i])+'\n')
    # print("raw data saved")

    os.chmod(rawdata_filename,stat.S_IREAD) # make file read only

    pass

def save_data_formatted(data_namefile, data_struct, right_keys, left_keys):
	# """
	# Save contents of data_struct to output file in HARDCODED format.
	
	# Format is:
	# 1 	- right key down (pressed)
	# 2	- right key up (released)
	# -1	- left  key down (pressed)
	# -2	- left key up (released)
	
	# arguments
	# 	- rawdata_filename: 	name of output file
	# 	- data_struct: 			instance of DataStruct class
	# 	- right_keys:			array with ascii codes for right keys
	# 	- left_keys:			array with ascii codes for left keys
	# returns
	# 	Nothing --
	# """

    timeStampStart = 0#data_struct.time_array[0]

    length = len(data_struct.event_counter_array)
    with open(data_namefile, 'w' ) as txtfile:
        
    	for i in xrange(0,length,1): # equal to for(i = 1, i <length, < i++)
            
    		# this will look at the last two characters of the current event_type_array and will determine if it is up
or down
    		isdown  =
(data_struct.event_type_array[i][len(data_struct.event_type_array[i])-2:len(data_struct.event_type_array[i])]
== "DW")
    		isup    =
(data_struct.event_type_array[i][len(data_struct.event_type_array[i])-2:len(data_struct.event_type_array[i])]
== "UP")
            
            
    		if   (data_struct.ID_array[i] in right_keys) and (isdown):
    			code = 1
    			pass
            
    		elif (data_struct.ID_array[i] in right_keys) and (isup):
    			code = 2
            
    		elif (data_struct.ID_array[i] in left_keys) and (isdown):
    			code = -1
    			pass
            
    		elif (data_struct.ID_array[i] in left_keys) and (isup):
    			code = -2
            
    		else: # key not in right and left arrays
    			code = 999 
            

            # data file
            # ToDo: put a column for number of trials too
    		txtfile.write(str(data_struct.event_counter_array[i]) +'\t'+
str(data_struct.trial_index_array[i]) +'\t'+
str((data_struct.time_array[i]-timeStampStart)) +'\t'+ str(code) +'\n')
 
    os.chmod(data_namefile,stat.S_IREAD) # make file read only
	# print("formatted data saved")
 
    pass

def write_data_file(data_namefile, data_struct):

    # fields in header:
    fields = ['Timestamp', 'EventType', 'EventID', 'EventValue']

    timeStampStart = data_struct.time_array[0]      
   
    with open(data_namefile, 'w' ) as f:            # open or create text file 'filename' to append             
        f.write('\t'.join(fields)+'\n')             # write header. Separate the fields into tabs

        length = len(data_struct.event_counter_array)

        for i in range(length):
            f.write(''.format())
            txtfile.write(str(data_struct.event_counter_array[i]) +'\t'+
str(data_struct.trial_index_array[i]) +'\t'+
str((data_struct.time_array[i]-timeStampStart)) +'\t'+ str(data_struct.event_type_array[i]) +'\t'+str(data_struct.ID_array[i])+'\n')

            
    os.chmod(data_namefile,stat.S_IREAD) # make file read only


    pass



def create_unique_name(subject_info):
    
    ## Create output data file name
    
    # Get subject and time information
    exp_name = 'pythonMigration'
    time_string = time.strftime("%y.%m.%d_%H.%M.%S", time.localtime())
    subject_name = subject_info["Name"]
    
    textfilename = (exp_name + '_' + subject_name + '_' + time_string + '.txt')
    
    # Save output file in the folder "data".
    # following command will create the native file separator caracter. e.g.: '\' for windows
    out_file_name = os.path.join('data', textfilename) 

    return out_file_name    

########################################
## 
########################################

def my_dispatch_events(mywindow, event):
	"""
	Appends each new event of an instance of the class 
	LastEvent() to the correspondent array of an instance 
	of the the class LastEvent()
	
	arguments
		- mywindow: instance of a pyglet Window class
		- event: instance of LastEvent class
		
	returns
		- event: event will be updated

	"""
	 <at> mywindow.event
	def on_key_press(symbol, modifiers): 
		event.type       = "Key_DW"
		event.id         = symbol
        # event.counter    += 1

	 <at> mywindow.event
	def on_key_release(symbol, modifiers):
		event.type       = "Key_UP"
		event.id         = symbol
        # event.counter    += 1

	 <at> mywindow.event
	def on_mouse_press(x, y, button, modifiers):
		event.type       = "Mouse_DW"
		event.id         = button
        # event.counter    += 1

	 <at> mywindow.event
	def on_mouse_release(x, y, button, modifiers):
		event.type       = "Mouse_UP"
		event.id         = button
        # event.counter    += 1

    
	 <at> mywindow.event
	def on_close():
		# The closing of the window is taken care in the while loop
		pass
	return event

def wait_for_go_function(mywindow, event, expected_type = 'Mouse_UP', expected_id = 2):
    
    wait_for_go = 0
    
    mywindow.dispatch_events()
    event = my_dispatch_events(mywindow,event)

    # Calculate condition for "go", for example:
    #  -the mouse was clicked (any key), OR
    #  -SPACE key was pressed (ASCII 32 key)
    # if (event.type == "Key_DW" and event.id == 32) or (event.type=="Mouse_UP"):
        # wait_for_go = 1

    # Calculate condition for "go", for example:
    # Default: when mouse-wheel is released
    if (event.type == expected_type and event.id == expected_id):
        wait_for_go = 1

	event.reset_values()
            
    return wait_for_go
    pass    

def my_on_close(mywindow):
    # Save data +do whatever other pre-exit cleanup necessary
    print("closed nicely")   
    mywindow.clear()
    mywindow.close()


########################################
## Stimulus functions and classes
########################################

def drawCircle(x, y, numTheta = 90, radius = 100, circle_color = (0,0,0)):

    deltaTheta = 2 * math.pi / numTheta

    glColor3f( circle_color[0] , circle_color[1], circle_color[2])
      
    for i in range (0, numTheta):
        cx1 = x + radius * math.sin(deltaTheta * i)
        cy1 = y + radius * math.cos(deltaTheta * i)
        cx2 = x + radius * math.sin(deltaTheta * (i+1))
        cy2 = y + radius * math.cos(deltaTheta * (i+1))
          
        glBegin( GL_TRIANGLES )
        glVertex2f(x, y )
        glVertex2f(cx1 , cy1 )
        glVertex2f(cx2 , cy2 )
        glEnd()

def drawGrating(x, y, fill_color, orientation, mylambda, duty_cycle, apertRad_pix):
     
    bar_length = 1000
 
    radio_aux = (2 * apertRad_pix) + mylambda #diameter 
    num_bars = int(1 + math.floor(radio_aux / mylambda))+3
   
    glStencilFunc (GL_EQUAL, 0x1, 0x1) 
    glStencilOp (GL_KEEP, GL_KEEP, GL_KEEP)
         
    glLoadIdentity() #replace current matrix with the identity matrix
    glTranslatef(x, y, 0)
    glRotatef(orientation,0,0,1)    
    glTranslatef(-x, -y, 0)
 
    glColor3f(fill_color[0] , fill_color[1], fill_color[2] )
     
    glBlendFunc(GL_ZERO, GL_SRC_COLOR)  
     
    for i in range(int(-num_bars/2),int(num_bars/2)):    
         
        x1 = mylambda * i + x
        x2 = (duty_cycle * mylambda) + (mylambda * i + x)
         
        glBegin(GL_QUADS)
         
        glVertex2f(x1, y - bar_length) 
        glVertex2f(x1, y + bar_length) 
        glVertex2f(x2, y + bar_length) 
        glVertex2f(x2, y - bar_length)
         
        glEnd()
     
    # glRotatef(-orientation, 0, 0, 1)#Is it necessary?
    glBlendFunc(GL_ONE, GL_ZERO)
    glLoadIdentity()
    pass

def drawAperture(x0_pix, y0_pix, radius_pix, color, numTheta):

    # Enable stencil
    glClearStencil(0x0)
    glEnable(GL_STENCIL_TEST) 
        
    #define the region where the stencil is 1
    glClear(GL_STENCIL_BUFFER_BIT)
    glStencilFunc(GL_ALWAYS, 0x1, 0x1) #Always pass stencil functions test
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE) #Replace stencil value with reference value
    
    drawCircle(x0_pix, y0_pix, numTheta, radius_pix, color)
    pass


class Grating():
    def __init__(self, MyWin, x, y, fill_color, orientation, mylambda, duty_cycle, apertRad_pix, speed):
        self.x            = x
        self.y            = y
        self.fill_color   = fill_color
        self.orientation  = orientation
        self.mylambda     = mylambda
        self.duty_cycle   = duty_cycle
        self.apertRad_pix = apertRad_pix
        self.speed        = speed

        # decide if horizontal or vertical motion, depending on orientation:
        # self.threshold_angle = 50
        # if orientation < self.threshold_angle:
        #     self.motion_cycle = mylambda/(math.cos(math.radians(orientation)))
        #     self.initialpos = x
        # elif orientation >= self.threshold_angle:
        #     self.motion_cycle = mylambda/(math.sin(math.radians(orientation)))
        #     self.initialpos = y
        #     # self.initialpos = MyWin.width/2 - apertRad_pix - mylambda/2
        self.motion_cycle = mylambda/(math.cos(math.radians(orientation)))
        self.initialpos = x
 
        pass
     
    def draw(self):
        x            = self.x
        y            = self.y
        fill_color   = self.fill_color
        orientation  = self.orientation
        mylambda     = self.mylambda
        duty_cycle   = self.duty_cycle
        apertRad_pix = self.apertRad_pix
         
         
        bar_length = 1000
     
        radio_aux = (2 * apertRad_pix) + mylambda #diameter 
        num_bars = int(1 + math.floor(radio_aux / mylambda))+3
       
        glStencilFunc (GL_EQUAL, 0x1, 0x1) 
        glStencilOp (GL_KEEP, GL_KEEP, GL_KEEP)
             
        glLoadIdentity() #replace current matrix with the identity matrix
        glTranslatef(x, y, 0)
        glRotatef(orientation,0,0,1)    
        glTranslatef(-x, -y, 0)
     
        glColor3f(fill_color[0] , fill_color[1], fill_color[2] )
         
        glBlendFunc(GL_ZERO, GL_SRC_COLOR)  
         
        for i in range(int(-num_bars/2),int(num_bars/2)):    
             
            x1 = mylambda * i + x
            x2 = (duty_cycle * mylambda) + (mylambda * i + x)
             
            glBegin(GL_QUADS)
             
            glVertex2f(x1, y - bar_length) 
            glVertex2f(x1, y + bar_length) 
            glVertex2f(x2, y + bar_length) 
            glVertex2f(x2, y - bar_length)
             
            glEnd()
         
        # glRotatef(-orientation, 0, 0, 1)#Is it necessary?
        #glBlendFunc(GL_ONE, GL_ZERO) #150116 comment out NR
        glLoadIdentity()
        pass
     
    def update_position(self, runningTime, stereo):
        motion_cycle = self.motion_cycle
        speed        = self.speed
        initialpos   = self.initialpos
         
        timeNow = time.time()

        position = initialpos + stereo

        self.x = position + math.fmod(speed*(timeNow-runningTime), motion_cycle)
        # if self.orientation < self.threshold_angle:
        #     self.x = position + math.fmod(speed*(timeNow-runningTime), motion_cycle)
        # elif self.orientation >= self.threshold_angle:
        #     self.y = initialpos + math.fmod(speed*(timeNow-runningTime), motion_cycle)

        pass
     
    pass    

class mycoords():
    # OpenGL coordinate system (0,0) is at the bottom left of the screen
    # this funciton makes the cordinate system at the center of the scree
    def __init__(self,x,y,window):
        self.x = x + window.width/2
        self.y = y + window.height/2

########################################
## Forced mode functions
########################################
def read_forced_transitions(transfilename='datatestN_NR_5_trans.txt'):
	transfilename = 'datatestN_NR_5_trans.txt'
    #forced = 1
	deltaXaux1_ini = 0
	deltaXaux2_ini = 0
	deltaX1 = 0.01
	deltaX2 = 0.01
	# transfilename = 'datatestN_NR_5_trans.txt'
	# transfilename_full = os.path.join(application_path, transfilename)	# Full path name of the
transition file
	# 5.1 - Read file with transition time stamps (for forced mode)
	transTimeL = []
	transTimeR = []
    
	try:                                                            # try/except is used here to handle errors such 
		with open(transfilename, 'r') as f:                 # as the transition file name is wrong
        #with open(transfilename) as f:
        #with open('trans.txt') as f: 
			reader=csv.reader(f,delimiter='\t')                     # reader is a csv class to parse data files
        
			for L_item,R_item in reader:                            #L_item and R_item are the time stamps
            #for R_item,L_item in reader:                            #L_item and R_item are the time stamps
                #L_array.append(float(L_item))                              # Append time stamps to array
                #R_array.append(float(R_item))
				transTimeL.append(float(L_item))                              # Append time stamps to array
				transTimeR.append(float(R_item))
        
        #L_array.append(timeTrialMax)                                # Append total duration of trial at the end?
        #R_array.append(timeTrialMax)
                
        #timeTransL = L_array[0]        
        #timeTransR = R_array[0]
        # timeRamp = 0.5
        
        
        
	except EnvironmentError:
        #print srt(transfilename)+' could not be opened'
		print "transition file could not be opened"
		sys.exit()
    
	return transTimeL,transTimeR       

def compute_forced_values(i_R, i_L, Ron, Lon, timeTransR, timeTransL, deltaXaux1, deltaXaux2,
timeRamp, timeStartTrial,timeNow, transTimeL, transTimeR, deltaX1=0.01, deltaX2=0.01,
deltaXaux1_ini=0, deltaXaux2_ini=0):
	# Apply forced mode changes to the stereo
    # Moving the Depth
    scale = 500

    if (timeNow - timeStartTrial > timeTransR) & (timeNow - timeStartTrial < timeTransR + timeRamp):
        
        deltaXaux1 = deltaX1 * (timeNow - timeStartTrial - timeTransR) / timeRamp
        Ron = 1
        
        if deltaXaux2_ini > deltaX2/2:
            deltaXaux2 = deltaX2 - deltaX2 * (timeNow - timeStartTrial - timeTransR) / timeRamp
        
        deltaXaux1_ini = deltaXaux1
        
    if (timeNow - timeStartTrial > timeTransR + timeRamp) & (Ron == 1):
        Ron = 0
        i_R = i_R + 1
        timeTransR = transTimeR[i_R]
    # print timeTransR
        
    if (timeNow - timeStartTrial > timeTransL) & (timeNow - timeStartTrial < timeTransL + timeRamp):
        
        deltaXaux2 = deltaX2 * (timeNow - timeStartTrial - timeTransL) / timeRamp
        Lon = 1
        
        if (deltaXaux1_ini > deltaX1/2):
            deltaXaux1 = deltaX1 - deltaX1 * (timeNow - timeStartTrial - timeTransL) / timeRamp
        
        deltaXaux2_ini = deltaXaux2
    
    if (timeNow - timeStartTrial > timeTransL + timeRamp) & (Lon == 1):
        Lon = 0
        i_L = i_L + 1
        timeTransL = transTimeL[i_L]
    
    # update stereo value
    stereo1 = (-deltaXaux1/2 + deltaXaux2/2) * scale
    stereo2 =  (deltaXaux1/2 - deltaXaux2/2) * scale

    return stereo1, stereo2, i_R, i_L, Ron, Lon, timeTransR, timeTransL, deltaXaux1, deltaXaux2

########################################
## Not used
########################################
class Aperture():
    def __init__(self, color, numTheta, x0_pix, y0_pix, radius_pix):
        self.color      = color
        self.numTheta   = numTheta
        self.x0         = x0_pix
        self.y0         = y0_pix
        self.radius     = radius_pix
        pass
    
    def draw(self):
        color           = self.color
        numTheta        = self.numTheta
        x0_pix          = self.x0
        y0_pix          = self.y0
        apertRad_pix    = self.radius
        
        
        # Enable stencil
        glClearStencil(0x0)
        glEnable(GL_STENCIL_TEST) 
            
        #define the region where the stencil is 1
        glClear(GL_STENCIL_BUFFER_BIT)
        glStencilFunc(GL_ALWAYS, 0x1, 0x1) #Always pass stencil functions test
        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE) #Replace stencil value with reference value
        
        drawCircle(x0_pix, y0_pix, numTheta, apertRad_pix, color)
        pass
    
    pass



# if __name__ == '__main__':
# 	lastevent = LastEvent()
# 	lastevent.reset_values()
#     # main()
Kambiz Tavabi | 24 Feb 21:03 2015
Picon

Inconsistency detected by ld.so?!

I am running linuxmint17 (i.e., Ubuntu 14.04) on a 64bit machine and trying to work with pyglet version 1.2.0 with python 2.7.9. lsmod returns

snd_hda_codec_hdmi     46207  1 
snd_hda_codec_realtek    61438  1 
snd_usb_audio         153411  1 
snd_usbmidi_lib        29215  1 snd_usb_audio
snd_hda_intel          52355  6 
snd_hda_codec         192906  3 snd_hda_codec_realtek,snd_hda_codec_hdmi,snd_hda_intel
snd_hwdep              13602  2 snd_usb_audio,snd_hda_codec
snd_pcm               102099  4 snd_usb_audio,snd_hda_codec_hdmi,snd_hda_codec,snd_hda_intel
snd_page_alloc         18710  2 snd_pcm,snd_hda_intel
snd_seq_midi           13324  0 
snd_seq_midi_event     14899  1 snd_seq_midi
snd_rawmidi            30144  2 snd_usbmidi_lib,snd_seq_midi
snd_seq                61560  2 snd_seq_midi_event,snd_seq_midi
snd_seq_device         14497  3 snd_seq,snd_rawmidi,snd_seq_midi
snd_timer              29482  2 snd_pcm,snd_seq
snd                    69238  27 snd_hda_codec_realtek,snd_usb_audio,snd_hwdep,snd_timer,snd_hda_codec_hdmi,snd_pcm,snd_seq,snd_rawmidi,snd_usbmidi_lib,snd_hda_codec,snd_hda_intel,snd_seq_device,snd_seq_midi
soundcore              12680  1 snd


From what I can tell both pulseaudio and alsa drivers seem to be present. System sounds, and all audioplay back works except for the following:

import pyglet
src=pyglet.media.load('sound.wav')
src.play()

 Inconsistency detected by ld.so: dl-open.c: 689: _dl_open: Assertion `_dl_debug_initialize (0, args.nsid)->r_state == RT_CONSISTENT' failed!

What is that? Any ideas or fixes?

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
Rob | 20 Feb 21:07 2015
Picon

Pyglet 1.2.1 bugfix release

Hi all,

I uploaded a minor bugfix release:

Pyglet 1.2.1                                                                                        
============                                                                                        
Minor bugfix release. Fixes some issues on Linux.                                                   
                                                                                                    
Bugfixes                                                                                            
--------                                                                                            
- BB#18: X11: Events not processed while animating                                                  
- X11: on_resize event not triggered                                                                
- X11: Fix deletion of PulseAudioPlayer. 

Rob

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
Sebastian Meyer | 17 Feb 11:36 2015

pyglet for sound and KDE mixer (Linux) problem

Hi there!

I have a small project which uses pyQt for the GUI. It is OS-independent and I want to add some sound-notifacation on it.
After some searching I decided the best solution to have OS-independent sound-output is using pyglet for it. And it works great.

But there is one problem:
I'm using Linux with KDE and the mixer for adjusting the volume-level shows a modulator for every program that plays sound.
But for my programm it shows a new regulator everytime I use pyglet to play a sound. So after the first sound, there appears one, after the second there are two and so on.

I'm playing the sound as descripted here:
http://www.pyglet.org/doc/programming_guide/playing_sounds_and_music.html

Any ideas?

Cheers
Sebastian

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
Luke Miller | 17 Feb 01:41 2015
Picon

custom mouse image stutter in 1.2

I use window.set_mouse_cursor(cursor) to have a custom mouse cursor.

On 1.2alpha it runs fine, installing 1.2 the mouse seems to have the
slightest stutter about once a second. Switching back to 1.2alpha
fixes the problem. Not a big issue but flagging it here in case others
have noticed.

--

-- 
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.

Alessandro Re | 16 Feb 15:36 2015
Picon

Unable to handle events while animating

Hello,

I started recently to use cocos2d, but I had an issue. Since cocos uses pyglet, a very kind user translated my code to pure pyglet and the result is that, in pyglet, I am unable to process events while animation are running. If no animations are running, events are handled correctly by the callbacks, otherwise, it seems that events are randomly handled (with low probability of being handled).

The discussion about cocos, if you are interested, is here: https://groups.google.com/forum/#!topic/cocos-discuss/6uviIoGzII8

The pyglet code I'm talking about is the following: http://pastebin.com/W5vLtubk

If I run it, and I press some keys, the label is not updated.
If I comment the line "pyglet.clock.schedule(update_actor)", events are correctly handled and I can see pressed keys appearing.

Note that the code does not work in python2 either.
I am using Fedora Linux 21, Mesa drivers 10.4.3 for OpenGL, pyglet 1.2.0, python 3.4.1 or 2.7.8.
I also tried with pyglet from the repository, but result is the same.

Am I the only one with this issue? Looks something pretty weird.

Thanks in advance
~Ale

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
Rob | 12 Feb 19:10 2015
Picon

Pyglet 1.2.0

Hi all,

I just released Pyglet 1.2.0 into the wild. In case you cannot believe it, see it at: https://pypi.python.org/pypi/pyglet

The website still needs to be updated. Richard, can you help here?

Rob

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
Rob | 8 Feb 14:47 2015
Picon

Roadmap for 1.3.0

Hi all,

Hopefully 1.2.0 is almost ready to release. So we can start thinking about the next version. I was thinking about doing the following:

- Make the codebase compatible with both Py2 and Py3 by using future (starting with the tests)
- Improve the test code to run more automatic
- Improve test coverage
- Import fixes from Leif's fork
- Mark Carbon support deprecated
- Bugfixes, many bugfixes

There are also some other things we need to take care of:
- Finish migration to BitBucket
- Move documentation to rtfd
- Update the website for above

What are your thoughts?

Rob

--
You received this message because you are subscribed to the Google Groups "pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyglet-users+unsubscribe <at> googlegroups.com.
To post to this group, send email to pyglet-users <at> googlegroups.com.
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.

Gmane