DEADSOFTWARE

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