DEADSOFTWARE

6ffa8ff05468b132ff35b3eaa2e8b4b988979a7e
[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 {$MODE DELPHI}
17 unit g_window;
19 interface
21 uses
22 wadreader;
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 ProcessLoading();
32 procedure ReDrawWindow();
33 procedure SwapBuffers();
34 procedure Sleep(ms: LongWord);
35 function GetDisplayModes(dBPP: DWORD; var SelRes: DWORD): SArray;
36 function g_Window_SetDisplay(PreserveGL: Boolean = False): Boolean;
37 function g_Window_SetSize(W, H: Word; FScreen: Boolean): Boolean;
39 var
40 gwin_dump_extensions: Boolean = false;
42 implementation
44 uses
45 {$IFDEF WINDOWS}Windows,{$ENDIF}
46 SDL2, GL, GLExt, e_graphics, e_log, g_main,
47 g_console, SysUtils, e_input, g_options, g_game,
48 g_basic, g_textures, e_sound, g_sound, g_menu, ENet, g_net;
50 var
51 h_Wnd: PSDL_Window;
52 h_GL: TSDL_GLContext;
53 wFlags: LongWord = 0;
54 Time, Time_Delta, Time_Old: Int64;
55 flag: Boolean;
56 wTitle: PChar = nil;
57 wNeedTimeReset: Boolean = False;
58 //wWindowCreated: Boolean = False;
59 //wCursorShown: Boolean = False;
60 wMinimized: Boolean = False;
61 //wNeedFree: Boolean = True;
62 wLoadingProgress: Boolean = False;
63 wLoadingQuit: Boolean = False;
64 {wWinPause: Byte = 0;}
65 {$IFNDEF WINDOWS}
66 ticksOverflow: Int64 = -1;
67 lastTicks: Uint32 = 0; // to detect overflow
68 {$ENDIF}
70 const
71 // TODO: move this to a separate file
72 CP1251: array [0..127] of Word = (
73 $0402,$0403,$201A,$0453,$201E,$2026,$2020,$2021,$20AC,$2030,$0409,$2039,$040A,$040C,$040B,$040F,
74 $0452,$2018,$2019,$201C,$201D,$2022,$2013,$2014,$003F,$2122,$0459,$203A,$045A,$045C,$045B,$045F,
75 $00A0,$040E,$045E,$0408,$00A4,$0490,$00A6,$00A7,$0401,$00A9,$0404,$00AB,$00AC,$00AD,$00AE,$0407,
76 $00B0,$00B1,$0406,$0456,$0491,$00B5,$00B6,$00B7,$0451,$2116,$0454,$00BB,$0458,$0405,$0455,$0457,
77 $0410,$0411,$0412,$0413,$0414,$0415,$0416,$0417,$0418,$0419,$041A,$041B,$041C,$041D,$041E,$041F,
78 $0420,$0421,$0422,$0423,$0424,$0425,$0426,$0427,$0428,$0429,$042A,$042B,$042C,$042D,$042E,$042F,
79 $0430,$0431,$0432,$0433,$0434,$0435,$0436,$0437,$0438,$0439,$043A,$043B,$043C,$043D,$043E,$043F,
80 $0440,$0441,$0442,$0443,$0444,$0445,$0446,$0447,$0448,$0449,$044A,$044B,$044C,$044D,$044E,$044F
81 );
83 // TODO: make a transition table or something
84 function WCharToCP1251(wc: Word): Word;
85 var
86 n: Word;
87 begin
88 Result := 0;
89 for n := 0 to 127 do
90 if CP1251[n] = wc then begin Result := n; break end;
91 Result := Result + 128;
92 end;
94 function g_Window_SetDisplay(PreserveGL: Boolean = False): Boolean;
95 var
96 mode, cmode: TSDL_DisplayMode;
97 begin
98 {$IFDEF HEADLESS}
99 Result := True;
100 Exit;
101 {$ENDIF}
103 Result := False;
105 e_WriteLog('Setting display mode...', MSG_NOTIFY);
107 wFlags := SDL_WINDOW_OPENGL or SDL_WINDOW_RESIZABLE;
108 if gFullscreen then wFlags := wFlags or SDL_WINDOW_FULLSCREEN;
109 if gWinMaximized then wFlags := wFlags or SDL_WINDOW_MAXIMIZED;
111 if h_Wnd <> nil then
112 begin
113 SDL_DestroyWindow(h_Wnd);
114 h_Wnd := nil;
115 end;
117 if gFullscreen then
118 begin
119 mode.w := gScreenWidth;
120 mode.h := gScreenHeight;
121 mode.format := 0;
122 mode.refresh_rate := 0;
123 mode.driverdata := nil;
124 if SDL_GetClosestDisplayMode(0, @mode, @cmode) = nil then
125 begin
126 gScreenWidth := 800;
127 gScreenHeight := 600;
128 end
129 else
130 begin
131 gScreenWidth := cmode.w;
132 gScreenHeight := cmode.h;
133 end;
134 end;
136 h_Wnd := SDL_CreateWindow(PChar(wTitle), gWinRealPosX, gWinRealPosY, gScreenWidth, gScreenHeight, wFlags);
137 if h_Wnd = nil then Exit;
139 SDL_GL_MakeCurrent(h_Wnd, h_GL);
140 SDL_ShowCursor(SDL_DISABLE);
142 Result := True;
143 end;
145 procedure ReShowCursor();
146 begin
147 // TODO: what was this for?
148 end;
150 function GetDisplayModes(dBPP: DWORD; var SelRes: DWORD): SArray;
151 var
152 mode: TSDL_DisplayMode;
153 res, i, k, n, pw, ph: Integer;
154 begin
155 SetLength(Result, 0);
156 {$IFDEF HEADLESS}Exit;{$ENDIF}
157 k := 0; SelRes := 0;
158 n := SDL_GetNumDisplayModes(0);
159 pw := 0; ph := 0;
160 for i := 0 to n do
161 begin
162 res := SDL_GetDisplayMode(0, i, @mode);
163 if res < 0 then continue;
164 if SDL_BITSPERPIXEL(mode.format) = gBPP then continue;
165 if (mode.w = pw) and (mode.h = ph) then continue;
166 if (mode.w = gScreenWidth) and (mode.h = gScreenHeight) then
167 SelRes := k;
168 Inc(k);
169 SetLength(Result, k);
170 Result[k-1] := IntToStr(mode.w) + 'x' + IntToStr(mode.h);
171 pw := mode.w; ph := mode.h
172 end;
174 e_WriteLog('SDL: Got ' + IntToStr(k) + ' resolutions.', MSG_NOTIFY);
175 end;
177 procedure Sleep(ms: LongWord);
178 begin
179 SDL_Delay(ms);
180 end;
182 procedure ChangeWindowSize();
183 begin
184 gWinSizeX := gScreenWidth;
185 gWinSizeY := gScreenHeight;
186 {$IFDEF HEADLESS}Exit;{$ENDIF}
187 e_ResizeWindow(gScreenWidth, gScreenHeight);
188 g_Game_SetupScreenSize();
189 g_Menu_Reset();
190 g_Game_ClearLoading();
191 end;
193 function g_Window_SetSize(W, H: Word; FScreen: Boolean): Boolean;
194 var
195 Preserve: Boolean;
196 begin
197 Result := False;
198 {$IFDEF HEADLESS}Exit;{$ENDIF}
199 Preserve := False;
201 if (gScreenWidth <> W) or (gScreenHeight <> H) then
202 begin
203 Result := True;
204 gScreenWidth := W;
205 gScreenHeight := H;
206 end;
208 if gFullscreen <> FScreen then
209 begin
210 Result := True;
211 gFullscreen := FScreen;
212 Preserve := True;
213 end;
215 if Result then
216 begin
217 g_Window_SetDisplay(Preserve);
218 ChangeWindowSize();
219 end;
220 end;
222 function WindowEventHandler(ev: TSDL_WindowEvent): Boolean;
223 var
224 wActivate, wDeactivate: Boolean;
225 begin
226 Result := False;
227 wActivate := False;
228 wDeactivate := False;
230 case ev.event of
231 SDL_WINDOWEVENT_MOVED:
232 begin
233 if not (gFullscreen or gWinMaximized) then
234 begin
235 gWinRealPosX := ev.data1;
236 gWinRealPosY := ev.data2;
237 end;
238 end;
240 SDL_WINDOWEVENT_MINIMIZED:
241 begin
242 if not wMinimized then
243 begin
244 e_ResizeWindow(0, 0);
245 wMinimized := True;
247 if g_debug_WinMsgs then
248 begin
249 g_Console_Add('Now minimized');
250 e_WriteLog('[DEBUG] WinMsgs: Now minimized', MSG_NOTIFY);
251 end;
252 wDeactivate := True;
253 end;
254 end;
256 SDL_WINDOWEVENT_RESIZED:
257 begin
258 gScreenWidth := ev.data1;
259 gScreenHeight := ev.data2;
260 ChangeWindowSize();
261 SwapBuffers();
262 if g_debug_WinMsgs then
263 begin
264 g_Console_Add('Resized to ' + IntToStr(ev.data1) + 'x' + IntToStr(ev.data2));
265 e_WriteLog('[DEBUG] WinMsgs: Resized to ' + IntToStr(ev.data1) + 'x' + IntToStr(ev.data2), MSG_NOTIFY);
266 end;
267 end;
269 SDL_WINDOWEVENT_EXPOSED:
270 SwapBuffers();
272 SDL_WINDOWEVENT_MAXIMIZED:
273 begin
274 if wMinimized then
275 begin
276 e_ResizeWindow(gScreenWidth, gScreenHeight);
277 wMinimized := False;
278 wActivate := True;
279 end;
280 if not gWinMaximized then
281 begin
282 gWinMaximized := True;
283 if g_debug_WinMsgs then
284 begin
285 g_Console_Add('Now maximized');
286 e_WriteLog('[DEBUG] WinMsgs: Now maximized', MSG_NOTIFY);
287 end;
288 end;
289 end;
291 SDL_WINDOWEVENT_RESTORED:
292 begin
293 if wMinimized then
294 begin
295 e_ResizeWindow(gScreenWidth, gScreenHeight);
296 wMinimized := False;
297 wActivate := True;
298 end;
299 if gWinMaximized then
300 gWinMaximized := False;
301 if g_debug_WinMsgs then
302 begin
303 g_Console_Add('Now restored');
304 e_WriteLog('[DEBUG] WinMsgs: Now restored', MSG_NOTIFY);
305 end;
306 end;
308 SDL_WINDOWEVENT_FOCUS_GAINED:
309 begin
310 wActivate := True;
311 //e_WriteLog('window gained focus!', MSG_NOTIFY);
312 end;
314 SDL_WINDOWEVENT_FOCUS_LOST:
315 begin
316 wDeactivate := True;
317 //e_WriteLog('window lost focus!', MSG_NOTIFY);
318 end;
319 end;
321 if wDeactivate then
322 begin
323 if gWinActive then
324 begin
325 e_WriteLog('deactivating window', MSG_NOTIFY);
326 e_EnableInput := False;
327 e_ClearInputBuffer();
329 if gMuteWhenInactive then
330 begin
331 //e_WriteLog('deactivating sounds', MSG_NOTIFY);
332 e_MuteChannels(True);
333 end;
335 if g_debug_WinMsgs then
336 begin
337 g_Console_Add('Now inactive');
338 e_WriteLog('[DEBUG] WinMsgs: Now inactive', MSG_NOTIFY);
339 end;
341 gWinActive := False;
342 end;
343 end
344 else if wActivate then
345 begin
346 if not gWinActive then
347 begin
348 //e_WriteLog('activating window', MSG_NOTIFY);
349 e_EnableInput := True;
351 if gMuteWhenInactive then
352 begin
353 //e_WriteLog('activating sounds', MSG_NOTIFY);
354 e_MuteChannels(False);
355 end;
357 if g_debug_WinMsgs then
358 begin
359 g_Console_Add('Now active');
360 e_WriteLog('[DEBUG] WinMsgs: Now active', MSG_NOTIFY);
361 end;
363 gWinActive := True;
364 end;
365 end;
366 end;
368 function EventHandler(ev: TSDL_Event): Boolean;
369 var
370 key, keychr: Word;
371 uc: UnicodeChar;
372 //joy: Integer;
373 begin
374 Result := False;
375 case ev.type_ of
376 SDL_WINDOWEVENT:
377 Result := WindowEventHandler(ev.window);
379 SDL_QUITEV:
380 begin
381 if gExit <> EXIT_QUIT then
382 begin
383 if not wLoadingProgress then
384 begin
385 g_Game_Free();
386 g_Game_Quit();
387 end
388 else
389 wLoadingQuit := True;
390 end;
391 Result := True;
392 end;
394 SDL_KEYDOWN:
395 begin
396 key := ev.key.keysym.scancode;
397 KeyPress(key);
398 end;
400 SDL_TEXTINPUT:
401 begin
402 Utf8ToUnicode(@uc, PChar(ev.text.text), 1);
403 keychr := Word(uc);
404 if (keychr > 127) then
405 keychr := WCharToCP1251(keychr);
406 CharPress(Chr(keychr));
407 end;
409 // other key presses and joysticks are handled in e_input
410 end;
411 end;
413 procedure SwapBuffers();
414 begin
415 {$IFDEF HEADLESS}Exit;{$ENDIF}
416 SDL_GL_SwapWindow(h_Wnd);
417 end;
419 procedure KillGLWindow();
420 begin
421 if h_Wnd <> nil then SDL_DestroyWindow(h_Wnd);
422 if h_GL <> nil then SDL_GL_DeleteContext(h_GL);
423 h_Wnd := nil;
424 h_GL := nil;
425 //wWindowCreated := False;
426 end;
428 function CreateGLWindow(Title: PChar): Boolean;
429 //var
430 // flags: LongWord;
431 begin
432 Result := False;
434 gWinSizeX := gScreenWidth;
435 gWinSizeY := gScreenHeight;
437 wTitle := Title;
438 e_WriteLog('Creating window', MSG_NOTIFY);
440 if not g_Window_SetDisplay() then
441 begin
442 KillGLWindow();
443 e_WriteLog('Window creation error (resolution not supported?)', MSG_FATALERROR);
444 exit;
445 end;
447 {$IFNDEF HEADLESS}
448 h_Gl := SDL_GL_CreateContext(h_Wnd);
449 if h_Gl = nil then Exit;
450 {$ENDIF}
451 //wWindowCreated := True;
453 e_ResizeWindow(gScreenWidth, gScreenHeight);
454 e_InitGL();
456 Result := True;
457 end;
459 {$IFDEF WINDOWS}
460 // windoze sux; in headless mode `GetTickCount()` (and SDL) returns shit
461 function GetTimer(): Int64;
462 var
463 F, C: Int64;
464 begin
465 QueryPerformanceFrequency(F);
466 QueryPerformanceCounter(C);
467 Result := Round(C/F*1000{000});
468 end;
469 {$ELSE}
470 function GetTimer(): Int64;
471 var
472 t: Uint32;
473 tt: Int64;
474 begin
475 t := SDL_GetTicks() {* 1000}; // TODO: do we really need microseconds here? k8: NOPE!
476 if ticksOverflow = -1 then
477 begin
478 ticksOverflow := 0;
479 lastTicks := t;
480 end
481 else
482 begin
483 if lastTicks > t then
484 begin
485 // overflow, increment overflow ;-)
486 ticksOverflow := ticksOverflow+(Int64($ffffffff)+Int64(1));
487 tt := (Int64($ffffffff)+Int64(1))+Int64(t);
488 t := Uint32(tt-lastTicks);
489 end;
490 end;
491 lastTicks := t;
492 result := ticksOverflow+Int64(t);
493 end;
494 {$ENDIF}
496 procedure ResetTimer();
497 begin
498 wNeedTimeReset := True;
499 end;
501 procedure PushExitEvent();
502 var
503 ev: TSDL_Event;
504 begin
505 ev.type_ := SDL_QUITEV;
506 SDL_PushEvent(@ev);
507 end;
509 procedure ProcessLoading();
510 var
511 ev: TSDL_Event;
512 ID: DWORD;
513 begin
514 FillChar(ev, SizeOf(ev), 0);
515 //wNeedFree := False;
516 wLoadingProgress := True;
517 while SDL_PollEvent(@ev) > 0 do
518 begin
519 if (ev.type_ = SDL_QUITEV) then
520 break;
521 end;
522 //wNeedFree := True;
524 if (ev.type_ = SDL_QUITEV) or (gExit = EXIT_QUIT) then
525 begin
526 wLoadingProgress := False;
527 exit;
528 end;
530 if not wMinimized then
531 begin
532 if g_Texture_Get('INTER', ID) then
533 e_DrawSize(ID, 0, 0, 0, False, False, gScreenWidth, gScreenHeight)
534 else
535 e_Clear(GL_COLOR_BUFFER_BIT, 0, 0, 0);
537 DrawLoadingStat();
538 SwapBuffers();
540 ReShowCursor();
541 end;
543 e_SoundUpdate();
545 if NetMode = NET_SERVER then
546 g_Net_Host_Update
547 else
548 if (NetMode = NET_CLIENT) and (NetState <> NET_STATE_AUTH) then
549 g_Net_Client_UpdateWhileLoading;
550 wLoadingProgress := False;
551 end;
553 function ProcessMessage(): Boolean;
554 var
555 i, t: Integer;
556 ev: TSDL_Event;
557 begin
558 Result := False;
559 FillChar(ev, SizeOf(ev), 0);
561 while SDL_PollEvent(@ev) > 0 do
562 begin
563 Result := EventHandler(ev);
564 if ev.type_ = SDL_QUITEV then exit;
565 end;
567 Time := GetTimer();
568 Time_Delta := Time - Time_Old;
570 flag := False;
572 if wNeedTimeReset then
573 begin
574 Time_Delta := 28{(27777 div 1000)};
575 wNeedTimeReset := False;
576 end;
578 t := Time_Delta div 28{(27777 div 1000)};
579 if t > 0 then
580 begin
581 flag := True;
582 for i := 1 to t do
583 begin
584 if NetMode = NET_SERVER then g_Net_Host_Update()
585 else if NetMode = NET_CLIENT then g_Net_Client_Update();
586 Update();
587 end;
588 end
589 else
590 begin
591 if NetMode = NET_SERVER then g_Net_Host_Update()
592 else if NetMode = NET_CLIENT then g_Net_Client_Update();
593 end;
595 if wLoadingQuit then
596 begin
597 g_Game_Free();
598 g_Game_Quit();
599 end;
601 if gExit = EXIT_QUIT then
602 begin
603 Result := True;
604 Exit;
605 end;
607 // Âðåìÿ ïðåäûäóùåãî îáíîâëåíèÿ:
608 if flag then
609 begin
610 Time_Old := Time - (Time_Delta mod 28{(27777 div 1000)});
611 if (not wMinimized) then
612 begin
613 Draw();
614 SwapBuffers();
615 ReShowCursor();
616 end;
617 end
618 else
619 Sleep(1);
621 e_SoundUpdate();
622 end;
624 procedure ReDrawWindow;
625 begin
626 SwapBuffers();
627 ReShowCursor();
628 end;
630 procedure InitOpenGL(VSync: Boolean);
631 var
632 v: Byte;
633 begin
634 {$IFDEF HEADLESS}Exit;{$ENDIF}
635 if VSync then v := 1 else v := 0;
636 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
637 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
638 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
639 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
640 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
641 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
642 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
643 SDL_GL_SetSwapInterval(v);
644 end;
646 function glHasExtension (name: AnsiString): Boolean;
647 var
648 exts: PChar;
649 i: Integer;
650 found: Boolean;
651 extName: ShortString;
652 begin
653 result := false;
654 if length(name) = 0 then exit;
655 exts := glGetString(GL_EXTENSIONS);
656 if exts = nil then exit;
657 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
658 while exts[0] <> #0 do
659 begin
660 if gwin_dump_extensions then
661 begin
662 i := 0;
663 while (exts[i] <> #0) and (exts[i] <> ' ') do Inc(i);
664 if i > 255 then
665 begin
666 e_WriteLog('FUUUUUUUUUUUUU', MSG_WARNING);
667 end
668 else
669 begin
670 Move(exts^, extName[1], i);
671 extName[0] := Char(i);
672 e_WriteLog(Format('EXT: %s', [extName]), MSG_NOTIFY);
673 end;
674 end;
675 found := true;
676 for i := 0 to length(name)-1 do
677 begin
678 if exts[i] = #0 then begin found := false; break; end;
679 if exts[i] <> name[i+1] then begin found := false; break; end;
680 end;
681 if found and ((exts[length(name)] = #0) or (exts[length(name)] = ' ')) then begin result := true; exit; end;
682 while (exts[0] <> #0) and (exts[0] <> ' ') do Inc(exts);
683 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
684 end;
685 end;
687 function SDLMain(): Integer;
688 begin
689 {$IFDEF HEADLESS}
690 e_NoGraphics := True;
691 {$ENDIF}
693 e_WriteLog('Initializing OpenGL', MSG_NOTIFY);
694 InitOpenGL(gVSync);
696 e_WriteLog('Creating GL window', MSG_NOTIFY);
697 if not CreateGLWindow(PChar(Format('Doom 2D: Forever %s', [GAME_VERSION]))) then
698 begin
699 Result := 0;
700 exit;
701 end;
703 {EnumDisplayModes();}
705 if not glHasExtension('GL_ARB_texture_non_power_of_two') then
706 begin
707 e_WriteLog('Driver DID''T advertised NPOT textures support', MSG_WARNING);
708 glLegacyNPOT := true;
709 end
710 else
711 begin
712 e_WriteLog('Driver advertised NPOT textures support', MSG_NOTIFY);
713 glLegacyNPOT := false;
714 end;
716 Init();
717 Time_Old := GetTimer();
719 // Êîìàíäíàÿ ñòðîêà:
720 if ParamCount > 0 then
721 g_Game_Process_Params();
723 // Çàïðîñ ÿçûêà:
724 if (not gGameOn) and gAskLanguage then
725 g_Menu_AskLanguage();
727 e_WriteLog('Entering the main loop', MSG_NOTIFY);
729 while not ProcessMessage() do
730 { Main Loop } ;
732 Release();
733 KillGLWindow();
735 Result := 0;
736 end;
738 end.