DEADSOFTWARE

added optional framebuffer and resolution scaling
[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 glRenderToFBO := False; // TODO: check for GL_OES_framebuffer_object
162 {$ELSE}
163 if glRenderToFBO then
164 if not Load_GL_ARB_framebuffer_object() then
165 if not Load_GL_EXT_framebuffer_object() then
166 begin
167 e_LogWriteln('SDL: no framebuffer support detected');
168 glRenderToFBO := False
169 end;
170 {$ENDIF}
171 if (fullscreen = false) and (maximized = false) and (wc = false) then
172 begin
173 SDL_GetWindowPosition(window, @x, @y);
174 wx := x; wy := y
175 end;
176 gFullScreen := fullscreen;
177 gWinMaximized := maximized;
178 gRC_FullScreen := fullscreen;
179 gRC_Maximized := maximized;
180 UpdateSize(w, h);
181 result := true
182 end
183 else
184 begin
185 // SDL_DestroyWindow(window);
186 e_LogWritefln('SDL: unable to create OpenGL context: %s', [SDL_GetError])
187 end
188 end
189 else
190 begin
191 e_LogWritefln('SDL: unable to create window: %s', [SDL_GetError])
192 end
193 end
194 else
195 begin
196 SDL_SetWindowSize(window, w, h);
197 if wc then
198 begin
199 x := SDL_WINDOWPOS_CENTERED;
200 y := SDL_WINDOWPOS_CENTERED
201 end
202 else
203 begin
204 x := wx;
205 y := wy
206 end;
207 SDL_SetWindowPosition(window, x, y);
208 if (fullscreen = false) and (maximized = false) and (wc = false) then
209 begin
210 SDL_GetWindowPosition(window, @x, @y);
211 wx := x; wy := y
212 end;
213 if maximized then
214 SDL_MaximizeWindow(window);
215 if fullScreen then flags := SDL_WINDOW_FULLSCREEN else flags := 0;
216 SDL_SetWindowFullscreen(window, flags);
217 gFullScreen := fullscreen;
218 gWinMaximized := maximized;
219 gRC_FullScreen := fullscreen;
220 gRC_Maximized := maximized;
221 UpdateSize(w, h);
222 result := true
223 end
224 end;
226 procedure sys_Repaint;
227 begin
228 if glRenderToFBO then
229 e_BlitFramebuffer(gWinSizeX, gWinSizeY);
230 SDL_GL_SwapWindow(window)
231 end;
233 procedure sys_EnableVSync (yes: Boolean);
234 begin
235 if yes then
236 SDL_GL_SetSwapInterval(1)
237 else
238 SDL_GL_SetSwapInterval(0)
239 end;
241 function sys_GetDisplayModes (bpp: Integer): SSArray;
242 var i, count, num, pw, ph: Integer; m: TSDL_DisplayMode;
243 begin
244 result := nil;
245 num := SDL_GetNumDisplayModes(display);
246 if num < 0 then
247 e_LogWritefln('SDL: unable to get numer of available display modes: %s', [SDL_GetError]);
248 if num > 0 then
249 begin
250 e_LogWritefln('Video modes for display %s:', [display]);
251 SetLength(result, num);
252 i := 0; count := 0; pw := 0; ph := 0;
253 while i < num do
254 begin
255 SDL_GetDisplayMode(display, i, @m);
256 if ((pw <> m.w) or (ph <> m.h)) then
257 begin
258 e_LogWritefln('* %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
259 pw := m.w; ph := m.h;
260 result[count] := IntToStr(m.w) + 'x' + IntToStr(m.h);
261 Inc(count);
262 end
263 else
264 begin
265 e_LogWritefln('- %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
266 end;
267 Inc(i)
268 end;
269 SetLength(result, count)
270 end
271 end;
273 function sys_SetDisplayMode (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
274 begin
275 result := InitWindow(w, h, bpp, fullScreen, maximized)
276 end;
278 (* --------- Joystick --------- *)
280 procedure HandleJoyButton (var ev: TSDL_JoyButtonEvent);
281 var down: Boolean; key: Integer;
282 begin
283 if (ev.which < e_MaxJoys) and (ev.button < e_MaxJoyBtns) then
284 begin
285 key := e_JoyButtonToKey(ev.which, ev.button);
286 down := ev.type_ = SDL_JOYBUTTONDOWN;
287 if g_dbg_input then
288 e_LogWritefln('Input Debug: jbutton, joy=%s, button=%s, keycode=%s, press=%s', [ev.which, ev.button, key, down]);
289 e_KeyUpDown(key, down);
290 g_Console_ProcessBind(key, down)
291 end
292 else
293 begin
294 if g_dbg_input then
295 begin
296 down := ev.type_ = SDL_JOYBUTTONDOWN;
297 e_LogWritefln('Input Debug: NOT IN RANGE! jbutton, joy=%s, button=%s, press=%s', [ev.which, ev.button, down])
298 end
299 end
300 end;
302 procedure HandleJoyAxis (var ev: TSDL_JoyAxisEvent);
303 var key, minuskey: Integer;
304 begin
305 if (ev.which < e_MaxJoys) and (ev.axis < e_MaxJoyAxes) then
306 begin
307 key := e_JoyAxisToKey(ev.which, ev.axis, AX_PLUS);
308 minuskey := e_JoyAxisToKey(ev.which, ev.axis, AX_MINUS);
310 if g_dbg_input then
311 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]]);
313 if ev.value < JoystickZeroAxes[ev.which, ev.axis] - e_JoystickDeadzones[ev.which] then
314 begin
315 if (e_KeyPressed(key)) then
316 begin
317 e_KeyUpDown(key, False);
318 g_Console_ProcessBind(key, False)
319 end;
320 e_KeyUpDown(minuskey, True);
321 g_Console_ProcessBind(minuskey, True)
322 end
323 else if ev.value > JoystickZeroAxes[ev.which, ev.axis] + e_JoystickDeadzones[ev.which] then
324 begin
325 if (e_KeyPressed(minuskey)) then
326 begin
327 e_KeyUpDown(minuskey, False);
328 g_Console_ProcessBind(minuskey, False)
329 end;
330 e_KeyUpDown(key, True);
331 g_Console_ProcessBind(key, True)
332 end
333 else
334 begin
335 if (e_KeyPressed(minuskey)) then
336 begin
337 e_KeyUpDown(minuskey, False);
338 g_Console_ProcessBind(minuskey, False)
339 end;
340 if (e_KeyPressed(key)) then
341 begin
342 e_KeyUpDown(key, False);
343 g_Console_ProcessBind(key, False)
344 end
345 end
346 end
347 else
348 begin
349 if g_dbg_input then
350 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]])
351 end
352 end;
354 procedure HandleJoyHat (var ev: TSDL_JoyHatEvent);
355 var
356 down: Boolean;
357 i, key: Integer;
358 hat: array [HAT_LEFT..HAT_DOWN] of Boolean;
359 begin
360 if (ev.which < e_MaxJoys) and (ev.hat < e_MaxJoyHats) then
361 begin
362 if g_dbg_input then
363 e_LogWritefln('Input Debug: jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value]);
364 hat[HAT_UP] := LongBool(ev.value and SDL_HAT_UP);
365 hat[HAT_DOWN] := LongBool(ev.value and SDL_HAT_DOWN);
366 hat[HAT_LEFT] := LongBool(ev.value and SDL_HAT_LEFT);
367 hat[HAT_RIGHT] := LongBool(ev.value and SDL_HAT_RIGHT);
368 for i := HAT_LEFT to HAT_DOWN do
369 begin
370 if JoystickHatState[ev.which, ev.hat, i] <> hat[i] then
371 begin
372 down := hat[i];
373 key := e_JoyHatToKey(ev.which, ev.hat, i);
374 e_KeyUpDown(key, down);
375 g_Console_ProcessBind(key, down)
376 end
377 end;
378 JoystickHatState[ev.which, ev.hat] := hat
379 end
380 else
381 begin
382 if g_dbg_input then
383 e_LogWritefln('Input Debug: NOT IN RANGE! jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value])
384 end
385 end;
387 procedure HandleJoyAdd (var ev: TSDL_JoyDeviceEvent);
388 var i: Integer;
389 begin
390 if (ev.which < e_MaxJoys) then
391 begin
392 JoystickHandle[ev.which] := SDL_JoystickOpen(ev.which);
393 if JoystickHandle[ev.which] <> nil then
394 begin
395 e_LogWritefln('Added Joystick %s', [ev.which]);
396 e_JoystickAvailable[ev.which] := True;
397 for i := 0 to Min(SDL_JoystickNumAxes(JoystickHandle[ev.which]), e_MaxJoyAxes) - 1 do
398 JoystickZeroAxes[ev.which, i] := SDL_JoystickGetAxis(JoystickHandle[ev.which], i)
399 end
400 else
401 begin
402 e_LogWritefln('Warning! Failed to open Joystick %s', [ev.which])
403 end
404 end
405 else
406 begin
407 e_LogWritefln('Warning! Added Joystick %s, but we support only <= %s', [ev.which, e_MaxJoys])
408 end
409 end;
411 procedure HandleJoyRemove (var ev: TSDL_JoyDeviceEvent);
412 begin
413 e_LogWritefln('Removed Joystick %s', [ev.which]);
414 if (ev.which < e_MaxJoys) then
415 begin
416 e_JoystickAvailable[ev.which] := False;
417 if JoystickHandle[ev.which] <> nil then
418 SDL_JoystickClose(JoystickHandle[ev.which]);
419 JoystickHandle[ev.which] := nil
420 end
421 end;
423 (* --------- Input --------- *)
425 function HandleWindow (var ev: TSDL_WindowEvent): Boolean;
426 begin
427 result := false;
428 if g_dbg_input then
429 e_LogWritefln('Window Event: event = %s, data1 = %s, data2 = %s', [ev.event, ev.data1, ev.data2]);
430 case ev.event of
431 SDL_WINDOWEVENT_RESIZED: UpdateSize(ev.data1, ev.data2);
432 SDL_WINDOWEVENT_EXPOSED: sys_Repaint;
433 SDL_WINDOWEVENT_CLOSE: result := true;
434 SDL_WINDOWEVENT_MOVED:
435 begin
436 wx := ev.data1;
437 wy := ev.data2
438 end;
439 SDL_WINDOWEVENT_FOCUS_LOST, SDL_WINDOWEVENT_MINIMIZED:
440 begin
441 e_UnpressAllKeys;
442 if gMuteWhenInactive then
443 e_MuteChannels(true);
444 {$IFDEF ENABLE_HOLMES}
445 if assigned(winBlurCB) then winBlurCB;
446 {$ENDIF}
447 end;
448 SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_MAXIMIZED, SDL_WINDOWEVENT_RESTORED:
449 begin
450 if ev.event = SDL_WINDOWEVENT_MAXIMIZED then
451 begin
452 gWinMaximized := true;
453 gRC_Maximized := true
454 end
455 else if ev.event = SDL_WINDOWEVENT_RESTORED then
456 begin
457 gWinMaximized := false;
458 gRC_Maximized := false
459 end;
460 e_MuteChannels(false);
461 {$IFDEF ENABLE_HOLMES}
462 if assigned(winFocusCB) then winFocusCB;
463 {$ENDIF}
464 end;
465 end
466 end;
468 procedure HandleKeyboard (var ev: TSDL_KeyboardEvent);
469 var down: Boolean; key: Integer;
470 begin
471 key := ev.keysym.scancode;
472 down := (ev.type_ = SDL_KEYDOWN);
473 if key = SDL_SCANCODE_AC_BACK then
474 key := SDL_SCANCODE_ESCAPE;
475 {$IFDEF ENABLE_HOLMES}
476 if fuiOnSDLEvent(PSDL_Event(@ev)^) then
477 begin
478 // event eaten, but...
479 if not down then e_KeyUpDown(key, false);
480 exit;
481 end;
482 {$ENDIF}
483 if ev._repeat = 0 then
484 begin
485 if g_dbg_input then
486 e_LogWritefln('Input Debug: keysym, press=%s, scancode=%s', [down, key]);
487 e_KeyUpDown(key, down);
488 g_Console_ProcessBind(key, down);
489 end
490 else if gConsoleShow or gChatShow or (g_ActiveWindow <> nil) then
491 begin
492 KeyPress(key) // key repeat in menus and shit
493 end
494 end;
496 procedure HandleTextInput (var ev: TSDL_TextInputEvent);
497 var ch: UnicodeChar; sch: AnsiChar;
498 begin
499 Utf8ToUnicode(@ch, PChar(ev.text), 1);
500 sch := AnsiChar(wchar2win(ch));
501 if g_dbg_input then
502 e_LogWritefln('Input Debug: text, text="%s", ch = %s, sch = %s', [ev.text, Ord(ch), Ord(sch)]);
503 if IsValid1251(Word(ch)) and IsPrintable1251(ch) then
504 CharPress(sch);
505 end;
507 function sys_HandleInput (): Boolean;
508 var ev: TSDL_Event;
509 begin
510 result := false;
511 ZeroMemory(@ev, sizeof(ev));
512 while SDL_PollEvent(@ev) <> 0 do
513 begin
514 case ev.type_ of
515 SDL_QUITEV: result := true;
516 SDL_WINDOWEVENT: result := HandleWindow(ev.window);
517 SDL_KEYUP, SDL_KEYDOWN: HandleKeyboard(ev.key);
518 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP: HandleJoyButton(ev.jbutton);
519 SDL_JOYAXISMOTION: HandleJoyAxis(ev.jaxis);
520 SDL_JOYHATMOTION: HandleJoyHat(ev.jhat);
521 SDL_JOYDEVICEADDED: HandleJoyAdd(ev.jdevice);
522 SDL_JOYDEVICEREMOVED: HandleJoyRemove(ev.jdevice);
523 SDL_TEXTINPUT: HandleTextInput(ev.text);
524 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP: g_Touch_HandleEvent(ev.tfinger);
525 {$IFDEF ENABLE_HOLMES}
526 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION: fuiOnSDLEvent(ev);
527 {$ENDIF}
528 end
529 end
530 end;
532 procedure sys_RequestQuit;
533 var ev: TSDL_Event;
534 begin
535 ev.type_ := SDL_QUITEV;
536 SDL_PushEvent(@ev)
537 end;
539 (* --------- Init --------- *)
541 procedure sys_Init;
542 var flags: UInt32;
543 begin
544 e_WriteLog('Init SDL2', TMsgType.Notify);
545 {$IFDEF HEADLESS}
546 {$IFDEF USE_SDLMIXER}
547 flags := SDL_INIT_TIMER or SDL_INIT_AUDIO or $00004000;
548 {$ELSE}
549 flags := SDL_INIT_TIMER or $00004000;
550 {$ENDIF}
551 {$ELSE}
552 flags := SDL_INIT_TIMER or SDL_INIT_VIDEO;
553 {$ENDIF}
554 SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, '0');
555 if SDL_Init(flags) <> 0 then
556 raise Exception.Create('SDL: Init failed: ' + SDL_GetError);
557 {$IFNDEF HEADLESS}
558 if SDL_InitSubSystem(SDL_INIT_JOYSTICK) <> 0 then
559 e_LogWritefln('SDL: Init subsystem failed: %s', [SDL_GetError()]);
560 {$ENDIF}
561 SDL_ShowCursor(SDL_DISABLE);
562 end;
564 procedure sys_Final;
565 begin
566 e_WriteLog('Releasing SDL2', TMsgType.Notify);
567 if context <> nil then
568 begin
569 {$IFDEF NOGL_INIT}
570 nogl_Quit;
571 {$ENDIF}
572 SDL_GL_DeleteContext(context);
573 context := nil;
574 end;
575 if window <> nil then
576 begin
577 SDL_DestroyWindow(window);
578 window := nil;
579 end;
580 SDL_Quit
581 end;
583 initialization
584 conRegVar('sdl2_display_index', @display, 'use display index as base', '');
585 conRegVar('sdl2_window_x', @wx, 'window position x', '');
586 conRegVar('sdl2_window_y', @wy, 'window position y', '');
587 conRegVar('sdl2_window_center', @wc, 'force window creation at center', '');
588 display := 0;
589 wx := SDL_WINDOWPOS_CENTERED;
590 wy := SDL_WINDOWPOS_CENTERED;
591 wc := false
592 end.