2009-08-21 21:21:05 +01:00
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
2011-07-21 17:13:34 +01:00
/** @file cocoa_v.mm Code related to the cocoa video driver(s). */
2007-11-22 21:48:17 +00:00
/******************************************************************************
* Cocoa video driver *
* Known things left to do: *
* Nothing at the moment. *
******************************************************************************/
#ifdef WITH_COCOA
2009-07-14 17:43:45 +01:00
#include "../../stdafx.h"
2009-10-04 22:08:30 +01:00
#include "../../os/macosx/macos.h"
2007-11-22 21:48:17 +00:00
2009-07-14 17:43:45 +01:00
#define Rect OTTDRect
#define Point OTTDPoint
2007-11-22 21:48:17 +00:00
#import <Cocoa/Cocoa.h>
2009-07-14 17:43:45 +01:00
#undef Rect
#undef Point
#include "../../openttd.h"
#include "../../debug.h"
#include "../../core/geometry_type.hpp"
2021-02-06 19:22:37 +00:00
#include "../../core/math_func.hpp"
2009-07-14 17:43:45 +01:00
#include "cocoa_v.h"
2020-12-26 15:07:47 +00:00
#include "cocoa_wnd.h"
2009-07-14 17:43:45 +01:00
#include "../../blitter/factory.hpp"
2021-02-06 19:22:37 +00:00
#include "../../framerate_type.h"
#include "../../network/network.h"
2009-07-14 17:43:45 +01:00
#include "../../gfx_func.h"
2021-02-06 19:22:37 +00:00
#include "../../thread.h"
#include "../../core/random_func.hpp"
#include "../../settings_type.h"
2013-08-05 21:37:44 +01:00
#include "../../window_func.h"
#include "../../window_gui.h"
2009-07-14 17:43:45 +01:00
2007-11-22 21:48:17 +00:00
#import <sys/param.h> /* for MAXPATHLEN */
2021-02-06 19:22:37 +00:00
#import <sys/time.h> /* gettimeofday */
2007-11-22 21:48:17 +00:00
/**
* Important notice regarding all modifications!!!!!!!
* There are certain limitations because the file is objective C++.
* gdb has limitations.
* C++ and objective C code can't be joined in all cases (classes stuff).
* Read http://developer.apple.com/releasenotes/Cocoa/Objective-C++.html for more information.
*/
2020-12-26 15:07:47 +00:00
/* On some old versions of MAC OS this may not be defined.
* Those versions generally only produce code for PPC. So it should be safe to
* set this to 0. */
#ifndef kCGBitmapByteOrder32Host
#define kCGBitmapByteOrder32Host 0
#endif
2007-11-22 21:48:17 +00:00
2020-12-26 15:07:47 +00:00
bool _cocoa_video_started = false;
2007-11-22 21:48:17 +00:00
2021-02-06 19:22:37 +00:00
extern bool _tab_is_down;
#ifdef _DEBUG
static uint32 _tEvent;
#endif
2013-11-08 20:18:27 +00:00
2021-01-10 21:27:31 +00:00
/** List of common display/window sizes. */
static const Dimension _default_resolutions[] = {
{ 640, 480 },
{ 800, 600 },
{ 1024, 768 },
{ 1152, 864 },
{ 1280, 800 },
{ 1280, 960 },
{ 1280, 1024 },
{ 1400, 1050 },
{ 1600, 1200 },
{ 1680, 1050 },
{ 1920, 1200 },
{ 2560, 1440 }
};
2013-11-08 20:18:27 +00:00
2021-01-22 21:29:46 +00:00
static FVideoDriver_Cocoa iFVideoDriver_Cocoa;
2021-02-12 00:19:00 +00:00
/**
* Get current realtime.
* @return Tick time in milliseconds.
*/
2021-02-06 19:22:37 +00:00
static uint32 GetTick()
{
struct timeval tim;
gettimeofday(&tim, NULL);
return tim.tv_usec / 1000 + tim.tv_sec * 1000;
}
2021-02-12 00:19:00 +00:00
/** Subclass of NSView for drawing to screen. */
2021-01-31 17:58:23 +00:00
@interface OTTD_QuartzView : NSView {
VideoDriver_Cocoa *driver;
}
- (instancetype)initWithFrame:(NSRect)frameRect andDriver:(VideoDriver_Cocoa *)drv;
2021-01-30 18:13:29 +00:00
@end
2021-01-22 21:29:46 +00:00
VideoDriver_Cocoa::VideoDriver_Cocoa()
2007-11-22 21:48:17 +00:00
{
2021-01-22 21:29:46 +00:00
this->window_width = 0;
this->window_height = 0;
2021-02-06 19:23:53 +00:00
this->window_pitch = 0;
2021-01-22 21:29:46 +00:00
this->buffer_depth = 0;
this->window_buffer = nullptr;
this->pixel_buffer = nullptr;
this->setup = false;
2021-01-10 21:27:31 +00:00
2021-01-22 21:29:46 +00:00
this->window = nil;
this->cocoaview = nil;
2021-01-30 18:13:29 +00:00
this->delegate = nil;
2007-11-22 21:48:17 +00:00
2021-01-22 21:29:46 +00:00
this->color_space = nullptr;
this->cgcontext = nullptr;
2007-11-22 21:48:17 +00:00
2021-02-11 21:54:43 +00:00
this->num_dirty_rects = lengthof(this->dirty_rects);
2021-01-22 21:29:46 +00:00
}
2007-11-22 21:48:17 +00:00
2021-02-12 00:19:00 +00:00
/** Stop Cocoa video driver. */
2007-11-22 21:48:17 +00:00
void VideoDriver_Cocoa::Stop()
{
if (!_cocoa_video_started) return;
2020-12-26 15:07:47 +00:00
CocoaExitApplication();
2013-08-05 21:36:10 +01:00
2021-01-22 21:29:46 +00:00
/* Release window mode resources */
if (this->window != nil) [ this->window close ];
2021-01-30 18:13:29 +00:00
[ this->cocoaview release ];
[ this->delegate release ];
2021-01-22 21:29:46 +00:00
CGContextRelease(this->cgcontext);
CGColorSpaceRelease(this->color_space);
2021-01-30 18:13:29 +00:00
2021-01-22 21:29:46 +00:00
free(this->window_buffer);
free(this->pixel_buffer);
2007-11-22 21:48:17 +00:00
_cocoa_video_started = false;
}
2021-02-12 00:19:00 +00:00
/** Try to start Cocoa video driver. */
2020-05-17 22:32:08 +01:00
const char *VideoDriver_Cocoa::Start(const StringList &parm)
2007-11-22 21:48:17 +00:00
{
2020-12-26 15:07:51 +00:00
if (!MacOSVersionIsAtLeast(10, 7, 0)) return "The Cocoa video driver requires Mac OS X 10.7 or later.";
2007-11-25 14:43:16 +00:00
2007-11-22 21:48:17 +00:00
if (_cocoa_video_started) return "Already started";
_cocoa_video_started = true;
/* Don't create a window or enter fullscreen if we're just going to show a dialog. */
2021-01-09 17:43:12 +00:00
if (!CocoaSetupApplication()) return nullptr;
2007-11-22 21:48:17 +00:00
2021-01-14 20:53:06 +00:00
this->UpdateAutoResolution();
2021-01-03 14:23:08 +00:00
this->orig_res = _cur_resolution;
2007-11-22 21:48:17 +00:00
2021-01-30 18:13:29 +00:00
int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
2020-12-26 15:07:51 +00:00
if (bpp != 8 && bpp != 32) {
Stop();
return "The cocoa quartz subdriver only supports 8 and 32 bpp.";
}
2021-01-30 18:13:29 +00:00
bool fullscreen = _fullscreen;
if (!this->MakeWindow(_cur_resolution.width, _cur_resolution.height)) {
2007-11-22 21:48:17 +00:00
Stop();
2021-01-30 18:13:29 +00:00
return "Could not create window";
2007-11-22 21:48:17 +00:00
}
2021-01-30 18:13:29 +00:00
if (fullscreen) this->ToggleFullscreen(fullscreen);
2021-01-09 17:43:12 +00:00
2021-01-03 14:23:08 +00:00
this->GameSizeChanged();
2021-01-10 21:27:31 +00:00
this->UpdateVideoModes();
2007-11-22 21:48:17 +00:00
2021-01-22 21:29:46 +00:00
return nullptr;
2007-11-22 21:48:17 +00:00
}
2011-07-21 17:13:34 +01:00
/**
* Set dirty a rectangle managed by a cocoa video subdriver.
* @param left Left x cooordinate of the dirty rectangle.
* @param top Uppder y coordinate of the dirty rectangle.
* @param width Width of the dirty rectangle.
* @param height Height of the dirty rectangle.
*/
2007-11-22 21:48:17 +00:00
void VideoDriver_Cocoa::MakeDirty(int left, int top, int width, int height)
{
2021-02-11 21:54:43 +00:00
if (this->num_dirty_rects < lengthof(this->dirty_rects)) {
2021-01-22 21:29:46 +00:00
dirty_rects[this->num_dirty_rects].left = left;
dirty_rects[this->num_dirty_rects].top = top;
dirty_rects[this->num_dirty_rects].right = left + width;
dirty_rects[this->num_dirty_rects].bottom = top + height;
}
this->num_dirty_rects++;
2007-11-22 21:48:17 +00:00
}
2011-07-21 17:13:34 +01:00
/**
* Start the main programme loop when using a cocoa video driver.
*/
2007-11-22 21:48:17 +00:00
void VideoDriver_Cocoa::MainLoop()
{
2013-08-05 21:36:10 +01:00
/* Restart game loop if it was already running (e.g. after bootstrapping),
* otherwise this call is a no-op. */
[ [ NSNotificationCenter defaultCenter ] postNotificationName:OTTDMainLaunchGameEngine object:nil ];
/* Start the main event loop. */
2009-10-04 22:36:17 +01:00
[ NSApp run ];
2007-11-22 21:48:17 +00:00
}
2011-07-21 17:13:34 +01:00
/**
* Change the resolution when using a cocoa video driver.
* @param w New window width.
* @param h New window height.
* @return Whether the video driver was successfully updated.
*/
2007-11-22 21:48:17 +00:00
bool VideoDriver_Cocoa::ChangeResolution(int w, int h)
{
2021-01-30 18:13:29 +00:00
NSSize screen_size = [ [ NSScreen mainScreen ] frame ].size;
w = std::min(w, (int)screen_size.width);
h = std::min(h, (int)screen_size.height);
2021-01-24 12:12:55 +00:00
2021-01-30 18:13:29 +00:00
NSRect contentRect = NSMakeRect(0, 0, w, h);
[ this->window setContentSize:contentRect.size ];
/* Ensure frame height - title bar height >= view height */
float content_height = [ this->window contentRectForFrameRect:[ this->window frame ] ].size.height;
contentRect.size.height = Clamp(h, 0, (int)content_height);
if (this->cocoaview != nil) {
h = (int)contentRect.size.height;
[ this->cocoaview setFrameSize:contentRect.size ];
2021-01-24 12:12:55 +00:00
}
2021-01-30 18:13:29 +00:00
this->window_width = w;
this->window_height = h;
[ (OTTD_CocoaWindow *)this->window center ];
this->AllocateBackingStore();
return true;
2007-11-22 21:48:17 +00:00
}
2011-07-21 17:13:34 +01:00
/**
* Toggle between windowed and full screen mode for cocoa display driver.
* @param full_screen Whether to switch to full screen or not.
* @return Whether the mode switch was successful.
*/
2008-01-01 14:20:48 +00:00
bool VideoDriver_Cocoa::ToggleFullscreen(bool full_screen)
2007-11-22 21:48:17 +00:00
{
2021-01-22 21:29:46 +00:00
if (this->IsFullscreen() == full_screen) return true;
2007-11-22 21:48:17 +00:00
2021-01-22 21:29:46 +00:00
if ([ this->window respondsToSelector:@selector(toggleFullScreen:) ]) {
[ this->window performSelector:@selector(toggleFullScreen:) withObject:this->window ];
this->UpdateVideoModes();
return true;
}
return false;
2007-11-22 21:48:17 +00:00
}
2011-10-04 22:35:40 +01:00
/**
* Callback invoked after the blitter was changed.
* @return True if no error.
*/
bool VideoDriver_Cocoa::AfterBlitterChange()
{
2021-01-06 22:02:10 +00:00
this->ChangeResolution(_cur_resolution.width, _cur_resolution.height);
2021-01-30 18:13:29 +00:00
this->UpdatePalette(0, 256);
return true;
2011-10-04 22:35:40 +01:00
}
2013-08-05 21:37:33 +01:00
/**
* An edit box lost the input focus. Abort character compositing if necessary.
*/
void VideoDriver_Cocoa::EditBoxLostFocus()
{
2021-01-22 21:29:46 +00:00
[ [ this->cocoaview inputContext ] discardMarkedText ];
2013-11-14 23:03:54 +00:00
/* Clear any marked string from the current edit box. */
HandleTextInput(NULL, true);
2013-08-05 21:37:33 +01:00
}
2021-01-14 20:53:06 +00:00
/**
* Get the resolution of the main screen.
*/
Dimension VideoDriver_Cocoa::GetScreenSize() const
{
NSRect frame = [ [ NSScreen mainScreen ] frame ];
return { static_cast<uint>(NSWidth(frame)), static_cast<uint>(NSHeight(frame)) };
}
2021-02-14 12:26:46 +00:00
/** Get DPI scale of our window. */
float VideoDriver_Cocoa::GetDPIScale()
{
return this->cocoaview != nil ? [ this->cocoaview getContentsScale ] : 1.0f;
}
2021-01-30 18:13:29 +00:00
/**
2021-02-12 00:19:00 +00:00
* Are we in fullscreen mode?
2021-01-30 18:13:29 +00:00
* @return whether fullscreen mode is currently used
*/
bool VideoDriver_Cocoa::IsFullscreen()
{
return this->window != nil && ([ this->window styleMask ] & NSWindowStyleMaskFullScreen) != 0;
}
2021-01-03 14:23:08 +00:00
/**
* Handle a change of the display area.
*/
void VideoDriver_Cocoa::GameSizeChanged()
{
/* Tell the game that the resolution has changed */
2021-02-06 19:23:53 +00:00
_screen.width = this->window_width;
_screen.height = this->window_height;
_screen.pitch = this->buffer_depth == 8 ? this->window_width : this->window_pitch;
2021-01-24 12:12:55 +00:00
_screen.dst_ptr = this->buffer_depth == 8 ? this->pixel_buffer : this->window_buffer;
2021-01-03 14:23:08 +00:00
/* Store old window size if we entered fullscreen mode. */
2021-01-22 21:29:46 +00:00
bool fullscreen = this->IsFullscreen();
2021-01-03 14:23:08 +00:00
if (fullscreen && !_fullscreen) this->orig_res = _cur_resolution;
_fullscreen = fullscreen;
BlitterFactory::GetCurrentBlitter()->PostResize();
::GameSizeChanged();
2021-01-07 20:18:25 +00:00
/* We need to store the window size as non-Retina size in
* the config file to get same windows size on next start. */
_cur_resolution.width = [ this->cocoaview frame ].size.width;
_cur_resolution.height = [ this->cocoaview frame ].size.height;
2021-01-03 14:23:08 +00:00
}
2021-01-22 21:29:46 +00:00
/**
2021-02-12 00:19:00 +00:00
* Update the video mode.
2021-01-22 21:29:46 +00:00
*/
void VideoDriver_Cocoa::UpdateVideoModes()
{
_resolutions.clear();
if (this->IsFullscreen()) {
/* Full screen, there is only one possible resolution. */
NSSize screen = [ [ this->window screen ] frame ].size;
_resolutions.emplace_back((uint)screen.width, (uint)screen.height);
} else {
/* Windowed; offer a selection of common window sizes up until the
* maximum usable screen space. This excludes the menu and dock areas. */
NSSize maxSize = [ [ NSScreen mainScreen] visibleFrame ].size;
for (const auto &d : _default_resolutions) {
if (d.width < maxSize.width && d.height < maxSize.height) _resolutions.push_back(d);
}
_resolutions.emplace_back((uint)maxSize.width, (uint)maxSize.height);
}
}
2021-01-24 12:13:25 +00:00
/**
2021-01-30 18:13:29 +00:00
* Build window and view with a given size.
* @param width Window width.
* @param height Window height.
2021-01-24 12:13:25 +00:00
*/
2021-01-30 18:13:29 +00:00
bool VideoDriver_Cocoa::MakeWindow(int width, int height)
2010-12-21 16:02:55 +00:00
{
2020-12-26 15:07:47 +00:00
this->setup = true;
2010-12-21 16:02:55 +00:00
2021-02-12 00:19:00 +00:00
/* Limit window size to screen frame. */
2021-01-30 18:13:29 +00:00
NSSize screen_size = [ [ NSScreen mainScreen ] frame ].size;
if (width > screen_size.width) width = screen_size.width;
if (height > screen_size.height) height = screen_size.height;
2010-12-21 16:02:55 +00:00
2020-12-26 15:07:47 +00:00
NSRect contentRect = NSMakeRect(0, 0, width, height);
2010-12-21 16:02:55 +00:00
2021-01-30 18:13:29 +00:00
/* Create main window. */
unsigned int style = NSTitledWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask | NSClosableWindowMask;
2021-01-31 17:58:23 +00:00
this->window = [ [ OTTD_CocoaWindow alloc ] initWithContentRect:contentRect styleMask:style backing:NSBackingStoreBuffered defer:NO driver:this ];
2020-12-26 15:07:47 +00:00
if (this->window == nil) {
2021-01-30 18:13:29 +00:00
DEBUG(driver, 0, "Could not create the Cocoa window.");
this->setup = false;
return false;
}
2013-08-05 21:37:37 +01:00
2021-01-30 18:13:29 +00:00
/* Add built in full-screen support when available (OS X 10.7 and higher)
* This code actually compiles for 10.5 and later, but only makes sense in conjunction
2021-02-12 00:19:00 +00:00
* with the quartz fullscreen support as found only in 10.7 and later. */
2021-01-30 18:13:29 +00:00
if ([ this->window respondsToSelector:@selector(toggleFullScreen:) ]) {
NSWindowCollectionBehavior behavior = [ this->window collectionBehavior ];
behavior |= NSWindowCollectionBehaviorFullScreenPrimary;
[ this->window setCollectionBehavior:behavior ];
2013-08-05 21:37:37 +01:00
2021-01-30 18:13:29 +00:00
NSButton* fullscreenButton = [ this->window standardWindowButton:NSWindowFullScreenButton ];
[ fullscreenButton setAction:@selector(toggleFullScreen:) ];
[ fullscreenButton setTarget:this->window ];
}
2013-08-05 21:38:02 +01:00
2021-01-30 18:13:29 +00:00
this->delegate = [ [ OTTD_CocoaWindowDelegate alloc ] initWithDriver:this ];
[ this->window setDelegate:this->delegate ];
2013-08-05 21:38:02 +01:00
2021-02-05 23:23:29 +00:00
[ this->window center ];
2021-01-30 18:13:29 +00:00
[ this->window makeKeyAndOrderFront:nil ];
2013-08-05 21:37:37 +01:00
2021-02-12 00:19:00 +00:00
/* Create wrapper view for input and event handling. */
2021-01-31 17:58:23 +00:00
NSRect view_frame = [ this->window contentRectForFrameRect:[ this->window frame ] ];
2021-02-03 21:43:06 +00:00
this->cocoaview = [ [ OTTD_CocoaView alloc ] initWithFrame:view_frame ];
2020-12-26 15:07:47 +00:00
if (this->cocoaview == nil) {
2021-02-12 00:19:00 +00:00
DEBUG(driver, 0, "Could not create the event wrapper view.");
2021-01-31 17:58:23 +00:00
this->setup = false;
return false;
}
2021-02-05 23:23:29 +00:00
[ this->cocoaview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable ];
2021-01-31 17:58:23 +00:00
/* Create content view. */
NSView *draw_view = [ [ OTTD_QuartzView alloc ] initWithFrame:[ this->cocoaview bounds ] andDriver:this ];
if (draw_view == nil) {
DEBUG(driver, 0, "Could not create the drawing view.");
2021-01-30 18:13:29 +00:00
this->setup = false;
return false;
2013-08-05 21:37:44 +01:00
}
2021-01-31 17:58:23 +00:00
[ draw_view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable ];
2013-08-05 21:37:40 +01:00
2021-02-12 00:19:00 +00:00
/* Create view chain: window -> input wrapper view -> content view. */
2021-01-31 17:58:23 +00:00
[ this->window setContentView:this->cocoaview ];
[ this->cocoaview addSubview:draw_view ];
2021-02-06 01:49:09 +00:00
[ this->window makeFirstResponder:this->cocoaview ];
2021-01-31 17:58:23 +00:00
[ draw_view release ];
2021-01-30 18:13:29 +00:00
2020-12-26 15:07:47 +00:00
[ this->window setColorSpace:[ NSColorSpace sRGBColorSpace ] ];
2021-01-30 18:13:29 +00:00
CGColorSpaceRelease(this->color_space);
2020-12-26 15:07:47 +00:00
this->color_space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
if (this->color_space == nullptr) this->color_space = CGColorSpaceCreateDeviceRGB();
if (this->color_space == nullptr) error("Could not get a valid colour space for drawing.");
2013-08-05 21:38:02 +01:00
2020-12-26 15:07:47 +00:00
this->setup = false;
2013-08-05 21:37:44 +01:00
2021-01-30 18:13:29 +00:00
this->UpdatePalette(0, 256);
this->AllocateBackingStore();
return true;
2013-08-05 21:37:40 +01:00
}
2021-01-24 12:13:25 +00:00
/**
2021-02-12 00:19:00 +00:00
* This function copies 8bpp pixels to the screen buffer in 32bpp windowed mode.
2021-01-24 12:13:25 +00:00
*
* @param left The x coord for the left edge of the box to blit.
* @param top The y coord for the top edge of the box to blit.
* @param right The x coord for the right edge of the box to blit.
* @param bottom The y coord for the bottom edge of the box to blit.
*/
2021-01-22 21:29:46 +00:00
void VideoDriver_Cocoa::BlitIndexedToView32(int left, int top, int right, int bottom)
2013-08-05 21:37:40 +01:00
{
2020-12-26 15:07:47 +00:00
const uint32 *pal = this->palette;
const uint8 *src = (uint8*)this->pixel_buffer;
uint32 *dst = (uint32*)this->window_buffer;
uint width = this->window_width;
2021-02-06 19:23:53 +00:00
uint pitch = this->window_pitch;
2013-08-05 21:37:44 +01:00
2020-12-26 15:07:47 +00:00
for (int y = top; y < bottom; y++) {
for (int x = left; x < right; x++) {
dst[y * pitch + x] = pal[src[y * width + x]];
}
2013-08-05 21:37:44 +01:00
}
2013-08-05 21:37:40 +01:00
}
2021-02-12 00:19:00 +00:00
/**
* Draw window.
2021-01-24 12:13:25 +00:00
* @param force_update Whether to redraw unconditionally
*/
2021-01-22 21:29:46 +00:00
void VideoDriver_Cocoa::Draw(bool force_update)
2013-08-05 21:37:40 +01:00
{
2020-12-26 15:07:47 +00:00
PerformanceMeasurer framerate(PFE_VIDEO);
2013-08-05 21:37:53 +01:00
2020-12-26 15:07:47 +00:00
/* Check if we need to do anything */
if (this->num_dirty_rects == 0 || [ this->window isMiniaturized ]) return;
2013-08-05 21:37:53 +01:00
2021-02-11 21:54:43 +00:00
if (this->num_dirty_rects >= lengthof(this->dirty_rects)) {
2020-12-26 15:07:47 +00:00
this->num_dirty_rects = 1;
this->dirty_rects[0].left = 0;
this->dirty_rects[0].top = 0;
this->dirty_rects[0].right = this->window_width;
this->dirty_rects[0].bottom = this->window_height;
}
2013-08-05 21:37:40 +01:00
2020-12-26 15:07:47 +00:00
/* Build the region of dirty rectangles */
2021-02-11 21:54:43 +00:00
for (uint i = 0; i < this->num_dirty_rects; i++) {
2020-12-26 15:07:47 +00:00
/* We only need to blit in indexed mode since in 32bpp mode the game draws directly to the image. */
if (this->buffer_depth == 8) {
BlitIndexedToView32(
this->dirty_rects[i].left,
this->dirty_rects[i].top,
this->dirty_rects[i].right,
this->dirty_rects[i].bottom
);
}
2013-08-05 21:37:48 +01:00
2020-12-26 15:07:47 +00:00
NSRect dirtyrect;
dirtyrect.origin.x = this->dirty_rects[i].left;
dirtyrect.origin.y = this->window_height - this->dirty_rects[i].bottom;
dirtyrect.size.width = this->dirty_rects[i].right - this->dirty_rects[i].left;
dirtyrect.size.height = this->dirty_rects[i].bottom - this->dirty_rects[i].top;
2013-08-05 21:37:48 +01:00
2020-12-26 15:07:47 +00:00
/* Normally drawRect will be automatically called by Mac OS X during next update cycle,
* and then blitting will occur. If force_update is true, it will be done right now. */
2021-01-07 20:18:25 +00:00
[ this->cocoaview setNeedsDisplayInRect:[ this->cocoaview getVirtualRect:dirtyrect ] ];
2020-12-26 15:07:47 +00:00
if (force_update) [ this->cocoaview displayIfNeeded ];
}
2013-08-05 21:37:48 +01:00
2020-12-26 15:07:47 +00:00
this->num_dirty_rects = 0;
2013-08-05 21:37:40 +01:00
}
2021-02-12 00:19:00 +00:00
/** Update the palette. */
2021-01-22 21:29:46 +00:00
void VideoDriver_Cocoa::UpdatePalette(uint first_color, uint num_colors)
2013-08-05 21:37:40 +01:00
{
2020-12-26 15:07:47 +00:00
if (this->buffer_depth != 8) return;
2013-08-05 21:37:40 +01:00
2020-12-26 15:07:47 +00:00
for (uint i = first_color; i < first_color + num_colors; i++) {
uint32 clr = 0xff000000;
clr |= (uint32)_cur_palette.palette[i].r << 16;
clr |= (uint32)_cur_palette.palette[i].g << 8;
clr |= (uint32)_cur_palette.palette[i].b;
this->palette[i] = clr;
}
2014-08-24 11:34:43 +01:00
2021-02-11 21:54:43 +00:00
this->num_dirty_rects = lengthof(this->dirty_rects);
2014-08-24 11:34:43 +01:00
}
2020-12-26 15:07:54 +00:00
/** Clear buffer to opaque black. */
static void ClearWindowBuffer(uint32 *buffer, uint32 pitch, uint32 height)
2014-09-13 23:00:10 +01:00
{
2020-12-26 15:07:54 +00:00
uint32 fill = Colour(0, 0, 0).data;
for (uint32 y = 0; y < height; y++) {
for (uint32 x = 0; x < pitch; x++) {
buffer[y * pitch + x] = fill;
}
2020-12-26 15:07:47 +00:00
}
2014-08-24 11:34:43 +01:00
}
2021-01-30 18:13:29 +00:00
/** Resize the window. */
void VideoDriver_Cocoa::AllocateBackingStore()
2014-08-24 11:34:43 +01:00
{
2021-01-30 18:13:29 +00:00
if (this->window == nil || this->cocoaview == nil || this->setup) return;
2014-08-24 11:34:43 +01:00
2021-01-07 20:18:25 +00:00
NSRect newframe = [ this->cocoaview getRealRect:[ this->cocoaview frame ] ];
2014-08-24 11:34:43 +01:00
2020-12-26 15:07:47 +00:00
this->window_width = (int)newframe.size.width;
this->window_height = (int)newframe.size.height;
2021-02-06 19:23:53 +00:00
this->window_pitch = Align(this->window_width, 16 / sizeof(uint32)); // Quartz likes lines that are multiple of 16-byte.
2021-01-30 18:13:29 +00:00
this->buffer_depth = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
2014-08-24 11:34:43 +01:00
2020-12-26 15:07:47 +00:00
/* Create Core Graphics Context */
free(this->window_buffer);
2021-02-06 19:23:53 +00:00
this->window_buffer = malloc(this->window_pitch * this->window_height * sizeof(uint32));
2020-12-26 15:07:54 +00:00
/* Initialize with opaque black. */
2021-02-06 19:23:53 +00:00
ClearWindowBuffer((uint32 *)this->window_buffer, this->window_pitch, this->window_height);
2013-08-05 21:37:37 +01:00
2020-12-26 15:07:47 +00:00
CGContextRelease(this->cgcontext);
this->cgcontext = CGBitmapContextCreate(
this->window_buffer, // data
this->window_width, // width
this->window_height, // height
8, // bits per component
2021-02-06 19:23:53 +00:00
this->window_pitch * 4, // bytes per row
2020-12-26 15:07:47 +00:00
this->color_space, // color space
kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host
);
2010-12-21 16:00:42 +00:00
2020-12-26 15:07:47 +00:00
assert(this->cgcontext != NULL);
CGContextSetShouldAntialias(this->cgcontext, FALSE);
CGContextSetAllowsAntialiasing(this->cgcontext, FALSE);
CGContextSetInterpolationQuality(this->cgcontext, kCGInterpolationNone);
2010-12-21 16:00:42 +00:00
2020-12-26 15:07:47 +00:00
if (this->buffer_depth == 8) {
free(this->pixel_buffer);
this->pixel_buffer = malloc(this->window_width * this->window_height);
2021-01-30 18:13:29 +00:00
if (this->pixel_buffer == nullptr) usererror("Out of memory allocating pixel buffer");
2021-02-06 19:23:53 +00:00
} else {
free(this->pixel_buffer);
this->pixel_buffer = nullptr;
2020-12-26 15:07:47 +00:00
}
2010-12-21 16:00:42 +00:00
2020-12-26 15:07:47 +00:00
/* Redraw screen */
2021-02-11 21:54:43 +00:00
this->num_dirty_rects = lengthof(this->dirty_rects);
2021-01-30 18:13:29 +00:00
this->GameSizeChanged();
2010-12-21 15:57:55 +00:00
}
2020-12-26 15:07:47 +00:00
2021-02-12 00:19:00 +00:00
/** Check if palette updates need to be performed. */
2021-01-22 21:29:46 +00:00
void VideoDriver_Cocoa::CheckPaletteAnim()
{
if (_cur_palette.count_dirty != 0) {
Blitter *blitter = BlitterFactory::GetCurrentBlitter();
switch (blitter->UsePaletteAnimation()) {
case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
this->UpdatePalette(_cur_palette.first_dirty, _cur_palette.count_dirty);
break;
case Blitter::PALETTE_ANIMATION_BLITTER:
blitter->PaletteAnimate(_cur_palette);
break;
case Blitter::PALETTE_ANIMATION_NONE:
break;
default:
NOT_REACHED();
}
_cur_palette.count_dirty = 0;
}
}
2021-02-05 23:23:29 +00:00
2021-02-12 00:19:00 +00:00
/**
* Poll and handle a single event from the OS.
* @return True if there was an event to handle.
*/
2021-02-06 19:22:37 +00:00
bool VideoDriver_Cocoa::PollEvent()
{
#ifdef _DEBUG
uint32 et0 = GetTick();
#endif
NSEvent *event = [ NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[ NSDate distantPast ] inMode:NSDefaultRunLoopMode dequeue:YES ];
#ifdef _DEBUG
_tEvent += GetTick() - et0;
#endif
if (event == nil) return false;
[ NSApp sendEvent:event ];
return true;
}
2021-02-12 00:19:00 +00:00
/** Main game loop. */
2021-02-06 19:22:37 +00:00
void VideoDriver_Cocoa::GameLoop()
{
2021-02-17 13:46:19 +00:00
auto cur_ticks = std::chrono::steady_clock::now();
2021-02-17 13:49:45 +00:00
auto last_realtime_tick = cur_ticks;
Add: draw the screen at a steady pace, also during fast-forward
During fast-forward, the game was drawing as fast as it could. This
means that the fast-forward was limited also by how fast we could
draw, something that people in general don't expect.
To give an extreme case, if you are fully zoomed out on a busy
map, fast-forward would be mostly limited because of the time it
takes to draw the screen.
By decoupling the draw-tick and game-tick, we can keep the pace
of the draw-tick the same while speeding up the game-tick. To use
the extreme case as example again, if you are fully zoomed out
now, the screen only redraws 33.33 times per second, fast-forwarding
or not. This means fast-forward is much more likely to go at the
same speed, no matter what you are looking at.
2021-02-17 14:04:46 +00:00
auto next_game_tick = cur_ticks;
auto next_draw_tick = cur_ticks;
2021-02-06 19:22:37 +00:00
for (;;) {
@autoreleasepool {
InteractiveRandom(); // randomness
while (this->PollEvent()) {}
if (_exit_game) {
/* Restore saved resolution if in fullscreen mode. */
if (this->IsFullscreen()) _cur_resolution = this->orig_res;
break;
}
NSUInteger cur_mods = [ NSEvent modifierFlags ];
#if defined(_DEBUG)
if (cur_mods & NSShiftKeyMask) {
#else
if (_tab_is_down) {
#endif
if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
} else if (_fast_forward & 2) {
_fast_forward = 0;
}
2021-02-17 13:46:19 +00:00
cur_ticks = std::chrono::steady_clock::now();
2021-02-17 13:49:45 +00:00
/* If more than a millisecond has passed, increase the _realtime_tick. */
if (cur_ticks - last_realtime_tick > std::chrono::milliseconds(1)) {
auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(cur_ticks - last_realtime_tick);
_realtime_tick += delta.count();
last_realtime_tick += delta;
}
Add: draw the screen at a steady pace, also during fast-forward
During fast-forward, the game was drawing as fast as it could. This
means that the fast-forward was limited also by how fast we could
draw, something that people in general don't expect.
To give an extreme case, if you are fully zoomed out on a busy
map, fast-forward would be mostly limited because of the time it
takes to draw the screen.
By decoupling the draw-tick and game-tick, we can keep the pace
of the draw-tick the same while speeding up the game-tick. To use
the extreme case as example again, if you are fully zoomed out
now, the screen only redraws 33.33 times per second, fast-forwarding
or not. This means fast-forward is much more likely to go at the
same speed, no matter what you are looking at.
2021-02-17 14:04:46 +00:00
if (cur_ticks >= next_game_tick || (_fast_forward && !_pause_mode)) {
Change: allow video-drivers to miss deadlines slightly
Before, every next frame was calculated from the current time.
If for some reason the current frame was drifting a bit, the
next would too, and the next more, etc etc. This meant we rarely
hit the targets we would like, like 33.33fps.
Instead, allow video-drivers to drift slightly, and schedule the
next frame based on the time the last should have happened. Only
if the drift gets too much, that deadlines are missed for longer
period of times, schedule the next frame based on the current
time.
This makes the FPS a lot smoother, as sleeps aren't as exact as
you might think.
2021-02-17 14:14:59 +00:00
if (_fast_forward && !_pause_mode) {
2021-02-17 14:31:09 +00:00
next_game_tick = cur_ticks + this->GetGameInterval();
Change: allow video-drivers to miss deadlines slightly
Before, every next frame was calculated from the current time.
If for some reason the current frame was drifting a bit, the
next would too, and the next more, etc etc. This meant we rarely
hit the targets we would like, like 33.33fps.
Instead, allow video-drivers to drift slightly, and schedule the
next frame based on the time the last should have happened. Only
if the drift gets too much, that deadlines are missed for longer
period of times, schedule the next frame based on the current
time.
This makes the FPS a lot smoother, as sleeps aren't as exact as
you might think.
2021-02-17 14:14:59 +00:00
} else {
2021-02-17 14:31:09 +00:00
next_game_tick += this->GetGameInterval();
Change: allow video-drivers to miss deadlines slightly
Before, every next frame was calculated from the current time.
If for some reason the current frame was drifting a bit, the
next would too, and the next more, etc etc. This meant we rarely
hit the targets we would like, like 33.33fps.
Instead, allow video-drivers to drift slightly, and schedule the
next frame based on the time the last should have happened. Only
if the drift gets too much, that deadlines are missed for longer
period of times, schedule the next frame based on the current
time.
This makes the FPS a lot smoother, as sleeps aren't as exact as
you might think.
2021-02-17 14:14:59 +00:00
/* Avoid next_game_tick getting behind more and more if it cannot keep up. */
2021-02-17 14:31:09 +00:00
if (next_game_tick < cur_ticks - ALLOWED_DRIFT * this->GetGameInterval()) next_game_tick = cur_ticks;
Change: allow video-drivers to miss deadlines slightly
Before, every next frame was calculated from the current time.
If for some reason the current frame was drifting a bit, the
next would too, and the next more, etc etc. This meant we rarely
hit the targets we would like, like 33.33fps.
Instead, allow video-drivers to drift slightly, and schedule the
next frame based on the time the last should have happened. Only
if the drift gets too much, that deadlines are missed for longer
period of times, schedule the next frame based on the current
time.
This makes the FPS a lot smoother, as sleeps aren't as exact as
you might think.
2021-02-17 14:14:59 +00:00
}
Add: draw the screen at a steady pace, also during fast-forward
During fast-forward, the game was drawing as fast as it could. This
means that the fast-forward was limited also by how fast we could
draw, something that people in general don't expect.
To give an extreme case, if you are fully zoomed out on a busy
map, fast-forward would be mostly limited because of the time it
takes to draw the screen.
By decoupling the draw-tick and game-tick, we can keep the pace
of the draw-tick the same while speeding up the game-tick. To use
the extreme case as example again, if you are fully zoomed out
now, the screen only redraws 33.33 times per second, fast-forwarding
or not. This means fast-forward is much more likely to go at the
same speed, no matter what you are looking at.
2021-02-17 14:04:46 +00:00
::GameLoop();
}
if (cur_ticks >= next_draw_tick) {
2021-02-17 14:31:09 +00:00
next_draw_tick += this->GetDrawInterval();
Change: allow video-drivers to miss deadlines slightly
Before, every next frame was calculated from the current time.
If for some reason the current frame was drifting a bit, the
next would too, and the next more, etc etc. This meant we rarely
hit the targets we would like, like 33.33fps.
Instead, allow video-drivers to drift slightly, and schedule the
next frame based on the time the last should have happened. Only
if the drift gets too much, that deadlines are missed for longer
period of times, schedule the next frame based on the current
time.
This makes the FPS a lot smoother, as sleeps aren't as exact as
you might think.
2021-02-17 14:14:59 +00:00
/* Avoid next_draw_tick getting behind more and more if it cannot keep up. */
2021-02-17 14:31:09 +00:00
if (next_draw_tick < cur_ticks - ALLOWED_DRIFT * this->GetDrawInterval()) next_draw_tick = cur_ticks;
2021-02-06 19:22:37 +00:00
bool old_ctrl_pressed = _ctrl_pressed;
_ctrl_pressed = (cur_mods & ( _settings_client.gui.right_mouse_btn_emulation != RMBE_CONTROL ? NSControlKeyMask : NSCommandKeyMask)) != 0;
_shift_pressed = (cur_mods & NSShiftKeyMask) != 0;
if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
Add: draw the screen at a steady pace, also during fast-forward
During fast-forward, the game was drawing as fast as it could. This
means that the fast-forward was limited also by how fast we could
draw, something that people in general don't expect.
To give an extreme case, if you are fully zoomed out on a busy
map, fast-forward would be mostly limited because of the time it
takes to draw the screen.
By decoupling the draw-tick and game-tick, we can keep the pace
of the draw-tick the same while speeding up the game-tick. To use
the extreme case as example again, if you are fully zoomed out
now, the screen only redraws 33.33 times per second, fast-forwarding
or not. This means fast-forward is much more likely to go at the
same speed, no matter what you are looking at.
2021-02-17 14:04:46 +00:00
InputLoop();
2021-02-06 19:22:37 +00:00
UpdateWindows();
this->CheckPaletteAnim();
Add: draw the screen at a steady pace, also during fast-forward
During fast-forward, the game was drawing as fast as it could. This
means that the fast-forward was limited also by how fast we could
draw, something that people in general don't expect.
To give an extreme case, if you are fully zoomed out on a busy
map, fast-forward would be mostly limited because of the time it
takes to draw the screen.
By decoupling the draw-tick and game-tick, we can keep the pace
of the draw-tick the same while speeding up the game-tick. To use
the extreme case as example again, if you are fully zoomed out
now, the screen only redraws 33.33 times per second, fast-forwarding
or not. This means fast-forward is much more likely to go at the
same speed, no matter what you are looking at.
2021-02-17 14:04:46 +00:00
2021-02-06 19:22:37 +00:00
this->Draw();
Add: draw the screen at a steady pace, also during fast-forward
During fast-forward, the game was drawing as fast as it could. This
means that the fast-forward was limited also by how fast we could
draw, something that people in general don't expect.
To give an extreme case, if you are fully zoomed out on a busy
map, fast-forward would be mostly limited because of the time it
takes to draw the screen.
By decoupling the draw-tick and game-tick, we can keep the pace
of the draw-tick the same while speeding up the game-tick. To use
the extreme case as example again, if you are fully zoomed out
now, the screen only redraws 33.33 times per second, fast-forwarding
or not. This means fast-forward is much more likely to go at the
same speed, no matter what you are looking at.
2021-02-17 14:04:46 +00:00
}
2021-02-17 14:19:33 +00:00
/* If we are not in fast-forward, create some time between calls to ease up CPU usage. */
Add: draw the screen at a steady pace, also during fast-forward
During fast-forward, the game was drawing as fast as it could. This
means that the fast-forward was limited also by how fast we could
draw, something that people in general don't expect.
To give an extreme case, if you are fully zoomed out on a busy
map, fast-forward would be mostly limited because of the time it
takes to draw the screen.
By decoupling the draw-tick and game-tick, we can keep the pace
of the draw-tick the same while speeding up the game-tick. To use
the extreme case as example again, if you are fully zoomed out
now, the screen only redraws 33.33 times per second, fast-forwarding
or not. This means fast-forward is much more likely to go at the
same speed, no matter what you are looking at.
2021-02-17 14:04:46 +00:00
if (!_fast_forward || _pause_mode) {
2021-02-17 14:19:33 +00:00
/* See how much time there is till we have to process the next event, and try to hit that as close as possible. */
auto next_tick = std::min(next_draw_tick, next_game_tick);
auto now = std::chrono::steady_clock::now();
if (next_tick > now) {
std::this_thread::sleep_for(next_tick - now);
}
2021-02-06 19:22:37 +00:00
}
}
}
}
2021-02-05 23:23:29 +00:00
@implementation OTTD_QuartzView
- (instancetype)initWithFrame:(NSRect)frameRect andDriver:(VideoDriver_Cocoa *)drv
{
if (self = [ super initWithFrame:frameRect ]) {
self->driver = drv;
2021-02-06 21:58:51 +00:00
/* We manage our content updates ourselves. */
self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay;
self.wantsLayer = YES;
self.layer.magnificationFilter = kCAFilterNearest;
2021-02-05 23:23:29 +00:00
}
return self;
}
- (BOOL)acceptsFirstResponder
{
return NO;
}
- (BOOL)isOpaque
{
return YES;
}
2021-02-06 21:58:51 +00:00
- (BOOL)wantsUpdateLayer
2021-02-05 23:23:29 +00:00
{
2021-02-06 21:58:51 +00:00
return YES;
}
2021-02-05 23:23:29 +00:00
2021-02-06 21:58:51 +00:00
- (void)updateLayer
{
if (driver->cgcontext == nullptr) return;
2021-02-05 23:23:29 +00:00
2021-02-06 21:58:51 +00:00
/* Set layer contents to our backing buffer, which avoids needless copying. */
2021-02-05 23:23:29 +00:00
CGImageRef fullImage = CGBitmapContextCreateImage(driver->cgcontext);
2021-02-06 21:58:51 +00:00
self.layer.contents = (__bridge id)fullImage;
2021-02-05 23:23:29 +00:00
CGImageRelease(fullImage);
}
2021-01-07 20:18:25 +00:00
- (void)viewDidChangeBackingProperties
{
[ super viewDidChangeBackingProperties ];
self.layer.contentsScale = [ driver->cocoaview getContentsScale ];
}
2021-02-05 23:23:29 +00:00
@end
2007-11-22 21:48:17 +00:00
#endif /* WITH_COCOA */