DEADSOFTWARE

always try to load FBO extensions in case user enables r_fbo later
[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 procedure UpdateSize (w, h: Integer);
78 begin
79 gWinSizeX := w;
80 gWinSizeY := h;
81 gRC_Width := w;
82 gRC_Height := h;
83 if glRenderToFBO then
84 begin
85 // store real window size in gWinSize, downscale resolution now
86 w := round(w / r_pixel_scale);
87 h := round(h / r_pixel_scale);
88 e_ResizeFramebuffer(w, h);
89 end;
90 gScreenWidth := w;
91 gScreenHeight := h;
92 {$IFDEF ENABLE_HOLMES}
93 fuiScrWdt := w;
94 fuiScrHgt := h;
95 {$ENDIF}
96 e_ResizeWindow(w, h);
97 e_InitGL;
98 g_Game_SetupScreenSize;
99 {$IFNDEF ANDOIRD}
100 (* This will fix menu reset on keyboard showing *)
101 g_Menu_Reset;
102 {$ENDIF}
103 g_Game_ClearLoading;
104 {$IFDEF ENABLE_HOLMES}
105 if assigned(oglInitCB) then oglInitCB;
106 {$ENDIF}
107 end;
109 function GetTitle (): PChar;
110 var info: AnsiString;
111 begin
112 info := g_GetBuildHash(false);
113 if info = 'custom build' then
114 info := info + ' by ' + g_GetBuilderName() + ' ' + GAME_BUILDDATE + ' ' + GAME_BUILDTIME;
115 result := PChar(Format(GameTitle, [info]))
116 end;
118 function InitWindow (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
119 var flags: UInt32; x, y: cint;
120 begin
121 // note: on window close make: if assigned(oglDeinitCB) then oglDeinitCB;
122 e_LogWritefln('InitWindow %s %s %s %s', [w, h, bpp, fullScreen]);
123 result := false;
124 if window = nil then
125 begin
126 {$IFDEF USE_GLES1}
127 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
128 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
129 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
130 {$ELSE}
131 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
132 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
133 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
134 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
135 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
136 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
137 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
138 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
139 {$ENDIF}
140 flags := SDL_WINDOW_OPENGL or SDL_WINDOW_RESIZABLE;
141 if fullScreen then flags := flags or SDL_WINDOW_FULLSCREEN;
142 if maximized then flags := flags or SDL_WINDOW_MAXIMIZED;
143 if wc then
144 begin
145 x := SDL_WINDOWPOS_CENTERED;
146 y := SDL_WINDOWPOS_CENTERED
147 end
148 else
149 begin
150 x := wx;
151 y := wy
152 end;
153 window := SDL_CreateWindow(GetTitle(), x, y, w, h, flags);
154 if window <> nil then
155 begin
156 context := SDL_GL_CreateContext(window);
157 if context <> nil then
158 begin
159 {$IFDEF NOGL_INIT}
160 nogl_Init;
161 if (not nogl_ExtensionSupported('GL_OES_framebuffer_object')) and glRenderToFBO then
162 {$ELSE}
163 if (not Load_GL_ARB_framebuffer_object()) and glRenderToFBO then
164 {$ENDIF}
165 begin
166 e_LogWriteln('SDL: no framebuffer object support detected');
167 glRenderToFBO := False
168 end;
169 if (fullscreen = false) and (maximized = false) and (wc = false) then
170 begin
171 SDL_GetWindowPosition(window, @x, @y);
172 wx := x; wy := y
173 end;
174 gFullScreen := fullscreen;
175 gWinMaximized := maximized;
176 gRC_FullScreen := fullscreen;
177 gRC_Maximized := maximized;
178 UpdateSize(w, h);
179 result := true
180 end
181 else
182 begin
183 // SDL_DestroyWindow(window);
184 e_LogWritefln('SDL: unable to create OpenGL context: %s', [SDL_GetError])
185 end
186 end
187 else
188 begin
189 e_LogWritefln('SDL: unable to create window: %s', [SDL_GetError])
190 end
191 end
192 else
193 begin
194 if fullScreen then flags := SDL_WINDOW_FULLSCREEN else flags := 0;
195 SDL_SetWindowFullscreen(window, flags);
196 SDL_SetWindowSize(window, w, h);
197 if maximized then SDL_MaximizeWindow(window);
198 // always reset to center when changing fullscreen->windowed for safety purposes
199 if wc or (gFullscreen and not fullscreen) or (gWinMaximized and not maximized) then
200 begin
201 x := SDL_WINDOWPOS_CENTERED;
202 y := SDL_WINDOWPOS_CENTERED
203 end
204 else
205 begin
206 x := wx;
207 y := wy
208 end;
209 SDL_SetWindowPosition(window, x, y);
210 if (fullscreen = false) and (maximized = false) and (wc = false) then
211 begin
212 SDL_GetWindowPosition(window, @x, @y);
213 wx := x; wy := y
214 end;
215 gFullScreen := fullscreen;
216 gWinMaximized := maximized;
217 gRC_FullScreen := fullscreen;
218 gRC_Maximized := maximized;
219 UpdateSize(w, h);
220 result := true
221 end
222 end;
224 procedure sys_Repaint;
225 begin
226 if glRenderToFBO then
227 e_BlitFramebuffer(gWinSizeX, gWinSizeY);
228 SDL_GL_SwapWindow(window)
229 end;
231 procedure sys_EnableVSync (yes: Boolean);
232 begin
233 if yes then
234 SDL_GL_SetSwapInterval(1)
235 else
236 SDL_GL_SetSwapInterval(0)
237 end;
239 function sys_GetDisplayModes (bpp: Integer): SSArray;
240 var i, count, num, pw, ph: Integer; m: TSDL_DisplayMode;
241 begin
242 result := nil;
243 num := SDL_GetNumDisplayModes(display);
244 if num < 0 then
245 e_LogWritefln('SDL: unable to get numer of available display modes: %s', [SDL_GetError]);
246 if num > 0 then
247 begin
248 e_LogWritefln('Video modes for display %s:', [display]);
249 SetLength(result, num);
250 i := 0; count := 0; pw := 0; ph := 0;
251 while i < num do
252 begin
253 SDL_GetDisplayMode(display, i, @m);
254 if ((pw <> m.w) or (ph <> m.h)) then
255 begin
256 e_LogWritefln('* %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
257 pw := m.w; ph := m.h;
258 result[count] := IntToStr(m.w) + 'x' + IntToStr(m.h);
259 Inc(count);
260 end
261 else
262 begin
263 e_LogWritefln('- %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
264 end;
265 Inc(i)
266 end;
267 SetLength(result, count)
268 end
269 end;
271 function sys_SetDisplayMode (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
272 begin
273 result := InitWindow(w, h, bpp, fullScreen, maximized)
274 end;
276 (* --------- Joystick --------- *)
278 procedure HandleJoyButton (var ev: TSDL_JoyButtonEvent);
279 var down: Boolean; key: Integer;
280 begin
281 if (ev.which < e_MaxJoys) and (ev.button < e_MaxJoyBtns) then
282 begin
283 key := e_JoyButtonToKey(ev.which, ev.button);
284 down := ev.type_ = SDL_JOYBUTTONDOWN;
285 if g_dbg_input then
286 e_LogWritefln('Input Debug: jbutton, joy=%s, button=%s, keycode=%s, press=%s', [ev.which, ev.button, key, down]);
287 e_KeyUpDown(key, down);
288 g_Console_ProcessBind(key, down)
289 end
290 else
291 begin
292 if g_dbg_input then
293 begin
294 down := ev.type_ = SDL_JOYBUTTONDOWN;
295 e_LogWritefln('Input Debug: NOT IN RANGE! jbutton, joy=%s, button=%s, press=%s', [ev.which, ev.button, down])
296 end
297 end
298 end;
300 procedure HandleJoyAxis (var ev: TSDL_JoyAxisEvent);
301 var key, minuskey: Integer;
302 begin
303 if (ev.which < e_MaxJoys) and (ev.axis < e_MaxJoyAxes) then
304 begin
305 key := e_JoyAxisToKey(ev.which, ev.axis, AX_PLUS);
306 minuskey := e_JoyAxisToKey(ev.which, ev.axis, AX_MINUS);
308 if g_dbg_input then
309 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]]);
311 if ev.value < JoystickZeroAxes[ev.which, ev.axis] - e_JoystickDeadzones[ev.which] then
312 begin
313 if (e_KeyPressed(key)) then
314 begin
315 e_KeyUpDown(key, False);
316 g_Console_ProcessBind(key, False)
317 end;
318 e_KeyUpDown(minuskey, True);
319 g_Console_ProcessBind(minuskey, True)
320 end
321 else if ev.value > JoystickZeroAxes[ev.which, ev.axis] + e_JoystickDeadzones[ev.which] then
322 begin
323 if (e_KeyPressed(minuskey)) then
324 begin
325 e_KeyUpDown(minuskey, False);
326 g_Console_ProcessBind(minuskey, False)
327 end;
328 e_KeyUpDown(key, True);
329 g_Console_ProcessBind(key, True)
330 end
331 else
332 begin
333 if (e_KeyPressed(minuskey)) then
334 begin
335 e_KeyUpDown(minuskey, False);
336 g_Console_ProcessBind(minuskey, False)
337 end;
338 if (e_KeyPressed(key)) then
339 begin
340 e_KeyUpDown(key, False);
341 g_Console_ProcessBind(key, False)
342 end
343 end
344 end
345 else
346 begin
347 if g_dbg_input then
348 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]])
349 end
350 end;
352 procedure HandleJoyHat (var ev: TSDL_JoyHatEvent);
353 var
354 down: Boolean;
355 i, key: Integer;
356 hat: array [HAT_LEFT..HAT_DOWN] of Boolean;
357 begin
358 if (ev.which < e_MaxJoys) and (ev.hat < e_MaxJoyHats) then
359 begin
360 if g_dbg_input then
361 e_LogWritefln('Input Debug: jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value]);
362 hat[HAT_UP] := LongBool(ev.value and SDL_HAT_UP);
363 hat[HAT_DOWN] := LongBool(ev.value and SDL_HAT_DOWN);
364 hat[HAT_LEFT] := LongBool(ev.value and SDL_HAT_LEFT);
365 hat[HAT_RIGHT] := LongBool(ev.value and SDL_HAT_RIGHT);
366 for i := HAT_LEFT to HAT_DOWN do
367 begin
368 if JoystickHatState[ev.which, ev.hat, i] <> hat[i] then
369 begin
370 down := hat[i];
371 key := e_JoyHatToKey(ev.which, ev.hat, i);
372 e_KeyUpDown(key, down);
373 g_Console_ProcessBind(key, down)
374 end
375 end;
376 JoystickHatState[ev.which, ev.hat] := hat
377 end
378 else
379 begin
380 if g_dbg_input then
381 e_LogWritefln('Input Debug: NOT IN RANGE! jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value])
382 end
383 end;
385 procedure HandleJoyAdd (var ev: TSDL_JoyDeviceEvent);
386 var i: Integer;
387 begin
388 if (ev.which < e_MaxJoys) then
389 begin
390 JoystickHandle[ev.which] := SDL_JoystickOpen(ev.which);
391 if JoystickHandle[ev.which] <> nil then
392 begin
393 e_LogWritefln('Added Joystick %s', [ev.which]);
394 e_JoystickAvailable[ev.which] := True;
395 for i := 0 to Min(SDL_JoystickNumAxes(JoystickHandle[ev.which]), e_MaxJoyAxes) - 1 do
396 JoystickZeroAxes[ev.which, i] := SDL_JoystickGetAxis(JoystickHandle[ev.which], i)
397 end
398 else
399 begin
400 e_LogWritefln('Warning! Failed to open Joystick %s', [ev.which])
401 end
402 end
403 else
404 begin
405 e_LogWritefln('Warning! Added Joystick %s, but we support only <= %s', [ev.which, e_MaxJoys])
406 end
407 end;
409 procedure HandleJoyRemove (var ev: TSDL_JoyDeviceEvent);
410 begin
411 e_LogWritefln('Removed Joystick %s', [ev.which]);
412 if (ev.which < e_MaxJoys) then
413 begin
414 e_JoystickAvailable[ev.which] := False;
415 if JoystickHandle[ev.which] <> nil then
416 SDL_JoystickClose(JoystickHandle[ev.which]);
417 JoystickHandle[ev.which] := nil
418 end
419 end;
421 (* --------- Input --------- *)
423 function HandleWindow (var ev: TSDL_WindowEvent): Boolean;
424 begin
425 result := false;
426 if g_dbg_input then
427 e_LogWritefln('Window Event: event = %s, data1 = %s, data2 = %s', [ev.event, ev.data1, ev.data2]);
428 case ev.event of
429 SDL_WINDOWEVENT_RESIZED: UpdateSize(ev.data1, ev.data2);
430 SDL_WINDOWEVENT_EXPOSED: sys_Repaint;
431 SDL_WINDOWEVENT_CLOSE: result := true;
432 SDL_WINDOWEVENT_MOVED:
433 begin
434 wx := ev.data1;
435 wy := ev.data2
436 end;
437 SDL_WINDOWEVENT_FOCUS_LOST, SDL_WINDOWEVENT_MINIMIZED:
438 begin
439 e_UnpressAllKeys;
440 if gMuteWhenInactive then
441 e_MuteChannels(true);
442 {$IFDEF ENABLE_HOLMES}
443 if assigned(winBlurCB) then winBlurCB;
444 {$ENDIF}
445 end;
446 SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_MAXIMIZED, SDL_WINDOWEVENT_RESTORED:
447 begin
448 if ev.event = SDL_WINDOWEVENT_MAXIMIZED then
449 begin
450 gWinMaximized := true;
451 gRC_Maximized := true
452 end
453 else if ev.event = SDL_WINDOWEVENT_RESTORED then
454 begin
455 gWinMaximized := false;
456 gRC_Maximized := false
457 end;
458 e_MuteChannels(false);
459 {$IFDEF ENABLE_HOLMES}
460 if assigned(winFocusCB) then winFocusCB;
461 {$ENDIF}
462 end;
463 end
464 end;
466 procedure HandleKeyboard (var ev: TSDL_KeyboardEvent);
467 var down: Boolean; key: Integer;
468 begin
469 key := ev.keysym.scancode;
470 down := (ev.type_ = SDL_KEYDOWN);
471 if key = SDL_SCANCODE_AC_BACK then
472 key := SDL_SCANCODE_ESCAPE;
473 {$IFDEF ENABLE_HOLMES}
474 if fuiOnSDLEvent(PSDL_Event(@ev)^) then
475 begin
476 // event eaten, but...
477 if not down then e_KeyUpDown(key, false);
478 exit;
479 end;
480 {$ENDIF}
481 if ev._repeat = 0 then
482 begin
483 if g_dbg_input then
484 e_LogWritefln('Input Debug: keysym, press=%s, scancode=%s', [down, key]);
485 e_KeyUpDown(key, down);
486 g_Console_ProcessBind(key, down);
487 end
488 else if gConsoleShow or gChatShow or (g_ActiveWindow <> nil) then
489 begin
490 KeyPress(key) // key repeat in menus and shit
491 end
492 end;
494 procedure HandleTextInput (var ev: TSDL_TextInputEvent);
495 var ch: UnicodeChar; sch: AnsiChar;
496 begin
497 Utf8ToUnicode(@ch, PChar(ev.text), 1);
498 sch := AnsiChar(wchar2win(ch));
499 if g_dbg_input then
500 e_LogWritefln('Input Debug: text, text="%s", ch = %s, sch = %s', [ev.text, Ord(ch), Ord(sch)]);
501 if IsValid1251(Word(ch)) and IsPrintable1251(ch) then
502 CharPress(sch);
503 end;
505 function sys_HandleInput (): Boolean;
506 var ev: TSDL_Event;
507 begin
508 result := false;
509 ZeroMemory(@ev, sizeof(ev));
510 while SDL_PollEvent(@ev) <> 0 do
511 begin
512 case ev.type_ of
513 SDL_QUITEV: result := true;
514 SDL_WINDOWEVENT: result := HandleWindow(ev.window);
515 SDL_KEYUP, SDL_KEYDOWN: HandleKeyboard(ev.key);
516 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP: HandleJoyButton(ev.jbutton);
517 SDL_JOYAXISMOTION: HandleJoyAxis(ev.jaxis);
518 SDL_JOYHATMOTION: HandleJoyHat(ev.jhat);
519 SDL_JOYDEVICEADDED: HandleJoyAdd(ev.jdevice);
520 SDL_JOYDEVICEREMOVED: HandleJoyRemove(ev.jdevice);
521 SDL_TEXTINPUT: HandleTextInput(ev.text);
522 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP: g_Touch_HandleEvent(ev.tfinger);
523 {$IFDEF ENABLE_HOLMES}
524 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION: fuiOnSDLEvent(ev);
525 {$ENDIF}
526 end
527 end
528 end;
530 procedure sys_RequestQuit;
531 var ev: TSDL_Event;
532 begin
533 ev.type_ := SDL_QUITEV;
534 SDL_PushEvent(@ev)
535 end;
537 (* --------- Init --------- *)
539 procedure sys_Init;
540 var flags: UInt32;
541 begin
542 e_WriteLog('Init SDL2', TMsgType.Notify);
543 {$IFDEF HEADLESS}
544 {$IFDEF USE_SDLMIXER}
545 flags := SDL_INIT_TIMER or SDL_INIT_AUDIO or $00004000;
546 {$ELSE}
547 flags := SDL_INIT_TIMER or $00004000;
548 {$ENDIF}
549 {$ELSE}
550 flags := SDL_INIT_TIMER or SDL_INIT_VIDEO;
551 {$ENDIF}
552 SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, '0');
553 if SDL_Init(flags) <> 0 then
554 raise Exception.Create('SDL: Init failed: ' + SDL_GetError);
555 {$IFNDEF HEADLESS}
556 if SDL_InitSubSystem(SDL_INIT_JOYSTICK) <> 0 then
557 e_LogWritefln('SDL: Init subsystem failed: %s', [SDL_GetError()]);
558 {$ENDIF}
559 SDL_ShowCursor(SDL_DISABLE);
560 end;
562 procedure sys_Final;
563 begin
564 e_WriteLog('Releasing SDL2', TMsgType.Notify);
565 if context <> nil then
566 begin
567 {$IFDEF NOGL_INIT}
568 nogl_Quit;
569 {$ENDIF}
570 SDL_GL_DeleteContext(context);
571 context := nil;
572 end;
573 if window <> nil then
574 begin
575 SDL_DestroyWindow(window);
576 window := nil;
577 end;
578 SDL_Quit
579 end;
581 initialization
582 conRegVar('sdl2_display_index', @display, 'use display index as base', '');
583 conRegVar('sdl2_window_x', @wx, 'window position x', '');
584 conRegVar('sdl2_window_y', @wy, 'window position y', '');
585 conRegVar('sdl2_window_center', @wc, 'force window creation at center', '');
586 display := 0;
587 wx := SDL_WINDOWPOS_CENTERED;
588 wy := SDL_WINDOWPOS_CENTERED;
589 wc := false
590 end.