summaryrefslogtreecommitdiff
path: root/src/video/cocoa/cocoa_ogl.mm
blob: 96c3ea1bfe90d59fca04f995059f0f7f532b95b7 (plain)
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
/*
 * 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/>.
 */

/** @file cocoa_ogl.mm Code related to the cocoa OpengL video driver. */

#ifdef WITH_COCOA

#include "../../stdafx.h"
#include "../../os/macosx/macos.h"

#define Rect  OTTDRect
#define Point OTTDPoint
#import <Cocoa/Cocoa.h>
#import <QuartzCore/QuartzCore.h>
#undef Rect
#undef Point

#include "../../openttd.h"
#include "../../debug.h"
#include "../../core/geometry_func.hpp"
#include "../../core/math_func.hpp"
#include "../../core/mem_func.hpp"
#include "cocoa_ogl.h"
#include "cocoa_wnd.h"
#include "../../blitter/factory.hpp"
#include "../../gfx_func.h"
#include "../../framerate_type.h"
#include "../opengl.h"

#import <dlfcn.h>
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl3.h>


/**
 * 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.
 */

/** Platform-specific callback to get an OpenGL funtion pointer. */
static OGLProc GetOGLProcAddressCallback(const char *proc)
{
	static void *dl = nullptr;

	if (dl == nullptr) {
		dl = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
	}

	return reinterpret_cast<OGLProc>(dlsym(dl, proc));
}

@interface OTTD_CGLLayer : CAOpenGLLayer {
@private
	CGLContextObj _context;
}

@property (class) bool allowSoftware;
+ (CGLPixelFormatObj)defaultPixelFormat;

- (instancetype)initWithContext:(CGLContextObj)context;
@end

@implementation OTTD_CGLLayer

static bool _allowSoftware;
+ (bool)allowSoftware
{
	return _allowSoftware;
}
+ (void)setAllowSoftware:(bool)newVal
{
	_allowSoftware = newVal;
}

- (instancetype)initWithContext:(CGLContextObj)context
{
	if (self = [ super init ]) {
		self->_context = context;

		self.opaque = YES;
		self.magnificationFilter = kCAFilterNearest;
	}
	return self;
}

+ (CGLPixelFormatObj)defaultPixelFormat
{
	CGLPixelFormatAttribute attribs[] = {
		kCGLPFAOpenGLProfile, (CGLPixelFormatAttribute)kCGLOGLPVersion_3_2_Core,
		kCGLPFAColorSize, (CGLPixelFormatAttribute)24,
		kCGLPFAAlphaSize, (CGLPixelFormatAttribute)0,
		kCGLPFADepthSize, (CGLPixelFormatAttribute)0,
		kCGLPFADoubleBuffer,
		kCGLPFAAllowOfflineRenderers,
		kCGLPFASupportsAutomaticGraphicsSwitching,
		kCGLPFANoRecovery,
		_allowSoftware ? (CGLPixelFormatAttribute)0 : kCGLPFAAccelerated,
		(CGLPixelFormatAttribute)0
	};

	CGLPixelFormatObj pxfmt = nullptr;
	GLint numPixelFormats;
	CGLChoosePixelFormat(attribs, &pxfmt, &numPixelFormats);

	return pxfmt;
}

- (CGLPixelFormatObj)copyCGLPixelFormatForDisplayMask:(uint32_t)mask
{
	return [ OTTD_CGLLayer defaultPixelFormat ];
}

