Debian Codegraph @

tools/build-tool/data/ios/xcode_project/cge_project_name/OpenGLController.m

raw
1 /*
2 Copyright 2013-2017 Jan Adamec, Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in the "Castle Game Engine" distribution,
8 for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 */
16
17 #import "OpenGLController.h"
18 #include "castleiosappglue.h"
19 #import "CgeUtils.h"
20
21 #define MAX_TOUCHES 12
22
23 typedef struct TouchInfo {
24 // nil if nothing registered
25 UITouch* uiTouch;
26 // We should send motion event for this
27 bool pendingMotion;
28 } TouchInfo;
29
30 @interface OpenGLController ()
31 {
32 CGFloat m_fScale;
33 TouchInfo m_touches[MAX_TOUCHES];
34 int m_currentViewWidth;
35 int m_currentViewHeight;
36 }
37
38 @property (strong, nonatomic) EAGLContext *context;
39
40 @end
41
42 //-----------------------------------------------------------------
43 @implementation OpenGLController
44
45 - (void)viewDidLoad
46 {
47 [super viewDidLoad];
48
49 // Try to initialize OpenGLES 3, fallback on version 2
50 // (following https://developer.apple.com/library/archive/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/WorkingwithOpenGLESContexts/WorkingwithOpenGLESContexts.html )
51 /*
52 EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
53 if (context == nil) {
54 context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
55 }
56 */
57 /* TODO: OpenGLES 3 commented out for now.
58 It breaks Unholy rendering of "evil plane".
59 Looks like on iOS, something in OpenGLES3 is subtly broken compared to OpenGLES2,
60 maybe related to ScreenFbo which is already weird (non-zero) in OpenGLES2,
61 see
62 src/images/opengl/castleglimages_rendertotexture.inc
63 https://stackoverflow.com/questions/11617013/why-would-glbindframebuffergl-framebuffer-0-result-in-blank-screen-in-cocos2d)
64
65 Ideally we should just fix it, and work flawlessly in both OpenGLES2 and OpenGLES3 on iOS.
66
67 Eventually we can add a flag, like IOS_ENABLE_ES3, to make it optional decision
68 per-application.
69 */
70 EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
71
72 self.context = context;
73
74 if (!self.context) {
75 NSLog(@"Failed to create ES context");
76 }
77
78 GLKView *view = (GLKView *)self.view;
79 view.context = self.context;
80
81 /* Configure OpenGLES buffer sizes.
82 GLKView provides very limited configuration options, see
83 https://developer.apple.com/library/archive/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/DrawingWithOpenGLES/DrawingWithOpenGLES.html#//apple_ref/doc/uid/TP40008793-CH503-SW1
84 https://developer.apple.com/documentation/glkit/glkview
85 */
86 int redBits, greenBits, blueBits, alphaBits, depthBits, stencilBits, multiSampling;
87 CGEApp_ContextProperties(&redBits, &greenBits, &blueBits, &alphaBits, &depthBits, &stencilBits, &multiSampling);
88 // view.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888; // default
89
90 if (depthBits == 0) {
91 view.drawableDepthFormat = GLKViewDrawableDepthFormatNone;
92 } else
93 if (depthBits <= 16) {
94 view.drawableDepthFormat = GLKViewDrawableDepthFormat16;
95 } else {
96 view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
97 }
98
99 if (stencilBits == 0) {
100 view.drawableStencilFormat = GLKViewDrawableStencilFormatNone;
101 } else {
102 view.drawableStencilFormat = GLKViewDrawableStencilFormat8;
103 }
104
105 if (multiSampling < 4) {
106 view.drawableMultisample = GLKViewDrawableMultisampleNone;
107 } else {
108 view.drawableMultisample = GLKViewDrawableMultisample4X;
109 }
110
111 // initialize input
112
113 self.view.multipleTouchEnabled = YES;
114 for (int i = 0; i < MAX_TOUCHES; i++) {
115 m_touches[i].uiTouch = nil;
116 m_touches[i].pendingMotion = FALSE;
117 }
118
119 [self setupGL];
120 }
121
122 //-----------------------------------------------------------------
123 - (void)dealloc
124 {
125 [self tearDownGL];
126
127 if ([EAGLContext currentContext] == self.context) {
128 [EAGLContext setCurrentContext:nil];
129 }
130 }
131
132 //-----------------------------------------------------------------
133 - (void)didReceiveMemoryWarning
134 {
135 [super didReceiveMemoryWarning];
136
137 if ([self isViewLoaded] && ([[self view] window] == nil)) {
138 self.view = nil;
139
140 [self tearDownGL];
141
142 if ([EAGLContext currentContext] == self.context) {
143 [EAGLContext setCurrentContext:nil];
144 }
145 self.context = nil;
146 }
147
148 // Dispose of any resources that can be recreated.
149 }
150
151 //-----------------------------------------------------------------
152 - (int)statusBarHeight
153 {
154 CGSize statusBarSize = [[UIApplication sharedApplication] statusBarFrame].size;
155 return MIN(statusBarSize.width, statusBarSize.height) * m_fScale;
156 }
157
158 //-----------------------------------------------------------------
159 - (void)setupGL
160 {
161 [EAGLContext setCurrentContext:self.context];
162
163 /* We need to look at scale, to apply Retina.
164
165 Moreover, iPhone 8 Plus does more tricks,
166 and we need to look at nativeScale.
167 See https://www.paintcodeapp.com/news/iphone-6-screens-demystified
168 for explanation what is happening under the hood.
169
170 (Using [[UIScreen mainScreen] nativeBounds] also gets correct size,
171 but not adjusted to orientation.)
172 */
173 if ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)])
174 m_fScale = [UIScreen mainScreen].nativeScale;
175 else
176 m_fScale = 1.0;
177
178 /*
179 Get the DPI/PPI. The real values (132*scale for iPhones, 163*scale for iPads)
180 are too high when used in reality. The concept of scaling UI using DPI fails
181 on iOS. It is much better to use screen scale only (m_fScale). In that case,
182 when you define 25 px large icon, it will have 50 px at Retina resolution,
183 which is what we want.
184
185 Also, it is impossible to get the precise iDevice PPI other then enumerating all
186 existing devices.
187 */
188 /*unsigned dpi = 160;
189 if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
190 dpi = 132;
191 else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
192 dpi = 163;*/
193 unsigned dpi = 96; // CastleWindow.DefaultDpi
194
195 m_currentViewWidth = self.view.bounds.size.width * m_fScale;
196 m_currentViewHeight = self.view.bounds.size.height * m_fScale;
197
198 // Get a directory where we can write files,
199 // see http://stackoverflow.com/questions/1567134/how-can-i-get-a-writable-path-on-the-iphone/1567147#1567147
200 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
201 NSString *libraryDirectory = [paths objectAtIndex:0];
202
203 CGEApp_Initialize([libraryDirectory fileSystemRepresentation]);
204 CGEApp_Open(m_currentViewWidth, m_currentViewHeight, [self statusBarHeight], (unsigned)(dpi * m_fScale));
205
206 [self update];
207 }
208
209 //-----------------------------------------------------------------
210 - (void)tearDownGL
211 {
212 [EAGLContext setCurrentContext:self.context];
213
214 CGEApp_Close(true);
215 CGEApp_Finalize();
216 }
217
218 #pragma mark - GLKView and GLKViewController delegate methods
219 //-----------------------------------------------------------------
220 - (void)update
221 {
222 // update the viewport size, if changed
223 int newViewWidth = self.view.bounds.size.width * m_fScale;
224 int newViewHeight = self.view.bounds.size.height * m_fScale;
225 if (m_currentViewWidth != newViewWidth ||
226 m_currentViewHeight != newViewHeight)
227 {
228 m_currentViewWidth = newViewWidth;
229 m_currentViewHeight = newViewHeight;
230 CGEApp_Resize(newViewWidth, newViewHeight, [self statusBarHeight]);
231 }
232
233 // send accumulated motion events (sending them right away can jam the engine)
234 for (NSInteger i = 0; i < MAX_TOUCHES; i++)
235 {
236 if (m_touches[i].uiTouch == nil) continue;
237 if (!m_touches[i].pendingMotion) continue;
238
239 CGPoint pt = [m_touches[i].uiTouch locationInView:self.view];
240 [self RecalcTouchPosForCGE:&pt];
241 CGEApp_Motion(pt.x, pt.y, (int)i);
242 m_touches[i].pendingMotion = FALSE;
243 }
244
245 CGEApp_Update();
246 }
247
248 //-----------------------------------------------------------------
249 - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
250 {
251 CGEApp_Render();
252 }
253
254 #pragma mark - gestures
255
256 //-----------------------------------------------------------------
257 - (void)RecalcTouchPosForCGE:(CGPoint *)pt
258 {
259 pt->x *= m_fScale;
260 pt->y *= m_fScale;
261 pt->y = m_currentViewHeight - 1 - pt->y;
262 }
263
264 //-----------------------------------------------------------------
265 - (NSInteger)IndexOfTouch:(UITouch*)touch
266 {
267 for (NSInteger i = 0; i < MAX_TOUCHES; i++)
268 if (m_touches[i].uiTouch == touch) {
269 return i;
270 }
271 return -1;
272 }
273
274 //-----------------------------------------------------------------
275 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
276 {
277 for (UITouch *touch in touches)
278 {
279 NSInteger nFingerIdx = [self IndexOfTouch:touch];
280 if (nFingerIdx != -1) continue; // we already have it (should not happen)
281
282 for (NSInteger i = 0; i < MAX_TOUCHES; i++)
283 {
284 if (m_touches[i].uiTouch == nil) // find empty place
285 {
286 nFingerIdx = i;
287 m_touches[i].uiTouch = touch;
288 m_touches[i].pendingMotion = FALSE; // initial value
289 break;
290 }
291 }
292 if (nFingerIdx==-1) continue; // array full, should not happen
293
294 CGPoint pt = [touch locationInView:self.view];
295 [self RecalcTouchPosForCGE:&pt];
296 CGEApp_MouseDown(pt.x, pt.y, true, (int)nFingerIdx);
297 }
298
299 [super touchesBegan:touches withEvent:event];
300 }
301
302 //-----------------------------------------------------------------
303 - (void)TouchesEndedOrCancelled:(NSSet *)touches
304 {
305 for (UITouch *touch in touches)
306 {
307 NSInteger nFingerIdx = [self IndexOfTouch:touch];
308 if (nFingerIdx == -1) continue;
309
310 m_touches[nFingerIdx].uiTouch = nil;
311
312 CGPoint pt = [touch locationInView:self.view];
313 [self RecalcTouchPosForCGE:&pt];
314 CGEApp_MouseUp(pt.x, pt.y, true, (int)nFingerIdx, false);
315 }
316 }
317
318 //-----------------------------------------------------------------
319 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
320 {
321 [self TouchesEndedOrCancelled:touches];
322 [super touchesEnded:touches withEvent:event];
323 }
324
325 //-----------------------------------------------------------------
326 - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
327 {
328 [self TouchesEndedOrCancelled:touches];
329 [super touchesCancelled:touches withEvent:event];
330 }
331
332 //-----------------------------------------------------------------
333 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
334 {
335 // CGEApp_Motion will be called in the Update function. Calling it too frequently can jam the engine.
336 for (UITouch *touch in touches)
337 {
338 NSInteger nFingerIdx = [self IndexOfTouch:touch];
339 if (nFingerIdx == -1) continue;
340
341 m_touches[nFingerIdx].pendingMotion = TRUE;
342 }
343
344 [super touchesMoved:touches withEvent:event];
345 }
346
347 #pragma mark - interface
348
349 //-----------------------------------------------------------------
350 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
351 {
352 // TODO: This probably can be removed?
353 // This is deprecated:
354 // https://developer.apple.com/documentation/uikit/uiviewcontroller/1621459-shouldautorotatetointerfaceorien
355 // And results of this are intersected with orientations we define in project already:
356 // https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc
357 return YES;
358 }
359
360 //---------------------------------------------------------------------------
361 - (BOOL)prefersStatusBarHidden // hide status bar (iOS7)
362 {
363 return ${IOS_STATUSBAR_HIDDEN};
364 }
365
366 //---------------------------------------------------------------------------
367 - (UIStatusBarStyle)preferredStatusBarStyle
368 {
369 return UIStatusBarStyleLightContent;
370 }
371
372 @end