DEADSOFTWARE

gl: add new opengl render (initial implementation)
[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 {$IFDEF ENABLE_GFX}
127 g_gfx in 'g_gfx.pas',
128 {$ENDIF}
129 {$IFDEF ENABLE_GIBS}
130 g_gibs in 'g_gibs.pas',
131 {$ENDIF}
132 {$IFDEF ENABLE_SHELLS}
133 g_shells in 'g_shells.pas',
134 {$ENDIF}
135 {$IFDEF ENABLE_CORPSES}
136 g_corpses in 'g_corpses.pas',
137 {$ENDIF}
138 g_items in 'g_items.pas',
139 g_map in 'g_map.pas',
140 g_monsters in 'g_monsters.pas',
141 g_options in 'g_options.pas',
142 g_phys in 'g_phys.pas',
143 g_player in 'g_player.pas',
144 g_playermodel in 'g_playermodel.pas',
145 g_saveload in 'g_saveload.pas',
146 g_sound in 'g_sound.pas',
147 g_textures in 'g_textures.pas',
148 g_triggers in 'g_triggers.pas',
149 g_weapons in 'g_weapons.pas',
150 g_window in 'g_window.pas',
152 {$IFDEF ENABLE_SYSTEM}
153 {$IFDEF USE_SYSSTUB}
154 g_system in 'stub/g_system.pas',
155 {$ENDIF}
156 {$IFDEF USE_SDL}
157 g_system in 'sdl/g_system.pas',
158 {$ENDIF}
159 {$IFDEF USE_SDL2}
160 g_system in 'sdl2/g_system.pas',
161 {$ENDIF}
162 {$ENDIF}
164 {$IFDEF ENABLE_MENU}
165 g_gui in 'g_gui.pas',
166 g_menu in 'g_menu.pas',
167 {$ENDIF}
169 {$IFDEF ENABLE_RENDER}
170 {$IF DEFINED(USE_OPENGL) OR DEFINED(USE_GLES1) OR DEFINED(USE_GLSTUB)}
171 {$I ../shared/vampimg.inc}
172 r_animations in 'opengl/r_animations.pas',
173 r_console in 'opengl/r_console.pas',
174 r_game in 'opengl/r_game.pas',
175 {$IFDEF ENABLE_GFX}
176 r_gfx in 'opengl/r_gfx.pas',
177 {$ENDIF}
178 r_graphics in 'opengl/r_graphics.pas',
179 r_items in 'opengl/r_items.pas',
180 r_map in 'opengl/r_map.pas',
181 r_monsters in 'opengl/r_monsters.pas',
182 r_netmaster in 'opengl/r_netmaster.pas',
183 r_player in 'opengl/r_player.pas',
184 r_playermodel in 'opengl/r_playermodel.pas',
185 r_render in 'opengl/r_render.pas',
186 r_texture in 'opengl/r_texture.pas',
187 r_textures in 'opengl/r_textures.pas',
188 r_weapons in 'opengl/r_weapons.pas',
189 r_window in 'opengl/r_window.pas',
190 {$IFDEF ENABLE_TOUCH}
191 r_touch in 'opengl/r_touch.pas',
192 {$ENDIF}
193 {$IFDEF ENABLE_MENU}
194 r_gui in 'opengl/r_gui.pas',
195 {$ENDIF}
196 {$ELSEIF DEFINED(USE_STUBRENDER)}
197 r_render in 'renders/stub/r_render.pas',
198 {$ELSEIF DEFINED(USE_NEWGL)}
199 {$I ../shared/vampimg.inc}
200 r_render in 'renders/opengl/r_render.pas',
201 r_atlas in 'renders/opengl/r_atlas.pas',
202 r_textures in 'renders/opengl/r_textures.pas',
203 r_draw in 'renders/opengl/r_draw.pas',
204 r_map in 'renders/opengl/r_map.pas',
205 {$ELSE}
206 {$FATAL render driver not selected}
207 {$ENDIF}
208 {$ENDIF}
210 {$IFDEF USE_FMOD}
211 fmod in '../lib/FMOD/fmod.pas',
212 fmoderrors in '../lib/FMOD/fmoderrors.pas',
213 fmodpresets in '../lib/FMOD/fmodpresets.pas',
214 fmodtypes in '../lib/FMOD/fmodtypes.pas',
215 {$ENDIF}
216 xprofiler in '../shared/xprofiler.pas',
217 binheap in '../shared/binheap.pas',
218 hashtable in '../shared/hashtable.pas',
219 fhashdb in '../shared/fhashdb.pas',
220 idpool in '../shared/idpool.pas',
221 xparser in '../shared/xparser.pas',
222 xdynrec in '../shared/xdynrec.pas',
223 exoma in '../shared/exoma.pas',
224 envvars in '../shared/envvars.pas',
225 g_panel in 'g_panel.pas',
226 g_language in 'g_language.pas',
228 {$IFDEF ENABLE_HOLMES}
229 g_holmes in 'g_holmes.pas',
231 sdlcarcass in '../flexui/sdlcarcass.pas',
232 //sdlstandalone in '../flexui/sdlstandalone.pas',
234 fui_wadread in '../flexui/fui_wadread.pas',
235 fui_common in '../flexui/fui_common.pas',
236 fui_gfx_gl in '../flexui/fui_gfx_gl.pas',
237 fui_events in '../flexui/fui_events.pas',
238 fui_style in '../flexui/fui_style.pas',
239 fui_flexlay in '../flexui/fui_flexlay.pas',
240 fui_ctls in '../flexui/fui_ctls.pas',
241 {$ENDIF}
243 SysUtils, Classes;
245 {$IFDEF WINDOWS}
246 {$R *.res}
247 {$ENDIF}
249 const
250 autoexecScript = 'autoexec.cfg';
252 var
253 noct: Boolean = False;
254 binPath: AnsiString = '';
255 forceBinDir: Boolean = False;
256 {$IFDEF USE_SDLMIXER}
257 UseNativeMusic: Boolean;
258 {$ENDIF}
260 Time_Old: Int64;
261 NoSound: Boolean;
263 procedure Update ();
264 begin
265 // remember old mobj positions, prepare for update
266 g_Game_PreUpdate();
267 // server: receive client commands for new frame
268 // client: receive game state changes from server
269 if (NetMode = NET_SERVER) then g_Net_Host_Update()
270 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
271 // think
272 {$IFDEF ENABLE_RENDER}
273 r_Render_Update;
274 {$ENDIF}
275 g_Game_Update();
276 // server: send any accumulated outgoing data to clients
277 if NetMode = NET_SERVER then g_Net_Flush();
278 end;
280 function ProcessMessage (): Boolean;
281 var
282 i, t: Integer;
283 flag: Boolean;
284 Time, Time_Delta: Int64;
285 Frame: Int64;
286 begin
287 {$IFDEF ENABLE_SYSTEM}
288 Result := sys_HandleInput();
289 {$ELSE}
290 Result := False;
291 {$ENDIF}
293 Time := GetTickCount64();
294 Time_Delta := Time-Time_Old;
296 flag := false;
298 if wNeedTimeReset then
299 begin
300 Frame := 0;
301 Time_Delta := 28;
302 wNeedTimeReset := false;
303 end;
305 g_Map_ProfilersBegin();
306 g_Mons_ProfilersBegin();
308 t := Time_Delta div 28;
309 if (t > 0) then
310 begin
311 flag := true;
312 for i := 1 to t do
313 Update();
314 end;
316 g_Map_ProfilersEnd();
317 g_Mons_ProfilersEnd();
319 if (gExit = EXIT_QUIT) then
320 begin
321 result := true;
322 exit;
323 end;
325 // Время предыдущего обновления
326 if flag then
327 Time_Old := Time - (Time_Delta mod 28);
329 // don't wait if VSync is on, GL already probably waits enough
330 if gLerpActors then
331 flag := (Time - Frame >= gFrameTime) or gVSync;
333 if flag then
334 begin
335 if gPause or (not gLerpActors) or (gState = STATE_FOLD) then
336 gLerpFactor := 1.0
337 else
338 gLerpFactor := nmin(1.0, (Time - Time_Old) / 28.0);
339 {$IFDEF ENABLE_RENDER}
340 r_Render_Draw;
341 {$ENDIF}
342 {$IFDEF ENABLE_SYSTEM}
343 sys_Repaint;
344 {$ENDIF}
345 Frame := Time
346 end
347 else
348 Sleep(1);
350 e_SoundUpdate();
351 end;
353 procedure DebugOptions;
354 var
355 idx: Integer;
356 arg: AnsiString;
357 mdfo: TStream;
358 {$IFDEF ENABLE_HOLMES}
359 itmp: Integer;
360 valres: Word;
361 {$ENDIF}
362 begin
363 idx := 1;
364 while (idx <= ParamCount) do
365 begin
366 arg := ParamStr(idx);
367 Inc(idx);
368 //if arg = '--twinkletwinkle' then gwin_k8_enable_light_experiments := true;
369 if arg = '--jah' then g_profile_history_size := 100;
370 if arg = '--no-los' then gmon_dbg_los_enabled := false;
372 if arg = '--profile-render' then g_profile_frame_draw := true;
373 if arg = '--profile-coldet' then g_profile_collision := true;
374 if arg = '--profile-los' then g_profile_los := true;
376 {$IFDEF ENABLE_GFX}
377 if arg = '--no-particles' then gpart_dbg_enabled := false;
378 if arg = '--no-part-phys' then gpart_dbg_phys_enabled := false;
379 if arg = '--no-part-physics' then gpart_dbg_phys_enabled := false;
380 if arg = '--no-particles-phys' then gpart_dbg_phys_enabled := false;
381 if arg = '--no-particles-physics' then gpart_dbg_phys_enabled := false;
382 if arg = '--no-particle-phys' then gpart_dbg_phys_enabled := false;
383 if arg = '--no-particle-physics' then gpart_dbg_phys_enabled := false;
384 {$ENDIF}
386 if arg = '--debug-input' then g_dbg_input := True;
388 {.$IF DEFINED(D2F_DEBUG)}
389 if arg = '--aimline' then g_dbg_aimline_on := true;
390 {.$ENDIF}
392 {$IFDEF ENABLE_HOLMES}
393 if arg = '--holmes' then begin g_holmes_enabled := true; g_Game_SetDebugMode(); end;
395 if (arg = '--holmes-ui-scale') or (arg = '-holmes-ui-scale') then
396 begin
397 if (idx <= ParamCount) then
398 begin
399 if not conParseFloat(fuiRenderScale, ParamStr(idx)) then fuiRenderScale := 1.0;
400 Inc(idx);
401 end;
402 end;
404 if (arg = '--holmes-font') or (arg = '-holmes-font') then
405 begin
406 if (idx <= ParamCount) then
407 begin
408 itmp := 0;
409 val(ParamStr(idx), itmp, valres);
410 if (valres = 0) and (not g_holmes_imfunctional) then
411 begin
412 case itmp of
413 8: uiContext.font := 'win8';
414 14: uiContext.font := 'win14';
415 16: uiContext.font := 'win16';
416 end;
417 end;
418 Inc(idx);
419 end;
420 end;
421 {$ENDIF}
423 if (arg = '--game-scale') or (arg = '-game-scale') then
424 begin
425 if (idx <= ParamCount) then
426 begin
427 if not conParseFloat(g_dbg_scale, ParamStr(idx)) then g_dbg_scale := 1.0;
428 Inc(idx);
429 end;
430 end;
432 if (arg = '--write-mapdef') or (arg = '-write-mapdef') then
433 begin
434 mdfo := createDiskFile('mapdef.txt');
435 mdfo.WriteBuffer(defaultMapDef[1], Length(defaultMapDef));
436 mdfo.Free();
437 Halt(0);
438 end;
440 if (arg = '--pixel-scale') or (arg = '-pixel-scale') then
441 begin
442 if (idx <= ParamCount) then
443 begin
444 if not conParseFloat(r_pixel_scale, ParamStr(idx)) then r_pixel_scale := 1.0;
445 Inc(idx);
446 end;
447 end;
448 end;
449 end;
451 function GetBinaryPath (): AnsiString;
452 {$IFDEF LINUX}
453 var sl: AnsiString;
454 {$ENDIF}
455 begin
456 result := ExtractFilePath(ParamStr(0));
457 {$IFDEF LINUX}
458 // it may be a symlink; do some guesswork here
459 sl := fpReadLink(ExtractFileName(ParamStr(0)));
460 if (sl = ParamStr(0)) then
461 begin
462 // use current directory, as we don't have anything better
463 //result := '.';
464 GetDir(0, result);
465 end;
466 {$ENDIF}
467 result := fixSlashes(result);
468 if (length(result) > 0) and (result[length(result)] <> '/') then
469 result := result + '/';
470 end;
472 procedure PrintDirs (msg: AnsiString; dirs: SSArray);
473 var dir: AnsiString;
474 begin
475 e_LogWriteln(msg + ':');
476 for dir in dirs do
477 e_LogWriteln(' ' + dir);
478 end;
480 {$IFDEF DARWIN}
481 function NSStringToAnsiString (s: NSString): AnsiString;
482 var i: Integer;
483 begin
484 result := '';
485 for i := 0 to s.length - 1 do
486 result := result + AnsiChar(s.characterAtIndex(i));
487 end;
489 function GetBundlePath (): AnsiString;
490 var pathRef: CFURLRef; pathCFStr: CFStringRef; pathStr: ShortString;
491 begin
492 pathRef := CFBundleCopyBundleURL(CFBundleGetMainBundle());
493 pathCFStr := CFURLCopyFileSystemPath(pathRef, kCFURLPOSIXPathStyle);
494 CFStringGetPascalString(pathCFStr, @pathStr, 255, CFStringGetSystemEncoding());
495 CFRelease(pathRef);
496 CFRelease(pathCFStr);
497 Result := pathStr;
498 end;
499 {$ENDIF}
501 procedure InitPath;
502 var i: Integer; rwdir, rodir: AnsiString; rwdirs, rodirs: SSArray;
504 procedure AddDir (var dirs: SSArray; append: AnsiString);
505 begin
506 SetLength(dirs, Length(dirs) + 1);
507 dirs[High(dirs)] := ExpandFileName(append)
508 end;
510 function IsSep (ch: Char): Boolean;
511 begin
512 {$IFDEF WINDOWS}
513 result := (ch = '/') or (ch = '\');
514 {$ELSE}
515 result := (ch = '/');
516 {$ENDIF}
517 end;
519 function OptimizePath (dir: AnsiString): AnsiString;
520 var i, len: Integer; s: AnsiString;
521 begin
522 i := 1; len := Length(dir); s := '';
523 while i <= len do
524 begin
525 if IsSep(dir[i]) then
526 begin
527 s := s + DirectorySeparator;
528 Inc(i);
529 while (i <= len) and IsSep(dir[i]) do Inc(i);
530 if (i <= len) and (dir[i] = '.') then
531 begin
532 if (i = len) or IsSep(dir[i + 1]) then
533 begin
534 Inc(i)
535 end
536 else if (i + 1 <= len) and (dir[i + 1] = '.') then
537 begin
538 if (i + 1 = len) or IsSep(dir[i + 2]) then
539 begin
540 s := e_UpperDir(s);
541 Inc(i, 2)
542 end
543 end
544 end
545 end
546 else
547 begin
548 s := s + dir[i];
549 Inc(i)
550 end
551 end;
552 result := s
553 end;
555 procedure OptimizeDirs (var dirs: SSArray);
556 var i, j, k: Integer;
557 begin
558 for i := 0 to High(dirs) do
559 dirs[i] := OptimizePath(dirs[i]);
560 // deduplicate
561 i := High(dirs);
562 while i >= 0 do
563 begin
564 j := 0;
565 while j < i do
566 begin
567 if dirs[j] = dirs[i] then
568 begin
569 for k := j + 1 to High(dirs) do
570 dirs[k - 1] := dirs[k];
571 Dec(i);
572 SetLength(dirs, High(dirs))
573 end
574 else
575 begin
576 Inc(j)
577 end
578 end;
579 Dec(i)
580 end
581 end;
583 procedure AddDef (var dirs: SSArray; base: SSArray; append: AnsiString);
584 var s: AnsiString;
585 begin
586 if Length(dirs) = 0 then
587 for s in base do
588 AddDir(dirs, e_CatPath(s, append));
589 OptimizeDirs(dirs)
590 end;
592 function GetDefaultRODirs (): SSArray;
593 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
594 var home: AnsiString;
595 {$ENDIF}
596 {$IFDEF WINDOWS}
597 var appdata: AnsiString;
598 {$ENDIF}
599 {$IFDEF DARWIN}
600 var bundle, s: AnsiString; dirArr: NSArray; i: Integer;
601 {$ENDIF}
602 begin
603 result := nil;
604 {$IFDEF DARWIN}
605 bundle := GetBundlePath();
606 if ExtractFileExt(bundle) <> '.app' then
607 AddDir(result, binpath);
608 {$ELSE}
609 AddDir(result, binPath);
610 {$ENDIF}
611 if forceBinDir = false then
612 begin
613 {$IFDEF USE_SDL2}
614 AddDir(result, SDL_GetBasePath());
615 AddDir(result, SDL_GetPrefPath('', 'doom2df'));
616 {$ENDIF}
617 {$IFDEF WINDOWS}
618 appdata := GetEnvironmentVariable('APPDATA') + '\doom2df';
619 if appdata <> '' then
620 AddDir(result, appdata);
621 {$ENDIF}
622 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
623 AddDir(result, '/usr/share/doom2df');
624 AddDir(result, '/usr/local/share/doom2df');
625 home := GetEnvironmentVariable('HOME');
626 if home <> '' then
627 AddDir(result, e_CatPath(home, '.doom2df'));
628 {$ENDIF}
629 {$IFDEF DARWIN}
630 bundle := GetBundlePath();
631 if bundle <> '' then
632 AddDir(result, e_CatPath(bundle, 'Contents/Resources'));
633 dirArr := NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, true);
634 for i := 0 to dirArr.count - 1 do
635 begin
636 s := NSStringToAnsiString(dirArr.objectAtIndex(i));
637 AddDir(result, e_CatPath(s, 'Doom 2D Forever'))
638 end;
639 {$ENDIF}
640 {$IF DEFINED(ANDROID) AND DEFINED(USE_SDL2)}
641 AddDir(result, SDL_AndroidGetInternalStoragePath());
642 if SDL_AndroidGetExternalStorageState() <> 0 then
643 AddDir(result, SDL_AndroidGetExternalStoragePath());
644 {$ENDIF}
645 end
646 end;
648 function GetDefaultRWDirs (): SSArray;
649 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
650 var home: AnsiString;
651 {$ENDIF}
652 {$IFDEF WINDOWS}
653 var appdata: AnsiString;
654 {$ENDIF}
655 {$IFDEF DARWIN}
656 var bundle, s: AnsiString; dirArr: NSArray; i: Integer;
657 {$ENDIF}
658 begin
659 result := nil;
660 {$IFDEF DARWIN}
661 bundle := GetBundlePath();
662 if ExtractFileExt(bundle) <> '.app' then
663 AddDir(result, binPath);
664 {$ELSE}
665 AddDir(result, binPath);
666 {$ENDIF}
667 if forceBinDir = false then
668 begin
669 {$IFDEF USE_SDL2}
670 AddDir(result, SDL_GetPrefPath('', 'doom2df'));
671 {$ENDIF}
672 {$IFDEF WINDOWS}
673 appdata := GetEnvironmentVariable('APPDATA') + '\doom2df';
674 if appdata <> '' then
675 AddDir(result, appdata);
676 {$ENDIF}
677 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
678 home := GetEnvironmentVariable('HOME');
679 if home <> '' then
680 AddDir(result, e_CatPath(home, '.doom2df'));
681 {$ENDIF}
682 {$IFDEF DARWIN}
683 dirArr := NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, true);
684 for i := 0 to dirArr.count - 1 do
685 begin
686 s := NSStringToAnsiString(dirArr.objectAtIndex(i));
687 AddDir(result, e_CatPath(s, 'Doom 2D Forever'))
688 end;
689 {$ENDIF}
690 {$IF DEFINED(ANDROID) AND DEFINED(USE_SDL2)}
691 if SDL_AndroidGetExternalStorageState() <> 0 then
692 AddDir(result, SDL_AndroidGetExternalStoragePath());
693 {$ENDIF}
694 end
695 end;
697 begin
698 forceBinDir := false;
699 binPath := GetBinaryPath();
701 i := 1;
702 while i < ParamCount do
703 begin
704 case ParamStr(i) of
705 '--like-windoze': forceBinDir := true;
706 '--rw-dir':
707 begin
708 Inc(i);
709 rwdir := ParamStr(i);
710 (* RW *)
711 AddDir(LogDirs, e_CatPath(rwdir, ''));
712 AddDir(SaveDirs, e_CatPath(rwdir, 'data'));
713 AddDir(CacheDirs, e_CatPath(rwdir, 'data/cache'));
714 AddDir(ConfigDirs, e_CatPath(rwdir, ''));
715 AddDir(MapDownloadDirs, e_CatPath(rwdir, 'maps/downloads'));
716 AddDir(WadDownloadDirs, e_CatPath(rwdir, 'wads/downloads'));
717 AddDir(ScreenshotDirs, e_CatPath(rwdir, 'screenshots'));
718 AddDir(StatsDirs, e_CatPath(rwdir, 'stats'));
719 (* RO *)
720 AddDir(DataDirs, e_CatPath(rwdir, 'data'));
721 AddDir(ModelDirs, e_CatPath(rwdir, 'data/models'));
722 AddDir(MegawadDirs, e_CatPath(rwdir, 'maps/megawads'));
723 AddDir(MapDirs, e_CatPath(rwdir, 'maps'));
724 AddDir(WadDirs, e_CatPath(rwdir, 'wads'));
725 end;
726 '--ro-dir':
727 begin
728 Inc(i);
729 rodir := ParamStr(i);
730 (* RO *)
731 AddDir(DataDirs, e_CatPath(rodir, 'data'));
732 AddDir(ModelDirs, e_CatPath(rodir, 'data/models'));
733 AddDir(MegawadDirs, e_CatPath(rodir, 'maps/megawads'));
734 AddDir(MapDirs, e_CatPath(rodir, 'maps'));
735 AddDir(WadDirs, e_CatPath(rodir, 'wads'));
736 end;
737 '--game-wad':
738 begin
739 Inc(i);
740 GameWADName := ParamStr(i);
741 end;
742 '--config':
743 begin
744 Inc(i);
745 gConfigScript := ParamStr(i);
746 end;
747 end;
748 Inc(i)
749 end;
751 // prefer bin dir if it writable and contains game.wad
752 if forceBinDir = false then
753 begin
754 if findDiskWad(binPath + 'data' + '/' + GameWADName) <> '' then
755 if e_CanCreateFilesAt(binPath) then
756 forceBinDir := true
757 end;
759 (* RO *)
760 rodirs := GetDefaultRODirs();
761 AddDef(DataDirs, rodirs, 'data');
762 AddDef(ModelDirs, rodirs, 'data/models');
763 AddDef(MegawadDirs, rodirs, 'maps/megawads');
764 AddDef(MapDirs, rodirs, 'maps');
765 AddDef(WadDirs, rodirs, 'wads');
767 (* RW *)
768 rwdirs := GetDefaultRWDirs();
769 AddDef(LogDirs, rwdirs, '');
770 AddDef(SaveDirs, rwdirs, 'data');
771 AddDef(CacheDirs, rwdirs, 'data/cache');
772 AddDef(ConfigDirs, rwdirs, '');
773 AddDef(MapDownloadDirs, rwdirs, 'maps/downloads');
774 AddDef(WadDownloadDirs, rwdirs, 'wads/downloads');
775 AddDef(ScreenshotDirs, rwdirs, 'screenshots');
776 AddDef(StatsDirs, rwdirs, 'stats');
778 for i := 0 to High(MapDirs) do
779 AddDir(AllMapDirs, MapDirs[i]);
780 for i := 0 to High(MegawadDirs) do
781 AddDir(AllMapDirs, MegawadDirs[i]);
782 OptimizeDirs(AllMapDirs);
784 // HACK: ensure the screenshots folder also has a stats subfolder in it
785 rwdir := e_GetWriteableDir(ScreenshotDirs, false);
786 if rwdir <> '' then CreateDir(rwdir + '/stats');
787 end;
789 procedure EntryParams;
790 var i: Integer;
791 begin
792 i := 1;
793 while i <= ParamCount do
794 begin
795 case ParamStr(i) of
796 '--gdb': noct := true;
797 '--log', '--con-stdout': conbufDumpToStdOut := true;
798 '--safe-log': e_SetSafeSlowLog(true);
799 '--log-file':
800 if i + 1 <= ParamCount then
801 begin
802 Inc(i);
803 LogFileName := ParamStr(i)
804 end;
805 '--no-fbo': glRenderToFBO := false;
806 end;
807 Inc(i)
808 end
809 end;
811 procedure InitLog;
812 var rwdir: AnsiString;
813 begin
814 if LogFileName = '' then
815 begin
816 rwdir := e_GetWriteableDir(LogDirs, false);
817 if rwdir <> '' then
818 begin
819 {$IFDEF HEADLESS}
820 LogFileName := e_CatPath(rwdir, 'Doom2DF_H.log');
821 {$ELSE}
822 LogFileName := e_CatPath(rwdir, 'Doom2DF.log');
823 {$ENDIF}
824 end
825 end;
826 if LogFileName <> '' then
827 e_InitLog(LogFileName, TWriteMode.WM_NEWFILE);
828 e_InitWritelnDriver
829 end;
831 procedure InitPrep;
832 begin
833 e_WriteLog('Doom 2D: Forever version ' + GAME_VERSION + ' proto ' + IntToStr(NET_PROTOCOL_VER), TMsgType.Notify);
834 e_WriteLog('Build arch: ' + g_GetBuildArch(), TMsgType.Notify);
835 e_WriteLog('Build date: ' + GAME_BUILDDATE + ' ' + GAME_BUILDTIME, TMsgType.Notify);
836 e_WriteLog('Build hash: ' + g_GetBuildHash(), TMsgType.Notify);
837 e_WriteLog('Build by: ' + g_GetBuilderName(), TMsgType.Notify);
839 e_LogWritefln('Force bin dir: %s', [forceBinDir], TMsgType.Notify);
840 e_LogWritefln('BINARY PATH: [%s]', [binPath], TMsgType.Notify);
842 PrintDirs('DataDirs', DataDirs);
843 PrintDirs('ModelDirs', ModelDirs);
844 PrintDirs('MegawadDirs', MegawadDirs);
845 PrintDirs('MapDirs', MapDirs);
846 PrintDirs('WadDirs', WadDirs);
848 PrintDirs('LogDirs', LogDirs);
849 PrintDirs('SaveDirs', SaveDirs);
850 PrintDirs('CacheDirs', CacheDirs);
851 PrintDirs('ConfigDirs', ConfigDirs);
852 PrintDirs('ScreenshotDirs', ScreenshotDirs);
853 PrintDirs('StatsDirs', StatsDirs);
854 PrintDirs('MapDownloadDirs', MapDownloadDirs);
855 PrintDirs('WadDownloadDirs', WadDownloadDirs);
857 {$IFDEF HEADLESS}
858 {$IFDEF USE_SDLMIXER}
859 NoSound := False; // hope env has set SDL_AUDIODRIVER to dummy
860 {$ELSE}
861 NoSound := True; // FMOD backend will sort it out
862 {$ENDIF}
863 {$ELSE}
864 NoSound := False;
865 {$ENDIF}
867 GameWAD := e_FindWad(DataDirs, GameWADName);
868 if GameWad = '' then
869 begin
870 e_WriteLog('WAD ' + GameWADName + ' not found in data directories.', TMsgType.Fatal);
871 {$IF DEFINED(USE_SDL2) AND NOT DEFINED(HEADLESS)}
872 if forceBinDir = false then
873 SDL_ShowSimpleMessageBox(
874 SDL_MESSAGEBOX_ERROR,
875 'Doom 2D Forever',
876 PChar('WAD ' + GameWADName + ' not found in data directories.'),
877 nil
878 );
879 {$ENDIF}
880 e_DeinitLog;
881 Halt(1);
882 end
883 end;
885 {$IFDEF ENABLE_HOLMES}
886 procedure InitHolmes;
887 var flexloaded: Boolean;
888 begin
889 flexloaded := true;
890 if not fuiAddWad('flexui.wad') then
891 begin
892 if not fuiAddWad('./data/flexui.wad') then fuiAddWad('./flexui.wad');
893 end;
894 try
895 fuiGfxLoadFont('win8', 'flexui/fonts/win8.fuifont');
896 fuiGfxLoadFont('win14', 'flexui/fonts/win14.fuifont');
897 fuiGfxLoadFont('win16', 'flexui/fonts/win16.fuifont');
898 fuiGfxLoadFont('dos8', 'flexui/fonts/dos8.fuifont');
899 fuiGfxLoadFont('msx6', 'flexui/fonts/msx6.fuifont');
900 except on e: Exception do
901 begin
902 writeln('ERROR loading FlexUI fonts');
903 flexloaded := false;
904 //raise;
905 end;
906 else
907 begin
908 flexloaded := false;
909 //raise;
910 end;
911 end;
912 if flexloaded then
913 begin
914 try
915 e_LogWriteln('FlexUI: loading stylesheet...');
916 uiLoadStyles('flexui/widgets.wgs');
917 except on e: TParserException do
918 begin
919 writeln('ERROR at (', e.tokLine, ',', e.tokCol, '): ', e.message);
920 //raise;
921 flexloaded := false;
922 end;
923 else
924 begin
925 //raise;
926 flexloaded := false;
927 end;
928 end;
929 end;
930 g_holmes_imfunctional := not flexloaded;
931 if not g_holmes_imfunctional then
932 begin
933 uiInitialize();
934 uiContext.font := 'win14';
935 end;
936 if assigned(oglInitCB) then oglInitCB;
937 end;
939 procedure FreeHolmes;
940 begin
941 if assigned(oglDeinitCB) then
942 oglDeinitCB
943 end;
944 {$ENDIF}
946 procedure InitSound;
947 {$IFDEF USE_SDLMIXER}
948 var timiditycfg: AnsiString;
949 var oldcwd, newcwd: RawByteString;
950 {$ENDIF}
951 begin
952 if NoSound = false then
953 begin
954 e_WriteLog('Initializing sound system', TMsgType.Notify);
955 {$IFDEF USE_SDLMIXER}
956 newcwd := '';
957 if UseNativeMusic then
958 SetEnvVar('SDL_NATIVE_MUSIC', '1');
959 timiditycfg := GetEnvironmentVariable('TIMIDITY_CFG');
960 if timiditycfg = '' then
961 begin
962 timiditycfg := 'timidity.cfg';
963 if e_FindResource(ConfigDirs, timiditycfg) OR e_FindResource(DataDirs, timiditycfg) then
964 begin
965 timiditycfg := ExpandFileName(timiditycfg);
966 newcwd := ExtractFileDir(timiditycfg);
967 SetEnvVar('TIMIDITY_CFG', timiditycfg);
968 end
969 else
970 timiditycfg := '';
971 end;
972 e_LogWritefln('TIMIDITY_CFG = "%s"', [timiditycfg]);
973 e_LogWritefln('SDL_NATIVE_MUSIC = "%s"', [GetEnvironmentVariable('SDL_NATIVE_MUSIC')]);
974 {$ENDIF}
975 e_InitSoundSystem(NoSound);
976 {$IFDEF USE_SDLMIXER}
977 if e_TimidityDecoder and (newcwd <> '') then
978 begin
979 (* HACK: Set CWD to load GUS patches relatively to cfg file. *)
980 (* CWD not restored after sound init because timidity *)
981 (* store relative pathes internally and load patches *)
982 (* later. I hope game never relies on CWD. *)
983 oldcwd := '';
984 GetDir(0, oldcwd);
985 ChDir(newcwd);
986 e_logwritefln('WARNING: USED TIMIDITY CONFIG HACK, CWD SWITCHED "%s" -> "%s"', [oldcwd, newcwd]);
987 end;
988 {$ENDIF}
989 end;
990 end;
992 procedure ScreenResize (w, h: Integer);
993 begin
994 {$IFDEF ENABLE_RENDER}
995 r_Render_Resize(w, h);
996 {$IFDEF ENABLE_HOLMES}
997 fuiScrWdt := w;
998 fuiScrHgt := h;
999 {$ENDIF}
1000 {$IFNDEF ANDROID}
1001 (* This will fix menu reset on keyboard showing *)
1002 {$IFDEF ENABLE_MENU}
1003 g_Menu_Reset;
1004 {$ENDIF}
1005 {$ENDIF}
1006 //g_Game_ClearLoading;
1007 {$IFDEF ENABLE_HOLMES}
1008 if assigned(oglInitCB) then oglInitCB;
1009 {$ENDIF}
1010 {$ENDIF}
1011 end;
1013 procedure Startup;
1014 begin
1015 Randomize;
1016 InitPath;
1017 InitLog;
1018 InitPrep;
1019 e_Input_Initialize;
1020 InitSound;
1021 {$IFDEF ENABLE_SYSTEM}
1022 sys_Init;
1023 sys_CharPress := @CharPress; (* install hook *)
1024 sys_ScreenResize := @ScreenResize; (* install hook *)
1025 {$ENDIF}
1026 g_Options_SetDefault;
1027 g_Options_SetDefaultVideo;
1028 g_Console_Initialize;
1029 // TODO move load configs here
1030 g_Language_Set(gLanguage);
1031 {$IFDEF ENABLE_RENDER}
1032 r_Render_Initialize;
1033 {$ENDIF}
1034 DebugOptions;
1035 g_Net_InitLowLevel;
1036 // TODO init serverlist
1037 {$IFDEF ENABLE_HOLMES}
1038 InitHolmes;
1039 {$ENDIF}
1040 {$IFDEF ENABLE_RENDER}
1041 g_PlayerModel_LoadAll;
1042 r_Render_Load;
1043 {$ELSE}
1044 g_PlayerModel_LoadFake('doomer', 'doomer.wad');
1045 {$ENDIF}
1046 g_Game_Init;
1047 {$IFDEF ENABLE_MENU}
1048 g_Menu_Init;
1049 {$ENDIF}
1050 g_Game_Process_Params;
1051 // TODO reload GAME textures
1052 g_Console_Init; // welcome message
1053 {$IFDEF ENABLE_MENU}
1054 if (not gGameOn) and gAskLanguage then
1055 g_Menu_AskLanguage;
1056 {$ENDIF}
1057 Time_Old := GetTickCount64();
1058 while not ProcessMessage() do begin end;
1059 g_Console_WriteGameConfig;
1060 {$IFDEF ENABLE_MENU}
1061 g_GUI_Destroy;
1062 g_Menu_Free;
1063 {$ENDIF}
1064 {$IFDEF ENABLE_RENDER}
1065 r_Render_Free;
1066 {$ENDIF}
1067 {$IFDEF ENABLE_HOLMES}
1068 FreeHolmes;
1069 {$ENDIF}
1070 g_Net_Slist_ShutdownAll;
1071 g_Net_DeinitLowLevel;
1072 (* g_Touch_Finalize; *)
1073 {$IFDEF ENABLE_RENDER}
1074 r_Render_Finalize;
1075 {$ENDIF}
1076 {$IFDEF ENABLE_SYSTEM}
1077 sys_Final;
1078 {$ENDIF}
1079 g_Console_Finalize;
1080 e_ReleaseSoundSystem;
1081 e_Input_Finalize;
1082 e_WriteLog('Shutdown with no errors.', TMsgType.Notify)
1083 end;
1085 procedure InitCVars;
1086 begin
1087 {$IFDEF USE_SDLMIXER}
1088 conRegVar('sdl_native_music', @UseNativeMusic, 'use native midi music output when possible', 'use native midi');
1089 {$IFDEF DARWIN}
1090 UseNativeMusic := true; (* OSX have a good midi support, so why not? *)
1091 {$ELSE}
1092 UseNativeMusic := false;
1093 {$ENDIF}
1094 {$ENDIF}
1095 end;
1097 procedure EntryPoint;
1098 begin
1099 SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]); //k8: fuck off, that's why
1100 InitCVars;
1101 EntryParams;
1102 e_Log_Initialize;
1103 {$IFDEF HEADLESS}
1104 conbufDumpToStdOut := true;
1105 {$ENDIF}
1106 if noct then
1107 Startup
1108 else
1109 try
1110 Startup
1111 except on e: Exception do
1112 e_WriteStackTrace(e.message)
1113 else
1114 e_WriteStackTrace('FATAL ERROR')
1115 end;
1116 e_Log_Finalize
1117 end;
1119 {$IFDEF ANDROID}
1120 function SDL_main (argc: CInt; argv: PPChar): CInt; cdecl;
1121 begin
1122 {$IFDEF ANDROID}
1123 System.argc := argc;
1124 System.argv := argv;
1125 {$ENDIF}
1126 EntryPoint;
1127 result := 0
1128 end;
1130 function JNI_OnLoad (vm: PJavaVM; reserved: pointer): JInt; cdecl;
1131 begin
1132 result:= JNI_VERSION_1_6;
1133 end;
1135 procedure JNI_OnUnload(vm: PJavaVM; reserved: pointer); cdecl;
1136 begin
1137 end;
1139 // DONT REMOVE JNI FUNCTIONS. SPECIAL HANDLING BY FPC.
1140 exports SDL_main name 'SDL_main';
1141 exports JNI_OnLoad name 'JNI_OnLoad';
1142 exports JNI_OnUnload name 'JNI_Unload';
1143 {$ELSE}
1144 begin
1145 EntryPoint
1146 {$ENDIF}
1148 end.