1 (* Copyright (C) Doom 2D: Forever Developers
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.
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.
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/>.
16 {$INCLUDE ../shared/a_modes.inc}
24 function SDLMain (): Integer;
25 function GetTimer (): Int64;
26 procedure ResetTimer ();
27 function CreateGLWindow (Title
: PChar): Boolean;
28 procedure KillGLWindow ();
29 procedure PushExitEvent ();
30 function ProcessMessage (): Boolean;
31 procedure ReDrawWindow ();
32 procedure SwapBuffers ();
33 procedure Sleep (ms
: LongWord);
34 function GetDisplayModes (dbpp
: LongWord; var selres
: LongWord): SSArray
;
35 function g_Window_SetDisplay (preserveGL
: Boolean=false): Boolean;
36 function g_Window_SetSize (w
, h
: Word; fullscreen
: Boolean): Boolean;
38 procedure ProcessLoading (forceUpdate
: Boolean=false);
40 // returns `true` if quit event was received
41 function g_ProcessMessages (): Boolean;
45 gwin_dump_extensions
: Boolean = false;
46 gwin_has_stencil
: Boolean = false;
47 gwin_k8_enable_light_experiments
: Boolean = false;
48 g_dbg_aimline_on
: Boolean = false;
54 {$IFDEF WINDOWS}Windows
,{$ENDIF}
55 SysUtils
, Classes
, MAPDEF
,
56 SDL2
, GL
, GLExt
, e_graphics
, e_log
, e_texture
, g_main
,
57 g_console
, e_input
, g_options
, g_game
,
58 g_basic
, g_textures
, e_sound
, g_sound
, g_menu
, ENet
, g_net
,
59 g_map
, g_gfx
, g_monsters
, g_holmes
, xprofiler
,
64 ProgressUpdateMSecs
= 1;//100;
67 h_Wnd
: PSDL_Window
= nil;
68 h_GL
: TSDL_GLContext
= nil;
69 Time
, Time_Delta
, Time_Old
: Int64;
71 {$IF not DEFINED(HEADLESS)}
74 wNeedTimeReset
: Boolean = false;
75 wMinimized
: Boolean = false;
76 wLoadingProgress
: Boolean = false;
77 wLoadingQuit
: Boolean = false;
79 ticksOverflow
: Int64 = -1;
80 lastTicks
: Uint32
= 0; // to detect overflow
84 procedure KillGLWindow ();
86 if (h_GL
<> nil) then begin if (assigned(oglDeinitCB
)) then oglDeinitCB(); end;
87 if (h_Wnd
<> nil) then SDL_DestroyWindow(h_Wnd
);
88 if (h_GL
<> nil) then SDL_GL_DeleteContext(h_GL
);
94 function g_Window_SetDisplay (preserveGL
: Boolean = false): Boolean;
95 {$IF not DEFINED(HEADLESS)}
97 mode
, cmode
: TSDL_DisplayMode
;
101 {$IF not DEFINED(HEADLESS)}
104 e_WriteLog('Setting display mode...', TMsgType
.Notify
);
106 wFlags
:= SDL_WINDOW_OPENGL
or SDL_WINDOW_RESIZABLE
;
107 if gFullscreen
then wFlags
:= wFlags
or SDL_WINDOW_FULLSCREEN
;
108 if gWinMaximized
then wFlags
:= wFlags
or SDL_WINDOW_MAXIMIZED
;
114 mode
.w
:= gScreenWidth
;
115 mode
.h
:= gScreenHeight
;
117 mode
.refresh_rate
:= 0;
118 mode
.driverdata
:= nil;
119 if (SDL_GetClosestDisplayMode(0, @mode
, @cmode
) = nil) then
122 gScreenHeight
:= 600;
126 gScreenWidth
:= cmode
.w
;
127 gScreenHeight
:= cmode
.h
;
131 h_Wnd
:= SDL_CreateWindow(PChar(wTitle
), gWinRealPosX
, gWinRealPosY
, gScreenWidth
, gScreenHeight
, wFlags
);
132 if (h_Wnd
= nil) then exit
;
134 SDL_GL_MakeCurrent(h_Wnd
, h_GL
);
135 SDL_ShowCursor(SDL_DISABLE
);
136 fuiScrWdt
:= gScreenWidth
;
137 fuiScrHgt
:= gScreenHeight
;
138 if (h_GL
<> nil) then begin if (assigned(oglInitCB
)) then oglInitCB(); end;
145 function GetDisplayModes (dbpp
: LongWord; var selres
: LongWord): SSArray
;
147 mode
: TSDL_DisplayMode
;
148 res
, i
, k
, n
, pw
, ph
: Integer;
150 SetLength(result
, 0);
151 {$IFDEF HEADLESS}exit
;{$ENDIF}
153 n
:= SDL_GetNumDisplayModes(0);
157 res
:= SDL_GetDisplayMode(0, i
, @mode
);
158 if res
< 0 then continue
;
159 if SDL_BITSPERPIXEL(mode
.format
) = gBPP
then continue
;
160 if (mode
.w
= pw
) and (mode
.h
= ph
) then continue
;
161 if (mode
.w
= gScreenWidth
) and (mode
.h
= gScreenHeight
) then
164 SetLength(result
, k
);
165 result
[k
-1] := IntToStr(mode
.w
) + 'x' + IntToStr(mode
.h
);
166 pw
:= mode
.w
; ph
:= mode
.h
169 e_WriteLog('SDL: Got ' + IntToStr(k
) + ' resolutions.', TMsgType
.Notify
);
173 procedure Sleep (ms
: LongWord);
179 procedure ChangeWindowSize ();
181 gWinSizeX
:= gScreenWidth
;
182 gWinSizeY
:= gScreenHeight
;
183 {$IF not DEFINED(HEADLESS)}
184 fuiScrWdt
:= gScreenWidth
;
185 fuiScrHgt
:= gScreenHeight
;
186 e_ResizeWindow(gScreenWidth
, gScreenHeight
);
187 g_Game_SetupScreenSize();
189 g_Game_ClearLoading();
194 function g_Window_SetSize (w
, h
: Word; fullscreen
: Boolean): Boolean;
195 {$IF not DEFINED(HEADLESS)}
201 {$IF not DEFINED(HEADLESS)}
204 if (gScreenWidth
<> w
) or (gScreenHeight
<> h
) then
211 if (gFullscreen
<> fullscreen
) then
214 gFullscreen
:= fullscreen
;
220 g_Window_SetDisplay(preserve
);
227 function WindowEventHandler (constref ev
: TSDL_WindowEvent
): Boolean;
229 wActivate
, wDeactivate
: Boolean;
233 wDeactivate
:= false;
236 SDL_WINDOWEVENT_MOVED
:
238 if not (gFullscreen
or gWinMaximized
) then
240 gWinRealPosX
:= ev
.data1
;
241 gWinRealPosY
:= ev
.data2
;
245 SDL_WINDOWEVENT_MINIMIZED
:
248 if not wMinimized
then
250 e_ResizeWindow(0, 0);
252 if g_debug_WinMsgs
then
254 g_Console_Add('Now minimized');
255 e_WriteLog('[DEBUG] WinMsgs: Now minimized', TMsgType
.Notify
);
261 SDL_WINDOWEVENT_RESIZED
:
263 gScreenWidth
:= ev
.data1
;
264 gScreenHeight
:= ev
.data2
;
267 if g_debug_WinMsgs
then
269 g_Console_Add('Resized to ' + IntToStr(ev
.data1
) + 'x' + IntToStr(ev
.data2
));
270 e_WriteLog('[DEBUG] WinMsgs: Resized to ' + IntToStr(ev
.data1
) + 'x' + IntToStr(ev
.data2
), TMsgType
.Notify
);
274 SDL_WINDOWEVENT_EXPOSED
:
277 SDL_WINDOWEVENT_MAXIMIZED
:
281 e_ResizeWindow(gScreenWidth
, gScreenHeight
);
285 if not gWinMaximized
then
287 gWinMaximized
:= true;
288 if g_debug_WinMsgs
then
290 g_Console_Add('Now maximized');
291 e_WriteLog('[DEBUG] WinMsgs: Now maximized', TMsgType
.Notify
);
296 SDL_WINDOWEVENT_RESTORED
:
300 e_ResizeWindow(gScreenWidth
, gScreenHeight
);
304 if gWinMaximized
then gWinMaximized
:= false;
305 if g_debug_WinMsgs
then
307 g_Console_Add('Now restored');
308 e_WriteLog('[DEBUG] WinMsgs: Now restored', TMsgType
.Notify
);
312 SDL_WINDOWEVENT_FOCUS_GAINED
:
315 //e_WriteLog('window gained focus!', MSG_NOTIFY);
318 SDL_WINDOWEVENT_FOCUS_LOST
:
322 //e_WriteLog('window lost focus!', MSG_NOTIFY);
330 e_WriteLog('deactivating window', TMsgType
.Notify
);
331 e_EnableInput
:= false;
332 e_ClearInputBuffer();
334 if gMuteWhenInactive
then
336 //e_WriteLog('deactivating sounds', MSG_NOTIFY);
337 e_MuteChannels(true);
340 if g_debug_WinMsgs
then
342 g_Console_Add('Now inactive');
343 e_WriteLog('[DEBUG] WinMsgs: Now inactive', TMsgType
.Notify
);
348 if assigned(winBlurCB
) then winBlurCB();
351 else if wActivate
then
353 if not gWinActive
then
355 //e_WriteLog('activating window', MSG_NOTIFY);
356 e_EnableInput
:= true;
358 if gMuteWhenInactive
then
360 //e_WriteLog('activating sounds', MSG_NOTIFY);
361 e_MuteChannels(false);
364 if g_debug_WinMsgs
then
366 g_Console_Add('Now active');
367 e_WriteLog('[DEBUG] WinMsgs: Now active', TMsgType
.Notify
);
371 if assigned(winFocusCB
) then winFocusCB();
377 function EventHandler (var ev
: TSDL_Event
): Boolean;
387 result
:= WindowEventHandler(ev
.window
);
391 if (gExit
<> EXIT_QUIT
) then
393 if not wLoadingProgress
then
400 wLoadingQuit
:= true;
406 SDL_KEYDOWN
, SDL_KEYUP
:
408 key
:= ev
.key
.keysym
.scancode
;
409 down
:= (ev
.type_
= SDL_KEYDOWN
);
410 {$IF not DEFINED(HEADLESS)}
411 if fuiOnSDLEvent(ev
) then
413 // event eaten, but...
414 if not down
then e_KeyUpDown(key
, false);
418 if down
then KeyPress(key
);
419 e_KeyUpDown(key
, down
);
422 {$IF not DEFINED(HEADLESS)}
423 SDL_MOUSEBUTTONDOWN
, SDL_MOUSEBUTTONUP
, SDL_MOUSEWHEEL
, SDL_MOUSEMOTION
:
429 Utf8ToUnicode(@uc
, PChar(ev
.text.text), 1);
431 if (keychr
> 127) then keychr
:= Word(wchar2win(WideChar(keychr
)));
432 if (keychr
> 0) and (keychr
<= 255) then CharPress(AnsiChar(keychr
));
435 // other key presses and joysticks are handled in e_input
440 procedure SwapBuffers ();
442 {$IF not DEFINED(HEADLESS)}
443 SDL_GL_SwapWindow(h_Wnd
);
448 function CreateGLWindow (Title
: PChar): Boolean;
452 gWinSizeX
:= gScreenWidth
;
453 gWinSizeY
:= gScreenHeight
;
455 {$IF not DEFINED(HEADLESS)}
458 e_WriteLog('Creating window', TMsgType
.Notify
);
460 if not g_Window_SetDisplay() then
463 e_WriteLog('Window creation error (resolution not supported?)', TMsgType
.Fatal
);
467 {$IF not DEFINED(HEADLESS)}
468 h_Gl
:= SDL_GL_CreateContext(h_Wnd
);
469 if (h_Gl
= nil) then exit
;
470 fuiScrWdt
:= gScreenWidth
;
471 fuiScrHgt
:= gScreenHeight
;
472 if (assigned(oglInitCB
)) then oglInitCB();
475 e_ResizeWindow(gScreenWidth
, gScreenHeight
);
483 // windoze sux; in headless mode `GetTickCount()` (and SDL) returns shit
484 function GetTimer (): Int64;
488 QueryPerformanceFrequency(F
);
489 QueryPerformanceCounter(C
);
490 result
:= Round(C
/F
*1000{000});
493 function GetTimer (): Int64;
499 if (ticksOverflow
= -1) then
506 if (lastTicks
> t
) then
508 // overflow, increment overflow ;-)
509 ticksOverflow
:= ticksOverflow
+(Int64($ffffffff)+Int64(1));
510 tt
:= (Int64($ffffffff)+Int64(1))+Int64(t
);
511 t
:= Uint32(tt
-lastTicks
);
515 result
:= ticksOverflow
+Int64(t
);
520 procedure ResetTimer ();
522 wNeedTimeReset
:= true;
526 procedure PushExitEvent ();
530 ev
.type_
:= SDL_QUITEV
;
536 prevLoadingUpdateTime
: UInt64 = 0;
538 procedure ProcessLoading (forceUpdate
: Boolean=false);
544 FillChar(ev
, sizeof(ev
), 0);
545 wLoadingProgress
:= true;
547 while (SDL_PollEvent(@ev
) > 0) do
550 if (ev
.type_
= SDL_QUITEV
) then break
;
554 if (ev
.type_
= SDL_QUITEV
) or (gExit
= EXIT_QUIT
) then
556 wLoadingProgress
:= false;
560 if not wMinimized
then
564 prevLoadingUpdateTime
:= getTimeMilli();
568 stt
:= getTimeMilli();
569 if (stt
< prevLoadingUpdateTime
) or (stt
-prevLoadingUpdateTime
>= ProgressUpdateMSecs
) then
571 prevLoadingUpdateTime
:= stt
;
578 if g_Texture_Get('INTER', ID
) then
580 e_DrawSize(ID
, 0, 0, 0, false, false, gScreenWidth
, gScreenHeight
);
581 e_DarkenQuadWH(0, 0, gScreenWidth
, gScreenHeight
, 150);
585 e_Clear(GL_COLOR_BUFFER_BIT
, 0, 0, 0);
595 if NetMode
= NET_SERVER
then
601 if (NetMode
= NET_CLIENT
) and (NetState
<> NET_STATE_AUTH
) then g_Net_Client_UpdateWhileLoading();
604 wLoadingProgress
:= false;
608 function g_ProcessMessages (): Boolean;
613 FillChar(ev
, SizeOf(ev
), 0);
614 while (SDL_PollEvent(@ev
) > 0) do
616 result
:= EventHandler(ev
);
617 if (ev
.type_
= SDL_QUITEV
) then exit
;
623 function ProcessMessage (): Boolean;
627 result
:= g_ProcessMessages();
630 Time_Delta
:= Time
-Time_Old
;
634 if wNeedTimeReset
then
637 wNeedTimeReset
:= false;
640 g_Map_ProfilersBegin();
641 g_Mons_ProfilersBegin();
643 t
:= Time_Delta
div 28;
649 if (NetMode
= NET_SERVER
) then g_Net_Host_Update()
650 else if (NetMode
= NET_CLIENT
) then g_Net_Client_Update();
656 if (NetMode
= NET_SERVER
) then g_Net_Host_Update()
657 else if (NetMode
= NET_CLIENT
) then g_Net_Client_Update();
660 g_Map_ProfilersEnd();
661 g_Mons_ProfilersEnd();
669 if (gExit
= EXIT_QUIT
) then
675 // Âðåìÿ ïðåäûäóùåãî îáíîâëåíèÿ
678 Time_Old
:= Time
-(Time_Delta
mod 28);
679 if (not wMinimized
) then
687 Sleep(1); // release time slice, so we won't eat 100% CPU
694 procedure ReDrawWindow ();
700 procedure InitOpenGL (vsync
: Boolean);
701 {$IF not DEFINED(HEADLESS)}
706 {$IF not DEFINED(HEADLESS)}
707 if vsync
then v
:= 1 else v
:= 0;
708 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION
, 2);
709 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION
, 1);
710 SDL_GL_SetAttribute(SDL_GL_RED_SIZE
, 8);
711 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE
, 8);
712 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE
, 8);
713 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE
, 16);
714 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER
, 1);
715 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE
, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
716 SDL_GL_SetSwapInterval(v
);
721 function glHasExtension (const name
: AnsiString): Boolean;
726 extName
: ShortString;
729 if (Length(name
) = 0) then exit
;
730 exts
:= glGetString(GL_EXTENSIONS
);
731 if (exts
= nil) then exit
;
732 while (exts
[0] <> #0) and (exts
[0] = ' ') do Inc(exts
);
733 while (exts
[0] <> #0) do
735 if gwin_dump_extensions
then
738 while (exts
[i
] <> #0) and (exts
[i
] <> ' ') do Inc(i
);
741 e_WriteLog('FUUUUUUUUUUUUU', TMsgType
.Warning
);
745 Move(exts
^, extName
[1], i
);
746 extName
[0] := Char(i
);
747 e_WriteLog(Format('EXT: %s', [extName
]), TMsgType
.Notify
);
751 for i
:= 0 to length(name
)-1 do
753 if (exts
[i
] = #0) then begin found
:= false; break
; end;
754 if (exts
[i
] <> name
[i
+1]) then begin found
:= false; break
; end;
756 if found
and ((exts
[Length(name
)] = #0) or (exts
[Length(name
)] = ' ')) then begin result
:= true; exit
; end;
757 while (exts
[0] <> #0) and (exts
[0] <> ' ') do Inc(exts
);
758 while (exts
[0] <> #0) and (exts
[0] = ' ') do Inc(exts
);
763 function SDLMain (): Integer;
766 {$IF not DEFINED(HEADLESS)}
775 e_NoGraphics
:= true;
777 if (not g_holmes_imfunctional
) then
780 uiContext
.font
:= 'win14';
785 while (idx
<= ParamCount
) do
787 arg
:= ParamStr(idx
);
789 if arg
= '--opengl-dump-exts' then gwin_dump_extensions
:= true;
790 //if arg = '--twinkletwinkle' then gwin_k8_enable_light_experiments := true;
791 if arg
= '--jah' then g_profile_history_size
:= 100;
792 if arg
= '--no-particles' then gpart_dbg_enabled
:= false;
793 if arg
= '--no-los' then gmon_dbg_los_enabled
:= false;
795 if arg
= '--profile-render' then g_profile_frame_draw
:= true;
796 if arg
= '--profile-coldet' then g_profile_collision
:= true;
797 if arg
= '--profile-los' then g_profile_los
:= true;
799 if arg
= '--no-part-phys' then gpart_dbg_phys_enabled
:= false;
800 if arg
= '--no-part-physics' then gpart_dbg_phys_enabled
:= false;
801 if arg
= '--no-particles-phys' then gpart_dbg_phys_enabled
:= false;
802 if arg
= '--no-particles-physics' then gpart_dbg_phys_enabled
:= false;
803 if arg
= '--no-particle-phys' then gpart_dbg_phys_enabled
:= false;
804 if arg
= '--no-particle-physics' then gpart_dbg_phys_enabled
:= false;
806 {.$IF DEFINED(D2F_DEBUG)}
807 if arg
= '--aimline' then g_dbg_aimline_on
:= true;
810 if arg
= '--holmes' then begin g_holmes_enabled
:= true; g_Game_SetDebugMode(); end;
812 if (arg
= '--holmes-ui-scale') or (arg
= '-holmes-ui-scale') then
814 if (idx
<= ParamCount
) then
816 if not conParseFloat(fuiRenderScale
, ParamStr(idx
)) then fuiRenderScale
:= 1.0;
821 if (arg
= '--holmes-font') or (arg
= '-holmes-font') then
823 if (idx
<= ParamCount
) then
826 val(ParamStr(idx
), itmp
, valres
);
828 if (valres
= 0) and (not g_holmes_imfunctional
) then
831 8: uiContext
.font
:= 'win8';
832 14: uiContext
.font
:= 'win14';
833 16: uiContext
.font
:= 'win16';
845 if (arg
= '--game-scale') or (arg
= '-game-scale') then
847 if (idx
<= ParamCount
) then
849 if not conParseFloat(g_dbg_scale
, ParamStr(idx
)) then g_dbg_scale
:= 1.0;
854 if (arg
= '--write-mapdef') or (arg
= '-write-mapdef') then
856 mdfo
:= createDiskFile('mapdef.txt');
857 mdfo
.WriteBuffer(defaultMapDef
[1], Length(defaultMapDef
));
863 e_WriteLog('Initializing OpenGL', TMsgType
.Notify
);
866 e_WriteLog('Creating GL window', TMsgType
.Notify
);
867 if not CreateGLWindow(PChar(Format('Doom 2D: Forever %s', [GAME_VERSION
]))) then
873 {EnumDisplayModes();}
876 //gwin_k8_enable_light_experiments := false;
877 gwin_has_stencil
:= false;
878 glLegacyNPOT
:= false;
879 gwin_dump_extensions
:= false;
881 SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE
, @ltmp
);
882 e_LogWritefln('stencil buffer size: %s', [ltmp
]);
883 gwin_has_stencil
:= (ltmp
> 0);
885 if not glHasExtension('GL_ARB_texture_non_power_of_two') then
887 e_WriteLog('NPOT textures: NO', TMsgType
.Warning
);
888 glLegacyNPOT
:= true;
892 e_WriteLog('NPOT textures: YES', TMsgType
.Notify
);
893 glLegacyNPOT
:= false;
895 gwin_dump_extensions
:= false;
899 Time_Old
:= GetTimer();
902 if (ParamCount
> 0) then g_Game_Process_Params();
905 if (not gGameOn
) and gAskLanguage
then g_Menu_AskLanguage();
907 e_WriteLog('Entering the main loop', TMsgType
.Notify
);
910 while not ProcessMessage() do begin end;