-
Notifications
You must be signed in to change notification settings - Fork 9
/
PixelToasterApple.mm
1966 lines (1604 loc) · 64 KB
/
PixelToasterApple.mm
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
// Apple MacOS X Platform
// Copyright © 2004-2007 Glenn Fiedler
// Part of the PixelToaster Framebuffer Library - http://www.pixeltoaster.com
// native Cocoa output implemented by Thorsten Schaaps <[email protected]>
#include "PixelToaster.h"
#include "PixelToasterCommon.h"
#include "PixelToasterConversion.h"
#include "PixelToasterApple.h"
#if !PIXELTOASTER_APPLE_USE_X11
# import <Cocoa/Cocoa.h>
# import <QuartzCore/CIContext.h>
# import <OpenGL/OpenGL.h>
# include <OpenGL/glu.h>
using namespace PixelToaster;
# ifndef PIXELTOASTER_APPLE_ALLOW_ZOOM
// adds Zoom1x, 2x, 3x, 4x to "Window" menu and allows
// resizing the window by dragging the lower right corner
# define PIXELTOASTER_APPLE_ALLOW_ZOOM 1
# endif
// allows PixelToaster to change the screen resolution
// when switching to fullscreen mode (not yet implemented)
# define PIXELTOASTER_APPLE_ALLOW_MODESWITCH 0
# ifndef PIXELTOASTER_APPLE_DEBUG
// enables some debug output, disables fades and
// capturing the mouse cursor
# define PIXELTOASTER_APPLE_DEBUG 0
# endif
# ifndef PIXELTOASTER_APPLE_VBSYNC
// switches sync to vertical blank on/off (0=off, 1=on)
# define PIXELTOASTER_APPLE_VBSYNC 1
# endif
// fade time in seconds
static const double FADE_TIME = 0.5;
// number of steps per fade
static const int FADE_STEPS = 30;
# if PIXELTOASTER_APPLE_DEBUG
# define GL_CHECK_ERROR(cmd) \
cmd; \
{ \
GLenum error = glGetError(); \
if (GL_NO_ERROR != error) \
fprintf(stderr, "%s:%d:: ’%s’ failed with error: '%s'\n", \
__FILE__, __LINE__, #cmd, gluErrorString(error)); \
}
# else
# define GL_CHECK_ERROR(cmd) cmd;
# endif
// to get rid of the unused parameter warning in ObjC methods
# define PARAMETER_UNUSED(x) (void)(x);
# pragma mark -
# pragma mark Objective-C classes
# pragma mark -
@interface PTApplication : NSApplication <NSApplicationDelegate> {
@private
BOOL messageLoopIsRunning;
}
- (id)init;
// since we never actually call [NSApp run] we need to overwrite -isRunning
- (BOOL)isRunning;
- (void)setIsRunning:(BOOL)isRunning;
- (void)performAbout:(id)sender;
- (void)setupApplicationMenu;
@end
@implementation PTApplication
- (id)init {
self = [super init];
if (self != nil)
{
messageLoopIsRunning = NO;
[self setDelegate:self];
}
return self;
}
- (BOOL)isRunning {
return messageLoopIsRunning;
}
- (void)setIsRunning:(BOOL)isRunning {
messageLoopIsRunning = isRunning;
}
// Called on Cmd-Q / Quit menu item
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender {
PARAMETER_UNUSED(sender)
// try to close all windows..
NSArray* windows = [self windows];
NSEnumerator* enumerator = [windows objectEnumerator];
NSWindow* window;
while ((window = [enumerator nextObject]) != nil)
{
[window performClose:nil];
}
// if no windows are left open, we allow the application to terminate
if ([[self windows] count] == 0)
{
[self setIsRunning:NO];
return NSTerminateNow;
}
else
return NSTerminateCancel;
}
// a small custom about box
- (void)performAbout:(id)sender {
PARAMETER_UNUSED(sender)
NSString* versionString = [NSString stringWithFormat:@"using PixelToaster v%.1f", PIXELTOASTER_VERSION];
NSAttributedString* creditString = [[[NSAttributedString alloc] initWithString:versionString] autorelease];
NSString* copyRightString = [NSString stringWithCString:"Copyright \xc2\xa9 2004-2007 Glenn Fiedler\n"
"Mac OS X implementation by Thorsten Schaaps"
encoding:NSUTF8StringEncoding];
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:creditString, @"Credits",
copyRightString, @"Copyright",
nil];
[NSApp orderFrontStandardAboutPanelWithOptions:dict];
}
// Set up a menu bar, so the PixelToaster application looks a bit more "native"
// Besides the well known apple menu there is only a "Window" menu added.
// This only gets called when we create the NSApp instance, so if PixelToaster
// is used from a true Cocoa context, this should not interfere...
- (void)setupApplicationMenu {
NSString* applicationName = [[NSProcessInfo processInfo] processName];
NSMenu* mainMenu = [[NSMenu alloc] initWithTitle:@"MainMenu"];
// Setup Application menu.. this needs a hack (see below)
{
// the title of the menu and item don't matter, they will be replaced by the processname anyway
NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"AppleMenu"];
// "About "applicationName
[appMenu addItemWithTitle:[@"About " stringByAppendingString:applicationName]
action:@selector(performAbout:)
keyEquivalent:@""];
// ---
[appMenu addItem:[NSMenuItem separatorItem]];
// Preferences TODO: nothing implemented yet, we could let the user choose a code path
// or an initial screen here...
[appMenu addItemWithTitle:@"Preferences"
action:@selector(showPreferences:)
keyEquivalent:@","];
// ---
[appMenu addItem:[NSMenuItem separatorItem]];
// Services
NSMenuItem* servicesItem = [appMenu addItemWithTitle:@"Services"
action:nil
keyEquivalent:@""];
NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle:@""];
[servicesItem setSubmenu:servicesMenu];
[NSApp setServicesMenu:servicesMenu];
[servicesMenu release];
// ---
[appMenu addItem:[NSMenuItem separatorItem]];
// Hide Application
[appMenu addItemWithTitle:[@"Hide " stringByAppendingString:applicationName]
action:@selector(hide:)
keyEquivalent:@"h"];
// Hide Others
NSMenuItem* hideOthersItem = [appMenu addItemWithTitle:@"Hide Others"
action:@selector(hideOtherApplications:)
keyEquivalent:@"h"];
[hideOthersItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)];
// Show All
[appMenu addItemWithTitle:@"Show All"
action:@selector(unhideAllApplications:)
keyEquivalent:@""];
// ---
[appMenu addItem:[NSMenuItem separatorItem]];
// Quit <applicationName>
[appMenu addItemWithTitle:[@"Quit " stringByAppendingString:applicationName]
action:@selector(terminate:)
keyEquivalent:@"q"];
// setAppleMenu is private since Mac OS X 10.4 Tiger, but it still seems to be available
// (and does work) in 10.5 Leopard.
if ([NSApp respondsToSelector:@selector(setAppleMenu:)])
{
[NSApp performSelector:@selector(setAppleMenu:) withObject:appMenu];
}
NSMenuItem* appItem = [[NSMenuItem alloc] initWithTitle:@"AppMenuItem"
action:nil
keyEquivalent:@""];
[appItem setSubmenu:appMenu];
[mainMenu addItem:appItem];
[appItem release];
[appMenu release];
}
// Setup "Window" menu
{
NSMenu* windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
// Close Window
[windowMenu addItemWithTitle:@"Close Window"
action:@selector(performClose:)
keyEquivalent:@"w"];
// ---
[windowMenu addItem:[NSMenuItem separatorItem]];
// Minimize
[windowMenu addItemWithTitle:@"Minimize"
action:@selector(performMiniaturize:)
keyEquivalent:@"m"];
# if PIXELTOASTER_APPLE_ALLOW_ZOOM
// Zoom
[windowMenu addItemWithTitle:@"Zoom"
action:@selector(performZoom:)
keyEquivalent:@""];
# endif
// ---
[windowMenu addItem:[NSMenuItem separatorItem]];
// Toggle Fullscreen
[windowMenu addItemWithTitle:@"Toggle Fullscreen"
action:@selector(menuToggleFullscreen:)
keyEquivalent:@"F"];
# if PIXELTOASTER_APPLE_ALLOW_ZOOM
// ---
[windowMenu addItem:[NSMenuItem separatorItem]];
// 1 x
NSMenuItem* zoomItem;
zoomItem = [windowMenu addItemWithTitle:@"1 x"
action:@selector(zoomX:)
keyEquivalent:@"1"];
[zoomItem setTag:1];
// 2 x
zoomItem = [windowMenu addItemWithTitle:@"2 x"
action:@selector(zoomX:)
keyEquivalent:@"2"];
[zoomItem setTag:2];
// 3 x
zoomItem = [windowMenu addItemWithTitle:@"3 x"
action:@selector(zoomX:)
keyEquivalent:@"3"];
[zoomItem setTag:3];
// 4 x
zoomItem = [windowMenu addItemWithTitle:@"4 x"
action:@selector(zoomX:)
keyEquivalent:@"4"];
[zoomItem setTag:4];
# endif
// ---
[windowMenu addItem:[NSMenuItem separatorItem]];
// Bring All to Front
[windowMenu addItemWithTitle:@"Bring All to Front"
action:@selector(arrangeInFront:)
keyEquivalent:@""];
// ---
[windowMenu addItem:[NSMenuItem separatorItem]];
NSMenuItem* windowItem = [[NSMenuItem alloc] initWithTitle:@""
action:nil
keyEquivalent:@""];
[mainMenu addItem:windowItem];
[windowItem setSubmenu:windowMenu];
[NSApp setWindowsMenu:windowMenu];
}
[NSApp setMainMenu:mainMenu];
[mainMenu release];
}
@end
# pragma mark -
@interface PixelToasterView : NSView <NSWindowDelegate> {
@private
NSOpenGLContext* _openGLContext;
NSOpenGLPixelFormat* _pixelFormat;
float glVersion;
GLint glMaxRectTextureSize;
GLint glMaxTextureUnits;
GLint glMaxTextureSize;
GLboolean glHasHWFloats;
GLboolean glHasTextureRange;
GLboolean glHasClientStorage;
GLboolean glHasTextureRectangle;
bool glHasFastFloats;
bool glIsIntelIntegratedGraphics;
bool glUseSharedHint;
GLuint glTexture;
// Gamma values used for fade operations
CGGammaValue redMin, redMax, redGamma;
CGGammaValue greenMin, greenMax, greenGamma;
CGGammaValue blueMin, blueMax, blueGamma;
// buffer used to convert floats into before uploading to graphics card
unsigned char* XRGB8888_buffer;
// Listener that should receive any events
Listener* displayListener;
// Display represented by this view
AppleDisplay* display;
// rectangle the pixel buffers are copied/stretched to,
// usually the whole window content, but may have offsets in
// fullscreen mode (e.g. for letterbox or square formats)
NSRect fillRect;
BOOL isFullscreen;
// screen ID that is used for output
CGDirectDisplayID displayID;
}
+ (NSOpenGLPixelFormat*)defaultPixelFormatForFullscreen:(BOOL)fullscreen displayID:(CGDirectDisplayID)displayID;
+ (NSOpenGLPixelFormat*)defaultPixelFormat;
- (id)initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat*)format display:(AppleDisplay*)theDisplay;
- (void)setOpenGLContext:(NSOpenGLContext*)context;
- (NSOpenGLContext*)openGLContext;
- (void)clearGLContext;
- (void)updateGLInfo;
- (void)releaseTexture;
- (void)prepareTexture:(const GLvoid*)textureData;
- (void)prepareOpenGL;
- (void)update;
- (void)reshape;
- (void)setPixelFormat:(NSOpenGLPixelFormat*)pixelFormat;
- (NSOpenGLPixelFormat*)pixelFormat;
- (void)setListener:(Listener*)listener;
- (Listener*)listener;
// no setter for "display", as this is set once in -init
- (AppleDisplay*)display;
- (CGDirectDisplayID)displayID;
- (void)setFillRect:(NSRect)newFillRect;
- (NSRect)fillRect;
- (void)hideCursor;
- (void)unhideCursor;
- (void)fadeInDisplay;
- (void)fadeOutDisplay;
- (void)clear;
- (void)copyTrueColorPixelsUsingOpenGL:(const TrueColorPixel*)trueColorPixels
floatingPointPixels:(const FloatingPointPixel*)floatingPointPixels
dirtyRect:(const Rectangle*)dirtyBox;
- (BOOL)setFullscreen:(BOOL)fullscreen;
- (void)menuToggleFullscreen:(id)sender;
- (void)zoomX:(id)sender;
@end
@implementation PixelToasterView
+ (NSOpenGLPixelFormat*)defaultPixelFormat {
return [self defaultPixelFormatForFullscreen:NO displayID:CGMainDisplayID()];
}
+ (NSOpenGLPixelFormat*)defaultPixelFormatForFullscreen:(BOOL)fullscreen displayID:(CGDirectDisplayID)displayID {
NSOpenGLPixelFormat* pixelFormat = nil;
NSOpenGLPixelFormatAttribute attributes[20];
int at_index = 0;
attributes[at_index++] = NSOpenGLPFADoubleBuffer;
attributes[at_index++] = NSOpenGLPFAAccelerated;
//attributes[ at_index++ ] = NSOpenGLPFAColorFloat;
attributes[at_index++] = NSOpenGLPFAColorSize;
attributes[at_index++] = (NSOpenGLPixelFormatAttribute)24;
attributes[at_index++] = NSOpenGLPFAScreenMask;
attributes[at_index++] = (NSOpenGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(displayID);
if (!fullscreen)
{
attributes[at_index++] = NSOpenGLPFABackingStore;
attributes[at_index++] = NSOpenGLPFANoRecovery;
}
else
{ // Fullscreen
attributes[at_index++] = NSOpenGLPFAFullScreen;
}
attributes[at_index] = (NSOpenGLPixelFormatAttribute)0;
pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
return [pixelFormat autorelease];
}
- (void)surfaceNeedsUpdate:(NSNotification*)notification {
PARAMETER_UNUSED(notification)
[self update];
}
- (id)initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat*)format display:(AppleDisplay*)theDisplay {
self = [super initWithFrame:frameRect];
display = theDisplay;
displayID = CGMainDisplayID();
glTexture = 0;
if (self != nil)
{
_pixelFormat = [format retain];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(surfaceNeedsUpdate:)
name:NSViewGlobalFrameDidChangeNotification
object:self];
}
return self;
}
- (void)releaseTexture {
if (XRGB8888_buffer != 0)
{
free(XRGB8888_buffer);
XRGB8888_buffer = 0;
}
if (glTexture > 0)
{
glDeleteTextures(1, &glTexture);
glTexture = 0;
}
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSViewGlobalFrameDidChangeNotification
object:self];
[self releaseTexture];
[self clearGLContext];
[_pixelFormat release];
[super dealloc];
}
- (void)setPixelFormat:(NSOpenGLPixelFormat*)pixelFormat {
[_pixelFormat release];
_pixelFormat = [pixelFormat retain];
}
- (NSOpenGLPixelFormat*)pixelFormat {
return _pixelFormat;
}
- (void)setOpenGLContext:(NSOpenGLContext*)context {
[self clearGLContext];
_openGLContext = [context retain];
}
- (NSOpenGLContext*)openGLContext {
// create a context if none exists
if (_openGLContext == nil)
{
[self updateGLInfo];
if (_pixelFormat == nil)
{
[self setPixelFormat:[[self class] defaultPixelFormatForFullscreen:isFullscreen displayID:displayID]];
}
_openGLContext = [[NSOpenGLContext alloc] initWithFormat:_pixelFormat shareContext:nil];
[_openGLContext makeCurrentContext];
[self prepareOpenGL];
}
if ((_openGLContext == nil) || (_pixelFormat == nil))
{
return nil;
}
return _openGLContext;
}
- (void)clearGLContext {
if (_openGLContext != nil)
{
[self releaseTexture];
if ([_openGLContext view] == self)
{
[_openGLContext clearDrawable];
}
[_openGLContext release];
_openGLContext = nil;
}
// release pixel format too
[self setPixelFormat:nil];
}
- (void)updateGLInfo {
const GLubyte *glVersionString, *glExtensions, *glRendererString;
if (displayID == 0)
displayID = CGMainDisplayID();
CGOpenGLDisplayMask displayMask = CGDisplayIDToOpenGLDisplayMask(displayID);
// Check capabilities of display represented by display mask
CGLPixelFormatAttribute attribs[] = {kCGLPFADisplayMask, (CGLPixelFormatAttribute)displayMask,
(CGLPixelFormatAttribute)0};
CGLPixelFormatObj pixelFormat = NULL;
GLint numPixelFormats = 0;
CGLContextObj cglContext = 0;
CGLContextObj curr_ctx = CGLGetCurrentContext();
CGLChoosePixelFormat(attribs, &pixelFormat, &numPixelFormats);
if (pixelFormat)
{
CGLCreateContext(pixelFormat, NULL, &cglContext);
CGLDestroyPixelFormat(pixelFormat);
CGLSetCurrentContext(cglContext);
if (cglContext)
{
// Check for capabilities and functionality
glVersionString = glGetString(GL_VERSION);
glExtensions = glGetString(GL_EXTENSIONS);
glRendererString = glGetString(GL_RENDERER);
sscanf((char*)glVersionString, "%f", &glVersion);
glGetIntegerv(GL_MAX_TEXTURE_UNITS, &glMaxTextureUnits);
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &glMaxTextureSize);
glHasHWFloats = gluCheckExtension((const GLubyte*)"GL_APPLE_float_pixels", glExtensions);
glHasTextureRange = gluCheckExtension((const GLubyte*)"GL_APPLE_texture_range", glExtensions);
glHasClientStorage = gluCheckExtension((const GLubyte*)"GL_APPLE_client_storage", glExtensions);
glHasTextureRectangle = gluCheckExtension((const GLubyte*)"GL_EXT_texture_rectangle", glExtensions);
// on my iMac handing floats directly to the GPU can keep up with
// PixelToaster's conversion, but on all other tested machines it
// absolutely destroys performance. We will need this later for
// PixelToaster's ToneMapping extension, but for now we leave it disabled
glHasFastFloats = false; // = glHasHWFloats
// the integrated graphics chipsets I could test on were slower with
// client storage, so we set a flag for this code path...
glIsIntelIntegratedGraphics = (NULL != strstr((const char*)glRendererString, "Intel"));
// generally GL_STORAGE_CACHED_APPLE seems to get the higher performance,
// but at least on the new iMacs (ATI HD 2600 Pro in my case)
// GL_STORAGE_SHARED_APPLE is a lot faster for TrueColor
glUseSharedHint = (NULL != strstr((const char*)glRendererString, "Radeon HD 2600"));
if (glHasTextureRectangle)
glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE_EXT, &glMaxRectTextureSize);
else
glMaxRectTextureSize = 0;
# if PIXELTOASTER_APPLE_DEBUG
const GLubyte* glVendorString = glGetString(GL_VENDOR);
printf("OpenGL Version: %s\n", glVersionString);
printf("Vendor: %s\n", glVendorString);
printf("Renderer: %s\n", glRendererString);
printf("Max Texture Size: %d\n", (int)glMaxTextureSize);
printf("Max Texture Size: %d\n", (int)glMaxTextureSize);
printf("Max Rectangle Texture Size: %d\n", (int)glMaxRectTextureSize);
printf("Texture Rectangle: %savailable\n", glHasTextureRectangle ? "" : "not ");
printf("Float Buffers....: %savailable\n", glHasHWFloats ? "" : "not ");
printf("Texture Range....: %savailable\n", glHasTextureRange ? "" : "not ");
printf("Client Storage...: %savailable\n", glHasClientStorage ? "" : "not ");
# endif
}
}
CGLDestroyContext(cglContext);
CGLSetCurrentContext(curr_ctx);
}
- (void)prepareTexture:(const GLvoid*)textureData {
if (glTexture == 0)
{
const int width = display->width();
const int height = display->height();
bool useFloat = (display->mode() == Mode::FloatingPoint);
GL_CHECK_ERROR(glGenTextures(1, &glTexture));
GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_RECTANGLE_ARB, glTexture));
if (!glIsIntelIntegratedGraphics)
{
GL_CHECK_ERROR(glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE));
GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_PRIORITY, 0.0f));
GL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_RECTANGLE_ARB,
GL_TEXTURE_STORAGE_HINT_APPLE,
glUseSharedHint ? GL_STORAGE_SHARED_APPLE
: GL_STORAGE_CACHED_APPLE));
}
GL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
GL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
GL_CHECK_ERROR(glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL));
GL_CHECK_ERROR(glPixelStorei(GL_UNPACK_ROW_LENGTH, width));
GL_CHECK_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
if (!glHasFastFloats)
{
const int buffer_size = width * height * 4;
if (!XRGB8888_buffer)
XRGB8888_buffer = (unsigned char*)malloc(buffer_size);
if (useFloat)
{
textureData = XRGB8888_buffer;
useFloat = false;
}
}
if (glHasTextureRange)
{
GL_CHECK_ERROR(glTextureRangeAPPLE(GL_TEXTURE_RECTANGLE_ARB,
width * height * (useFloat ? 16 : 4),
textureData));
}
GL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0,
useFloat ? GL_RGB_FLOAT32_APPLE : GL_RGB8,
// HERE: using floats directly is faster on my iMac, but slower on my MBP
// and slower on both compared to PixelToasters software conversion :-P
width, height, 0,
useFloat ? GL_RGBA : GL_BGRA_EXT,
useFloat ? GL_FLOAT : GL_UNSIGNED_INT_8_8_8_8_REV,
textureData));
}
}
- (void)prepareOpenGL {
// prepare OpenGL context (state, texture, etc.)
if (isFullscreen)
{
[_openGLContext setFullScreen];
}
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glDisable(GL_ALPHA_TEST);
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
GL_CHECK_ERROR(glEnable(GL_TEXTURE_RECTANGLE_ARB));
NSOpenGLContext* context = _openGLContext;
// Clear the view, so we get a black background
[self clear];
[context flushBuffer];
[self clear];
[context flushBuffer];
// enable/disable sync to VB
GLint swapInterval = PIXELTOASTER_APPLE_VBSYNC;
[context setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
}
- (void)updateDisplayID {
NSScreen* screen = [[self window] screen];
if (nil != screen)
{
NSDictionary* screenInfo = [screen deviceDescription];
NSNumber* screenID = [screenInfo objectForKey:@"NSScreenNumber"];
displayID = (CGDirectDisplayID)[screenID longValue];
}
}
- (void)update {
if ([_openGLContext view] == self)
{
[_openGLContext update];
[self updateDisplayID];
}
}
// In NSOpenGLView this is called automatically, for normal NSViews it is not,
// which is why the sample code does not implement it, we just call it
// manually when necessary
- (void)reshape {
NSOpenGLContext* context = [self openGLContext];
[context makeCurrentContext];
[context update];
NSRect drawableRect = [self convertRect:[self bounds] toView:nil];
// calculate fillRect
double drawableRatio = NSWidth(drawableRect) / NSHeight(drawableRect);
float displayRatio = (float)display->width() / (float)display->height();
if (drawableRatio <= displayRatio)
{
// display is wider than screen, so we leave black borders at top and bottom (letterbox)
double usedHeight = ceilf(NSWidth(drawableRect) / displayRatio);
[self setFillRect:NSMakeRect(0.0f, (NSHeight(drawableRect) - usedHeight) / 2.0f,
NSWidth(drawableRect), usedHeight)];
}
else
{
// screen is wider than display, leave black borders to the left and right
double usedWidth = ceilf(NSHeight(drawableRect) * displayRatio);
[self setFillRect:NSMakeRect((NSWidth(drawableRect) - usedWidth) / 2.0f, 0.0f,
usedWidth, NSHeight(drawableRect))];
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport((GLint)fillRect.origin.x, (GLint)fillRect.origin.y,
(GLsizei)fillRect.size.width, (GLsizei)fillRect.size.height);
[NSOpenGLContext clearCurrentContext];
}
- (BOOL)setFullscreen:(BOOL)fullscreen {
if (isFullscreen != fullscreen)
{
[self clearGLContext];
if (fullscreen == YES)
{
CGRect rect = CGDisplayBounds(displayID);
[self setFrame:*(NSRect*)&rect];
# if !PIXELTOASTER_APPLE_DEBUG
// Capture the display
CGDisplayErr err = CGDisplayCapture(displayID);
if (err != CGDisplayNoErr)
{
fprintf(stderr, "%s:%d:: -setFullscreen: could not capture display!\n", __FILE__, __LINE__);
return NO;
}
# if PIXELTOASTER_APPLE_ALLOW_MODESWITCH
//boolean_t exactMatch;
CFDictionaryRef bestMode = CGDisplayBestModeForParameters(displayID, 32, width(), height(), 0 /*&exactMatch*/);
if (bestMode)
CGDisplaySwitchToMode(displayID, bestMode);
# endif
# endif
}
else
{
// Release any captured display
CGReleaseAllDisplays();
}
isFullscreen = fullscreen;
[self reshape];
if (nil == [self openGLContext])
{
fprintf(stderr, "%s:%d:: -setFullscreen: could not get new context!\n", __FILE__, __LINE__);
return NO;
}
}
return YES;
}
- (BOOL)fullscreen {
return isFullscreen;
}
- (CGDirectDisplayID)displayID {
return displayID;
}
- (void)lockFocus {
NSOpenGLContext* context = [self openGLContext];
[super lockFocus];
if ([context view] != self)
{
[context setView:self];
}
[context makeCurrentContext];
}
- (void)viewDidMoveToWindow {
[super viewDidMoveToWindow];
if ([self window] == nil)
{
[_openGLContext clearDrawable];
}
else
{
[self updateDisplayID];
}
}
- (void)setListener:(Listener*)listener {
displayListener = listener;
}
- (Listener*)listener {
return displayListener;
}
- (AppleDisplay*)display {
return display;
}
- (void)setFillRect:(NSRect)newFillRect {
fillRect = newFillRect;
}
- (NSRect)fillRect {
return fillRect;
}
- (void)menuToggleFullscreen:(id)sender {
PARAMETER_UNUSED(sender)
if (display)
display->setShouldToggle();
}
// resize window using a factor taken from the tag of the
// menu item sending this message
- (void)zoomX:(id)sender {
NSWindow* window = [self window];
int zoomFactor = (int)[sender tag];
if ((display != nil) && (window != nil))
{
NSRect contentRect = [window contentRectForFrameRect:[window frame]];
NSRect newContentRect = contentRect;
newContentRect.size.width = display->width() * zoomFactor;
newContentRect.size.height = display->height() * zoomFactor;
// fix the y origin (else the window will keep it's *lower* right corner)
newContentRect.origin.y -= (newContentRect.size.height - contentRect.size.height);
[window setFrame:[window frameRectForContentRect:newContentRect] display:YES];
[self reshape];
}
}
- (void)hideCursor {
// the parameter to CGDisplayHideCursor is unused,
// so we just pass main display
CGDisplayHideCursor(kCGDirectMainDisplay);
CGAssociateMouseAndMouseCursorPosition(false);
// position the mouse cursor in the middle of the screen
size_t displayWidth = CGDisplayPixelsWide(displayID);
size_t displayHeight = CGDisplayPixelsHigh(displayID);
CGWarpMouseCursorPosition(CGPointMake(displayWidth / 2, displayHeight / 2));
}
- (void)unhideCursor {
// the parameter to CGDisplayShowCursor is unused,
// so we just pass main display
CGDisplayShowCursor(kCGDirectMainDisplay);
CGAssociateMouseAndMouseCursorPosition(true);
}
- (void)fadeOutDisplay {
# if !PIXELTOASTER_APPLE_DEBUG
const float FADE_INTERVAL = (1.0f / (float)FADE_STEPS);
const useconds_t SLEEP_TIME = (useconds_t)(1000000 * (FADE_TIME / (double)FADE_STEPS));
float fade;
CGGetDisplayTransferByFormula(displayID,
&redMin, &redMax, &redGamma,
&greenMin, &greenMax, &greenGamma,
&blueMin, &blueMax, &blueGamma);
for (int step = 0; step < FADE_STEPS; ++step)
{
fade = 1.0f - (step * FADE_INTERVAL);
CGSetDisplayTransferByFormula(displayID,
redMin, fade * redMax, redGamma,
greenMin, fade * greenMax, greenGamma,
blueMin, fade * blueMax, blueGamma);
usleep(SLEEP_TIME);
}
# endif
}
- (void)fadeInDisplay {
# if !PIXELTOASTER_APPLE_DEBUG
const float FADE_INTERVAL = (1.0f / (float)FADE_STEPS);
const useconds_t SLEEP_TIME = (useconds_t)(1000000 * (FADE_TIME / (double)FADE_STEPS));
float fade;
for (int step = 0; step < FADE_STEPS; ++step)
{
fade = step * FADE_INTERVAL;
CGSetDisplayTransferByFormula(displayID,
redMin, fade * redMax, redGamma,
greenMin, fade * greenMax, greenGamma,
blueMin, fade * blueMax, blueGamma);
usleep(SLEEP_TIME);
}
# endif
CGDisplayRestoreColorSyncSettings();
}
- (void)clear {
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
- (void)blitOpenGLTexture {
if (glTexture == 0)
return;
const int width = display->width();
const int height = display->height();
[[self openGLContext] makeCurrentContext];
glBegin(GL_QUADS);
glTexCoord2i(0, 0);
glVertex2f(-1.0f, 1.0f);
glTexCoord2i(width, 0);
glVertex2f(1.0f, 1.0f);
glTexCoord2i(width, height);
glVertex2f(1.0f, -1.0f);
glTexCoord2i(0, height);
glVertex2f(-1.0f, -1.0f);
glEnd();
[[self openGLContext] flushBuffer];
[NSOpenGLContext clearCurrentContext];
}
- (void)copyTrueColorPixelsUsingOpenGL:(const TrueColorPixel*)trueColorPixels
floatingPointPixels:(const FloatingPointPixel*)floatingPointPixels
dirtyRect:(const Rectangle*)dirtyBox {
const int width = display->width();
const int height = display->height();
bool useFloat = (floatingPointPixels != 0);
GLint x = 0;
GLint y = 0;
GLsizei w = width;
GLsizei h = height;
const GLvoid* bufferStart = useFloat ? (GLvoid*)floatingPointPixels : (GLvoid*)trueColorPixels;
unsigned char* buffer = (unsigned char*)bufferStart;
const int bytesPerPixel = useFloat ? 16 : 4;
if (dirtyBox != 0)
{
x = dirtyBox->xBegin;
y = dirtyBox->yBegin;
w = dirtyBox->xEnd - dirtyBox->xBegin;