DEADSOFTWARE

render: separate animation drawing from game code
[d2df-sdl.git] / src / game / Doom2DF.lpr
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 {$IFDEF ANDROID}library{$ELSE}program{$ENDIF} Doom2DF;
18 {$IFNDEF HEADLESS}
19 {$IFDEF WINDOWS}
20 {$APPTYPE GUI}
21 {$ENDIF}
22 {$ENDIF}
23 {$HINTS OFF}
25 uses
26 {$IFDEF ANDROID}
27 ctypes, jni,
28 {$ENDIF}
29 {$IFDEF UNIX}
30 cthreads, BaseUnix,
31 {$ENDIF}
32 {$IFDEF DARWIN}
33 MacOSAll, CocoaAll,
34 {$ENDIF}
35 mempool in '../shared/mempool.pas',
36 conbuf in '../shared/conbuf.pas',
37 geom in '../shared/geom.pas',
38 math,
40 {$IFDEF USE_MINIUPNPC}
41 miniupnpc in '../lib/miniupnpc/miniupnpc.pas',
42 {$ENDIF}
44 {$IFDEF USE_SDL}
45 SDL in '../lib/sdl/sdl.pas',
46 {$IFDEF USE_SDLMIXER}
47 SDL_mixer in '../lib/sdl/sdl_mixer.pas',
48 {$ENDIF}
49 {$ENDIF}
50 {$IFDEF USE_SDL2}
51 SDL2 in '../lib/sdl2/sdl2.pas',
52 {$IFDEF USE_SDLMIXER}
53 SDL2_mixer in '../lib/sdl2/SDL2_mixer.pas',
54 {$ENDIF}
55 {$ENDIF}
56 {$IFDEF USE_SYSSTUB}
57 {$IFDEF USE_SDLMIXER}
58 SDL2 in '../lib/sdl2/sdl2.pas',
59 SDL2_mixer in '../lib/sdl2/SDL2_mixer.pas',
60 {$ENDIF}
61 {$ENDIF}
63 {$IFDEF USE_OPENAL}
64 AL in '../lib/openal/al.pas',
65 e_soundfile in '../engine/e_soundfile.pas',
66 {$IF DEFINED(USE_SDL) OR DEFINED(USE_SDL2)}
67 e_soundfile_wav in '../engine/e_soundfile_wav.pas',
68 {$ENDIF}
69 {$IFDEF USE_VORBIS}
70 vorbis in '../lib/vorbis/vorbis.pas',
71 e_soundfile_vorbis in '../engine/e_soundfile_vorbis.pas',
72 {$ENDIF}
73 {$IFDEF USE_FLUIDSYNTH}
74 fluidsynth in '../lib/fluidsynth/fluidsynth.pas',
75 e_soundfile_fluid in '../engine/e_soundfile_fluid.pas',
76 {$ENDIF}
77 {$IFDEF USE_MODPLUG}
78 modplug in '../lib/modplug/modplug.pas',
79 e_soundfile_modplug in '../engine/e_soundfile_modplug.pas',
80 {$ENDIF}
81 {$IFDEF USE_XMP}
82 xmp in '../lib/xmp/xmp.pas',
83 e_soundfile_xmp in '../engine/e_soundfile_xmp.pas',
84 {$ENDIF}
85 {$IFDEF USE_GME}
86 gme in '../lib/gme/gme.pas',
87 e_soundfile_gme in '../engine/e_soundfile_gme.pas',
88 {$ENDIF}
89 {$IFDEF USE_MPG123}
90 mpg123 in '../lib/mpg123/mpg123.pas',
91 e_soundfile_mp3 in '../engine/e_soundfile_mp3.pas',
92 {$ENDIF}
93 {$IFDEF USE_OPUS}
94 opus in '../lib/opus/opus.pas',
95 e_soundfile_opus in '../engine/e_soundfile_opus.pas',
96 {$ENDIF}
97 {$IF DEFINED(USE_VORBIS) OR DEFINED(USE_OPUS)}
98 ogg in '../lib/vorbis/ogg.pas', // this has to come last because link order
99 {$ENDIF}
100 {$ENDIF}
102 ENet in '../lib/enet/enet.pp',
103 e_input in '../engine/e_input.pas',
104 e_log in '../engine/e_log.pas',
105 e_sound in '../engine/e_sound.pas',
106 e_msg in '../engine/e_msg.pas',
107 e_res in '../engine/e_res.pas',
108 utils in '../shared/utils.pas',
109 xstreams in '../shared/xstreams.pas',
110 sfs in '../sfs/sfs.pas',
111 sfsPlainFS in '../sfs/sfsPlainFS.pas',
112 sfsZipFS in '../sfs/sfsZipFS.pas',
113 wadreader in '../shared/wadreader.pas',
114 MAPDEF in '../shared/MAPDEF.pas',
115 CONFIG in '../shared/CONFIG.pas',
116 g_base in 'g_base.pas',
117 g_basic in 'g_basic.pas',
118 g_console in 'g_console.pas',
119 g_net in 'g_net.pas',
120 g_netmsg in 'g_netmsg.pas',
121 g_nethandler in 'g_nethandler.pas',
122 g_netmaster in 'g_netmaster.pas',
123 g_res_downloader in 'g_res_downloader.pas',
124 g_grid in 'g_grid.pas',
125 g_game in 'g_game.pas',
126 g_gfx in 'g_gfx.pas',
127 g_gui in 'g_gui.pas',
128 g_items in 'g_items.pas',
129 g_map in 'g_map.pas',
130 g_menu in 'g_menu.pas',
131 g_monsters in 'g_monsters.pas',
132 g_options in 'g_options.pas',
133 g_phys in 'g_phys.pas',
134 g_player in 'g_player.pas',
135 g_playermodel in 'g_playermodel.pas',
136 g_saveload in 'g_saveload.pas',
137 g_sound in 'g_sound.pas',
138 g_textures in 'g_textures.pas',
139 g_triggers in 'g_triggers.pas',
140 g_weapons in 'g_weapons.pas',
141 g_window in 'g_window.pas',
142 {$IFDEF USE_SYSSTUB}
143 g_system in 'stub/g_system.pas',
144 g_touch in 'stub/g_touch.pas',
145 {$ENDIF}
146 {$IFDEF USE_SDL}
147 g_system in 'sdl/g_system.pas',
148 g_touch in 'sdl/g_touch.pas',
149 {$ENDIF}
150 {$IFDEF USE_SDL2}
151 g_system in 'sdl2/g_system.pas',
152 g_touch in 'sdl2/g_touch.pas',
153 {$ENDIF}
155 r_animations in 'opengl/r_animations.pas',
156 r_console in 'opengl/r_console.pas',
157 r_game in 'opengl/r_game.pas',
158 r_gfx in 'opengl/r_gfx.pas',
159 r_graphics in 'opengl/r_graphics.pas',
160 r_items in 'opengl/r_items.pas',
161 r_map in 'opengl/r_map.pas',
162 r_monsters in 'opengl/r_monsters.pas',
163 r_netmaster in 'opengl/r_netmaster.pas',
164 r_panel in 'opengl/r_panel.pas',
165 r_player in 'opengl/r_player.pas',
166 r_playermodel in 'opengl/r_playermodel.pas',
167 r_render in 'opengl/r_render.pas',
168 r_texture in 'opengl/r_texture.pas',
169 r_weapons in 'opengl/r_weapons.pas',
170 r_window in 'opengl/r_window.pas',
172 {$IFDEF USE_FMOD}
173 fmod in '../lib/FMOD/fmod.pas',
174 fmoderrors in '../lib/FMOD/fmoderrors.pas',
175 fmodpresets in '../lib/FMOD/fmodpresets.pas',
176 fmodtypes in '../lib/FMOD/fmodtypes.pas',
177 {$ENDIF}
178 xprofiler in '../shared/xprofiler.pas',
179 binheap in '../shared/binheap.pas',
180 hashtable in '../shared/hashtable.pas',
181 fhashdb in '../shared/fhashdb.pas',
182 idpool in '../shared/idpool.pas',
183 xparser in '../shared/xparser.pas',
184 xdynrec in '../shared/xdynrec.pas',
185 exoma in '../shared/exoma.pas',
186 envvars in '../shared/envvars.pas',
187 g_panel in 'g_panel.pas',
188 g_language in 'g_language.pas',
190 {$IFDEF ENABLE_HOLMES}
191 g_holmes in 'g_holmes.pas',
193 sdlcarcass in '../flexui/sdlcarcass.pas',
194 //sdlstandalone in '../flexui/sdlstandalone.pas',
196 fui_wadread in '../flexui/fui_wadread.pas',
197 fui_common in '../flexui/fui_common.pas',
198 fui_gfx_gl in '../flexui/fui_gfx_gl.pas',
199 fui_events in '../flexui/fui_events.pas',
200 fui_style in '../flexui/fui_style.pas',
201 fui_flexlay in '../flexui/fui_flexlay.pas',
202 fui_ctls in '../flexui/fui_ctls.pas',
203 {$ENDIF}
204 {$I ../shared/vampimg.inc}
206 SysUtils, Classes;
208 {$IFDEF WINDOWS}
209 {$R *.res}
210 {$ENDIF}
212 const
213 autoexecScript = 'autoexec.cfg';
215 var
216 noct: Boolean = False;
217 binPath: AnsiString = '';
218 forceBinDir: Boolean = False;
219 {$IFDEF USE_SDLMIXER}
220 UseNativeMusic: Boolean;
221 {$ENDIF}
223 Time_Old: Int64;
224 NoSound: Boolean;
226 procedure Update ();
227 begin
228 // remember old mobj positions, prepare for update
229 g_Game_PreUpdate();
230 // server: receive client commands for new frame
231 // client: receive game state changes from server
232 if (NetMode = NET_SERVER) then g_Net_Host_Update()
233 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
234 // think
235 g_Game_Update();
236 // server: send any accumulated outgoing data to clients
237 if NetMode = NET_SERVER then g_Net_Flush();
238 end;
240 function ProcessMessage (): Boolean;
241 var
242 i, t: Integer;
243 flag: Boolean;
244 Time, Time_Delta: Int64;
245 Frame: Int64;
246 begin
247 result := sys_HandleInput();
249 Time := GetTickCount64();
250 Time_Delta := Time-Time_Old;
252 flag := false;
254 if wNeedTimeReset then
255 begin
256 Frame := 0;
257 Time_Delta := 28;
258 wNeedTimeReset := false;
259 end;
261 g_Map_ProfilersBegin();
262 g_Mons_ProfilersBegin();
264 t := Time_Delta div 28;
265 if (t > 0) then
266 begin
267 flag := true;
268 for i := 1 to t do
269 Update();
270 end;
272 g_Map_ProfilersEnd();
273 g_Mons_ProfilersEnd();
275 if (gExit = EXIT_QUIT) then
276 begin
277 result := true;
278 exit;
279 end;
281 // Время предыдущего обновления
282 if flag then
283 Time_Old := Time - (Time_Delta mod 28);
285 // don't wait if VSync is on, GL already probably waits enough
286 if gLerpActors then
287 flag := (Time - Frame >= gFrameTime) or gVSync;
289 if flag then
290 begin
291 if gPause or (not gLerpActors) or (gState = STATE_FOLD) then
292 gLerpFactor := 1.0
293 else
294 gLerpFactor := nmin(1.0, (Time - Time_Old) / 28.0);
295 r_Game_Draw;
296 sys_Repaint;
297 Frame := Time
298 end
299 else
300 Sleep(1);
302 e_SoundUpdate();
303 end;
305 procedure DebugOptions;
306 var
307 idx: Integer;
308 arg: AnsiString;
309 mdfo: TStream;
310 {$IFDEF ENABLE_HOLMES}
311 itmp: Integer;
312 valres: Word;
313 {$ENDIF}
314 begin
315 idx := 1;
316 while (idx <= ParamCount) do
317 begin
318 arg := ParamStr(idx);
319 Inc(idx);
320 //if arg = '--twinkletwinkle' then gwin_k8_enable_light_experiments := true;
321 if arg = '--jah' then g_profile_history_size := 100;
322 if arg = '--no-particles' then gpart_dbg_enabled := false;
323 if arg = '--no-los' then gmon_dbg_los_enabled := false;
325 if arg = '--profile-render' then g_profile_frame_draw := true;
326 if arg = '--profile-coldet' then g_profile_collision := true;
327 if arg = '--profile-los' then g_profile_los := true;
329 if arg = '--no-part-phys' then gpart_dbg_phys_enabled := false;
330 if arg = '--no-part-physics' then gpart_dbg_phys_enabled := false;
331 if arg = '--no-particles-phys' then gpart_dbg_phys_enabled := false;
332 if arg = '--no-particles-physics' then gpart_dbg_phys_enabled := false;
333 if arg = '--no-particle-phys' then gpart_dbg_phys_enabled := false;
334 if arg = '--no-particle-physics' then gpart_dbg_phys_enabled := false;
336 if arg = '--debug-input' then g_dbg_input := True;
338 {.$IF DEFINED(D2F_DEBUG)}
339 if arg = '--aimline' then g_dbg_aimline_on := true;
340 {.$ENDIF}
342 {$IFDEF ENABLE_HOLMES}
343 if arg = '--holmes' then begin g_holmes_enabled := true; g_Game_SetDebugMode(); end;
345 if (arg = '--holmes-ui-scale') or (arg = '-holmes-ui-scale') then
346 begin
347 if (idx <= ParamCount) then
348 begin
349 if not conParseFloat(fuiRenderScale, ParamStr(idx)) then fuiRenderScale := 1.0;
350 Inc(idx);
351 end;
352 end;
354 if (arg = '--holmes-font') or (arg = '-holmes-font') then
355 begin
356 if (idx <= ParamCount) then
357 begin
358 itmp := 0;
359 val(ParamStr(idx), itmp, valres);
360 {$IFNDEF HEADLESS}
361 if (valres = 0) and (not g_holmes_imfunctional) then
362 begin
363 case itmp of
364 8: uiContext.font := 'win8';
365 14: uiContext.font := 'win14';
366 16: uiContext.font := 'win16';
367 end;
368 end;
369 {$ELSE}
370 // fuck off, fpc!
371 itmp := itmp;
372 valres := valres;
373 {$ENDIF}
374 Inc(idx);
375 end;
376 end;
377 {$ENDIF}
379 if (arg = '--game-scale') or (arg = '-game-scale') then
380 begin
381 if (idx <= ParamCount) then
382 begin
383 if not conParseFloat(g_dbg_scale, ParamStr(idx)) then g_dbg_scale := 1.0;
384 Inc(idx);
385 end;
386 end;
388 if (arg = '--write-mapdef') or (arg = '-write-mapdef') then
389 begin
390 mdfo := createDiskFile('mapdef.txt');
391 mdfo.WriteBuffer(defaultMapDef[1], Length(defaultMapDef));
392 mdfo.Free();
393 Halt(0);
394 end;
396 if (arg = '--pixel-scale') or (arg = '-pixel-scale') then
397 begin
398 if (idx <= ParamCount) then
399 begin
400 if not conParseFloat(r_pixel_scale, ParamStr(idx)) then r_pixel_scale := 1.0;
401 Inc(idx);
402 end;
403 end;
404 end;
405 end;
407 function GetBinaryPath (): AnsiString;
408 {$IFDEF LINUX}
409 var sl: AnsiString;
410 {$ENDIF}
411 begin
412 result := ExtractFilePath(ParamStr(0));
413 {$IFDEF LINUX}
414 // it may be a symlink; do some guesswork here
415 sl := fpReadLink(ExtractFileName(ParamStr(0)));
416 if (sl = ParamStr(0)) then
417 begin
418 // use current directory, as we don't have anything better
419 //result := '.';
420 GetDir(0, result);
421 end;
422 {$ENDIF}
423 result := fixSlashes(result);
424 if (length(result) > 0) and (result[length(result)] <> '/') then
425 result := result + '/';
426 end;
428 procedure PrintDirs (msg: AnsiString; dirs: SSArray);
429 var dir: AnsiString;
430 begin
431 e_LogWriteln(msg + ':');
432 for dir in dirs do
433 e_LogWriteln(' ' + dir);
434 end;
436 {$IFDEF DARWIN}
437 function NSStringToAnsiString (s: NSString): AnsiString;
438 var i: Integer;
439 begin
440 result := '';
441 for i := 0 to s.length - 1 do
442 result := result + AnsiChar(s.characterAtIndex(i));
443 end;
445 function GetBundlePath (): AnsiString;
446 var pathRef: CFURLRef; pathCFStr: CFStringRef; pathStr: ShortString;
447 begin
448 pathRef := CFBundleCopyBundleURL(CFBundleGetMainBundle());
449 pathCFStr := CFURLCopyFileSystemPath(pathRef, kCFURLPOSIXPathStyle);
450 CFStringGetPascalString(pathCFStr, @pathStr, 255, CFStringGetSystemEncoding());
451 CFRelease(pathRef);
452 CFRelease(pathCFStr);
453 Result := pathStr;
454 end;
455 {$ENDIF}
457 procedure InitPath;
458 var i: Integer; rwdir, rodir: AnsiString; rwdirs, rodirs: SSArray;
460 procedure AddDir (var dirs: SSArray; append: AnsiString);
461 begin
462 SetLength(dirs, Length(dirs) + 1);
463 dirs[High(dirs)] := ExpandFileName(append)
464 end;
466 function IsSep (ch: Char): Boolean;
467 begin
468 {$IFDEF WINDOWS}
469 result := (ch = '/') or (ch = '\');
470 {$ELSE}
471 result := (ch = '/');
472 {$ENDIF}
473 end;
475 function OptimizePath (dir: AnsiString): AnsiString;
476 var i, len: Integer; s: AnsiString;
477 begin
478 i := 1; len := Length(dir); s := '';
479 while i <= len do
480 begin
481 if IsSep(dir[i]) then
482 begin
483 s := s + DirectorySeparator;
484 Inc(i);
485 while (i <= len) and IsSep(dir[i]) do Inc(i);
486 if (i <= len) and (dir[i] = '.') then
487 begin
488 if (i = len) or IsSep(dir[i + 1]) then
489 begin
490 Inc(i)
491 end
492 else if (i + 1 <= len) and (dir[i + 1] = '.') then
493 begin
494 if (i + 1 = len) or IsSep(dir[i + 2]) then
495 begin
496 s := e_UpperDir(s);
497 Inc(i, 2)
498 end
499 end
500 end
501 end
502 else
503 begin
504 s := s + dir[i];
505 Inc(i)
506 end
507 end;
508 result := s
509 end;
511 procedure OptimizeDirs (var dirs: SSArray);
512 var i, j, k: Integer;
513 begin
514 for i := 0 to High(dirs) do
515 dirs[i] := OptimizePath(dirs[i]);
516 // deduplicate
517 i := High(dirs);
518 while i >= 0 do
519 begin
520 j := 0;
521 while j < i do
522 begin
523 if dirs[j] = dirs[i] then
524 begin
525 for k := j + 1 to High(dirs) do
526 dirs[k - 1] := dirs[k];
527 Dec(i);
528 SetLength(dirs, High(dirs))
529 end
530 else
531 begin
532 Inc(j)
533 end
534 end;
535 Dec(i)
536 end
537 end;
539 procedure AddDef (var dirs: SSArray; base: SSArray; append: AnsiString);
540 var s: AnsiString;
541 begin
542 if Length(dirs) = 0 then
543 for s in base do
544 AddDir(dirs, e_CatPath(s, append));
545 OptimizeDirs(dirs)
546 end;
548 function GetDefaultRODirs (): SSArray;
549 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
550 var home: AnsiString;
551 {$ENDIF}
552 {$IFDEF WINDOWS}
553 var appdata: AnsiString;
554 {$ENDIF}
555 {$IFDEF DARWIN}
556 var bundle, s: AnsiString; dirArr: NSArray; i: Integer;
557 {$ENDIF}
558 begin
559 result := nil;
560 {$IFDEF DARWIN}
561 bundle := GetBundlePath();
562 if ExtractFileExt(bundle) <> '.app' then
563 AddDir(result, binpath);
564 {$ELSE}
565 AddDir(result, binPath);
566 {$ENDIF}
567 if forceBinDir = false then
568 begin
569 {$IFDEF USE_SDL2}
570 AddDir(result, SDL_GetBasePath());
571 AddDir(result, SDL_GetPrefPath('', 'doom2df'));
572 {$ENDIF}
573 {$IFDEF WINDOWS}
574 appdata := GetEnvironmentVariable('APPDATA') + '\doom2df';
575 if appdata <> '' then
576 AddDir(result, appdata);
577 {$ENDIF}
578 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
579 AddDir(result, '/usr/share/doom2df');
580 AddDir(result, '/usr/local/share/doom2df');
581 home := GetEnvironmentVariable('HOME');
582 if home <> '' then
583 AddDir(result, e_CatPath(home, '.doom2df'));
584 {$ENDIF}
585 {$IFDEF DARWIN}
586 bundle := GetBundlePath();
587 if bundle <> '' then
588 AddDir(result, e_CatPath(bundle, 'Contents/Resources'));
589 dirArr := NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, true);
590 for i := 0 to dirArr.count - 1 do
591 begin
592 s := NSStringToAnsiString(dirArr.objectAtIndex(i));
593 AddDir(result, e_CatPath(s, 'Doom 2D Forever'))
594 end;
595 {$ENDIF}
596 {$IF DEFINED(ANDROID) AND DEFINED(USE_SDL2)}
597 AddDir(result, SDL_AndroidGetInternalStoragePath());
598 if SDL_AndroidGetExternalStorageState() <> 0 then
599 AddDir(result, SDL_AndroidGetExternalStoragePath());
600 {$ENDIF}
601 end
602 end;
604 function GetDefaultRWDirs (): SSArray;
605 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
606 var home: AnsiString;
607 {$ENDIF}
608 {$IFDEF WINDOWS}
609 var appdata: AnsiString;
610 {$ENDIF}
611 {$IFDEF DARWIN}
612 var bundle, s: AnsiString; dirArr: NSArray; i: Integer;
613 {$ENDIF}
614 begin
615 result := nil;
616 {$IFDEF DARWIN}
617 bundle := GetBundlePath();
618 if ExtractFileExt(bundle) <> '.app' then
619 AddDir(result, binPath);
620 {$ELSE}
621 AddDir(result, binPath);
622 {$ENDIF}
623 if forceBinDir = false then
624 begin
625 {$IFDEF USE_SDL2}
626 AddDir(result, SDL_GetPrefPath('', 'doom2df'));
627 {$ENDIF}
628 {$IFDEF WINDOWS}
629 appdata := GetEnvironmentVariable('APPDATA') + '\doom2df';
630 if appdata <> '' then
631 AddDir(result, appdata);
632 {$ENDIF}
633 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
634 home := GetEnvironmentVariable('HOME');
635 if home <> '' then
636 AddDir(result, e_CatPath(home, '.doom2df'));
637 {$ENDIF}
638 {$IFDEF DARWIN}
639 dirArr := NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, true);
640 for i := 0 to dirArr.count - 1 do
641 begin
642 s := NSStringToAnsiString(dirArr.objectAtIndex(i));
643 AddDir(result, e_CatPath(s, 'Doom 2D Forever'))
644 end;
645 {$ENDIF}
646 {$IF DEFINED(ANDROID) AND DEFINED(USE_SDL2)}
647 if SDL_AndroidGetExternalStorageState() <> 0 then
648 AddDir(result, SDL_AndroidGetExternalStoragePath());
649 {$ENDIF}
650 end
651 end;
653 begin
654 forceBinDir := false;
655 binPath := GetBinaryPath();
657 i := 1;
658 while i < ParamCount do
659 begin
660 case ParamStr(i) of
661 '--like-windoze': forceBinDir := true;
662 '--rw-dir':
663 begin
664 Inc(i);
665 rwdir := ParamStr(i);
666 (* RW *)
667 AddDir(LogDirs, e_CatPath(rwdir, ''));
668 AddDir(SaveDirs, e_CatPath(rwdir, 'data'));
669 AddDir(CacheDirs, e_CatPath(rwdir, 'data/cache'));
670 AddDir(ConfigDirs, e_CatPath(rwdir, ''));
671 AddDir(MapDownloadDirs, e_CatPath(rwdir, 'maps/downloads'));
672 AddDir(WadDownloadDirs, e_CatPath(rwdir, 'wads/downloads'));
673 AddDir(ScreenshotDirs, e_CatPath(rwdir, 'screenshots'));
674 AddDir(StatsDirs, e_CatPath(rwdir, 'stats'));
675 (* RO *)
676 AddDir(DataDirs, e_CatPath(rwdir, 'data'));
677 AddDir(ModelDirs, e_CatPath(rwdir, 'data/models'));
678 AddDir(MegawadDirs, e_CatPath(rwdir, 'maps/megawads'));
679 AddDir(MapDirs, e_CatPath(rwdir, 'maps'));
680 AddDir(WadDirs, e_CatPath(rwdir, 'wads'));
681 end;
682 '--ro-dir':
683 begin
684 Inc(i);
685 rodir := ParamStr(i);
686 (* RO *)
687 AddDir(DataDirs, e_CatPath(rodir, 'data'));
688 AddDir(ModelDirs, e_CatPath(rodir, 'data/models'));
689 AddDir(MegawadDirs, e_CatPath(rodir, 'maps/megawads'));
690 AddDir(MapDirs, e_CatPath(rodir, 'maps'));
691 AddDir(WadDirs, e_CatPath(rodir, 'wads'));
692 end;
693 '--game-wad':
694 begin
695 Inc(i);
696 GameWADName := ParamStr(i);
697 end;
698 '--config':
699 begin
700 Inc(i);
701 gConfigScript := ParamStr(i);
702 end;
703 end;
704 Inc(i)
705 end;
707 // prefer bin dir if it writable and contains game.wad
708 if forceBinDir = false then
709 begin
710 if findDiskWad(binPath + 'data' + '/' + GameWADName) <> '' then
711 if e_CanCreateFilesAt(binPath) then
712 forceBinDir := true
713 end;
715 (* RO *)
716 rodirs := GetDefaultRODirs();
717 AddDef(DataDirs, rodirs, 'data');
718 AddDef(ModelDirs, rodirs, 'data/models');
719 AddDef(MegawadDirs, rodirs, 'maps/megawads');
720 AddDef(MapDirs, rodirs, 'maps');
721 AddDef(WadDirs, rodirs, 'wads');
723 (* RW *)
724 rwdirs := GetDefaultRWDirs();
725 AddDef(LogDirs, rwdirs, '');
726 AddDef(SaveDirs, rwdirs, 'data');
727 AddDef(CacheDirs, rwdirs, 'data/cache');
728 AddDef(ConfigDirs, rwdirs, '');
729 AddDef(MapDownloadDirs, rwdirs, 'maps/downloads');
730 AddDef(WadDownloadDirs, rwdirs, 'wads/downloads');
731 AddDef(ScreenshotDirs, rwdirs, 'screenshots');
732 AddDef(StatsDirs, rwdirs, 'stats');
734 for i := 0 to High(MapDirs) do
735 AddDir(AllMapDirs, MapDirs[i]);
736 for i := 0 to High(MegawadDirs) do
737 AddDir(AllMapDirs, MegawadDirs[i]);
738 OptimizeDirs(AllMapDirs);
740 // HACK: ensure the screenshots folder also has a stats subfolder in it
741 rwdir := e_GetWriteableDir(ScreenshotDirs, false);
742 if rwdir <> '' then CreateDir(rwdir + '/stats');
743 end;
745 procedure EntryParams;
746 var i: Integer;
747 begin
748 i := 1;
749 while i <= ParamCount do
750 begin
751 case ParamStr(i) of
752 '--gdb': noct := true;
753 '--log', '--con-stdout': conbufDumpToStdOut := true;
754 '--safe-log': e_SetSafeSlowLog(true);
755 '--log-file':
756 if i + 1 <= ParamCount then
757 begin
758 Inc(i);
759 LogFileName := ParamStr(i)
760 end;
761 '--no-fbo': glRenderToFBO := false;
762 end;
763 Inc(i)
764 end
765 end;
767 procedure InitLog;
768 var rwdir: AnsiString;
769 begin
770 if LogFileName = '' then
771 begin
772 rwdir := e_GetWriteableDir(LogDirs, false);
773 if rwdir <> '' then
774 begin
775 {$IFDEF HEADLESS}
776 LogFileName := e_CatPath(rwdir, 'Doom2DF_H.log');
777 {$ELSE}
778 LogFileName := e_CatPath(rwdir, 'Doom2DF.log');
779 {$ENDIF}
780 end
781 end;
782 if LogFileName <> '' then
783 e_InitLog(LogFileName, TWriteMode.WM_NEWFILE);
784 e_InitWritelnDriver
785 end;
787 procedure InitPrep;
788 begin
789 e_WriteLog('Doom 2D: Forever version ' + GAME_VERSION + ' proto ' + IntToStr(NET_PROTOCOL_VER), TMsgType.Notify);
790 e_WriteLog('Build arch: ' + g_GetBuildArch(), TMsgType.Notify);
791 e_WriteLog('Build date: ' + GAME_BUILDDATE + ' ' + GAME_BUILDTIME, TMsgType.Notify);
792 e_WriteLog('Build hash: ' + g_GetBuildHash(), TMsgType.Notify);
793 e_WriteLog('Build by: ' + g_GetBuilderName(), TMsgType.Notify);
795 e_LogWritefln('Force bin dir: %s', [forceBinDir], TMsgType.Notify);
796 e_LogWritefln('BINARY PATH: [%s]', [binPath], TMsgType.Notify);
798 PrintDirs('DataDirs', DataDirs);
799 PrintDirs('ModelDirs', ModelDirs);
800 PrintDirs('MegawadDirs', MegawadDirs);
801 PrintDirs('MapDirs', MapDirs);
802 PrintDirs('WadDirs', WadDirs);
804 PrintDirs('LogDirs', LogDirs);
805 PrintDirs('SaveDirs', SaveDirs);
806 PrintDirs('CacheDirs', CacheDirs);
807 PrintDirs('ConfigDirs', ConfigDirs);
808 PrintDirs('ScreenshotDirs', ScreenshotDirs);
809 PrintDirs('StatsDirs', StatsDirs);
810 PrintDirs('MapDownloadDirs', MapDownloadDirs);
811 PrintDirs('WadDownloadDirs', WadDownloadDirs);
813 {$IFDEF HEADLESS}
814 {$IFDEF USE_SDLMIXER}
815 NoSound := False; // hope env has set SDL_AUDIODRIVER to dummy
816 {$ELSE}
817 NoSound := True; // FMOD backend will sort it out
818 {$ENDIF}
819 {$ELSE}
820 NoSound := False;
821 {$ENDIF}
823 GameWAD := e_FindWad(DataDirs, GameWADName);
824 if GameWad = '' then
825 begin
826 e_WriteLog('WAD ' + GameWADName + ' not found in data directories.', TMsgType.Fatal);
827 {$IF DEFINED(USE_SDL2) AND NOT DEFINED(HEADLESS)}
828 if forceBinDir = false then
829 SDL_ShowSimpleMessageBox(
830 SDL_MESSAGEBOX_ERROR,
831 'Doom 2D Forever',
832 PChar('WAD ' + GameWADName + ' not found in data directories.'),
833 nil
834 );
835 {$ENDIF}
836 e_DeinitLog;
837 Halt(1);
838 end
839 end;
841 {$IFDEF ENABLE_HOLMES}
842 procedure InitHolmes;
843 var flexloaded: Boolean;
844 begin
845 flexloaded := true;
846 if not fuiAddWad('flexui.wad') then
847 begin
848 if not fuiAddWad('./data/flexui.wad') then fuiAddWad('./flexui.wad');
849 end;
850 try
851 fuiGfxLoadFont('win8', 'flexui/fonts/win8.fuifont');
852 fuiGfxLoadFont('win14', 'flexui/fonts/win14.fuifont');
853 fuiGfxLoadFont('win16', 'flexui/fonts/win16.fuifont');
854 fuiGfxLoadFont('dos8', 'flexui/fonts/dos8.fuifont');
855 fuiGfxLoadFont('msx6', 'flexui/fonts/msx6.fuifont');
856 except on e: Exception do
857 begin
858 writeln('ERROR loading FlexUI fonts');
859 flexloaded := false;
860 //raise;
861 end;
862 else
863 begin
864 flexloaded := false;
865 //raise;
866 end;
867 end;
868 if flexloaded then
869 begin
870 try
871 e_LogWriteln('FlexUI: loading stylesheet...');
872 uiLoadStyles('flexui/widgets.wgs');
873 except on e: TParserException do
874 begin
875 writeln('ERROR at (', e.tokLine, ',', e.tokCol, '): ', e.message);
876 //raise;
877 flexloaded := false;
878 end;
879 else
880 begin
881 //raise;
882 flexloaded := false;
883 end;
884 end;
885 end;
886 g_holmes_imfunctional := not flexloaded;
887 if not g_holmes_imfunctional then
888 begin
889 uiInitialize();
890 uiContext.font := 'win14';
891 end;
892 if assigned(oglInitCB) then oglInitCB;
893 end;
895 procedure FreeHolmes;
896 begin
897 if assigned(oglDeinitCB) then
898 oglDeinitCB
899 end;
900 {$ENDIF}
902 procedure InitSound;
903 {$IFDEF USE_SDLMIXER}
904 var timiditycfg: AnsiString;
905 var oldcwd, newcwd: RawByteString;
906 {$ENDIF}
907 begin
908 if NoSound = false then
909 begin
910 e_WriteLog('Initializing sound system', TMsgType.Notify);
911 {$IFDEF USE_SDLMIXER}
912 newcwd := '';
913 if UseNativeMusic then
914 SetEnvVar('SDL_NATIVE_MUSIC', '1');
915 timiditycfg := GetEnvironmentVariable('TIMIDITY_CFG');
916 if timiditycfg = '' then
917 begin
918 timiditycfg := 'timidity.cfg';
919 if e_FindResource(ConfigDirs, timiditycfg) OR e_FindResource(DataDirs, timiditycfg) then
920 begin
921 timiditycfg := ExpandFileName(timiditycfg);
922 newcwd := ExtractFileDir(timiditycfg);
923 SetEnvVar('TIMIDITY_CFG', timiditycfg);
924 end
925 else
926 timiditycfg := '';
927 end;
928 e_LogWritefln('TIMIDITY_CFG = "%s"', [timiditycfg]);
929 e_LogWritefln('SDL_NATIVE_MUSIC = "%s"', [GetEnvironmentVariable('SDL_NATIVE_MUSIC')]);
930 {$ENDIF}
931 e_InitSoundSystem(NoSound);
932 {$IFDEF USE_SDLMIXER}
933 if e_TimidityDecoder and (newcwd <> '') then
934 begin
935 (* HACK: Set CWD to load GUS patches relatively to cfg file. *)
936 (* CWD not restored after sound init because timidity *)
937 (* store relative pathes internally and load patches *)
938 (* later. I hope game never relies on CWD. *)
939 oldcwd := '';
940 GetDir(0, oldcwd);
941 ChDir(newcwd);
942 e_logwritefln('WARNING: USED TIMIDITY CONFIG HACK, CWD SWITCHED "%s" -> "%s"', [oldcwd, newcwd]);
943 end;
944 {$ENDIF}
945 end;
946 end;
948 procedure ScreenResize (w, h: Integer);
949 begin
950 r_Render_Resize(w, h);
951 {$IFDEF ENABLE_HOLMES}
952 fuiScrWdt := w;
953 fuiScrHgt := h;
954 {$ENDIF}
955 g_Game_SetupScreenSize;
956 {$IFNDEF ANDROID}
957 (* This will fix menu reset on keyboard showing *)
958 g_Menu_Reset;
959 {$ENDIF}
960 //g_Game_ClearLoading;
961 {$IFDEF ENABLE_HOLMES}
962 if assigned(oglInitCB) then oglInitCB;
963 {$ENDIF}
964 end;
966 procedure Startup;
967 begin
968 Randomize;
969 InitPath;
970 InitLog;
971 InitPrep;
972 e_Input_Initialize;
973 InitSound;
974 sys_Init;
975 sys_CharPress := @CharPress; (* install hook *)
976 sys_ScreenResize := @ScreenResize; (* install hook *)
977 g_Options_SetDefault;
978 g_Options_SetDefaultVideo;
979 g_Console_Initialize;
980 // TODO move load configs here
981 g_Language_Set(gLanguage);
982 r_Render_Initialize;
983 g_Touch_Init;
984 DebugOptions;
985 g_Net_InitLowLevel;
986 // TODO init serverlist
987 {$IFDEF ENABLE_HOLMES}
988 InitHolmes;
989 {$ENDIF}
990 g_Game_Init;
991 {$IFNDEF HEADLESS}
992 g_Menu_Init;
993 g_GUI_Init;
994 {$ENDIF}
995 g_Game_Process_Params;
996 // TODO reload GAME textures
997 g_Console_Init; // welcome message
998 {$IFNDEF HEADLESS}
999 if (not gGameOn) and gAskLanguage then
1000 g_Menu_AskLanguage;
1001 {$ENDIF}
1002 Time_Old := GetTickCount64();
1003 while not ProcessMessage() do begin end;
1004 g_Console_WriteGameConfig;
1005 {$IFNDEF HEADLESS}
1006 g_GUI_Destroy;
1007 g_Menu_Free;
1008 {$ENDIF}
1009 {$IFDEF ENABLE_HOLMES}
1010 FreeHolmes;
1011 {$ENDIF}
1012 g_Net_Slist_ShutdownAll;
1013 g_Net_DeinitLowLevel;
1014 (* g_Touch_Finalize; *)
1015 r_Render_Finalize;
1016 sys_Final;
1017 g_Console_Finalize;
1018 e_ReleaseSoundSystem;
1019 e_Input_Finalize;
1020 e_WriteLog('Shutdown with no errors.', TMsgType.Notify)
1021 end;
1023 procedure InitCVars;
1024 begin
1025 {$IFDEF USE_SDLMIXER}
1026 conRegVar('sdl_native_music', @UseNativeMusic, 'use native midi music output when possible', 'use native midi');
1027 {$IFDEF DARWIN}
1028 UseNativeMusic := true; (* OSX have a good midi support, so why not? *)
1029 {$ELSE}
1030 UseNativeMusic := false;
1031 {$ENDIF}
1032 {$ENDIF}
1033 end;
1035 procedure EntryPoint;
1036 begin
1037 SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]); //k8: fuck off, that's why
1038 InitCVars;
1039 EntryParams;
1040 e_Log_Initialize;
1041 {$IFDEF HEADLESS}
1042 conbufDumpToStdOut := true;
1043 {$ENDIF}
1044 if noct then
1045 Startup
1046 else
1047 try
1048 Startup
1049 except on e: Exception do
1050 e_WriteStackTrace(e.message)
1051 else
1052 e_WriteStackTrace('FATAL ERROR')
1053 end;
1054 e_Log_Finalize
1055 end;
1057 {$IFDEF ANDROID}
1058 function SDL_main (argc: CInt; argv: PPChar): CInt; cdecl;
1059 begin
1060 {$IFDEF ANDROID}
1061 System.argc := argc;
1062 System.argv := argv;
1063 {$ENDIF}
1064 EntryPoint;
1065 result := 0
1066 end;
1068 function JNI_OnLoad (vm: PJavaVM; reserved: pointer): JInt; cdecl;
1069 begin
1070 result:= JNI_VERSION_1_6;
1071 end;
1073 procedure JNI_OnUnload(vm: PJavaVM; reserved: pointer); cdecl;
1074 begin
1075 end;
1077 // DONT REMOVE JNI FUNCTIONS. SPECIAL HANDLING BY FPC.
1078 exports SDL_main name 'SDL_main';
1079 exports JNI_OnLoad name 'JNI_OnLoad';
1080 exports JNI_OnUnload name 'JNI_Unload';
1081 {$ELSE}
1082 begin
1083 EntryPoint
1084 {$ENDIF}
1086 end.