% ColorGratingDemo
% ColorGratingDemo
%
% Make a full-color movie.
% To correct gamma, just load appropriate values into the CLUT.

% 4/13/98  dhb  Wrote it.
% 4/15/98  dgp  Simplified 'PixelSizes' test.
% 4/25/98  dgp  Replaced "255" by "white", "128" by "inc".
% 4/25/98  dgp  Deleted superfluous call to SetClut. Tightened up.
% 11/4/02 dgp Add comments about R,G,B.

% Define some parameters
frameSize = 31;				% Image size is 2*frameSize+1
nFrames = 32;					% Movie runs for 4*nFrames, without repeats
nCycles = 4;					% Repeats

% Check for limitation of Student Matlab
[c,maxElements]=computer;	
maxSize=floor(sqrt(maxElements));

% Open window in full-color mode
whichScreen=0;
pixelSizes=Screen(whichScreen,'PixelSizes');
if max(pixelSizes)<16
	fprintf('Sorry, I need a screen that supports 16- or 32-bit pixelSize.\n');
	return;
end
[window,screenRect]=Screen(whichScreen,'OpenWindow',0,[],max(pixelSizes));
white=WhiteIndex(window);
black=BlackIndex(window);
gray=(white+black)/2;
inc=white-gray;
Screen(window,'FillRect',gray);

fprintf('Building the images ... ');
win=zeros(2*nFrames);
[x,y]=meshgrid(-frameSize:frameSize,-frameSize:frameSize);
m=exp(-((x/(frameSize/2)).^2)-((y/(frameSize/2)).^2)).*sin(x*0.03*2*pi);
amp = linspace(0,inc,nFrames);
colorFrame = zeros([size(m) 3]);
colorFrame(:,:,3) = repmat(gray,size(m)); % don't modulate Blue
frameRect = [0 0 size(m)];
for i = 1:nFrames
	frame=amp(i)*m;
	colorFrame(:,:,1) = gray+frame; % modulate Red
	colorFrame(:,:,2) = gray-frame; % modulate Green in opposite sign
	win(i) = Screen(window,'OpenOffscreenWindow',0,frameRect);
	Screen(win(i),'PutImage',colorFrame);
	colorFrame(:,:,1) = gray-frame;
	colorFrame(:,:,2) = gray+frame;
	win(i+nFrames) = Screen(window,'OpenOffscreenWindow',0,frameRect);
	Screen(win(i+nFrames),'PutImage',colorFrame);
end
fprintf('Done.\n');

fprintf('Show the movie.\n');
rect = CenterRect(frameRect,screenRect);
HideCursor;
for j = 1:nCycles
	for i = [1:nFrames, nFrames-1:-1:1, nFrames+1:2*nFrames, 2*nFrames-1:-1:nFrames+1]
		Screen(window,'WaitBlanking');
		Screen('CopyWindow',win(i),window,frameRect,rect);
	end
end
ShowCursor;
Screen('CloseAll');
