DEADSOFTWARE

SDL: separated GL loading code
[d2df-sdl.git] / src / game / sdl2 / g_system.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 unit g_system;
18 interface
20 uses Utils;
22 (* --- Utils --- *)
23 function sys_GetTicks (): Int64;
24 procedure sys_Delay (ms: Integer);
26 (* --- Graphics --- *)
27 function sys_GetDisplayModes (bpp: Integer): SSArray;
28 function sys_SetDisplayMode (w, h, bpp: Integer; fullscreen, maximized: Boolean): Boolean;
29 procedure sys_EnableVSync (yes: Boolean);
30 procedure sys_Repaint;
32 (* --- Input --- *)
33 function sys_HandleInput (): Boolean;
34 procedure sys_RequestQuit;
36 (* --- Init --- *)
37 procedure sys_Init;
38 procedure sys_Final;
40 implementation
42 uses
43 SysUtils, SDL2, Math, ctypes,
44 e_log, e_graphics, e_input, e_sound,
45 {$INCLUDE ../nogl/noGLuses.inc}
46 {$IFDEF ENABLE_HOLMES}
47 g_holmes, sdlcarcass, fui_ctls,
48 {$ENDIF}
49 g_touch, g_options, g_window, g_console, g_game, g_menu, g_gui, g_main, g_basic;
51 const
52 GameTitle = 'Doom 2D: Forever (SDL 2, %s)';
54 var
55 window: PSDL_Window;
56 context: TSDL_GLContext;
57 display, wx, wy: Integer;
58 wc: Boolean;
59 JoystickHandle: array [0..e_MaxJoys - 1] of PSDL_Joystick;
60 JoystickHatState: array [0..e_MaxJoys - 1, 0..e_MaxJoyHats - 1, HAT_LEFT..HAT_DOWN] of Boolean;
61 JoystickZeroAxes: array [0..e_MaxJoys - 1, 0..e_MaxJoyAxes - 1] of Integer;
63 (* --------- Utils --------- *)
65 function sys_GetTicks (): Int64;
66 begin
67 result := SDL_GetTicks()
68 end;
70 procedure sys_Delay (ms: Integer);
71 begin
72 SDL_Delay(ms)
73 end;
75 (* --------- Graphics --------- *)
77 function LoadGL: Boolean;
78 begin
79 result := true;
80 {$IFDEF NOGL_INIT}
81 nogl_Init;
82 if glRenderToFBO and (not nogl_ExtensionSupported('GL_OES_framebuffer_object')) then
83 {$ELSE}
84 if glRenderToFBO and (not Load_GL_ARB_framebuffer_object) then
85 {$ENDIF}
86 begin
87 e_LogWriteln('GL: framebuffer objects not supported; disabling FBO rendering');
88 glRenderToFBO := false;
89 end;
90 end;
92 procedure FreeGL;
93 begin
94 {$IFDEF NOGL_INIT}
95 nogl_Quit();
96 {$ENDIF}
97 end;
99 procedure UpdateSize (w, h: Integer);
100 begin
101 gWinSizeX := w;
102 gWinSizeY := h;
103 gRC_Width := w;
104 gRC_Height := h;
105 if glRenderToFBO then
106 begin
107 // store real window size in gWinSize, downscale resolution now
108 w := round(w / r_pixel_scale);
109 h := round(h / r_pixel_scale);
110 e_ResizeFramebuffer(w, h);
111 end;
112 gScreenWidth := w;
113 gScreenHeight := h;
114 {$IFDEF ENABLE_HOLMES}
115 fuiScrWdt := w;
116 fuiScrHgt := h;
117 {$ENDIF}
118 e_ResizeWindow(w, h);
119 e_InitGL;
120 g_Game_SetupScreenSize;
121 {$IFNDEF ANDOIRD}
122 (* This will fix menu reset on keyboard showing *)
123 g_Menu_Reset;
124 {$ENDIF}
125 g_Game_ClearLoading;
126 {$IFDEF ENABLE_HOLMES}
127 if assigned(oglInitCB) then oglInitCB;
128 {$ENDIF}
129 end;
131 function GetTitle (): PChar;
132 var info: AnsiString;
133 begin
134 info := g_GetBuildHash(false);
135 if info = 'custom build' then
136 info := info + ' by ' + g_GetBuilderName() + ' ' + GAME_BUILDDATE + ' ' + GAME_BUILDTIME;
137 result := PChar(Format(GameTitle, [info]))
138 end;
140 function InitWindow (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
141 var flags: UInt32; x, y: cint;
142 begin
143 // note: on window close make: if assigned(oglDeinitCB) then oglDeinitCB;
144 e_LogWritefln('InitWindow %s %s %s %s', [w, h, bpp, fullScreen]);
145 result := false;
146 if window = nil then
147 begin
148 {$IFDEF USE_GLES1}
149 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
150 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
151 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
152 {$ELSE}
153 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
154 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
155 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
156 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
157 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
158 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
159 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
160 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
161 {$ENDIF}
162 flags := SDL_WINDOW_OPENGL or SDL_WINDOW_RESIZABLE;
163 if fullScreen then flags := flags or SDL_WINDOW_FULLSCREEN;
164 if maximized then flags := flags or SDL_WINDOW_MAXIMIZED;
165 if wc then
166 begin
167 x := SDL_WINDOWPOS_CENTERED;
168 y := SDL_WINDOWPOS_CENTERED
169 end
170 else
171 begin
172 x := wx;
173 y := wy
174 end;
175 window := SDL_CreateWindow(GetTitle(), x, y, w, h, flags);
176 if window <> nil then
177 begin
178 context := SDL_GL_CreateContext(window);
179 if context <> nil then
180 begin
181 if not LoadGL then
182 begin
183 e_LogWriteln('GL: unable to load OpenGL functions', TMsgType.Fatal);
184 SDL_GL_DeleteContext(context); context := nil;
185 exit;
186 end;
187 if (fullscreen = false) and (maximized = false) and (wc = false) then
188 begin
189 SDL_GetWindowPosition(window, @x, @y);
190 wx := x; wy := y
191 end;
192 gFullScreen := fullscreen;
193 gWinMaximized := maximized;
194 gRC_FullScreen := fullscreen;
195 gRC_Maximized := maximized;
196 UpdateSize(w, h);
197 result := true
198 end
199 else
200 begin
201 // SDL_DestroyWindow(window);
202 e_LogWritefln('SDL: unable to create OpenGL context: %s', [SDL_GetError])
203 end
204 end
205 else
206 begin
207 e_LogWritefln('SDL: unable to create window: %s', [SDL_GetError])
208 end
209 end
210 else
211 begin
212 if fullScreen then flags := SDL_WINDOW_FULLSCREEN else flags := 0;
213 SDL_SetWindowFullscreen(window, flags);
214 SDL_SetWindowSize(window, w, h);
215 if maximized then SDL_MaximizeWindow(window);
216 // always reset to center when changing fullscreen->windowed for safety purposes
217 if wc or (gFullscreen and not fullscreen) or (gWinMaximized and not maximized) then
218 begin
219 x := SDL_WINDOWPOS_CENTERED;
220 y := SDL_WINDOWPOS_CENTERED
221 end
222 else
223 begin
224 x := wx;
225 y := wy
226 end;
227 SDL_SetWindowPosition(window, x, y);
228 if (fullscreen = false) and (maximized = false) and (wc = false) then
229 begin
230 SDL_GetWindowPosition(window, @x, @y);
231 wx := x; wy := y
232 end;
233 gFullScreen := fullscreen;
234 gWinMaximized := maximized;
235 gRC_FullScreen := fullscreen;
236 gRC_Maximized := maximized;
237 UpdateSize(w, h);
238 result := true
239 end
240 end;
242 procedure sys_Repaint;
243 begin
244 if glRenderToFBO then
245 e_BlitFramebuffer(gWinSizeX, gWinSizeY);
246 SDL_GL_SwapWindow(window)
247 end;
249 procedure sys_EnableVSync (yes: Boolean);
250 begin
251 if yes then
252 SDL_GL_SetSwapInterval(1)
253 else
254 SDL_GL_SetSwapInterval(0)
255 end;
257 function sys_GetDisplayModes (bpp: Integer): SSArray;
258 var i, count, num, pw, ph: Integer; m: TSDL_DisplayMode;
259 begin
260 result := nil;
261 num := SDL_GetNumDisplayModes(display);
262 if num < 0 then
263 e_LogWritefln('SDL: unable to get numer of available display modes: %s', [SDL_GetError]);
264 if num > 0 then
265 begin
266 e_LogWritefln('Video modes for display %s:', [display]);
267 SetLength(result, num);
268 i := 0; count := 0; pw := 0; ph := 0;
269 while i < num do
270 begin
271 SDL_GetDisplayMode(display, i, @m);
272 if ((pw <> m.w) or (ph <> m.h)) then
273 begin
274 e_LogWritefln('* %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
275 pw := m.w; ph := m.h;
276 result[count] := IntToStr(m.w) + 'x' + IntToStr(m.h);
277 Inc(count);
278 end
279 else
280 begin
281 e_LogWritefln('- %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
282 end;
283 Inc(i)
284 end;
285 SetLength(result, count)
286 end
287 end;
289 function sys_SetDisplayMode (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
290 begin
291 result := InitWindow(w, h, bpp, fullScreen, maximized)
292 end;
294 (* --------- Joystick --------- *)
296 procedure HandleJoyButton (var ev: TSDL_JoyButtonEvent);
297 var down: Boolean; key: Integer;
298 begin
299 if (ev.which < e_MaxJoys) and (ev.button < e_MaxJoyBtns) then
300 begin
301 key := e_JoyButtonToKey(ev.which, ev.button);
302 down := ev.type_ = SDL_JOYBUTTONDOWN;
303 if g_dbg_input then
304 e_LogWritefln('Input Debug: jbutton, joy=%s, button=%s, keycode=%s, press=%s', [ev.which, ev.button, key, down]);
305 e_KeyUpDown(key, down);
306 g_Console_ProcessBind(key, down)
307 end
308 else
309 begin
310 if g_dbg_input then
311 begin
312 down := ev.type_ = SDL_JOYBUTTONDOWN;
313 e_LogWritefln('Input Debug: NOT IN RANGE! jbutton, joy=%s, button=%s, press=%s', [ev.which, ev.button, down])
314 end
315 end
316 end;
318 procedure HandleJoyAxis (var ev: TSDL_JoyAxisEvent);
319 var key, minuskey: Integer;
320 begin
321 if (ev.which < e_MaxJoys) and (ev.axis < e_MaxJoyAxes) then
322 begin
323 key := e_JoyAxisToKey(ev.which, ev.axis, AX_PLUS);
324 minuskey := e_JoyAxisToKey(ev.which, ev.axis, AX_MINUS);
326 if g_dbg_input then
327 e_LogWritefln('Input Debug: jaxis, joy=%s, axis=%s, value=%s, zeroaxes=%s, deadzone=%s', [ev.which, ev.axis, ev.value, JoystickZeroAxes[ev.which, ev.axis], e_JoystickDeadzones[ev.which]]);
329 if ev.value < JoystickZeroAxes[ev.which, ev.axis] - e_JoystickDeadzones[ev.which] then
330 begin
331 if (e_KeyPressed(key)) then
332 begin
333 e_KeyUpDown(key, False);
334 g_Console_ProcessBind(key, False)
335 end;
336 e_KeyUpDown(minuskey, True);
337 g_Console_ProcessBind(minuskey, True)
338 end
339 else if ev.value > JoystickZeroAxes[ev.which, ev.axis] + e_JoystickDeadzones[ev.which] then
340 begin
341 if (e_KeyPressed(minuskey)) then
342 begin
343 e_KeyUpDown(minuskey, False);
344 g_Console_ProcessBind(minuskey, False)
345 end;
346 e_KeyUpDown(key, True);
347 g_Console_ProcessBind(key, True)
348 end
349 else
350 begin
351 if (e_KeyPressed(minuskey)) then
352 begin
353 e_KeyUpDown(minuskey, False);
354 g_Console_ProcessBind(minuskey, False)
355 end;
356 if (e_KeyPressed(key)) then
357 begin
358 e_KeyUpDown(key, False);
359 g_Console_ProcessBind(key, False)
360 end
361 end
362 end
363 else
364 begin
365 if g_dbg_input then
366 e_LogWritefln('Input Debug: NOT IN RANGE! jaxis, joy=%s, axis=%s, value=%s, zeroaxes=%s, deadzone=%s', [ev.which, ev.axis, ev.value, JoystickZeroAxes[ev.which, ev.axis], e_JoystickDeadzones[ev.which]])
367 end
368 end;
370 procedure HandleJoyHat (var ev: TSDL_JoyHatEvent);
371 var
372 down: Boolean;
373 i, key: Integer;
374 hat: array [HAT_LEFT..HAT_DOWN] of Boolean;
375 begin
376 if (ev.which < e_MaxJoys) and (ev.hat < e_MaxJoyHats) then
377 begin
378 if g_dbg_input then
379 e_LogWritefln('Input Debug: jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value]);
380 hat[HAT_UP] := LongBool(ev.value and SDL_HAT_UP);
381 hat[HAT_DOWN] := LongBool(ev.value and SDL_HAT_DOWN);
382 hat[HAT_LEFT] := LongBool(ev.value and SDL_HAT_LEFT);
383 hat[HAT_RIGHT] := LongBool(ev.value and SDL_HAT_RIGHT);
384 for i := HAT_LEFT to HAT_DOWN do
385 begin
386 if JoystickHatState[ev.which, ev.hat, i] <> hat[i] then
387 begin
388 down := hat[i];
389 key := e_JoyHatToKey(ev.which, ev.hat, i);
390 e_KeyUpDown(key, down);
391 g_Console_ProcessBind(key, down)
392 end
393 end;
394 JoystickHatState[ev.which, ev.hat] := hat
395 end
396 else
397 begin
398 if g_dbg_input then
399 e_LogWritefln('Input Debug: NOT IN RANGE! jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value])
400 end
401 end;
403 procedure HandleJoyAdd (var ev: TSDL_JoyDeviceEvent);
404 var i: Integer;
405 begin
406 if (ev.which < e_MaxJoys) then
407 begin
408 JoystickHandle[ev.which] := SDL_JoystickOpen(ev.which);
409 if JoystickHandle[ev.which] <> nil then
410 begin
411 e_LogWritefln('Added Joystick %s', [ev.which]);
412 e_JoystickAvailable[ev.which] := True;
413 for i := 0 to Min(SDL_JoystickNumAxes(JoystickHandle[ev.which]), e_MaxJoyAxes) - 1 do
414 JoystickZeroAxes[ev.which, i] := SDL_JoystickGetAxis(JoystickHandle[ev.which], i)
415 end
416 else
417 begin
418 e_LogWritefln('Warning! Failed to open Joystick %s', [ev.which])
419 end
420 end
421 else
422 begin
423 e_LogWritefln('Warning! Added Joystick %s, but we support only <= %s', [ev.which, e_MaxJoys])
424 end
425 end;
427 procedure HandleJoyRemove (var ev: TSDL_JoyDeviceEvent);
428 begin
429 e_LogWritefln('Removed Joystick %s', [ev.which]);
430 if (ev.which < e_MaxJoys) then
431 begin
432 e_JoystickAvailable[ev.which] := False;
433 if JoystickHandle[ev.which] <> nil then
434 SDL_JoystickClose(JoystickHandle[ev.which]);
435 JoystickHandle[ev.which] := nil
436 end
437 end;
439 (* --------- Input --------- *)
441 function HandleWindow (var ev: TSDL_WindowEvent): Boolean;
442 begin
443 result := false;
444 if g_dbg_input then
445 e_LogWritefln('Window Event: event = %s, data1 = %s, data2 = %s', [ev.event, ev.data1, ev.data2]);
446 case ev.event of
447 SDL_WINDOWEVENT_RESIZED: UpdateSize(ev.data1, ev.data2);
448 SDL_WINDOWEVENT_EXPOSED: sys_Repaint;
449 SDL_WINDOWEVENT_CLOSE: result := true;
450 SDL_WINDOWEVENT_MOVED:
451 begin
452 wx := ev.data1;
453 wy := ev.data2
454 end;
455 SDL_WINDOWEVENT_FOCUS_LOST, SDL_WINDOWEVENT_MINIMIZED:
456 begin
457 e_UnpressAllKeys;
458 if gMuteWhenInactive then
459 e_MuteChannels(true);
460 {$IFDEF ENABLE_HOLMES}
461 if assigned(winBlurCB) then winBlurCB;
462 {$ENDIF}
463 end;
464 SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_MAXIMIZED, SDL_WINDOWEVENT_RESTORED:
465 begin
466 if ev.event = SDL_WINDOWEVENT_MAXIMIZED then
467 begin
468 gWinMaximized := true;
469 gRC_Maximized := true
470 end
471 else if ev.event = SDL_WINDOWEVENT_RESTORED then
472 begin
473 gWinMaximized := false;
474 gRC_Maximized := false
475 end;
476 e_MuteChannels(false);
477 {$IFDEF ENABLE_HOLMES}
478 if assigned(winFocusCB) then winFocusCB;
479 {$ENDIF}
480 end;
481 end
482 end;
484 procedure HandleKeyboard (var ev: TSDL_KeyboardEvent);
485 var down: Boolean; key: Integer;
486 begin
487 key := ev.keysym.scancode;
488 down := (ev.type_ = SDL_KEYDOWN);
489 if key = SDL_SCANCODE_AC_BACK then
490 key := SDL_SCANCODE_ESCAPE;
491 {$IFDEF ENABLE_HOLMES}
492 if fuiOnSDLEvent(PSDL_Event(@ev)^) then
493 begin
494 // event eaten, but...
495 if not down then e_KeyUpDown(key, false);
496 exit;
497 end;
498 {$ENDIF}
499 if ev._repeat = 0 then
500 begin
501 if g_dbg_input then
502 e_LogWritefln('Input Debug: keysym, press=%s, scancode=%s', [down, key]);
503 e_KeyUpDown(key, down);
504 g_Console_ProcessBind(key, down);
505 end
506 else if gConsoleShow or gChatShow or (g_ActiveWindow <> nil) then
507 begin
508 KeyPress(key) // key repeat in menus and shit
509 end
510 end;
512 procedure HandleTextInput (var ev: TSDL_TextInputEvent);
513 var ch: UnicodeChar; sch: AnsiChar;
514 begin
515 Utf8ToUnicode(@ch, PChar(ev.text), 1);
516 sch := AnsiChar(wchar2win(ch));
517 if g_dbg_input then
518 e_LogWritefln('Input Debug: text, text="%s", ch = %s, sch = %s', [ev.text, Ord(ch), Ord(sch)]);
519 if IsValid1251(Word(ch)) and IsPrintable1251(ch) then
520 CharPress(sch);
521 end;
523 function sys_HandleInput (): Boolean;
524 var ev: TSDL_Event;
525 begin
526 result := false;
527 ZeroMemory(@ev, sizeof(ev));
528 while SDL_PollEvent(@ev) <> 0 do
529 begin
530 case ev.type_ of
531 SDL_QUITEV: result := true;
532 SDL_WINDOWEVENT: result := HandleWindow(ev.window);
533 SDL_KEYUP, SDL_KEYDOWN: HandleKeyboard(ev.key);
534 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP: HandleJoyButton(ev.jbutton);
535 SDL_JOYAXISMOTION: HandleJoyAxis(ev.jaxis);
536 SDL_JOYHATMOTION: HandleJoyHat(ev.jhat);
537 SDL_JOYDEVICEADDED: HandleJoyAdd(ev.jdevice);
538 SDL_JOYDEVICEREMOVED: HandleJoyRemove(ev.jdevice);
539 SDL_TEXTINPUT: HandleTextInput(ev.text);
540 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP: g_Touch_HandleEvent(ev.tfinger);
541 {$IFDEF ENABLE_HOLMES}
542 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION: fuiOnSDLEvent(ev);
543 {$ENDIF}
544 end
545 end
546 end;
548 procedure sys_RequestQuit;
549 var ev: TSDL_Event;
550 begin
551 ev.type_ := SDL_QUITEV;
552 SDL_PushEvent(@ev)
553 end;
555 (* --------- Init --------- *)
557 procedure sys_Init;
558 var flags: UInt32;
559 begin
560 e_WriteLog('Init SDL2', TMsgType.Notify);
561 {$IFDEF HEADLESS}
562 {$IFDEF USE_SDLMIXER}
563 flags := SDL_INIT_TIMER or SDL_INIT_AUDIO or $00004000;
564 {$ELSE}
565 flags := SDL_INIT_TIMER or $00004000;
566 {$ENDIF}
567 {$ELSE}
568 flags := SDL_INIT_TIMER or SDL_INIT_VIDEO;
569 {$ENDIF}
570 SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, '0');
571 if SDL_Init(flags) <> 0 then
572 raise Exception.Create('SDL: Init failed: ' + SDL_GetError);
573 {$IFNDEF HEADLESS}
574 if SDL_InitSubSystem(SDL_INIT_JOYSTICK) <> 0 then
575 e_LogWritefln('SDL: Init subsystem failed: %s', [SDL_GetError()]);
576 {$ENDIF}
577 SDL_ShowCursor(SDL_DISABLE);
578 end;
580 procedure sys_Final;
581 begin
582 e_WriteLog('Releasing SDL2', TMsgType.Notify);
583 if context <> nil then
584 begin
585 FreeGL;
586 SDL_GL_DeleteContext(context);
587 context := nil;
588 end;
589 if window <> nil then
590 begin
591 SDL_DestroyWindow(window);
592 window := nil;
593 end;
594 SDL_Quit
595 end;
597 initialization
598 conRegVar('sdl2_display_index', @display, 'use display index as base', '');
599 conRegVar('sdl2_window_x', @wx, 'window position x', '');
600 conRegVar('sdl2_window_y', @wy, 'window position y', '');
601 conRegVar('sdl2_window_center', @wc, 'force window creation at center', '');
602 display := 0;
603 wx := SDL_WINDOWPOS_CENTERED;
604 wy := SDL_WINDOWPOS_CENTERED;
605 wc := false
606 end.