-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
screenManager.m
2239 lines (2088 loc) · 76.8 KB
/
screenManager.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% ========================================================================
%> @class screenManager
%> @brief screenManager — manage opening and configuring the PTB screen
%>
%> screenManager manages the (many!) PTB screen settings. You can set many
%> properties of this class to control PTB screens, and use it to open and
%> close the screen based on those properties. This class controls the
%> transformation from degrees into pixels, and it can offset the screen
%> co-ordinates (i.e. you can set a global X and Y position offset, to a
%> screen position and then all other positions will be relative to this
%> global screen center). By setting `bitDepth` you can enable Display++,
%> DataPixx, HDR and high bit-depth display modes. This class also manages
%> movie recording of the screen buffer. Finally it wraps some generic
%> drawing commands like grids, text, spots or other basic things that would
%> be overkill for aa dedicated stimulus class.
%>
%> Copyright ©2014-2024 Ian Max Andolina — released: LGPL3, see LICENCE.md
% ========================================================================
classdef screenManager < optickaCore
properties
%> the display to use, 0 is the main display on macOS/Linux
%> default value will be set to `max(Screen('Screens'))`
screen double {mustBeInteger}
%> Pixels Per Centimeter — used for calculating the number of pixels
%> per visual degree (ppd). Use the calibrateSize.m function to
%> measure this value accurately for each monitor you will use.
%> Examples: MBP 1440x900 is 33.2x20.6cm so 44px/cm; Flexscan is
%> 32px/cm @1280 26px/cm @ 1024; Display++ is 27px/cm @1920x1080
pixelsPerCm(1,1) double = 36
%> distance in centimeters of subject from Display
%> rad2ang(2 * atan( size / (2 * distance) ) ) = Xdeg
%> when size == 1cm & distance == 57.3cm; X == 1deg
distance(1,1) double = 57.3
%> windowed: when FALSE use fullscreen; set to TRUE and it is
%> windowed 800x600pixels or you can add in a window width and
%> height i.e. [800 600] to specify windowed size. Remember that
%> windowed presentation should *never* be used for real
%> experimental presentation due to poor timing…
windowed = false
%> stereo mode
stereoMode(1,1) double = 0
%> enable debug for poorer temporal fidelity but no sync testing
%> etc.
debug(1,1) logical = false
%> shows some info text and position grid during stimulus
%> presentation if true
visualDebug(1,1) logical = false
%> normally should be left at 1 (1 is added to this number so
%> doublebuffering is enabled)
doubleBuffer(1,1) uint8 = 1
%> Mirror the content to a second window. In this case we need a
%> screen 0 and screen 1 and the main output to screen 1. We will get
%> an overlay window for this too we can draw to.
mirrorDisplay(1,1) logical = false
%> float precision and bitDepth of framebuffer/output: '8bit' is
%> best for old GPUs, but choose 'FloatingPoint32BitIfPossible' for
%> newer GPUs. Native high bitdepths (assumes FloatingPoint32Bit
%> internal processing): 'PseudoGray', 'HDR', 'Native10Bit',
%> 'Native11Bit', 'Native16Bit', 'Native16BitFloat' Options to
%> enable Display++ or VPixx modes: 'EnableBits++Bits++Output',
%> 'EnableBits++Mono++Output', 'EnableBits++Mono++OutputWithOverlay'
%> or 'EnableBits++Color++Output' 'EnableDataPixxM16Output',
%> 'EnableDataPixxC48Output'
bitDepth char {mustBeMember(bitDepth,{'FloatingPoint32BitIfPossible';...
'FloatingPoint32Bit'; '8bit'; 'HDR'; 'PseudoGray'; 'Native10Bit';...
'Native11Bit'; 'Native16Bit'; 'Native16BitFloat';...
'EnableNative10BitFrameBuffer'; 'EnableNative11BitFrameBuffer';...
'EnableNative16BitFrameBuffer'; 'FixedPoint16Bit'; 'FloatingPoint16Bit';...
'Bits++Bits++'; 'Bits++Mono++'; 'Bits++Color++';...
'Bits++Bits++Output'; 'Bits++Mono++Output'; 'Bits++Color++Output';...
'EnableBits++Bits++Output'; 'EnableBits++Color++Output';...
'EnableBits++Mono++Output';'EnableBits++Mono++OutputWithOverlay';...
'EnableDataPixxM16Output';...
'EnableDataPixxC48Output'})} = '8bit'
%> timestamping mode 1=beamposition,kernel fallback | 2=beamposition
%> crossvalidate with kernel
timestampingMode double = 1
%> multisampling sent to the graphics card, try values 0[disabled], 4, 8
%> and 16 -- useful for textures to minimise aliasing, but this does
%> provide extra work for the GPU
antiAlias(1,1) double = 0
%> background RGBA of display during stimulus presentation
backgroundColour(1,:) double = [0.5 0.5 0.5 1.0]
%> use OpenGL blending mode
blend logical = true
%> OpenGL blending source mode
srcMode char {mustBeMember(srcMode,{'GL_ZERO'; 'GL_ONE';...
'GL_DST_COLOR'; 'GL_ONE_MINUS_DST_COLOR';...
'GL_SRC_ALPHA'; 'GL_ONE_MINUS_SRC_ALPHA'; 'GL_DST_ALPHA';...
'GL_ONE_MINUS_DST_ALPHA'; 'GL_SRC_ALPHA_SATURATE' })} = 'GL_SRC_ALPHA'
%> OpenGL blending dst mode
dstMode char {mustBeMember(dstMode,{'GL_ZERO'; 'GL_ONE';...
'GL_DST_COLOR'; 'GL_ONE_MINUS_DST_COLOR';...
'GL_SRC_ALPHA'; 'GL_ONE_MINUS_SRC_ALPHA'; 'GL_DST_ALPHA';...
'GL_ONE_MINUS_DST_ALPHA'; 'GL_SRC_ALPHA_SATURATE' })} = 'GL_ONE_MINUS_SRC_ALPHA'
%> shunt center by X degrees (coordinates are in degrees from centre of
%> monitor)
screenXOffset(1,1) double = 0
%> shunt center by Y degrees (coordinates are in degrees from centre of
%> monitor)
screenYOffset(1,1) double = 0
%> gamma correction info saved as a calibrateLuminance object
gammaTable calibrateLuminance
%> settings for movie output
%> type 1 = video file, 2 = mat array, 3 = single pictures
movieSettings = struct('record',false,'type',1,'loop',inf,...
'size',[],'fps',[],'quality',0.7,...
'channels',3,'keyframe',5,'nFrames', inf,...
'prefix','Movie','codec','x264enc')
%> populated on window open; useful screen info, initial gamma tables
%> and the like
screenVals struct = struct('ifi',1/60,'fps',60,...
'winRect',[0 0 1920 1080])
%> verbose output?
verbose = false
%> level of PTB verbosity, set to 10 for full PTB logging
verbosityLevel double = 3
%> Use retina resolution natively (worse performance but double
%> resolution)
useRetina logical = false
%> Screen To Head Mapping, a Nx3 vector: Screen('Preference',
%> 'ScreenToHead', screen, head, crtc); Each N should be a different
%> display
screenToHead = []
%> force framerate for Display++ (120Hz or 100Hz, empty uses the default
%> OS setup)
displayPPRefresh double = []
%> hide the black flash as PTB tests its refresh timing, uses a gamma
%> trick from Mario
hideFlash logical = false
%> Details for drawing fonts, either sets defaults if window is closed or
%> or updates values if window open...
font struct = struct('TextSize',16,...
'TextColor',[0.95 0.95 0.95 1],...
'TextBackgroundColor',[0.2 0.3 0.3 0.8],...
'TextRenderer', 1,...
'FontName', 'Source Sans 3');
end
properties (SetAccess = private, GetAccess = public, Dependent = true)
%> dependent Pixels Per Degree property; calculated from distance and
%> pixelsPerCm.
%> pixelsPerDegree = pixelsPerCm × (distance ÷ 57.3)
ppd
end
properties (Constant)
%> possible bitDepth or display modes
bitDepths cell = {'FloatingPoint32BitIfPossible'; 'FloatingPoint32Bit'; '8bit';...
'HDR'; 'PseudoGray'; 'Native10Bit'; 'Native11Bit'; 'Native16Bit'; 'Native16BitFloat';...
'EnableNative10BitFrameBuffer'; 'EnableNative11BitFrameBuffer';...
'EnableNative16BitFrameBuffer'; 'FixedPoint16Bit'; 'FloatingPoint16Bit';...
'Bits++Bits++'; 'Bits++Mono++'; 'Bits++Color++';...
'Bits++Bits++Output'; 'Bits++Mono++Output'; 'Bits++Color++Output';...
'EnableBits++Bits++Output'; 'EnableBits++Color++Output';...
'EnableBits++Mono++Output';'EnableBits++Mono++OutputWithOverlay';...
'EnableDataPixxM16Output';'EnableDataPixxC48Output'}
%> possible OpenGL blend modes (src or dst)
blendModes cell = {'GL_ZERO'; 'GL_ONE'; 'GL_DST_COLOR'; 'GL_ONE_MINUS_DST_COLOR';...
'GL_SRC_ALPHA'; 'GL_ONE_MINUS_SRC_ALPHA'; 'GL_DST_ALPHA';...
'GL_ONE_MINUS_DST_ALPHA'; 'GL_SRC_ALPHA_SATURATE' }
end
properties (Hidden = true)
%> anaglyph channel gains
anaglyphLeft = [];
anaglyphRight = [];
%> The mode to use for color++ mode
colorMode = 2
%> for some development macOS and windows machines we have to disable
%> sync tests, but we hide this as we should remember this is for
%> development ONLY!
disableSyncTests logical = false
%> The acceptable variance in flip timing tests performed when
%> screen opens, set with Screen('Preference', 'SyncTestSettings',
%> syncVariance) AMD cards under Ubuntu are very low variance, PTB
%> default is 2e-04. DO NOT change this unless you know what you are
%> doing.
syncVariance double = 2e-04
%> overlay window if mirrorDisplay was enabled
overlayWin = -1
%> e.g. kPsychGUIWindow
specialFlags = []
%> try to enable vulkan?
useVulkan = false
end
properties (SetAccess = private, GetAccess = public)
%> do we have a working PTB, if not go into a silent mode
isPTB logical = false
%> is a window currently open?
isOpen logical = false
%> did we ask for a bitsPlusPlus mode?
isPlusPlus logical = false
%> the handle returned by opening a PTB window
win
%> the window rectangle
winRect
%> computed X center
xCenter double = 0
%> computed Y center
yCenter double = 0
%> set automatically on construction
maxScreen
end
properties (Access = private)
%> we cache ppd as it is used frequently
ppd_ double
%> properties allowed to be modified during construction
allowedProperties = {'colorMode','overlayWin','specialFlags','syncVariance',...
'disableSyncTests','displayPPRefresh','screenToHead','gammaTable',...
'useRetina','bitDepth','pixelsPerCm','distance','screen','windowed','backgroundColour',...
'screenXOffset','screenYOffset','blend','srcMode','dstMode','antiAlias',...
'debug','photoDiode','verbose','hideFlash',...
'stereoMode','anaglyphLeft','anaglyphRight'}
%> the photoDiode rectangle in pixel values
photoDiodeRect(1,4) double = [0, 0, 45, 45]
%> colour of the grid dots
gridColour = [0 0 0 1]
%> the values computed to draw the 1deg dotted grid in visualDebug mode
grid
%> the movie pointer
moviePtr = []
%> movie mat structure
movieMat = []
%screen flash logic
flashInterval = 20
flashTick = 0
flashOn = 1
% timed spot logic
timedSpotTime = 0
timedSpotTick = 0
timedSpotNextTick = 0
% async flip management
isInAsync = false
end
methods
% ===================================================================
function me = screenManager(varargin)
%> @fn me = screenManager(varargin)
%>
%> screenManager CONSTRUCTOR
%>
%> @param varargin can be simple name value pairs, a structure or cell array
%> @return instance of the class.
% ===================================================================
args = optickaCore.addDefaults(varargin,struct('name','screenManager'));
me=me@optickaCore(args); %superclass constructor
me.parseArgs(args,me.allowedProperties); %check remaining properties from varargin
try
AssertOpenGL;
me.isPTB = true;
salutation(me,'PTB + OpenGL supported!')
catch %#ok<*CTCH>
me.isPTB = false;
salutation(me,'CONSTRUCTOR','OpenGL support needed for PTB!!!',true)
end
me.font.FontName = me.monoFont;
prepareScreen(me);
end
% ===================================================================
function screenVals = prepareScreen(me)
%> @fn prepareScreen
%>
%> prepare the initial Screen values on the local machine
%>
%> @return screenVals structure of screen values
% ===================================================================
if me.isPTB == false; warning('No PTB!!!'); return; end
me.maxScreen = max(Screen('Screens'));
%by default choose the (largest number) screen
if isempty(me.screen) || me.screen > me.maxScreen
me.screen = me.maxScreen;
end
sv = struct();
checkWindowValid(me);
%get the gammatable and dac information
sv.resetGamma = false;
try
[sv.originalGamma, sv.dacBits, sv.lutSize]=Screen('ReadNormalizedGammaTable', me.screen);
sv.linearGamma = repmat(linspace(0,1,sv.lutSize)',1,3);
sv.gammaTable = sv.originalGamma;
catch
sv.gammaTable = [];
sv.dacBits = [];
if IsWin
sv.lutSize = 256;
else
sv.lutSize = 1024;
end
end
%get screen dimensions
sv = setScreenSize(me, sv);
%this is just a rough initial setting, it will be recalculated when we
%open the screen before showing stimuli.
sv.fps=Screen('FrameRate',me.screen);
if sv.fps == 0 || (sv.fps == 59 && IsWin)
sv.fps = 60;
end
sv.ifi = 1/sv.fps;
me.movieSettings.fps = sv.fps;
if me.debug == true %we yoke these together but they can then be overridden
me.visualDebug = true;
end
if ismac
me.disableSyncTests = true;
end
me.ppd; %generate our dependent propertie and caches it to ppd_ for speed
me.makeGrid; %our visualDebug size grid
if mean(me.backgroundColour) > 0.5
me.gridColour = [0.0 0 0.2];
else
me.gridColour = [0.7 1 0.7];
end
sv.white = WhiteIndex(me.screen);
sv.black = BlackIndex(me.screen);
sv.gray = GrayIndex(me.screen);
try sv.isVulkan = PsychVulkan('Supported'); end
if IsLinux
try
sv.display = Screen('ConfigureDisplay','Scanout',me.screen,0);
sv.name = sv.display.name;
sv.widthMM = sv.display.displayWidthMM;
sv.heightMM = sv.display.displayHeightMM;
end
end
me.screenVals = sv;
screenVals = sv;
end
% ===================================================================
function sv = open(me,debug,tL,forceScreen)
%> @fn open
%> @brief open a screen with object defined settings
%>
%> @param debug, whether we show debug status, called from runExperiment
%> @param tL timeLog object to add timing info on screen construction
%> @param forceScreen force a particular screen number to open
%> @return sv structure of basic info from the opened screen
% ===================================================================
if me.isOpen; fprintf('===>>> screenManager.open(): Screen already open!');return; end
if me.isPTB == false
warning('No PTB found!');
sv = me.screenVals;
return;
end
if ~exist('debug','var') || isempty(debug)
debug = me.debug;
end
if ~exist('tL','var') || isempty(tL)
tL = struct;
end
if ~exist('forceScreen','var')
forceScreen = [];
end
sv = me.screenVals;
try
PsychDefaultSetup(2);
sv.resetGamma = false;
me.hideScreenFlash();
if ~isempty(me.screenToHead) && isnumeric(me.screenToHead)
for i = 1:size(me.screenToHead,1)
sth = me.screenToHead(i,:);
if lengtht(stc) == 3
fprintf('\n---> screenManager: Custom Screen to Head: %i %i %i\n',sth(1), sth(2), sth(3));
Screen('Preference', 'ScreenToHead', sth(1), sth(2), sth(3));
end
end
end
%1=beamposition,kernel fallback | 2=beamposition crossvalidate with kernel
%Screen('Preference', 'VBLTimestampingMode', me.timestampingMode);
if ~islogical(me.windowed) && isnumeric(me.windowed) %force debug for windowed stimuli!
debug = true;
end
if debug == true || (length(me.windowed)==1 && me.windowed ~= 0)
fprintf('\n---> screenManager: Skipping Sync Tests etc. - ONLY FOR DEVELOPMENT!\n');
Screen('Preference','SyncTestSettings', 0.002); %up to 2ms variability
Screen('Preference', 'SkipSyncTests', 2);
Screen('Preference', 'VisualDebugLevel', 0);
Screen('Preference', 'Verbosity', me.verbosityLevel);
Screen('Preference', 'SuppressAllWarnings', 0);
else
if me.disableSyncTests
fprintf('\n---> screenManager: Sync Tests OVERRIDDEN, do not use for real experiments!!!\n');
warning('---> screenManager: Sync Tests OVERRIDDEN, do not use for real experiments!!!')
Screen('Preference', 'SkipSyncTests', 2);
else
fprintf('\n---> screenManager: Normal Screen Preferences used.\n');
Screen('Preference', 'SkipSyncTests', 0);
end
Screen('Preference','SyncTestSettings', me.syncVariance); %set acceptable variability
Screen('Preference', 'VisualDebugLevel', 3);
Screen('Preference', 'Verbosity', me.verbosityLevel); %errors and warnings
Screen('Preference', 'SuppressAllWarnings', 0);
end
tL.screenLog.preOpenWindow=GetSecs;
%=== check if system supports HDR mode
isHDR = logical(PsychHDR('Supported'));
if strcmp(me.bitDepth,'HDR') && ~isHDR
me.bitDepth = 'Native10Bit';
error('---> screenManager: tried to use HDR but it is not supported!\n');
end
%=== check stereomode is anaglyph
if ismember(me.stereoMode, 6:9)
stereo = me.stereoMode;
elseif me.stereoMode > 0
warning('Only Anaglyph stereo supported at present...')
stereo = 0;
else
stereo = 0;
end
%=== start to set up PTB screen
PsychImaging('PrepareConfiguration');
PsychImaging('AddTask', 'General', 'UseFastOffscreenWindows');
if me.useVulkan
if ~me.screenVals.isVulkan; fprintf('---> screenManager: Probing for Vulkan failed...\n'); end
try
PsychImaging('AddTask', 'General', 'UseVulkanDisplay');
fprintf('---> screenManager: Vulkan appears to be activated...\n');
catch
warning('Vulkan failed to be initialised...')
end
end
me.isPlusPlus = screenManager.bitsCheckOpen();
fprintf('---> screenManager: Probing for a Display++...');
bD = me.bitDepth;
normalMode = true;
if ~me.isPlusPlus && contains(bD, 'Bits++')
error('---> screenManager: You specified a Bits++ colour mode but cannot connect to the Display++!');
end
if me.isPlusPlus
fprintf('\tFound Display++ ');
if contains(bD, 'Bits++')
normalMode = false;
if isempty(regexpi(bD, '^Enable','ONCE')); bD = ['Enable' bD]; end
if isempty(regexpi(bD, 'Output$','ONCE')); bD = [bD 'Output']; end
fprintf('-> mode: %s\n', bD);
PsychImaging('AddTask', 'FinalFormatting', 'DisplayColorCorrection', 'ClampOnly');
if contains(me.bitDepth, 'Color')
PsychImaging('AddTask', 'General', bD, me.colorMode);
else
PsychImaging('AddTask', 'General', bD);
end
else
warning('---> screenManager: You are connected to a Display++ but not using a Bits++ mode...');
end
else
fprintf('\tNO Display++\n');
end
if normalMode
switch lower(bD)
case {'hdr','enablehdr'}
PsychImaging('AddTask', 'General', 'FloatingPoint32BitIfPossible');
PsychImaging('AddTask', 'General', 'EnableHDR');
case {'native10bit','native11bit','native16bit'}
if isempty(regexpi(bD, '^Enable','ONCE')); bD = ['Enable' bD]; end
if isempty(regexpi(bD, 'Framebuffer$','ONCE')); bD = [bD 'Framebuffer']; end
PsychImaging('AddTask', 'General', 'FloatingPoint32BitIfPossible');
PsychImaging('AddTask', 'General', bD);
fprintf('---> screenManager: 32-bit internal / %s Output bit-depth\n', bD);
case {'native16bitfloat'}
PsychImaging('AddTask', 'General', 'FloatingPoint32BitIfPossible');
PsychImaging('AddTask', 'General', ['Enable' bD 'ingPointFramebuffer']);
fprintf('---> screenManager: 32-bit internal / %s Output bit-depth\n', bD);
case {'pseudogray','enablepseudograyoutput'}
PsychImaging('AddTask', 'General', 'FloatingPoint32BitIfPossible');
PsychImaging('AddTask', 'General', 'EnablePseudoGrayOutput');
fprintf('---> screenManager: Internal processing set to: %s\n', 'PseudoGrayOutput');
case {'floatingpoint32bitifpossible','floatingpoint32bit'}
PsychImaging('AddTask', 'General', bD);
fprintf('---> screenManager: Internal processing set to: %s\n', bD);
case {'8bit'}
PsychImaging('AddTask', 'General', 'UseVirtualFramebuffer');
fprintf('---> screenManager: Internal processing set to: %s\n', '8 bits');
otherwise
fprintf('---> screenManager: No imaging pipeline requested...\n');
end
end
if me.useRetina
fprintf('---> screenManager: Retina mode enabled\n');
PsychImaging('AddTask', 'General', 'UseRetinaResolution');
end
try %#ok<*TRYNC>
if me.isPlusPlus && ~isempty(me.displayPPRefresh) && IsLinux
outputID = 0;
fprintf('\n---> screenManager: Set Display++ to %iHz\n',me.displayPPRefresh);
Screen('ConfigureDisplay','Scanout',me.screen,outputID,[],[],me.displayPPRefresh);
end
end
%===deal with windowed or full-screen
if isempty(me.windowed); me.windowed = false; end
if ~isempty(forceScreen)
thisScreen = forceScreen;
else
thisScreen = me.screen;
end
if me.windowed == false %full-screen
winSize = [];
sf = me.specialFlags;
else %windowed
if length(me.windowed) == 2
winSize = [0 0 me.windowed(1) me.windowed(2)];
elseif length(me.windowed) == 4
winSize = me.windowed;
else
winSize=[0 0 800 800];
end
if isempty(me.specialFlags)
sf = kPsychGUIWindow;
else
sf = me.specialFlags;
end
end
if thisScreen > 0 && me.mirrorDisplay
PsychImaging('AddTask', 'General', 'MirrorDisplayTo2ndOutputHead', ...
0, [0 0 900 600], [], 1);
end
% ==============================================================
[me.win, me.winRect] = PsychImaging('OpenWindow', thisScreen, ...
me.backgroundColour, winSize, [], me.doubleBuffer+1, stereo, ...
me.antiAlias, [], sf);
me.isOpen = true;
% ==============================================================
if thisScreen > 0 && me.mirrorDisplay
me.overlayWin = PsychImaging('GetMirrorOverlayWindow', me.win);
sv.mirror = true;
sv.overlayWin = me.overlayWin;
else
sv.mirror = false;
sv.overlayWin= [];
end
%===ANAGLYPH VALUES
if stereo > 0 && ~isempty(me.anaglyphLeft) && ~isempty(me.anaglyphRight)
SetAnaglyphStereoParameters('LeftGains', me.win, me.anaglyphLeft);
SetAnaglyphStereoParameters('RightGains', me.win, me.anaglyphRight);
elseif stereo > 0
switch stereo
case 6
SetAnaglyphStereoParameters('LeftGains', me.win, [1.0 0.0 0.0]);
SetAnaglyphStereoParameters('RightGains', me.win, [0.0 0.6 0.0]);
case 7
SetAnaglyphStereoParameters('LeftGains', me.win, [0.0 0.6 0.0]);
SetAnaglyphStereoParameters('RightGains', me.win, [1.0 0.0 0.0]);
case 8
SetAnaglyphStereoParameters('LeftGains', me.win, [0.4 0.0 0.0]);
SetAnaglyphStereoParameters('RightGains', me.win, [0.0 0.2 0.7]);
case 9
SetAnaglyphStereoParameters('LeftGains', me.win, [0.0 0.2 0.7]);
SetAnaglyphStereoParameters('RightGains', me.win, [0.4 0.0 0.0]);
end
end
sv.win = me.win; % make a copy
sv.winRect = me.winRect;
sv.useRetina = me.useRetina;
sv = setScreenSize(me, sv);
if me.verbose; fprintf('===>>>Made win: %i kind: %i\n',me.win,Screen(me.win,'WindowKind')); end
tL.screenLog.postOpenWindow=GetSecs;
tL.screenLog.deltaOpenWindow=(tL.screenLog.postOpenWindow-tL.screenLog.preOpenWindow);
%===check we have GLSL
try
AssertGLSL;
catch
close(me);
error('GLSL Shading support is required for octicka!');
end
% get HDR properties
if strcmpi(me.bitDepth,'HDR') && isHDR
sv.hdrProperties = PsychHDR('GetHDRProperties', me.win);
if IsWin; oldDim = PsychHDR('HDRLocalDimming', me.win, 0); end
else
sv.hdrProperties = [];
end
%===Linux can give us some more information
if IsLinux && ~isHDR && ~me.useVulkan
try
d = Screen('ConfigureDisplay','Scanout',me.screen,0);
sv.name = d.name;
sv.widthMM = d.displayWidthMM;
sv.heightMM = d.displayHeightMM;
sv.display = d;
end
end
%===get timing info
sv.ifi = Screen('GetFlipInterval', me.win);
sv.fps = Screen('NominalFramerate', me.win);
% find our fps if not defined above
if sv.fps == 0
sv.fps=round(1/sv.ifi);
if sv.fps == 0 || (sv.fps == 59 && IsWin)
sv.fps = 60;
end
elseif sv.fps == 59 && IsWin
sv.fps = 60;
sv.ifi = 1 / 60;
end
if me.windowed == false % full-screen
sv.halfifi = sv.ifi/2; sv.halfisi = sv.halfifi;
else
% windowed presentation doesn't handle the preferred method
% of specifying lastvbl+halfifi properly so we set halfifi to 0 which
% effectively makes flip occur ASAP.
sv.halfifi = 0; sv.halfisi = 0;
end
%===configure photodiode to top right
if me.useRetina
me.photoDiodeRect = [me.winRect(3)-90 0 me.winRect(3) 90];
else
me.photoDiodeRect = [me.winRect(3)-45 0 me.winRect(3) 45];
end
sv.photoDiodeRect = me.photoDiodeRect;
%===get gamma table and info
try
[sv.originalGamma, sv.dacBits, sv.lutSize]=Screen('ReadNormalizedGammaTable', me.win);
catch
sv.originalGamma = [];
sv.dacBits = 0;
sv.lutSize = 0;
end
sv.linearGamma = repmat(linspace(0,1,sv.lutSize)',1,3);
sv.gammaTable = sv.originalGamma;
if me.hideFlash == true && isempty(me.gammaTable) && sv.lutSize > 0
Screen('LoadNormalizedGammaTable', me.screen, sv.linearGamma);
sv.gammaTable = sv.linearGamma;
sv.resetGamma = false;
elseif ~isempty(me.gammaTable) && ~isempty(me.gammaTable.gammaTable) && (me.gammaTable.choice > 0)
choice = me.gammaTable.choice;
sv.resetGamma = true;
if size(me.gammaTable.gammaTable,2) > 1
if isprop(me.gammaTable,'finalCLUT') && ~isempty(me.gammaTable.finalCLUT)
gTmp = me.gammaTable.finalCLUT;
else
gTmp = [me.gammaTable.gammaTable{choice,2:4}];
end
else
if isprop(me.gammaTable,'finalCLUT') && ~isempty(me.gammaTable.finalCLUT)
gTmp = me.gammaTable.finalCLUT;
else
gTmp = repmat(me.gammaTable.gammaTable{choice,1},1,3);
end
end
sv.gammaTable = gTmp;
[sv.oldCLUT, success] = Screen('LoadNormalizedGammaTable', me.win, sv.gammaTable);
if success < 1;error('Cannot load gamma table!!!');end
fprintf('\n---> screenManager: SET GAMMA CORRECTION using: %s\n', me.gammaTable.modelFit{choice}.method);
if isprop(me.gammaTable,'correctColour') && me.gammaTable.correctColour == true
fprintf('---> screenManager: GAMMA CORRECTION used independent R, G & B Correction \n');
end
else
sv.linearGamma = repmat(linspace(0,1,sv.lutSize)',1,3);
%Screen('LoadNormalizedGammaTable', me.screen, sv.linearGamma);
%sv.oldCLUT = LoadIdentityClut(me.win);
sv.resetGamma = false;
end
% Enable alpha blending.
sv.blending = false;
sv.newSrc = me.srcMode;
sv.newDst = me.dstMode;
sv.srcdst = [me.srcMode '|' me.dstMode];
if me.blend==1
sv.blending = true;
[sv.oldSrc,sv.oldDst,sv.oldMask]...
= Screen('BlendFunction', me.win, me.srcMode, me.dstMode);
fprintf('\n---> screenManager: Previous OpenGL blending: %s | %s\n', sv.oldSrc, sv.oldDst);
fprintf('---> screenManager: OpenGL blending now: %s | %s\n', me.srcMode, me.dstMode);
else
[sv.oldSrc,sv.oldDst,sv.oldMask] = Screen('BlendFunction', me.win);
end
% set up text defaults
updateFontValues(me);
sv.ppd = me.ppd; %generate our dependent propertie and caches it to ppd_ for speed
me.makeGrid; %our visualDebug size grid
if mean(me.backgroundColour(1:3)) > 0.6
me.gridColour = [0 0 0.2];
else
me.gridColour = [1 1 0.8];
end
if me.movieSettings.record
prepareMovie(me);
end
sv.white = WhiteIndex(me.screen);
sv.black = BlackIndex(me.screen);
sv.gray = GrayIndex(me.screen);
me.screenVals = sv;
catch ME
getReport(ME);
close(me);
Priority(0);
prepareScreen(me);
rethrow(ME);
end
end
function switchChannel(me, channel)
persistent thisChannel
if me.isOpen
if ~exist('channel','var'); channel = ~thisChannel;end
thisChannel = channel;
Screen('SelectStereoDrawBuffer', me.win, thisChannel);
end
end
% ===================================================================
function demo(me)
%> @fn demo
%> @brief Small demo of screen opening, drawing, closing
%>
% ===================================================================
if ~me.isOpen
stim = dotsStimulus('mask',true,'size',10,'speed',2,...
'density',3,'dotSize',0.3);
open(me);
disp('--->>> screenManager running a quick demo...');
if me.stereoMode > 0
stim.mask = false;
stim.type='simple';
drawBackground(me,[0 0 0]);
flip(me);
WaitSecs(0.5);
end
disp(me.screenVals);
setup(stim, me);
x = stim.xFinal;
td = me.screenVals.topInDegrees;
bd = me.screenVals.bottomInDegrees;
ld = me.screenVals.leftInDegrees;
vbl = flip(me);
for i = 1:me.screenVals.fps*6
if me.stereoMode > 0
drawBackground(me,[0 0 0]);
stim.xFinal = x - 3;
switchChannel(me,0);
drawText(me,'Demo screenManager Left Channel...',ld+1,td+1);
draw(stim);
switchChannel(me,1);
stim.xFinal = x + 3;
drawText(me,'Demo screenManager Right...',ld+1,td+2);
draw(stim);
else
drawText(me,'Running a quick demo of screenManager...');
draw(stim);
end
finishDrawing(me);
animate(stim);
vbl = flip(me, vbl);
if i == 1;KbWait;end
end
WaitSecs(1);
clear stim;
close(me);
end
end
% ===================================================================
function [vbl, when, flipTime, missed] = flip(me, varargin)
%> @fn flip
%> @brief Flip the screen
%>
%> [VBLTimestamp StimulusOnsetTime FlipTimestamp Missed Beampos] =
%> Screen('Flip', me.win [, when] [, dontclear] [, dontsync] [, multiflip]);
%>
%> @param varargin - pass other options to screen flip
%> @return vbl - a vbl from this flip
% ===================================================================
if ~me.isOpen; return; end
[vbl, when, flipTime, missed] = Screen('Flip',me.win,varargin{:});
if me.movieSettings.record; addMovieFrame(me); end
end
% ===================================================================
function vbl = asyncFlip(me, when, varargin)
%> @fn asyncFlip
%> @brief Flip the screen asynchrounously
%>
%> @param when - when to flip
%> @return vbl - a vbl from this flip
% ===================================================================
if ~me.isOpen; return; end
if me.isInAsync
vbl = Screen('AsyncFlipCheckEnd', me.win);
if vbl == 0; return; end
end
if exist('when','var')
vbl = Screen('AsyncFlipBegin',me.win, when, varargin{:});
else
vbl = Screen('AsyncFlipBegin',me.win);
end
me.isInAsync = true;
end
% ===================================================================
function result = asyncCheck(me)
%> @fn asyncCheck
%> @brief Check async state?
%>
%> @return result - is in async state?
% ===================================================================
if ~me.isOpen; return; end
result = false;
if me.isInAsync
vbl = Screen('AsyncFlipCheckEnd', me.win);
if vbl == 0
result = true;
else
me.isInAsync = false;
end
end
end
% ===================================================================
function vbl = asyncEnd(me)
%> @fn asyncEnd
%> @brief end async state
%>
%>
%> @return vbl - return time
% ===================================================================
if ~me.isOpen; return; end
vbl = 0;
if me.isInAsync
vbl = Screen('AsyncFlipEnd', me.win);
me.isInAsync = false;
end
end
% ===================================================================
function forceWin(me,win)
%> @fn forceWin
%> @brief force this object to use an existing window handle
%>
%> @param win - the window handle to bind to
%> @return
% ===================================================================
me.win = win;
me.isOpen = true;
me.isPTB = true;
me.screenVals.ifi = Screen('GetFlipInterval', me.win);
me.screenVals.white = WhiteIndex(me.win);
me.screenVals.black = BlackIndex(me.win);
me.screenVals.gray = GrayIndex(me.win);
me.screenVals = setScreenSize(me, me.screenVals);
fprintf('---> screenManager slaved to external win: %i\n',win);
end
% ===================================================================
function hideScreenFlash(me)
%> @fn hideScreenFlash
%> @brief This is the trick Mario told us to "hide" the colour changes
%> as PTB starts -- we could use backgroundcolour here to be even better
%>
%> @param
%> @return
% ===================================================================
% This is the trick Mario told us to "hide" the colour changes as PTB
% intialises -- we could use backgroundcolour here to be even better
if me.hideFlash == true && all(me.windowed == false)
if ~isempty(me.gammaTable) && isa(me.gammaTable,'calibrateLuminance') && (me.gammaTable.choice > 0)
me.screenVals.oldGamma = Screen('LoadNormalizedGammaTable', me.screen, repmat(me.gammaTable.gammaTable{me.gammaTable.choice}(128,:), 256, 3));
me.screenVals.resetGamma = true;
else
table = repmat(me.backgroundColour(:,1:3), 256, 1);
me.screenVals.oldGamma = Screen('LoadNormalizedGammaTable', me.screen, table);
me.screenVals.resetGamma = true;
end
end
end
% ===================================================================
function close(me)
%> @fn close
%> @brief close the screen when finished or on error
%>
%> @param
%> @return
% ===================================================================
if ~me.isPTB; return; end
try Priority(0); end
try ListenChar(0); end
ShowCursor;
if me.screenVals.resetGamma && isfield(me.screenVals,'originalGamma') && ~isempty(me.screenVals.originalGamma)
Screen('LoadNormalizedGammaTable', me.win, me.screenVals.originalGamma);
fprintf('\n---> screenManager: REVERT GAMMA TABLES\n');
end
if me.isInAsync
try Screen('ASyncFlipEnd',me.win); end
end
if me.movieSettings.record
finaliseMovie(me);
end
me.isInAsync = false;
if me.isPlusPlus
try BitsPlusPlus('Close'); end
end
try me.finaliseMovie(); me.moviePtr = []; end
kind = Screen(me.win, 'WindowKind');
try
if kind == 1
fprintf('\n\n---> screenManager %s: Closing screen = %i, Win = %i, Kind = %i\n', me.uuid, me.screen, me.win, kind);
Screen('Close',me.win);
end
catch ME
getReport(ME);
end
me.win = [];
if isfield(me.screenVals,'win');me.screenVals=rmfield(me.screenVals,'win');end
me.isOpen = false;
me.isPlusPlus = false;
end
% ===================================================================
function resetScreenGamma(me)
%> @fn resetScreenGamma
%> @brief reset the gamma table
%>
%> @param
%> @return
% ===================================================================
if me.hideFlash == true || me.windowed(1) ~= 1 || (~isempty(me.screenVals) && me.screenVals.resetGamma == true && ~isempty(me.screenVals.linearGamma))
fprintf('\n---> screenManager: RESET GAMMA TABLES\n');
Screen('LoadNormalizedGammaTable', me.screen, me.screenVals.linearGamma);
end
end
function set.font(me,varargin)
if ~isempty(varargin{1}) && isstruct(varargin{1})
me.font = varargin{1};
updateFontValues(me);
end
end
% ===================================================================
function set.backgroundColour(me, value)
%> @fn set.backgroundColour
%> @brief Set method for backgroundColour
%>
% ===================================================================
switch length(value)
case 1
me.backgroundColour = [value value value 1];
case 3
me.backgroundColour = [value 1];
case 4
me.backgroundColour = value;