DEADSOFTWARE

added debug output for input
[d2df-sdl.git] / src / game / g_window.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, either version 3 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *)
16 {$INCLUDE ../shared/a_modes.inc}
17 unit g_window;
19 interface
21 uses
22 utils;
24 function SDLMain (): Integer;
25 function GetTimer (): Int64;
26 procedure ResetTimer ();
27 procedure PushExitEvent ();
28 function ProcessMessage (): Boolean;
29 procedure ReDrawWindow ();
30 procedure SwapBuffers ();
31 procedure Sleep (ms: LongWord);
32 function GetDisplayModes (dbpp: LongWord; var selres: LongWord): SSArray;
33 function g_Window_SetDisplay (preserveGL: Boolean=false): Boolean;
34 function g_Window_SetSize (w, h: Word; fullscreen: Boolean): Boolean;
35 procedure g_SetVSync (vsync: Boolean);
37 procedure ProcessLoading (forceUpdate: Boolean=false);
39 // returns `true` if quit event was received
40 function g_ProcessMessages (): Boolean;
43 var
44 gwin_dump_extensions: Boolean = false;
45 gwin_has_stencil: Boolean = false;
46 gwin_k8_enable_light_experiments: Boolean = false;
47 g_dbg_aimline_on: Boolean = false;
48 g_dbg_input: Boolean = False;
51 implementation
53 uses
54 {$IFDEF WINDOWS}Windows,{$ENDIF}
55 {$INCLUDE ../nogl/noGLuses.inc}
56 {$IFDEF ENABLE_HOLMES}
57 g_holmes, sdlcarcass, fui_ctls,
58 {$ENDIF}
59 SysUtils, Classes, MAPDEF, Math,
60 SDL2, e_graphics, e_log, e_texture, g_main,
61 g_console, e_input, g_options, g_game,
62 g_basic, g_textures, e_sound, g_sound, g_menu, ENet, g_net,
63 g_map, g_gfx, g_monsters, xprofiler,
64 g_touch;
67 const
68 ProgressUpdateMSecs = 1;//100;
70 var
71 h_Wnd: PSDL_Window = nil;
72 h_GL: TSDL_GLContext = nil;
73 Time, Time_Delta, Time_Old: Int64;
74 flag: Boolean;
75 {$IF not DEFINED(HEADLESS)}
76 wTitle: PChar = nil;
77 wasFullscreen: Boolean = true; // so we need to recreate the window
78 {$ENDIF}
79 wNeedTimeReset: Boolean = false;
80 wMinimized: Boolean = false;
81 wMaximized: Boolean = false;
82 wLoadingProgress: Boolean = false;
83 wLoadingQuit: Boolean = false;
84 {$IFNDEF WINDOWS}
85 ticksOverflow: Int64 = -1;
86 lastTicks: Uint32 = 0; // to detect overflow
87 {$ENDIF}
88 JoystickHatState: array [0..e_MaxJoys, 0..e_MaxJoyHats, HAT_LEFT..HAT_DOWN] of Boolean;
89 JoystickZeroAxes: array [0..e_MaxJoys, 0..e_MaxJoyAxes] of Integer;
91 procedure KillGLWindow (preserveGL: Boolean);
92 begin
93 {$IFDEF ENABLE_HOLMES}
94 if (h_GL <> nil) and (not preserveGL) then begin if (assigned(oglDeinitCB)) then oglDeinitCB(); end;
95 {$ENDIF}
96 if (h_Wnd <> nil) then SDL_DestroyWindow(h_Wnd);
97 if (h_GL <> nil) and (not preserveGL) then
98 begin
100 {$IFDEF USE_NANOGL}
101 nanoGL_Destroy;
102 {$ENDIF}
104 {$IFDEF USE_NOGL}
105 nogl_Quit;
106 {$ENDIF}
108 SDL_GL_DeleteContext(h_GL);
109 end;
110 h_Wnd := nil;
111 if (not preserveGL) then h_GL := nil;
112 end;
115 function g_Window_SetDisplay (preserveGL: Boolean = false): Boolean;
116 {$IF not DEFINED(HEADLESS)}
117 var
118 mode, cmode: TSDL_DisplayMode;
119 wFlags: LongWord = 0;
120 nw, nh: Integer;
121 {$ENDIF}
122 begin
123 {$IF not DEFINED(HEADLESS)}
124 result := false;
126 e_WriteLog('Setting display mode...', TMsgType.Notify);
128 wFlags := SDL_WINDOW_OPENGL {or SDL_WINDOW_RESIZABLE};
129 if gFullscreen then wFlags := wFlags {or SDL_WINDOW_FULLSCREEN} else wFlags := wFlags or SDL_WINDOW_RESIZABLE;
130 if (not gFullscreen) and (not preserveGL) and gWinMaximized then wFlags := wFlags or SDL_WINDOW_MAXIMIZED else gWinMaximized := false;
132 if gFullscreen then
133 begin
134 mode.w := gScreenWidth;
135 mode.h := gScreenHeight;
136 mode.format := 0;
137 mode.refresh_rate := 0;
138 mode.driverdata := nil;
139 if (SDL_GetClosestDisplayMode(0, @mode, @cmode) = nil) then
140 begin
141 e_WriteLog('SDL: cannot find display mode for '+IntToStr(gScreenWidth), TMsgType.Notify);
142 gScreenWidth := 800;
143 gScreenHeight := 600;
144 end
145 else
146 begin
147 e_WriteLog('SDL: found display mode for '+IntToStr(gScreenWidth)+'x'+IntToStr(gScreenHeight)+': '+IntToStr(cmode.w)+'x'+IntToStr(cmode.h), TMsgType.Notify);
148 gScreenWidth := cmode.w;
149 gScreenHeight := cmode.h;
150 end;
151 end;
153 if (preserveGL) and (h_Wnd <> nil) and (not gFullscreen) and (not wasFullscreen) then
154 begin
155 //SDL_SetWindowMaximumSize(h_Wnd, gScreenWidth, gScreenHeight);
156 //SDL_SetWindowDisplayMode(h_Wnd, @cmode);
157 if (wMaximized) then SDL_RestoreWindow(h_Wnd);
158 wMaximized := false;
159 gWinMaximized := false;
160 SDL_SetWindowSize(h_Wnd, gScreenWidth, gScreenHeight);
161 //SDL_SetWindowFullscreen(h_Wnd, SDL_WINDOW_FULLSCREEN);
162 //SDL_SetWindowFullscreen(h_Wnd, 0);
163 end
164 else
165 begin
166 KillGLWindow(preserveGL);
167 h_Wnd := SDL_CreateWindow(PChar(wTitle), gWinRealPosX, gWinRealPosY, gScreenWidth, gScreenHeight, wFlags);
168 if gFullscreen then
169 SDL_SetWindowFullscreen(h_Wnd, SDL_WINDOW_FULLSCREEN);
170 if (h_Wnd = nil) then exit;
171 end;
172 wasFullscreen := gFullscreen;
174 SDL_GL_MakeCurrent(h_Wnd, h_GL);
175 SDL_ShowCursor(SDL_DISABLE);
176 if (h_GL <> nil) then g_SetVSync(gVSync);
177 if (gFullscreen) then
178 begin
179 nw := 0;
180 nh := 0;
181 SDL_GetWindowSize(h_Wnd, @nw, @nh);
182 if (nw > 128) and (nh > 128) then
183 begin
184 e_WriteLog('SDL: fullscreen window got size '+IntToStr(nw)+'x'+IntToStr(nh)+': '+IntToStr(gScreenWidth)+'x'+IntToStr(gScreenHeight), TMsgType.Notify);
185 gScreenWidth := nw;
186 gScreenHeight := nh;
187 end
188 else
189 begin
190 e_WriteLog('SDL: fullscreen window got invalid size: '+IntToStr(nw)+'x'+IntToStr(nh), TMsgType.Notify);
191 end;
192 end;
194 {$IFDEF ENABLE_HOLMES}
195 fuiScrWdt := gScreenWidth;
196 fuiScrHgt := gScreenHeight;
197 if (h_GL <> nil) and (not preserveGL) then begin if (assigned(oglInitCB)) then oglInitCB(); end;
198 {$ENDIF}
199 {$ENDIF}
201 result := true;
202 end;
205 function GetDisplayModes (dbpp: LongWord; var selres: LongWord): SSArray;
206 var
207 mode: TSDL_DisplayMode;
208 res, i, k, n, pw, ph: Integer;
209 begin
210 SetLength(result, 0);
211 {$IFDEF HEADLESS}exit;{$ENDIF}
212 k := 0; selres := 0;
213 n := SDL_GetNumDisplayModes(0);
214 pw := 0; ph := 0;
215 for i := 0 to n do
216 begin
217 res := SDL_GetDisplayMode(0, i, @mode);
218 if res < 0 then continue;
219 if SDL_BITSPERPIXEL(mode.format) = gBPP then continue;
220 if (mode.w = pw) and (mode.h = ph) then continue;
221 if (mode.w = gScreenWidth) and (mode.h = gScreenHeight) then
222 selres := k;
223 Inc(k);
224 SetLength(result, k);
225 result[k-1] := IntToStr(mode.w) + 'x' + IntToStr(mode.h);
226 pw := mode.w; ph := mode.h
227 end;
229 e_WriteLog('SDL: Got ' + IntToStr(k) + ' resolutions.', TMsgType.Notify);
230 end;
233 procedure Sleep (ms: LongWord);
234 begin
235 SDL_Delay(ms);
236 end;
239 procedure ChangeWindowSize (requested: Boolean);
240 begin
241 e_LogWritefln(' ChangeWindowSize: (ws=%dx%d) (ss=%dx%d)', [gWinSizeX, gWinSizeY, gScreenWidth, gScreenHeight]);
242 gWinSizeX := gScreenWidth;
243 gWinSizeY := gScreenHeight;
244 {$IF not DEFINED(HEADLESS)}
245 {$IFDEF ENABLE_HOLMES}
246 fuiScrWdt := gScreenWidth;
247 fuiScrHgt := gScreenHeight;
248 {$ENDIF}
249 e_ResizeWindow(gScreenWidth, gScreenHeight);
250 g_Game_SetupScreenSize();
251 {$IF DEFINED(ANDROID)}
252 (* This will fix menu reset on keyboard showing *)
253 if requested then
254 g_Menu_Reset;
255 {$ELSE}
256 g_Menu_Reset;
257 {$ENDIF}
258 g_Game_ClearLoading();
259 {$ENDIF}
260 end;
263 function g_Window_SetSize (w, h: Word; fullscreen: Boolean): Boolean;
264 {$IF not DEFINED(HEADLESS)}
265 var
266 preserve: Boolean;
267 {$ENDIF}
268 begin
269 result := false;
270 {$IF not DEFINED(HEADLESS)}
271 preserve := false;
273 if (gScreenWidth <> w) or (gScreenHeight <> h) then
274 begin
275 result := true;
276 preserve := true;
277 gScreenWidth := w;
278 gScreenHeight := h;
279 end;
281 if (gFullscreen <> fullscreen) then
282 begin
283 result := true;
284 preserve := true;
285 gFullscreen := fullscreen;
286 preserve := true;
287 end;
289 if result then
290 begin
291 g_Window_SetDisplay(preserve);
292 ChangeWindowSize(true);
293 end;
294 {$ENDIF}
295 end;
298 function WindowEventHandler (constref ev: TSDL_WindowEvent): Boolean;
299 var
300 wActivate, wDeactivate: Boolean;
301 begin
302 result := false;
303 wActivate := false;
304 wDeactivate := false;
306 case ev.event of
307 SDL_WINDOWEVENT_MOVED:
308 begin
309 if not (gFullscreen or gWinMaximized) then
310 begin
311 gWinRealPosX := ev.data1;
312 gWinRealPosY := ev.data2;
313 end;
314 end;
316 SDL_WINDOWEVENT_MINIMIZED:
317 begin
318 e_UnpressAllKeys();
319 if not wMinimized then
320 begin
321 e_ResizeWindow(0, 0);
322 wMinimized := true;
323 if g_debug_WinMsgs then
324 begin
325 g_Console_Add('Now minimized');
326 e_WriteLog('[DEBUG] WinMsgs: Now minimized', TMsgType.Notify);
327 end;
328 wDeactivate := true;
329 end;
330 end;
332 SDL_WINDOWEVENT_RESIZED:
333 begin
334 e_LogWritefln('Resize: (os=%dx%d) (ns=%dx%d)', [gScreenWidth, gScreenHeight, Integer(ev.data1), Integer(ev.data2)]);
335 {if (gFullscreen) then
336 begin
337 e_LogWriteln(' fullscreen fix applied.');
338 if (gScreenWidth <> ev.data1) or (gScreenHeight <> ev.data2) then
339 begin
340 SDL_SetWindowSize(h_Wnd, gScreenWidth, gScreenHeight);
341 end;
342 end
343 else}
344 begin
345 gScreenWidth := ev.data1;
346 gScreenHeight := ev.data2;
347 end;
348 ChangeWindowSize(false);
349 SwapBuffers();
350 if g_debug_WinMsgs then
351 begin
352 g_Console_Add('Resized to ' + IntToStr(ev.data1) + 'x' + IntToStr(ev.data2));
353 e_WriteLog('[DEBUG] WinMsgs: Resized to ' + IntToStr(ev.data1) + 'x' + IntToStr(ev.data2), TMsgType.Notify);
354 end;
355 end;
357 SDL_WINDOWEVENT_EXPOSED:
358 SwapBuffers();
360 SDL_WINDOWEVENT_MAXIMIZED:
361 begin
362 wMaximized := true;
363 if wMinimized then
364 begin
365 e_ResizeWindow(gScreenWidth, gScreenHeight);
366 wMinimized := false;
367 wActivate := true;
368 end;
369 if (not gWinMaximized) and (not gFullscreen) then
370 begin
371 gWinMaximized := true;
372 if g_debug_WinMsgs then
373 begin
374 g_Console_Add('Now maximized');
375 e_WriteLog('[DEBUG] WinMsgs: Now maximized', TMsgType.Notify);
376 end;
377 end;
378 end;
380 SDL_WINDOWEVENT_RESTORED:
381 begin
382 wMaximized := false;
383 if wMinimized then
384 begin
385 e_ResizeWindow(gScreenWidth, gScreenHeight);
386 wMinimized := false;
387 wActivate := true;
388 end;
389 gWinMaximized := false;
390 if g_debug_WinMsgs then
391 begin
392 g_Console_Add('Now restored');
393 e_WriteLog('[DEBUG] WinMsgs: Now restored', TMsgType.Notify);
394 end;
395 end;
397 SDL_WINDOWEVENT_FOCUS_GAINED:
398 begin
399 wActivate := true;
400 //e_WriteLog('window gained focus!', MSG_NOTIFY);
401 end;
403 SDL_WINDOWEVENT_FOCUS_LOST:
404 begin
405 wDeactivate := true;
406 e_UnpressAllKeys();
407 //e_WriteLog('window lost focus!', MSG_NOTIFY);
408 end;
409 end;
411 if wDeactivate then
412 begin
413 if gWinActive then
414 begin
415 e_WriteLog('deactivating window', TMsgType.Notify);
416 e_UnpressAllKeys;
418 if gMuteWhenInactive then
419 begin
420 //e_WriteLog('deactivating sounds', MSG_NOTIFY);
421 e_MuteChannels(true);
422 end;
424 if g_debug_WinMsgs then
425 begin
426 g_Console_Add('Now inactive');
427 e_WriteLog('[DEBUG] WinMsgs: Now inactive', TMsgType.Notify);
428 end;
430 gWinActive := false;
432 {$IFDEF ENABLE_HOLMES}
433 if assigned(winBlurCB) then winBlurCB();
434 {$ENDIF}
435 end;
436 end
437 else if wActivate then
438 begin
439 if not gWinActive then
440 begin
441 //e_WriteLog('activating window', MSG_NOTIFY);
443 if gMuteWhenInactive then
444 begin
445 //e_WriteLog('activating sounds', MSG_NOTIFY);
446 e_MuteChannels(false);
447 end;
449 if g_debug_WinMsgs then
450 begin
451 g_Console_Add('Now active');
452 e_WriteLog('[DEBUG] WinMsgs: Now active', TMsgType.Notify);
453 end;
455 gWinActive := true;
457 {$IFDEF ENABLE_HOLMES}
458 if assigned(winFocusCB) then winFocusCB();
459 {$ENDIF}
460 end;
461 end;
462 end;
465 function EventHandler (var ev: TSDL_Event): Boolean;
466 var
467 key, keychr, minuskey: Word;
468 uc: UnicodeChar;
469 down: Boolean;
470 i: Integer;
471 hat: array [HAT_LEFT..HAT_DOWN] of Boolean;
472 joy: PSDL_Joystick;
473 begin
474 result := false;
476 case ev.type_ of
477 SDL_WINDOWEVENT:
478 result := WindowEventHandler(ev.window);
480 SDL_QUITEV:
481 begin
482 if (gExit <> EXIT_QUIT) then
483 begin
484 if not wLoadingProgress then
485 begin
486 g_Game_Free();
487 g_Game_Quit();
488 end
489 else
490 begin
491 wLoadingQuit := true;
492 end;
493 end;
494 result := true;
495 end;
497 SDL_KEYDOWN, SDL_KEYUP:
498 begin
499 key := ev.key.keysym.scancode;
500 if key = SDL_SCANCODE_AC_BACK then
501 key := SDL_SCANCODE_ESCAPE;
502 down := (ev.type_ = SDL_KEYDOWN);
503 {$IF not DEFINED(HEADLESS) and DEFINED(ENABLE_HOLMES)}
504 if fuiOnSDLEvent(ev) then
505 begin
506 // event eaten, but...
507 if not down then e_KeyUpDown(key, false);
508 exit;
509 end;
510 {$ENDIF}
511 if ev.key._repeat = 0 then
512 begin
513 if g_dbg_input then
514 e_LogWritefln('Input Debug: keysym, press=%s, scancode=%s', [down, key]);
515 e_KeyUpDown(key, down);
516 g_Console_ProcessBind(key, down)
517 end;
518 if down then KeyPress(key);
519 end;
521 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP:
522 if (ev.jbutton.which < e_MaxJoys) and (ev.jbutton.button < e_MaxJoyBtns) then
523 begin
524 key := e_JoyButtonToKey(ev.jbutton.which, ev.jbutton.button);
525 down := ev.type_ = SDL_JOYBUTTONDOWN;
526 if g_dbg_input then
527 e_LogWritefln('Input Debug: jbutton, joy=%s, button=%s, keycode=%s, press=%s', [ev.jbutton.which, ev.jbutton.button, key, down]);
528 e_KeyUpDown(key, down);
529 g_Console_ProcessBind(key, down);
530 if down then KeyPress(key)
531 end
532 else
533 begin
534 if g_dbg_input then
535 begin
536 down := ev.type_ = SDL_JOYBUTTONDOWN;
537 e_LogWritefln('Input Debug: NOT IN RANGE! jbutton, joy=%s, button=%s, press=%s', [ev.jbutton.which, ev.jbutton.button, down])
538 end
539 end;
541 SDL_JOYAXISMOTION:
542 if (ev.jaxis.which < e_MaxJoys) and (ev.jaxis.axis < e_MaxJoyAxes) then
543 begin
544 key := e_JoyAxisToKey(ev.jaxis.which, ev.jaxis.axis, AX_PLUS);
545 minuskey := e_JoyAxisToKey(ev.jaxis.which, ev.jaxis.axis, AX_MINUS);
547 if g_dbg_input then
548 e_LogWritefln('Input Debug: jaxis, joy=%s, axis=%s, value=%s, zeroaxes=%s, deadzone=%s', [ev.jaxis.which, ev.jaxis.axis, ev.jaxis.value, JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis], e_JoystickDeadzones[ev.jaxis.which]]);
550 if ev.jaxis.value < JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis] - e_JoystickDeadzones[ev.jaxis.which] then
551 begin
552 if (e_KeyPressed(key)) then
553 begin
554 e_KeyUpDown(key, False);
555 g_Console_ProcessBind(key, False);
556 end;
557 e_KeyUpDown(minuskey, True);
558 g_Console_ProcessBind(minuskey, True);
559 KeyPress(minuskey);
560 end
561 else if ev.jaxis.value > JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis] + e_JoystickDeadzones[ev.jaxis.which] then
562 begin
563 if (e_KeyPressed(minuskey)) then
564 begin
565 e_KeyUpDown(minuskey, False);
566 g_Console_ProcessBind(minuskey, False);
567 end;
568 e_KeyUpDown(key, True);
569 g_Console_ProcessBind(key, True);
570 KeyPress(key);
571 end
572 else
573 begin
574 if (e_KeyPressed(minuskey)) then
575 begin
576 e_KeyUpDown(minuskey, False);
577 g_Console_ProcessBind(minuskey, False);
578 end;
579 if (e_KeyPressed(key)) then
580 begin
581 e_KeyUpDown(key, False);
582 g_Console_ProcessBind(key, False);
583 end;
584 end;
585 end
586 else
587 begin
588 if g_dbg_input then
589 e_LogWritefln('Input Debug: NOT IN RANGE! jaxis, joy=%s, axis=%s, value=%s, zeroaxes=%s, deadzone=%s', [ev.jaxis.which, ev.jaxis.axis, ev.jaxis.value, JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis], e_JoystickDeadzones[ev.jaxis.which]])
590 end;
592 SDL_JOYHATMOTION:
593 if (ev.jhat.which < e_MaxJoys) and (ev.jhat.hat < e_MaxJoyHats) then
594 begin
595 if g_dbg_input then
596 e_LogWritefln('Input Debug: jhat, joy=%s, hat=%s, value=%s', [ev.jhat.which, ev.jhat.hat, ev.jhat.value]);
597 hat[HAT_UP] := LongBool(ev.jhat.value and SDL_HAT_UP);
598 hat[HAT_DOWN] := LongBool(ev.jhat.value and SDL_HAT_DOWN);
599 hat[HAT_LEFT] := LongBool(ev.jhat.value and SDL_HAT_LEFT);
600 hat[HAT_RIGHT] := LongBool(ev.jhat.value and SDL_HAT_RIGHT);
601 for i := HAT_LEFT to HAT_DOWN do
602 begin
603 if JoystickHatState[ev.jhat.which, ev.jhat.hat, i] <> hat[i] then
604 begin
605 down := hat[i];
606 key := e_JoyHatToKey(ev.jhat.which, ev.jhat.hat, i);
607 e_KeyUpDown(key, down);
608 g_Console_ProcessBind(key, down);
609 if down then KeyPress(key)
610 end
611 end;
612 JoystickHatState[ev.jhat.which, ev.jhat.hat] := hat
613 end
614 else
615 begin
616 if g_dbg_input then
617 e_LogWritefln('Input Debug: NOT IN RANGE! jhat, joy=%s, hat=%s, value=%s', [ev.jhat.which, ev.jhat.hat, ev.jhat.value])
618 end;
620 SDL_JOYDEVICEADDED:
621 if (ev.jdevice.which < e_MaxJoys) then
622 begin
623 joy := SDL_JoystickOpen(ev.jdevice.which);
624 ASSERT(joy <> nil);
625 e_LogWritefln('Added Joystick %s', [ev.jdevice.which]);
626 e_JoystickAvailable[ev.jdevice.which] := True;
627 for i := 0 to Min(SDL_JoystickNumAxes(joy), e_MaxJoyAxes) do
628 JoystickZeroAxes[ev.jdevice.which, i] := SDL_JoystickGetAxis(joy, i);
629 SDL_JoystickClose(joy)
630 end
631 else
632 begin
633 e_LogWritefln('Warning! Added Joystick %s, but we support only <= %s', [ev.jdevice.which, e_MaxJoys])
634 end;
636 SDL_JOYDEVICEREMOVED:
637 begin
638 e_LogWritefln('Removed Joystick %s', [ev.jdevice.which]);
639 if (ev.jdevice.which < e_MaxJoys) then
640 e_JoystickAvailable[ev.jdevice.which] := False
641 end;
643 {$IF not DEFINED(HEADLESS) and DEFINED(ENABLE_HOLMES)}
644 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION:
645 fuiOnSDLEvent(ev);
646 {$ENDIF}
648 SDL_TEXTINPUT:
649 begin
650 if g_dbg_input then
651 e_LogWritefln('Input Debug: text, text=%s', [ev.text.text]);
652 Utf8ToUnicode(@uc, PChar(ev.text.text), 1);
653 keychr := Word(uc);
654 if (keychr > 127) then keychr := Word(wchar2win(WideChar(keychr)));
655 if (keychr > 0) and (keychr <= 255) then CharPress(AnsiChar(keychr));
656 end;
658 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP:
659 g_Touch_HandleEvent(ev.tfinger);
661 // other key presses and joysticks are handled in e_input
662 end;
663 end;
666 procedure SwapBuffers ();
667 begin
668 {$IF not DEFINED(HEADLESS)}
669 SDL_GL_SwapWindow(h_Wnd);
670 {$ENDIF}
671 end;
674 function CreateGLWindow (Title: PChar): Boolean;
675 begin
676 result := false;
678 gWinSizeX := gScreenWidth;
679 gWinSizeY := gScreenHeight;
681 {$IF not DEFINED(HEADLESS)}
682 wTitle := Title;
683 {$ENDIF}
684 e_WriteLog('Creating window', TMsgType.Notify);
686 if not g_Window_SetDisplay() then
687 begin
688 KillGLWindow(false);
689 e_WriteLog('Window creation error (resolution not supported?)', TMsgType.Fatal);
690 exit;
691 end;
693 {$IF not DEFINED(HEADLESS)}
694 h_GL := SDL_GL_CreateContext(h_Wnd);
695 if (h_GL = nil) then exit;
696 {$IFDEF ENABLE_HOLMES}
697 fuiScrWdt := gScreenWidth;
698 fuiScrHgt := gScreenHeight;
699 {$ENDIF}
700 SDL_GL_MakeCurrent(h_Wnd, h_GL);
701 {$IFDEF USE_NANOGL}
702 if nanoGL_Init() = 0 then
703 begin
704 KillGLWindow(false);
705 e_WriteLog('nanoGL initialization error', TMsgType.Fatal);
706 exit;
707 end;
708 {$ENDIF}
709 {$IFDEF USE_NOGL}
710 nogl_Init;
711 {$ENDIF}
712 {$IFDEF ENABLE_HOLMES}
713 if (assigned(oglInitCB)) then oglInitCB();
714 {$ENDIF}
715 if (h_GL <> nil) then g_SetVSync(gVSync);
716 {$ENDIF}
718 e_ResizeWindow(gScreenWidth, gScreenHeight);
719 e_InitGL();
721 result := true;
722 end;
725 {$IFDEF WINDOWS}
726 // windoze sux; in headless mode `GetTickCount()` (and SDL) returns shit
727 function GetTimer (): Int64;
728 var
729 F, C: Int64;
730 begin
731 QueryPerformanceFrequency(F);
732 QueryPerformanceCounter(C);
733 result := Round(C/F*1000{000});
734 end;
735 {$ELSE}
736 function GetTimer (): Int64;
737 var
738 t: Uint32;
739 tt: Int64;
740 begin
741 t := SDL_GetTicks();
742 if (ticksOverflow = -1) then
743 begin
744 ticksOverflow := 0;
745 lastTicks := t;
746 end
747 else
748 begin
749 if (lastTicks > t) then
750 begin
751 // overflow, increment overflow ;-)
752 ticksOverflow := ticksOverflow+(Int64($ffffffff)+Int64(1));
753 tt := (Int64($ffffffff)+Int64(1))+Int64(t);
754 t := Uint32(tt-lastTicks);
755 end;
756 end;
757 lastTicks := t;
758 result := ticksOverflow+Int64(t);
759 end;
760 {$ENDIF}
763 procedure ResetTimer ();
764 begin
765 wNeedTimeReset := true;
766 end;
769 procedure PushExitEvent ();
770 var
771 ev: TSDL_Event;
772 begin
773 ev.type_ := SDL_QUITEV;
774 SDL_PushEvent(@ev);
775 end;
778 var
779 prevLoadingUpdateTime: UInt64 = 0;
781 procedure ProcessLoading (forceUpdate: Boolean=false);
782 var
783 ev: TSDL_Event;
784 ID: LongWord;
785 stt: UInt64;
786 begin
787 FillChar(ev, sizeof(ev), 0);
788 wLoadingProgress := true;
790 while (SDL_PollEvent(@ev) > 0) do
791 begin
792 EventHandler(ev);
793 if (ev.type_ = SDL_QUITEV) then break;
794 end;
795 //e_PollJoysticks();
797 if (ev.type_ = SDL_QUITEV) or (gExit = EXIT_QUIT) then
798 begin
799 wLoadingProgress := false;
800 exit;
801 end;
803 if not wMinimized then
804 begin
805 if forceUpdate then
806 begin
807 prevLoadingUpdateTime := getTimeMilli();
808 end
809 else
810 begin
811 stt := getTimeMilli();
812 if (stt < prevLoadingUpdateTime) or (stt-prevLoadingUpdateTime >= ProgressUpdateMSecs) then
813 begin
814 prevLoadingUpdateTime := stt;
815 forceUpdate := true;
816 end;
817 end;
819 if forceUpdate then
820 begin
821 if g_Texture_Get('INTER', ID) then
822 begin
823 e_DrawSize(ID, 0, 0, 0, false, false, gScreenWidth, gScreenHeight);
824 e_DarkenQuadWH(0, 0, gScreenWidth, gScreenHeight, 150);
825 end
826 else
827 begin
828 e_Clear(GL_COLOR_BUFFER_BIT, 0, 0, 0);
829 end;
831 DrawLoadingStat();
832 SwapBuffers();
833 end;
834 end;
836 e_SoundUpdate();
838 if NetMode = NET_SERVER then
839 begin
840 g_Net_Host_Update();
841 end
842 else
843 begin
844 if (NetMode = NET_CLIENT) and (NetState <> NET_STATE_AUTH) then g_Net_Client_UpdateWhileLoading();
845 end;
847 wLoadingProgress := false;
848 end;
851 function g_ProcessMessages (): Boolean;
852 var
853 ev: TSDL_Event;
854 begin
855 result := false;
856 FillChar(ev, SizeOf(ev), 0);
857 while (SDL_PollEvent(@ev) > 0) do
858 begin
859 result := EventHandler(ev);
860 if (ev.type_ = SDL_QUITEV) then exit;
861 end;
862 //e_PollJoysticks();
863 end;
866 function ProcessMessage (): Boolean;
867 var
868 i, t: Integer;
869 begin
870 result := g_ProcessMessages();
872 Time := GetTimer();
873 Time_Delta := Time-Time_Old;
875 flag := false;
877 if wNeedTimeReset then
878 begin
879 Time_Delta := 28;
880 wNeedTimeReset := false;
881 end;
883 g_Map_ProfilersBegin();
884 g_Mons_ProfilersBegin();
886 t := Time_Delta div 28;
887 if (t > 0) then
888 begin
889 flag := true;
890 for i := 1 to t do
891 begin
892 if (NetMode = NET_SERVER) then g_Net_Host_Update()
893 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
894 Update();
895 end;
896 end
897 else
898 begin
899 if (NetMode = NET_SERVER) then g_Net_Host_Update()
900 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
901 end;
903 g_Map_ProfilersEnd();
904 g_Mons_ProfilersEnd();
906 if wLoadingQuit then
907 begin
908 g_Game_Free();
909 g_Game_Quit();
910 end;
912 if (gExit = EXIT_QUIT) then
913 begin
914 result := true;
915 exit;
916 end;
918 // Âðåìÿ ïðåäûäóùåãî îáíîâëåíèÿ
919 if flag then
920 begin
921 Time_Old := Time-(Time_Delta mod 28);
922 if (not wMinimized) then
923 begin
924 Draw();
925 SwapBuffers();
926 end;
927 end
928 else
929 begin
930 Sleep(1); // release time slice, so we won't eat 100% CPU
931 end;
933 e_SoundUpdate();
934 end;
937 procedure ReDrawWindow ();
938 begin
939 SwapBuffers();
940 end;
943 procedure g_SetVSync (vsync: Boolean);
944 {$IF not DEFINED(HEADLESS)}
945 var
946 v: Byte;
947 {$ENDIF}
948 begin
949 {$IF not DEFINED(HEADLESS)}
950 if vsync then v := 1 else v := 0;
951 if (SDL_GL_SetSwapInterval(v) <> 0) then
952 begin
953 e_WriteLog('oops; can''t change vsync option, restart required', TMsgType.Warning);
954 end
955 else
956 begin
957 if vsync then e_WriteLog('VSync: ON', TMsgType.Notify) else e_WriteLog('VSync: OFF', TMsgType.Notify);
958 end;
959 {$ENDIF}
960 end;
963 procedure InitOpenGL ();
964 begin
965 {$IF not DEFINED(HEADLESS)}
966 {$IFDEF USE_GLES1}
967 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
968 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
969 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
970 {$ELSE}
971 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
972 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
973 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
974 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
975 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
976 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
977 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
978 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
979 {$ENDIF}
980 {$ENDIF}
981 end;
984 function glHasExtension (const name: AnsiString): Boolean;
985 var
986 exts: PChar;
987 i: Integer;
988 found: Boolean;
989 extName: ShortString;
990 begin
991 result := false;
992 if (Length(name) = 0) then exit;
993 exts := glGetString(GL_EXTENSIONS);
994 if (exts = nil) then exit;
995 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
996 while (exts[0] <> #0) do
997 begin
998 if gwin_dump_extensions then
999 begin
1000 i := 0;
1001 while (exts[i] <> #0) and (exts[i] <> ' ') do Inc(i);
1002 if i > 255 then
1003 begin
1004 e_WriteLog('FUUUUUUUUUUUUU', TMsgType.Warning);
1005 end
1006 else
1007 begin
1008 Move(exts^, extName[1], i);
1009 extName[0] := Char(i);
1010 e_WriteLog(Format('EXT: %s', [extName]), TMsgType.Notify);
1011 end;
1012 end;
1013 found := true;
1014 for i := 0 to length(name)-1 do
1015 begin
1016 if (exts[i] = #0) then begin found := false; break; end;
1017 if (exts[i] <> name[i+1]) then begin found := false; break; end;
1018 end;
1019 if found and ((exts[Length(name)] = #0) or (exts[Length(name)] = ' ')) then begin result := true; exit; end;
1020 while (exts[0] <> #0) and (exts[0] <> ' ') do Inc(exts);
1021 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
1022 end;
1023 end;
1026 function SDLMain (): Integer;
1027 var
1028 idx: Integer;
1029 {$IF not DEFINED(HEADLESS)}
1030 ltmp: Integer;
1031 {$ENDIF}
1032 arg: AnsiString;
1033 mdfo: TStream;
1034 {$IFDEF ENABLE_HOLMES}
1035 itmp: Integer;
1036 valres: Word;
1037 {$ENDIF}
1038 begin
1039 {$IFDEF HEADLESS}
1040 e_NoGraphics := true;
1041 {$ELSE}
1042 {$IFDEF ENABLE_HOLMES}
1043 if (not g_holmes_imfunctional) then
1044 begin
1045 uiInitialize();
1046 uiContext.font := 'win14';
1047 end;
1048 {$ENDIF}
1049 {$ENDIF}
1051 idx := 1;
1052 while (idx <= ParamCount) do
1053 begin
1054 arg := ParamStr(idx);
1055 Inc(idx);
1056 if arg = '--opengl-dump-exts' then gwin_dump_extensions := true;
1057 //if arg = '--twinkletwinkle' then gwin_k8_enable_light_experiments := true;
1058 if arg = '--jah' then g_profile_history_size := 100;
1059 if arg = '--no-particles' then gpart_dbg_enabled := false;
1060 if arg = '--no-los' then gmon_dbg_los_enabled := false;
1062 if arg = '--profile-render' then g_profile_frame_draw := true;
1063 if arg = '--profile-coldet' then g_profile_collision := true;
1064 if arg = '--profile-los' then g_profile_los := true;
1066 if arg = '--no-part-phys' then gpart_dbg_phys_enabled := false;
1067 if arg = '--no-part-physics' then gpart_dbg_phys_enabled := false;
1068 if arg = '--no-particles-phys' then gpart_dbg_phys_enabled := false;
1069 if arg = '--no-particles-physics' then gpart_dbg_phys_enabled := false;
1070 if arg = '--no-particle-phys' then gpart_dbg_phys_enabled := false;
1071 if arg = '--no-particle-physics' then gpart_dbg_phys_enabled := false;
1073 if arg = '--debug-input' then g_dbg_input := True;
1075 {.$IF DEFINED(D2F_DEBUG)}
1076 if arg = '--aimline' then g_dbg_aimline_on := true;
1077 {.$ENDIF}
1079 {$IFDEF ENABLE_HOLMES}
1080 if arg = '--holmes' then begin g_holmes_enabled := true; g_Game_SetDebugMode(); end;
1082 if (arg = '--holmes-ui-scale') or (arg = '-holmes-ui-scale') then
1083 begin
1084 if (idx <= ParamCount) then
1085 begin
1086 if not conParseFloat(fuiRenderScale, ParamStr(idx)) then fuiRenderScale := 1.0;
1087 Inc(idx);
1088 end;
1089 end;
1091 if (arg = '--holmes-font') or (arg = '-holmes-font') then
1092 begin
1093 if (idx <= ParamCount) then
1094 begin
1095 itmp := 0;
1096 val(ParamStr(idx), itmp, valres);
1097 {$IFNDEF HEADLESS}
1098 if (valres = 0) and (not g_holmes_imfunctional) then
1099 begin
1100 case itmp of
1101 8: uiContext.font := 'win8';
1102 14: uiContext.font := 'win14';
1103 16: uiContext.font := 'win16';
1104 end;
1105 end;
1106 {$ELSE}
1107 // fuck off, fpc!
1108 itmp := itmp;
1109 valres := valres;
1110 {$ENDIF}
1111 Inc(idx);
1112 end;
1113 end;
1114 {$ENDIF}
1116 if (arg = '--game-scale') or (arg = '-game-scale') then
1117 begin
1118 if (idx <= ParamCount) then
1119 begin
1120 if not conParseFloat(g_dbg_scale, ParamStr(idx)) then g_dbg_scale := 1.0;
1121 Inc(idx);
1122 end;
1123 end;
1125 if (arg = '--write-mapdef') or (arg = '-write-mapdef') then
1126 begin
1127 mdfo := createDiskFile('mapdef.txt');
1128 mdfo.WriteBuffer(defaultMapDef[1], Length(defaultMapDef));
1129 mdfo.Free();
1130 Halt(0);
1131 end;
1132 end;
1134 e_WriteLog('Initializing OpenGL', TMsgType.Notify);
1135 InitOpenGL();
1137 e_WriteLog('Creating GL window', TMsgType.Notify);
1138 if not CreateGLWindow(PChar(Format('Doom 2D: Forever %s', [GAME_VERSION]))) then
1139 begin
1140 result := 0;
1141 e_WriteLog('Unable to create GL window: ' + SDL_GetError(), TMsgType.Fatal);
1142 exit;
1143 end;
1145 {EnumDisplayModes();}
1147 {$IFDEF HEADLESS}
1148 //gwin_k8_enable_light_experiments := false;
1149 gwin_has_stencil := false;
1150 glLegacyNPOT := false;
1151 gwin_dump_extensions := false;
1152 {$ELSE}
1153 SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, @ltmp);
1154 e_LogWritefln('stencil buffer size: %s', [ltmp]);
1155 gwin_has_stencil := (ltmp > 0);
1157 if glHasExtension('GL_ARB_texture_non_power_of_two') or
1158 glHasExtension('GL_OES_texture_npot') then
1159 begin
1160 e_WriteLog('NPOT textures: YES', TMsgType.Notify);
1161 glLegacyNPOT := false;
1162 end
1163 else
1164 begin
1165 e_WriteLog('NPOT textures: NO', TMsgType.Warning);
1166 glLegacyNPOT := true;
1167 end;
1168 gwin_dump_extensions := false;
1169 {$ENDIF}
1171 Init();
1172 Time_Old := GetTimer();
1174 // Êîìàíäíàÿ ñòðîêà
1175 if (ParamCount > 0) then g_Game_Process_Params();
1177 // Çàïðîñ ÿçûêà
1178 if (not gGameOn) and gAskLanguage then g_Menu_AskLanguage();
1180 e_WriteLog('Entering the main loop', TMsgType.Notify);
1182 // main loop
1183 while not ProcessMessage() do begin end;
1185 Release();
1186 KillGLWindow(false);
1188 result := 0;
1189 end;
1192 initialization
1193 conRegVar('d_input', @g_dbg_input, '', '')
1194 end.