1 /* $Id: wnd_quartz.mm 26108 2013-11-25 14:30:22Z rubidium $ */
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /******************************************************************************
11 * Cocoa video driver *
12 * Known things left to do: *
13 * List available resolutions. *
14 ******************************************************************************/
17 #ifdef ENABLE_COCOA_QUARTZ
19 #include "../../stdafx.h"
20 #include "../../os/macosx/macos.h"
22 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
25 #define Point OTTDPoint
26 #import <Cocoa/Cocoa.h>
30 #include "../../debug.h"
31 #include "../../rev.h"
32 #include "../../core/geometry_type.hpp"
34 #include "../../core/math_func.hpp"
35 #include "../../gfx_func.h"
37 /* On some old versions of MAC OS this may not be defined.
38 * Those versions generally only produce code for PPC. So it should be safe to
40 #ifndef kCGBitmapByteOrder32Host
41 #define kCGBitmapByteOrder32Host 0
45 * Important notice regarding all modifications!!!!!!!
46 * There are certain limitations because the file is objective C++.
47 * gdb has limitations.
48 * C++ and objective C code can't be joined in all cases (classes stuff).
49 * Read http://developer.apple.com/releasenotes/Cocoa/Objective-C++.html for more information.
52 class WindowQuartzSubdriver;
54 /* Subclass of OTTD_CocoaView to fix Quartz rendering */
55 @interface OTTD_QuartzView : OTTD_CocoaView
56 - (void)setDriver:(WindowQuartzSubdriver*)drv;
57 - (void)drawRect:(NSRect)invalidRect;
60 class WindowQuartzSubdriver : public CocoaSubdriver {
63 * This function copies 8bpp pixels from the screen buffer in 32bpp windowed mode.
65 * @param left The x coord for the left edge of the box to blit.
66 * @param top The y coord for the top edge of the box to blit.
67 * @param right The x coord for the right edge of the box to blit.
68 * @param bottom The y coord for the bottom edge of the box to blit.
70 void BlitIndexedToView32(int left, int top, int right, int bottom);
72 virtual void GetDeviceInfo();
73 virtual bool SetVideoMode(int width, int height, int bpp);
76 WindowQuartzSubdriver();
77 virtual ~WindowQuartzSubdriver();
79 virtual void Draw(bool force_update);
80 virtual void MakeDirty(int left, int top, int width, int height);
81 virtual void UpdatePalette(uint first_color, uint num_colors);
83 virtual uint ListModes(OTTD_Point *modes, uint max_modes);
85 virtual bool ChangeResolution(int w, int h, int bpp);
87 virtual bool IsFullscreen() { return false; }
88 virtual bool ToggleFullscreen(); /* Full screen mode on OSX 10.7 */
90 virtual int GetWidth() { return window_width; }
91 virtual int GetHeight() { return window_height; }
92 virtual void *GetPixelBuffer() { return buffer_depth == 8 ? pixel_buffer : window_buffer; }
94 /* Convert local coordinate to window server (CoreGraphics) coordinate */
95 virtual CGPoint PrivateLocalToCG(NSPoint *p);
97 virtual NSPoint GetMouseLocation(NSEvent *event);
98 virtual bool MouseIsInsideView(NSPoint *pt);
100 virtual bool IsActive() { return active; }
103 void SetPortAlphaOpaque();
104 bool WindowResized();
108 static CGColorSpaceRef QZ_GetCorrectColorSpace()
110 static CGColorSpaceRef colorSpace = NULL;
112 if (colorSpace == NULL) {
113 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
114 if (MacOSVersionIsAtLeast(10, 5, 0)) {
115 colorSpace = CGDisplayCopyColorSpace(CGMainDisplayID());
119 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !defined(HAVE_OSX_1011_SDK)
120 CMProfileRef sysProfile;
121 if (CMGetSystemProfile(&sysProfile) == noErr) {
122 colorSpace = CGColorSpaceCreateWithPlatformColorSpace(sysProfile);
123 CMCloseProfile(sysProfile);
128 if (colorSpace == NULL) colorSpace = CGColorSpaceCreateDeviceRGB();
130 if (colorSpace == NULL) error("Could not get system colour space. You might need to recalibrate your monitor.");
137 @implementation OTTD_QuartzView
139 - (void)setDriver:(WindowQuartzSubdriver*)drv
143 - (void)drawRect:(NSRect)invalidRect
145 if (driver->cgcontext == NULL) return;
147 CGContextRef viewContext = (CGContextRef)[ [ NSGraphicsContext currentContext ] graphicsPort ];
148 CGContextSetShouldAntialias(viewContext, FALSE);
149 CGContextSetInterpolationQuality(viewContext, kCGInterpolationNone);
151 /* The obtained 'rect' is actually a union of all dirty rects, let's ask for an explicit list of rects instead */
152 const NSRect *dirtyRects;
153 NSInteger dirtyRectCount;
154 [ self getRectsBeingDrawn:&dirtyRects count:&dirtyRectCount ];
156 /* We need an Image in order to do blitting, but as we don't touch the context between this call and drawing no copying will actually be done here */
157 CGImageRef fullImage = CGBitmapContextCreateImage(driver->cgcontext);
159 /* Calculate total area we are blitting */
161 for (int n = 0; n < dirtyRectCount; n++) {
162 blitArea += (uint32)(dirtyRects[n].size.width * dirtyRects[n].size.height);
166 * This might be completely stupid, but in my extremely subjective opinion it feels faster
167 * The point is, if we're blitting less than 50% of the dirty rect union then it's still a good idea to blit each dirty
168 * rect separately but if we blit more than that, it's just cheaper to blit the entire union in one pass.
169 * Feel free to remove or find an even better value than 50% ... / blackis
171 NSRect frameRect = [ self frame ];
172 if (blitArea / (float)(invalidRect.size.width * invalidRect.size.height) > 0.5f) {
173 NSRect rect = invalidRect;
177 blitRect.origin.x = rect.origin.x;
178 blitRect.origin.y = rect.origin.y;
179 blitRect.size.width = rect.size.width;
180 blitRect.size.height = rect.size.height;
182 clipRect.origin.x = rect.origin.x;
183 clipRect.origin.y = frameRect.size.height - rect.origin.y - rect.size.height;
185 clipRect.size.width = rect.size.width;
186 clipRect.size.height = rect.size.height;
188 /* Blit dirty part of image */
189 CGImageRef clippedImage = CGImageCreateWithImageInRect(fullImage, clipRect);
190 CGContextDrawImage(viewContext, blitRect, clippedImage);
191 CGImageRelease(clippedImage);
193 for (int n = 0; n < dirtyRectCount; n++) {
194 NSRect rect = dirtyRects[n];
198 blitRect.origin.x = rect.origin.x;
199 blitRect.origin.y = rect.origin.y;
200 blitRect.size.width = rect.size.width;
201 blitRect.size.height = rect.size.height;
203 clipRect.origin.x = rect.origin.x;
204 clipRect.origin.y = frameRect.size.height - rect.origin.y - rect.size.height;
206 clipRect.size.width = rect.size.width;
207 clipRect.size.height = rect.size.height;
209 /* Blit dirty part of image */
210 CGImageRef clippedImage = CGImageCreateWithImageInRect(fullImage, clipRect);
211 CGContextDrawImage(viewContext, blitRect, clippedImage);
212 CGImageRelease(clippedImage);
216 CGImageRelease(fullImage);
222 void WindowQuartzSubdriver::GetDeviceInfo()
224 /* Initialize the video settings; this data persists between mode switches
225 * and gather some information that is useful to know about the display */
227 # if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
228 /* This way is deprecated as of OSX 10.6 but continues to work.Thus use it
229 * always, unless allowed to skip compatibility with 10.5 and earlier */
230 CFDictionaryRef cur_mode = CGDisplayCurrentMode(kCGDirectMainDisplay);
233 (const __CFNumber*)CFDictionaryGetValue(cur_mode, kCGDisplayWidth),
234 kCFNumberSInt32Type, &this->device_width
238 (const __CFNumber*)CFDictionaryGetValue(cur_mode, kCGDisplayHeight),
239 kCFNumberSInt32Type, &this->device_height
242 /* Use the new API when compiling for OSX 10.6 or later */
243 CGDisplayModeRef cur_mode = CGDisplayCopyDisplayMode(kCGDirectMainDisplay);
244 if (cur_mode == NULL) { return; }
246 this->device_width = CGDisplayModeGetWidth(cur_mode);
247 this->device_height = CGDisplayModeGetHeight(cur_mode);
249 CGDisplayModeRelease(cur_mode);
253 /** Switch to full screen mode on OSX 10.7
254 * @return Whether we switched to full screen
256 bool WindowQuartzSubdriver::ToggleFullscreen()
258 if ([ this->window respondsToSelector:@selector(toggleFullScreen:) ]) {
259 [ this->window performSelector:@selector(toggleFullScreen:) withObject:this->window ];
266 bool WindowQuartzSubdriver::SetVideoMode(int width, int height, int bpp)
269 this->GetDeviceInfo();
271 if (width > this->device_width) width = this->device_width;
272 if (height > this->device_height) height = this->device_height;
274 NSRect contentRect = NSMakeRect(0, 0, width, height);
276 /* Check if we should recreate the window */
277 if (this->window == nil) {
278 OTTD_CocoaWindowDelegate *delegate;
280 /* Set the window style */
281 unsigned int style = NSTitledWindowMask;
282 style |= (NSMiniaturizableWindowMask | NSClosableWindowMask);
283 style |= NSResizableWindowMask;
285 /* Manually create a window, avoids having a nib file resource */
286 this->window = [ [ OTTD_CocoaWindow alloc ]
287 initWithContentRect:contentRect
289 backing:NSBackingStoreBuffered
292 if (this->window == nil) {
293 DEBUG(driver, 0, "Could not create the Cocoa window.");
298 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
299 /* Add built in full-screen support when available (OS X 10.7 and higher)
300 * This code actually compiles for 10.5 and later, but only makes sense in conjunction
301 * with the quartz fullscreen support as found only in 10.7 and later
303 if ([this->window respondsToSelector:@selector(toggleFullScreen:)]) {
304 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
305 /* Constants needed to build on pre-10.7 SDKs. Source: NSWindow documentation. */
306 const int NSWindowCollectionBehaviorFullScreenPrimary = 1 << 7;
307 const int NSWindowFullScreenButton = 7;
310 NSWindowCollectionBehavior behavior = [ this->window collectionBehavior ];
311 behavior |= NSWindowCollectionBehaviorFullScreenPrimary;
312 [ this->window setCollectionBehavior:behavior ];
314 NSButton* fullscreenButton = [ this->window standardWindowButton:NSWindowFullScreenButton ];
315 [ fullscreenButton setAction:@selector(toggleFullScreen:) ];
316 [ fullscreenButton setTarget:this->window ];
318 [ this->window setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary ];
322 [ this->window setDriver:this ];
325 snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
326 NSString *nsscaption = [ [ NSString alloc ] initWithUTF8String:caption ];
327 [ this->window setTitle:nsscaption ];
328 [ this->window setMiniwindowTitle:nsscaption ];
329 [ nsscaption release ];
331 [ this->window setContentMinSize:NSMakeSize(64.0f, 64.0f) ];
333 [ this->window setAcceptsMouseMovedEvents:YES ];
334 [ this->window setViewsNeedDisplay:NO ];
336 [ this->window useOptimizedDrawing:YES ];
338 delegate = [ [ OTTD_CocoaWindowDelegate alloc ] init ];
339 [ delegate setDriver:this ];
340 [ this->window setDelegate:[ delegate autorelease ] ];
342 /* We already have a window, just change its size */
343 [ this->window setContentSize:contentRect.size ];
345 /* Ensure frame height - title bar height >= view height */
346 contentRect.size.height = Clamp(height, 0, (int)[ this->window frame ].size.height - 22 /* 22 is the height of title bar of window*/);
348 if (this->cocoaview != nil) {
349 height = (int)contentRect.size.height;
350 [ this->cocoaview setFrameSize:contentRect.size ];
354 this->window_width = width;
355 this->window_height = height;
356 this->buffer_depth = bpp;
358 [ this->window center ];
360 /* Only recreate the view if it doesn't already exist */
361 if (this->cocoaview == nil) {
362 this->cocoaview = [ [ OTTD_QuartzView alloc ] initWithFrame:contentRect ];
363 if (this->cocoaview == nil) {
364 DEBUG(driver, 0, "Could not create the Quartz view.");
369 [ this->cocoaview setDriver:this ];
371 [ (NSView*)this->cocoaview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable ];
372 [ this->window setContentView:cocoaview ];
373 [ this->cocoaview release ];
374 [ this->window makeKeyAndOrderFront:nil ];
377 bool ret = WindowResized();
378 this->UpdatePalette(0, 256);
385 void WindowQuartzSubdriver::BlitIndexedToView32(int left, int top, int right, int bottom)
387 const uint32 *pal = this->palette;
388 const uint8 *src = (uint8*)this->pixel_buffer;
389 uint32 *dst = (uint32*)this->window_buffer;
390 uint width = this->window_width;
391 uint pitch = this->window_width;
393 for (int y = top; y < bottom; y++) {
394 for (int x = left; x < right; x++) {
395 dst[y * pitch + x] = pal[src[y * width + x]];
401 WindowQuartzSubdriver::WindowQuartzSubdriver()
403 this->window_width = 0;
404 this->window_height = 0;
405 this->buffer_depth = 0;
406 this->window_buffer = NULL;
407 this->pixel_buffer = NULL;
408 this->active = false;
412 this->cocoaview = nil;
414 this->cgcontext = NULL;
416 this->num_dirty_rects = MAX_DIRTY_RECTS;
419 WindowQuartzSubdriver::~WindowQuartzSubdriver()
421 /* Release window mode resources */
422 if (this->window != nil) [ this->window close ];
424 CGContextRelease(this->cgcontext);
426 free(this->window_buffer);
427 free(this->pixel_buffer);
430 void WindowQuartzSubdriver::Draw(bool force_update)
432 /* Check if we need to do anything */
433 if (this->num_dirty_rects == 0 || [ this->window isMiniaturized ]) return;
435 if (this->num_dirty_rects >= MAX_DIRTY_RECTS) {
436 this->num_dirty_rects = 1;
437 this->dirty_rects[0].left = 0;
438 this->dirty_rects[0].top = 0;
439 this->dirty_rects[0].right = this->window_width;
440 this->dirty_rects[0].bottom = this->window_height;
443 /* Build the region of dirty rectangles */
444 for (int i = 0; i < this->num_dirty_rects; i++) {
445 /* We only need to blit in indexed mode since in 32bpp mode the game draws directly to the image. */
446 if (this->buffer_depth == 8) {
448 this->dirty_rects[i].left,
449 this->dirty_rects[i].top,
450 this->dirty_rects[i].right,
451 this->dirty_rects[i].bottom
456 dirtyrect.origin.x = this->dirty_rects[i].left;
457 dirtyrect.origin.y = this->window_height - this->dirty_rects[i].bottom;
458 dirtyrect.size.width = this->dirty_rects[i].right - this->dirty_rects[i].left;
459 dirtyrect.size.height = this->dirty_rects[i].bottom - this->dirty_rects[i].top;
461 /* Normally drawRect will be automatically called by Mac OS X during next update cycle,
462 * and then blitting will occur. If force_update is true, it will be done right now. */
463 [ this->cocoaview setNeedsDisplayInRect:dirtyrect ];
464 if (force_update) [ this->cocoaview displayIfNeeded ];
467 this->num_dirty_rects = 0;
470 void WindowQuartzSubdriver::MakeDirty(int left, int top, int width, int height)
472 if (this->num_dirty_rects < MAX_DIRTY_RECTS) {
473 dirty_rects[this->num_dirty_rects].left = left;
474 dirty_rects[this->num_dirty_rects].top = top;
475 dirty_rects[this->num_dirty_rects].right = left + width;
476 dirty_rects[this->num_dirty_rects].bottom = top + height;
478 this->num_dirty_rects++;
481 void WindowQuartzSubdriver::UpdatePalette(uint first_color, uint num_colors)
483 if (this->buffer_depth != 8) return;
485 for (uint i = first_color; i < first_color + num_colors; i++) {
486 uint32 clr = 0xff000000;
487 clr |= (uint32)_cur_palette.palette[i].r << 16;
488 clr |= (uint32)_cur_palette.palette[i].g << 8;
489 clr |= (uint32)_cur_palette.palette[i].b;
490 this->palette[i] = clr;
493 this->num_dirty_rects = MAX_DIRTY_RECTS;
496 uint WindowQuartzSubdriver::ListModes(OTTD_Point *modes, uint max_modes)
498 return QZ_ListModes(modes, max_modes, kCGDirectMainDisplay, this->buffer_depth);
501 bool WindowQuartzSubdriver::ChangeResolution(int w, int h, int bpp)
503 int old_width = this->window_width;
504 int old_height = this->window_height;
505 int old_bpp = this->buffer_depth;
507 if (this->SetVideoMode(w, h, bpp)) return true;
508 if (old_width != 0 && old_height != 0) this->SetVideoMode(old_width, old_height, old_bpp);
513 /* Convert local coordinate to window server (CoreGraphics) coordinate */
514 CGPoint WindowQuartzSubdriver::PrivateLocalToCG(NSPoint *p)
517 p->y = this->window_height - p->y;
518 *p = [ this->cocoaview convertPoint:*p toView:nil ];
520 *p = [ this->window convertBaseToScreen:*p ];
521 p->y = this->device_height - p->y;
530 NSPoint WindowQuartzSubdriver::GetMouseLocation(NSEvent *event)
534 if ( [ event window ] == nil) {
535 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
536 if ([ [ this->cocoaview window ] respondsToSelector:@selector(convertRectFromScreen:) ]) {
537 pt = [ this->cocoaview convertPoint:[ [ this->cocoaview window ] convertRectFromScreen:NSMakeRect([ event locationInWindow ].x, [ event locationInWindow ].y, 0, 0) ].origin fromView:nil ];
542 pt = [ this->cocoaview convertPoint:[ [ this->cocoaview window ] convertScreenToBase:[ event locationInWindow ] ] fromView:nil ];
545 pt = [ event locationInWindow ];
548 pt.y = this->window_height - pt.y;
553 bool WindowQuartzSubdriver::MouseIsInsideView(NSPoint *pt)
555 return [ cocoaview mouse:*pt inRect:[ this->cocoaview bounds ] ];
559 /* This function makes the *game region* of the window 100% opaque.
560 * The genie effect uses the alpha component. Otherwise,
561 * it doesn't seem to matter what value it has.
563 void WindowQuartzSubdriver::SetPortAlphaOpaque()
565 uint32 *pixels = (uint32*)this->window_buffer;
566 uint32 pitch = this->window_width;
568 for (int y = 0; y < this->window_height; y++)
569 for (int x = 0; x < this->window_width; x++) {
570 pixels[y * pitch + x] |= 0xFF000000;
574 bool WindowQuartzSubdriver::WindowResized()
576 if (this->window == nil || this->cocoaview == nil) return true;
578 NSRect newframe = [ this->cocoaview frame ];
580 this->window_width = (int)newframe.size.width;
581 this->window_height = (int)newframe.size.height;
583 /* Create Core Graphics Context */
584 free(this->window_buffer);
585 this->window_buffer = (uint32*)malloc(this->window_width * this->window_height * 4);
587 CGContextRelease(this->cgcontext);
588 this->cgcontext = CGBitmapContextCreate(
589 this->window_buffer, // data
590 this->window_width, // width
591 this->window_height, // height
592 8, // bits per component
593 this->window_width * 4, // bytes per row
594 QZ_GetCorrectColorSpace(), // color space
595 kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host
598 assert(this->cgcontext != NULL);
599 CGContextSetShouldAntialias(this->cgcontext, FALSE);
600 CGContextSetAllowsAntialiasing(this->cgcontext, FALSE);
601 CGContextSetInterpolationQuality(this->cgcontext, kCGInterpolationNone);
603 if (this->buffer_depth == 8) {
604 free(this->pixel_buffer);
605 this->pixel_buffer = malloc(this->window_width * this->window_height);
606 if (this->pixel_buffer == NULL) {
607 DEBUG(driver, 0, "Failed to allocate pixel buffer");
612 QZ_GameSizeChanged();
615 this->num_dirty_rects = MAX_DIRTY_RECTS;
621 CocoaSubdriver *QZ_CreateWindowQuartzSubdriver(int width, int height, int bpp)
623 if (!MacOSVersionIsAtLeast(10, 4, 0)) {
624 DEBUG(driver, 0, "The cocoa quartz subdriver requires Mac OS X 10.4 or later.");
628 if (bpp != 8 && bpp != 32) {
629 DEBUG(driver, 0, "The cocoa quartz subdriver only supports 8 and 32 bpp.");
633 WindowQuartzSubdriver *ret = new WindowQuartzSubdriver();
635 if (!ret->ChangeResolution(width, height, bpp)) {
644 #endif /* MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 */
645 #endif /* ENABLE_COCOA_QUARTZ */
646 #endif /* WITH_COCOA */