- (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pf
{
	CGLContextObj ctx;
	CGLCreateContext(pf, self->_context, &ctx);

	/* Set context state that is not shared. */
	CGLSetCurrentContext(ctx);
	OpenGLBackend::Get()->PrepareContext();

	return ctx;
}

- (void)drawInCGLContext:(CGLContextObj)ctx pixelFormat:(CGLPixelFormatObj)pf forLayerTime:(CFTimeInterval)t displayTime:(nullable const CVTimeStamp *)ts
{
	CGLSetCurrentContext(ctx);

	OpenGLBackend::Get()->Paint();
	OpenGLBackend::Get()->DrawMouseCursor();

	[ super drawInCGLContext:ctx pixelFormat:pf forLayerTime:t displayTime:ts ];
}
@end

@interface OTTD_CGLLayerView : NSView
- (instancetype)initWithFrame:(NSRect)frameRect context:(CGLContextObj)context;
@end

@implementation OTTD_CGLLayerView

- (instancetype)initWithFrame:(NSRect)frameRect context:(CGLContextObj)context
{
	if (self = [ super initWithFrame:frameRect ]) {
		/* We manage our content updates ourselves. */
		self.wantsBestResolutionOpenGLSurface = _allow_hidpi_window ? YES : NO;
		self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay;

		/* Create backing layer. */
		CALayer *l = [ [ OTTD_CGLLayer alloc ] initWithContext:context ];
		self.layer = l;
		self.wantsLayer = YES;
		[ l release ];
	}
	return self;
}

- (BOOL)acceptsFirstResponder
{
	return NO;
}

- (BOOL)isOpaque
{
	return YES;
}

- (void)viewDidChangeBackingProperties
{
	self.layer.contentsScale = _allow_hidpi_window && [ self.window respondsToSelector:@selector(backingScaleFactor) ] ? [ self.window backingScaleFactor ] : 1.0f;
}
@end


static FVideoDriver_CocoaOpenGL iFVideoDriver_CocoaOpenGL;


const char *VideoDriver_CocoaOpenGL::Start(const StringList &param)
{
	const char *err = this->Initialize();
	if (err != nullptr) return err;

	int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
	if (bpp != 8 && bpp != 32) {
		this->Stop();
		return "The cocoa OpenGL subdriver only supports 8 and 32 bpp.";
	}

	/* Try to allocate GL context. */
	err = this->AllocateContext(GetDriverParamBool(param, "software"));
	if (err != nullptr) {
		this->Stop();
		return err;
	}

	bool fullscreen = _fullscreen;
	if (!this->MakeWindow(_cur_resolution.width, _cur_resolution.height)) {
		this->Stop();
		return "Could not create window";
	}

	this->AllocateBackingStore(true);

	if (fullscreen) this->ToggleFullscreen(fullscreen);

	this->GameSizeChanged();
	this->UpdateVideoModes();
	MarkWholeScreenDirty();

	this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");

	return nullptr;

}

void VideoDriver_CocoaOpenGL::Stop()
{
	this->VideoDriver_Cocoa::Stop();

	CGLSetCurrentContext(this->gl_context);
	OpenGLBackend::Destroy();
	CGLReleaseContext(this->gl_context);
}

void VideoDriver_CocoaOpenGL::PopulateSystemSprites()
{
	OpenGLBackend::Get()->PopulateCursorCache();
}

void VideoDriver_CocoaOpenGL::ClearSystemSprites()
{
	CGLSetCurrentContext(this->gl_context);
	OpenGLBackend::Get()->ClearCursorCache();
}

const char *VideoDriver_CocoaOpenGL::AllocateContext(bool allow_software)
{
	[ OTTD_CGLLayer setAllowSoftware:allow_software ];

	CGLPixelFormatObj pxfmt = [ OTTD_CGLLayer defaultPixelFormat ];
	if (pxfmt == nullptr) return "No suitable pixel format found";

	CGLCreateContext(pxfmt, nullptr, &this->gl_context);
	CGLDestroyPixelFormat(pxfmt);

	if (this->gl_context == nullptr) return "Can't create a rendering context";

	CGLSetCurrentContext(this->gl_context);

	return OpenGLBackend::Create(&GetOGLProcAddressCallback, this->GetScreenSize());
}

NSView *VideoDriver_CocoaOpenGL::AllocateDrawView()
{
	return [ [ OTTD_CGLLayerView alloc ] initWithFrame:this->cocoaview.bounds context:this->gl_context ];
}

/** Resize the window. */
void VideoDriver_CocoaOpenGL::AllocateBackingStore(bool force)
{
	if (this->window == nil || this->setup) return;

	if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer();

	CGLSetCurrentContext(this->gl_context);
	NSRect frame = [ this->cocoaview getRealRect:[ this->cocoaview frame ] ];
	OpenGLBackend::Get()->Resize(frame.size.width, frame.size.height, force);
	if (this->buffer_locked) _screen.dst_ptr = this->GetVideoPointer();
	this->dirty_rect = {};

	/* Redraw screen */
	this->GameSizeChanged();
}

void *VideoDriver_CocoaOpenGL::GetVideoPointer()
{
	CGLSetCurrentContext(this->gl_context);
	if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
		this->anim_buffer = OpenGLBackend::Get()->GetAnimBuffer();
	}
	return OpenGLBackend::Get()->GetVideoBuffer();
}

void VideoDriver_CocoaOpenGL::ReleaseVideoPointer()
{
	CGLSetCurrentContext(this->gl_context);

	if (this->anim_buffer != nullptr) OpenGLBackend::Get()->ReleaseAnimBuffer(this->dirty_rect);
	OpenGLBackend::Get()->ReleaseVideoBuffer(this->dirty_rect);
	this->dirty_rect = {};
	_screen.dst_ptr = nullptr;
	this->anim_buffer = nullptr;
}

void VideoDriver_CocoaOpenGL::Paint()
{
	PerformanceMeasurer framerate(PFE_VIDEO);

	if (_cur_palette.count_dirty != 0) {
		Blitter *blitter = BlitterFactory::GetCurrentBlitter();

		/* Always push a changed palette to OpenGL. */
		CGLSetCurrentContext(this->gl_context);
		OpenGLBackend::Get()->UpdatePalette(_cur_palette.palette, _cur_palette.first_dirty, _cur_palette.count_dirty);
		if (blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_BLITTER) {
			blitter->PaletteAnimate(_cur_palette);
		}

		_cur_palette.count_dirty = 0;
	}

	[ CATransaction begin ];
	[ this->cocoaview.subviews[0].layer setNeedsDisplay ];
	[ CATransaction commit ];
}

#endif /* WITH_COCOA */