DEADSOFTWARE

render: system: move gl related code from system driver
[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 var (* hooks *)
41 sys_CharPress: procedure (ch: AnsiChar) = nil;
42 sys_ScreenResize: procedure (w, h: Integer) = nil;
44 implementation
46 uses
47 SysUtils, SDL2, Math, ctypes,
48 e_log, e_input, e_sound,
49 {$IFDEF ENABLE_HOLMES}
50 g_holmes, sdlcarcass, fui_ctls,
51 {$ENDIF}
52 g_touch, g_options, g_console, g_game, g_menu, g_gui, g_basic;
54 const
55 GameTitle = 'Doom 2D: Forever (SDL 2, %s)';
57 var
58 window: PSDL_Window;
59 context: TSDL_GLContext;
60 display, wx, wy: Integer;
61 wc: Boolean;
62 JoystickHandle: array [0..e_MaxJoys - 1] of PSDL_Joystick;
63 JoystickHatState: array [0..e_MaxJoys - 1, 0..e_MaxJoyHats - 1, HAT_LEFT..HAT_DOWN] of Boolean;
64 JoystickZeroAxes: array [0..e_MaxJoys - 1, 0..e_MaxJoyAxes - 1] of Integer;
66 (* --------- Utils --------- *)
68 function sys_GetTicks (): Int64;
69 begin
70 result := SDL_GetTicks()
71 end;
73 procedure sys_Delay (ms: Integer);
74 begin
75 SDL_Delay(ms)
76 end;
78 (* --------- Graphics --------- *)
80 function GetTitle (): AnsiString;
81 var info: AnsiString;
82 begin
83 info := g_GetBuildHash(false);
84 if info = 'custom build' then
85 info := info + ' by ' + g_GetBuilderName() + ' ' + GAME_BUILDDATE + ' ' + GAME_BUILDTIME;
86 result := Format(GameTitle, [info]);
87 end;
89 function InitWindow (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
90 var flags: UInt32; x, y: cint; title: AnsiString;
91 begin
92 // note: on window close make: if assigned(oglDeinitCB) then oglDeinitCB;
93 e_LogWritefln('InitWindow %s %s %s %s', [w, h, bpp, fullScreen]);
94 result := false;
95 if window = nil then
96 begin
97 {$IFDEF USE_GLES1}
98 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
99 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
100 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
101 {$ELSE}
102 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
103 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
104 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
105 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
106 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
107 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
108 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
109 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
110 {$ENDIF}
111 flags := SDL_WINDOW_OPENGL or SDL_WINDOW_RESIZABLE;
112 if fullScreen then flags := flags or SDL_WINDOW_FULLSCREEN;
113 if maximized then flags := flags or SDL_WINDOW_MAXIMIZED;
114 if wc then
115 begin
116 x := SDL_WINDOWPOS_CENTERED;
117 y := SDL_WINDOWPOS_CENTERED
118 end
119 else
120 begin
121 x := wx;
122 y := wy
123 end;
124 title := GetTitle();
125 window := SDL_CreateWindow(PChar(title), x, y, w, h, flags);
126 if window <> nil then
127 begin
128 context := SDL_GL_CreateContext(window);
129 if context <> nil then
130 begin
131 if (fullscreen = false) and (maximized = false) and (wc = false) then
132 begin
133 SDL_GetWindowPosition(window, @x, @y);
134 wx := x; wy := y
135 end;
136 gFullScreen := fullscreen;
137 gWinMaximized := maximized;
138 gRC_FullScreen := fullscreen;
139 gRC_Maximized := maximized;
140 if @sys_ScreenResize <> nil then
141 sys_ScreenResize(w, h);
142 result := true
143 end
144 else
145 begin
146 // SDL_DestroyWindow(window);
147 e_LogWritefln('SDL: unable to create OpenGL context: %s', [SDL_GetError])
148 end
149 end
150 else
151 begin
152 e_LogWritefln('SDL: unable to create window: %s', [SDL_GetError])
153 end
154 end
155 else
156 begin
157 if fullScreen then flags := SDL_WINDOW_FULLSCREEN else flags := 0;
158 SDL_SetWindowFullscreen(window, flags);
159 SDL_SetWindowSize(window, w, h);
160 if maximized then SDL_MaximizeWindow(window);
161 // always reset to center when changing fullscreen->windowed for safety purposes
162 if wc or (gFullscreen and not fullscreen) or (gWinMaximized and not maximized) then
163 begin
164 x := SDL_WINDOWPOS_CENTERED;
165 y := SDL_WINDOWPOS_CENTERED
166 end
167 else
168 begin
169 x := wx;
170 y := wy
171 end;
172 SDL_SetWindowPosition(window, x, y);
173 if (fullscreen = false) and (maximized = false) and (wc = false) then
174 begin
175 SDL_GetWindowPosition(window, @x, @y);
176 wx := x; wy := y
177 end;
178 gFullScreen := fullscreen;
179 gWinMaximized := maximized;
180 gRC_FullScreen := fullscreen;
181 gRC_Maximized := maximized;
182 if @sys_ScreenResize <> nil then
183 sys_ScreenResize(w, h);
184 result := true
185 end
186 end;
188 procedure sys_Repaint;
189 begin
190 SDL_GL_SwapWindow(window)
191 end;
193 procedure sys_EnableVSync (yes: Boolean);
194 begin
195 if yes then
196 SDL_GL_SetSwapInterval(1)
197 else
198 SDL_GL_SetSwapInterval(0)
199 end;
201 function sys_GetDisplayModes (bpp: Integer): SSArray;
202 var i, count, num, pw, ph: Integer; m: TSDL_DisplayMode;
203 begin
204 result := nil;
205 num := SDL_GetNumDisplayModes(display);
206 if num < 0 then
207 e_LogWritefln('SDL: unable to get numer of available display modes: %s', [SDL_GetError]);
208 if num > 0 then
209 begin
210 e_LogWritefln('Video modes for display %s:', [display]);
211 SetLength(result, num);
212 i := 0; count := 0; pw := 0; ph := 0;
213 while i < num do
214 begin
215 SDL_GetDisplayMode(display, i, @m);
216 if ((pw <> m.w) or (ph <> m.h)) then
217 begin
218 e_LogWritefln('* %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
219 pw := m.w; ph := m.h;
220 result[count] := IntToStr(m.w) + 'x' + IntToStr(m.h);
221 Inc(count);
222 end
223 else
224 begin
225 e_LogWritefln('- %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
226 end;
227 Inc(i)
228 end;
229 SetLength(result, count)
230 end
231 end;
233 function sys_SetDisplayMode (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
234 begin
235 result := InitWindow(w, h, bpp, fullScreen, maximized)
236 end;
238 (* --------- Joystick --------- *)
240 procedure HandleJoyButton (var ev: TSDL_JoyButtonEvent);
241 var down: Boolean; key: Integer;
242 begin
243 if (ev.which < e_MaxJoys) and (ev.button < e_MaxJoyBtns) then
244 begin
245 key := e_JoyButtonToKey(ev.which, ev.button);
246 down := ev.type_ = SDL_JOYBUTTONDOWN;
247 if g_dbg_input then
248 e_LogWritefln('Input Debug: jbutton, joy=%s, button=%s, keycode=%s, press=%s', [ev.which, ev.button, key, down]);
249 e_KeyUpDown(key, down);
250 g_Console_ProcessBind(key, down)
251 end
252 else
253 begin
254 if g_dbg_input then
255 begin
256 down := ev.type_ = SDL_JOYBUTTONDOWN;
257 e_LogWritefln('Input Debug: NOT IN RANGE! jbutton, joy=%s, button=%s, press=%s', [ev.which, ev.button, down])
258 end
259 end
260 end;
262 procedure HandleJoyAxis (var ev: TSDL_JoyAxisEvent);
263 var key, minuskey: Integer;
264 begin
265 if (ev.which < e_MaxJoys) and (ev.axis < e_MaxJoyAxes) then
266 begin
267 key := e_JoyAxisToKey(ev.which, ev.axis, AX_PLUS);
268 minuskey := e_JoyAxisToKey(ev.which, ev.axis, AX_MINUS);
270 if g_dbg_input then
271 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]]);
273 if ev.value < JoystickZeroAxes[ev.which, ev.axis] - e_JoystickDeadzones[ev.which] then
274 begin
275 if (e_KeyPressed(key)) then
276 begin
277 e_KeyUpDown(key, False);
278 g_Console_ProcessBind(key, False)
279 end;
280 e_KeyUpDown(minuskey, True);
281 g_Console_ProcessBind(minuskey, True)
282 end
283 else if ev.value > JoystickZeroAxes[ev.which, ev.axis] + e_JoystickDeadzones[ev.which] then
284 begin
285 if (e_KeyPressed(minuskey)) then
286 begin
287 e_KeyUpDown(minuskey, False);
288 g_Console_ProcessBind(minuskey, False)
289 end;
290 e_KeyUpDown(key, True);
291 g_Console_ProcessBind(key, True)
292 end
293 else
294 begin
295 if (e_KeyPressed(minuskey)) then
296 begin
297 e_KeyUpDown(minuskey, False);
298 g_Console_ProcessBind(minuskey, False)
299 end;
300 if (e_KeyPressed(key)) then
301 begin
302 e_KeyUpDown(key, False);
303 g_Console_ProcessBind(key, False)
304 end
305 end
306 end
307 else
308 begin
309 if g_dbg_input then
310 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]])
311 end
312 end;
314 procedure HandleJoyHat (var ev: TSDL_JoyHatEvent);
315 var
316 down: Boolean;
317 i, key: Integer;
318 hat: array [HAT_LEFT..HAT_DOWN] of Boolean;
319 begin
320 if (ev.which < e_MaxJoys) and (ev.hat < e_MaxJoyHats) then
321 begin
322 if g_dbg_input then
323 e_LogWritefln('Input Debug: jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value]);
324 hat[HAT_UP] := LongBool(ev.value and SDL_HAT_UP);
325 hat[HAT_DOWN] := LongBool(ev.value and SDL_HAT_DOWN);
326 hat[HAT_LEFT] := LongBool(ev.value and SDL_HAT_LEFT);
327 hat[HAT_RIGHT] := LongBool(ev.value and SDL_HAT_RIGHT);
328 for i := HAT_LEFT to HAT_DOWN do
329 begin
330 if JoystickHatState[ev.which, ev.hat, i] <> hat[i] then
331 begin
332 down := hat[i];
333 key := e_JoyHatToKey(ev.which, ev.hat, i);
334 e_KeyUpDown(key, down);
335 g_Console_ProcessBind(key, down)
336 end
337 end;
338 JoystickHatState[ev.which, ev.hat] := hat
339 end
340 else
341 begin
342 if g_dbg_input then
343 e_LogWritefln('Input Debug: NOT IN RANGE! jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value])
344 end
345 end;
347 procedure HandleJoyAdd (var ev: TSDL_JoyDeviceEvent);
348 var i: Integer;
349 begin
350 if (ev.which < e_MaxJoys) then
351 begin
352 JoystickHandle[ev.which] := SDL_JoystickOpen(ev.which);
353 if JoystickHandle[ev.which] <> nil then
354 begin
355 e_LogWritefln('Added Joystick %s', [ev.which]);
356 e_JoystickAvailable[ev.which] := True;
357 for i := 0 to Min(SDL_JoystickNumAxes(JoystickHandle[ev.which]), e_MaxJoyAxes) - 1 do
358 JoystickZeroAxes[ev.which, i] := SDL_JoystickGetAxis(JoystickHandle[ev.which], i)
359 end
360 else
361 begin
362 e_LogWritefln('Warning! Failed to open Joystick %s', [ev.which])
363 end
364 end
365 else
366 begin
367 e_LogWritefln('Warning! Added Joystick %s, but we support only <= %s', [ev.which, e_MaxJoys])
368 end
369 end;
371 procedure HandleJoyRemove (var ev: TSDL_JoyDeviceEvent);
372 begin
373 e_LogWritefln('Removed Joystick %s', [ev.which]);
374 if (ev.which < e_MaxJoys) then
375 begin
376 e_JoystickAvailable[ev.which] := False;
377 if JoystickHandle[ev.which] <> nil then
378 SDL_JoystickClose(JoystickHandle[ev.which]);
379 JoystickHandle[ev.which] := nil
380 end
381 end;
383 (* --------- Input --------- *)
385 function HandleWindow (var ev: TSDL_WindowEvent): Boolean;
386 begin
387 result := false;
388 if g_dbg_input then
389 e_LogWritefln('Window Event: event = %s, data1 = %s, data2 = %s', [ev.event, ev.data1, ev.data2]);
390 case ev.event of
391 SDL_WINDOWEVENT_RESIZED:
392 if @sys_ScreenResize <> nil then
393 sys_ScreenResize(ev.data1, ev.data2);
394 SDL_WINDOWEVENT_EXPOSED: sys_Repaint;
395 SDL_WINDOWEVENT_CLOSE: result := true;
396 SDL_WINDOWEVENT_MOVED:
397 begin
398 wx := ev.data1;
399 wy := ev.data2
400 end;
401 SDL_WINDOWEVENT_FOCUS_LOST, SDL_WINDOWEVENT_MINIMIZED:
402 begin
403 e_UnpressAllKeys;
404 if gMuteWhenInactive then
405 e_MuteChannels(true);
406 {$IFDEF ENABLE_HOLMES}
407 if assigned(winBlurCB) then winBlurCB;
408 {$ENDIF}
409 end;
410 SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_MAXIMIZED, SDL_WINDOWEVENT_RESTORED:
411 begin
412 if ev.event = SDL_WINDOWEVENT_MAXIMIZED then
413 begin
414 gWinMaximized := true;
415 gRC_Maximized := true
416 end
417 else if ev.event = SDL_WINDOWEVENT_RESTORED then
418 begin
419 gWinMaximized := false;
420 gRC_Maximized := false
421 end;
422 e_MuteChannels(false);
423 {$IFDEF ENABLE_HOLMES}
424 if assigned(winFocusCB) then winFocusCB;
425 {$ENDIF}
426 end;
427 end
428 end;
430 procedure HandleKeyboard (var ev: TSDL_KeyboardEvent);
431 var down: Boolean; key: Integer;
432 begin
433 key := ev.keysym.scancode;
434 down := (ev.type_ = SDL_KEYDOWN);
435 if key = SDL_SCANCODE_AC_BACK then
436 key := SDL_SCANCODE_ESCAPE;
437 {$IFDEF ENABLE_HOLMES}
438 if fuiOnSDLEvent(PSDL_Event(@ev)^) then
439 begin
440 // event eaten, but...
441 if not down then e_KeyUpDown(key, false);
442 exit;
443 end;
444 {$ENDIF}
445 if ev._repeat = 0 then
446 begin
447 if g_dbg_input then
448 e_LogWritefln('Input Debug: keysym, press=%s, scancode=%s', [down, key]);
449 e_KeyUpDown(key, down);
450 g_Console_ProcessBind(key, down);
451 end
452 else
453 begin
454 if g_dbg_input then
455 e_LogWritefln('Input Debug: keyrep, scancode=%s', [key]);
456 g_Console_ProcessBindRepeat(key);
457 end
458 end;
460 procedure HandleTextInput (var ev: TSDL_TextInputEvent);
461 var ch: UnicodeChar; sch: AnsiChar;
462 begin
463 Utf8ToUnicode(@ch, PChar(ev.text), 1);
464 sch := AnsiChar(wchar2win(ch));
465 if g_dbg_input then
466 e_LogWritefln('Input Debug: text, text="%s", ch = %s, sch = %s', [ev.text, Ord(ch), Ord(sch)]);
467 if @sys_CharPress <> nil then
468 if IsValid1251(Word(ch)) and IsPrintable1251(ch) then
469 sys_CharPress(sch)
470 end;
472 function sys_HandleInput (): Boolean;
473 var ev: TSDL_Event;
474 begin
475 result := false;
476 ZeroMemory(@ev, sizeof(ev));
477 while SDL_PollEvent(@ev) <> 0 do
478 begin
479 case ev.type_ of
480 SDL_QUITEV: result := true;
481 SDL_WINDOWEVENT: result := HandleWindow(ev.window);
482 SDL_KEYUP, SDL_KEYDOWN: HandleKeyboard(ev.key);
483 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP: HandleJoyButton(ev.jbutton);
484 SDL_JOYAXISMOTION: HandleJoyAxis(ev.jaxis);
485 SDL_JOYHATMOTION: HandleJoyHat(ev.jhat);
486 SDL_JOYDEVICEADDED: HandleJoyAdd(ev.jdevice);
487 SDL_JOYDEVICEREMOVED: HandleJoyRemove(ev.jdevice);
488 SDL_TEXTINPUT: HandleTextInput(ev.text);
489 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP: g_Touch_HandleEvent(ev.tfinger);
490 {$IFDEF ENABLE_HOLMES}
491 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION: fuiOnSDLEvent(ev);
492 {$ENDIF}
493 end
494 end
495 end;
497 procedure sys_RequestQuit;
498 var ev: TSDL_Event;
499 begin
500 ev.type_ := SDL_QUITEV;
501 SDL_PushEvent(@ev)
502 end;
504 (* --------- Init --------- *)
506 procedure sys_Init;
507 var flags: UInt32;
508 begin
509 e_WriteLog('Init SDL2', TMsgType.Notify);
510 {$IFDEF HEADLESS}
511 {$IFDEF USE_SDLMIXER}
512 flags := SDL_INIT_TIMER or SDL_INIT_AUDIO or $00004000;
513 {$ELSE}
514 flags := SDL_INIT_TIMER or $00004000;
515 {$ENDIF}
516 {$ELSE}
517 flags := SDL_INIT_TIMER or SDL_INIT_VIDEO;
518 {$ENDIF}
519 SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, '0');
520 if SDL_Init(flags) <> 0 then
521 raise Exception.Create('SDL: Init failed: ' + SDL_GetError);
522 {$IFNDEF HEADLESS}
523 if SDL_InitSubSystem(SDL_INIT_JOYSTICK) <> 0 then
524 e_LogWritefln('SDL: Init subsystem failed: %s', [SDL_GetError()]);
525 {$ENDIF}
526 SDL_ShowCursor(SDL_DISABLE);
527 end;
529 procedure sys_Final;
530 begin
531 e_WriteLog('Releasing SDL2', TMsgType.Notify);
532 if context <> nil then
533 begin
534 SDL_GL_DeleteContext(context);
535 context := nil;
536 end;
537 if window <> nil then
538 begin
539 SDL_DestroyWindow(window);
540 window := nil;
541 end;
542 SDL_Quit
543 end;
545 initialization
546 conRegVar('sdl2_display_index', @display, 'use display index as base', '');
547 conRegVar('sdl2_window_x', @wx, 'window position x', '');
548 conRegVar('sdl2_window_y', @wy, 'window position y', '');
549 conRegVar('sdl2_window_center', @wc, 'force window creation at center', '');
550 display := 0;
551 wx := SDL_WINDOWPOS_CENTERED;
552 wy := SDL_WINDOWPOS_CENTERED;
553 wc := false
554 end.