forked from stelic/limitload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1281 lines (1167 loc) · 50.7 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from argparse import ArgumentParser
import codecs
from ConfigParser import SafeConfigParser
import locale
from multiprocessing import cpu_count
import os
import re
import sys
import traceback
import pygame
from pandac.PandaModules import loadPrcFileData
from src import PACKAGE_NAME, PACKAGE_VERSION, MAX_DT, UI_TEXT_ENC
from src import path_exists, real_path, full_path, join_path
from src import decode_real_path, encode_full_path
from src import get_base_game_root, add_game_root
from src import list_dir_files, list_dir_subdirs
from src.bconf import PYTHON_CMD
from src.core.basestack import BaseStack
from src.core.game import Game
from src.core.interface import NarrowAspect
from src.core.misc import report, warning, error
from src.core.misc import SimpleProps, AutoProps
from src.core.misc import reset_random
from src.core.misc import fx_reset_random
from src.core.misc import rotate_logs
from src.core.transl import *
from src.core.transl import set_tr_language
def main ():
locale.setlocale(locale.LC_ALL, "")
enc = locale.getpreferredencoding()
# Language setting must be parsed manually here from
# the default configuration file, because translation
# call are needed before normal configuration loading.
lang = "system"
os_def_game_config_path = real_path("config", "config.ini")
if os.path.exists(os_def_game_config_path):
cp = SafeConfigParser()
fl = codecs.open(os_def_game_config_path, "r", "utf8")
cp.readfp(fl)
fl.close()
if cp.has_option("misc", "language"):
lang = cp.get("misc", "language")
lang = lang.replace(" ", "")
set_tr_language(lang)
description = p_("game description in command-line help",
"Limit Load -- an arcade cockpit flight game.")
ap = ArgumentParser(description=description, add_help=True,
prog=PACKAGE_NAME)
ap.add_argument(
"-m", "--start-mission",
action="store",
metavar=p_("command-line option argument pattern",
"PACK:MISSION[:ZONE]"),
default=None,
help=p_("command-line option description",
"Start game directly on the given campaign mission. "
"The mission starts on the mission menu, or in "
"the mission zone if given. "
"If empty campaign pack is given (i.e. just leading semicolon), "
"the mission is looked for through all known campaign packs; "
"if more than one mission is found, exits with error. "
"If empty zone is given (i.e. just trailing semicolon), "
"the mission starts in the default zone."))
ap.add_argument(
"-s", "--start-skirmish",
action="store",
metavar=p_("command-line option argument pattern",
"PACK:MISSION[:ZONE]"),
default=None,
help=p_("command-line option description",
"Start game directly on the given skirmish mission. "
"The mission starts with the intro dialogue (if any), "
"or in the mission zone if given. "
"If empty skirmish pack is given (i.e. just leading semicolon), "
"the mission is looked for through all known skirmish packs; "
"if more than one mission is found, exits with error. "
"If empty zone is given (i.e. just trailing semicolon), "
"the mission starts in the default zone."))
ap.add_argument(
"-t", "--start-test",
action="store",
metavar=p_("command-line option argument pattern",
"PACK:MISSION[:ZONE|.LOOP]"),
default=None,
help=p_("command-line option description",
"Start game directly on the given test mission. "
"The mission starts with the intro dialogue (if any), "
"or in the mission zone if given. "
"If empty test pack is given (i.e. just leading semicolon), "
"the mission is looked for through all known test packs; "
"if more than one mission is found, exits error. "
"If empty zone is given (i.e. just trailing semicolon), "
"the mission starts in the default zone. "
"Instead of the zone, a loop extension can be given "
"to request a particular mission loop to execute alone."))
ap.add_argument(
"-f", "--fixed-time-step",
action="store",
metavar=p_("command-line option argument pattern",
"SECONDS"),
default=None,
help=p_("command-line option description",
"Use the given fixed time step for game physics, "
"instead of variable, rendering-dependent time step. "
"Note that action will not run in real-time "
"with fixed time step."))
ap.add_argument(
"-r", "--random-seed",
action="store",
metavar=p_("command-line option argument pattern",
"SEED[:FXSEED]"),
default=None,
help=p_("command-line option description",
"Use the given integer number as random seed, "
"instead of system-derived seed. "
"If second seed is given, it is used for randomness "
"in game effects. "
"If negative number is given, "
"system-derived seed is used instead."))
ap.add_argument(
"-c", "--config-variant",
action="store",
metavar=p_("command-line option argument pattern",
"VARIANT"),
default=None,
help=p_("command-line option description",
"Read game configuration from config-VARIANT.ini "
"instead of from config.ini."))
ap.add_argument(
"-g", "--game-context",
action="append",
metavar=p_("command-line option argument pattern",
"ATTR=VALUE"),
default=[],
help=p_("command-line option description",
"Set a game context attribute. "
"Value will be converted to first possible type of "
"integer, float, True/False/None, string. "
"String type can be forced by prepending and appending "
"either two dots (e.g. foo=..123..), or single or double "
"quotes (which may need to be escaped for the shell). "
"Can be repeated to set multiple attributes."))
ap.add_argument(
"-V", "--version",
action="version",
version=(p_("game name with release string in command-line help",
u"Limit Load %s") % PACKAGE_VERSION))
options = ap.parse_args()
# Set game configuration and Panda configuration.
if options.config_variant:
config_variant_str = options.config_variant.decode(enc)
game_config_file = "config-%s.ini" % config_variant_str
else:
game_config_file = "config.ini"
gameconf = GameConf()
if path_exists("config", game_config_file):
gameconf.read_from_file(game_config_file)
elif options.config_variant:
os_game_config_path = real_path("config", game_config_file)
error(_("Requested game configuration file '%s' does not exist.") %
os_game_config_path)
set_panda_config(options, gameconf)
set_tr_language(gameconf.misc.language)
for full_path in reversed(gameconf.path.root_path):
add_game_root(full_path)
if sum((opv is not None) for opv in (
options.start_mission,
options.start_skirmish,
options.start_test,
)) > 1:
error(_("Only one of campaign, skirmish or test mission "
"can be started directly."))
# Set input configuration.
input_config_file = "input.ini"
inputconf = InputConf()
if path_exists("config", input_config_file):
inputconf.read_from_file(input_config_file)
def find_mission_packs (pack_type, pack_name, mission_name):
pack_dir = "src/%s" % pack_type
found_pnames = []
for pname in list_dir_subdirs("data", pack_dir):
pack_subdir = join_path(pack_dir, pname)
for fname in list_dir_files("data", pack_subdir):
mname = fname.replace(".py", "")
if mname == mission_name:
found_pnames.append(pname)
break
return found_pnames
# Parse start mission.
mission_spec = None
if options.start_mission:
start_mission_str = options.start_mission
mission_lst_str = start_mission_str.split(":")
if not 2 <= len(mission_lst_str) <= 3:
error(_("Campaign mission must be requested as PACK:MISSION[:ZONE], "
"got '%s' instead.") % start_mission_str)
if len(mission_lst_str) < 3:
mission_lst_str.append(None)
pname, mname, zname = mission_lst_str
if not pname:
pnames = find_mission_packs("campaigns", pname, mname)
if len(pnames) == 0:
error(_("Mission '%s' does not exist in any campaign pack.") %
mname)
elif len(pnames) >= 2:
error(_("Mission '%(m)s' exists in more than one campaign pack: "
"%(lst)s.") %
dict(m=mname, lst=(", ".join(pnames))))
pname = pnames[0]
mission_spec = (pname, mname, zname)
if not path_exists("data", "src/campaigns/%s" % pname):
error(_("There is no campaign '%s'.") % pname)
if not path_exists("data", "src/campaigns/%s/%s.py" % (pname, mname)):
error(_("There is no mission '%(m)s' in campaign '%(c)s'.") %
dict(m=mname, c=pname))
# Parse start skirmish.
skirmish_spec = None
if options.start_skirmish:
start_skirmish_str = options.start_skirmish.decode(enc)
skirmish_lst_str = start_skirmish_str.split(":")
if not 2 <= len(skirmish_lst_str) <= 3:
error(_("Skirmish mission must be requested as PACK:MISSION[:ZONE], "
"got '%s' instead.") % start_skirmish_str)
if len(skirmish_lst_str) < 3:
skirmish_lst_str.append(None)
pname, mname, zname = skirmish_lst_str
if not pname:
pnames = find_mission_packs("skirmish", pname, mname)
if len(pnames) == 0:
error(_("Mission '%s' does not exist in any skirmish pack.") %
mname)
elif len(pnames) >= 2:
error(_("Mission '%(m)s' exists in more than one skirmish pack: "
"%(lst)s.") %
dict(m=mname, lst=(", ".join(pnames))))
pname = pnames[0]
skirmish_spec = (pname, mname, zname)
if not path_exists("data", "src/skirmish/%s" % pname):
error(_("There is no skirmish '%s'.") % pname)
if not path_exists("data", "src/skirmish/%s/%s.py" % (pname, mname)):
error(_("There is no mission '%(m)s' in skirmish '%(s)s'.") %
dict(m=mname, s=pname))
# Parse start test.
test_spec = None
if options.start_test:
start_test_str = options.start_test.decode(enc)
test_lst_str_zone = start_test_str.split(":")
test_lst_str_loop = start_test_str.split(".")
if not ((len(test_lst_str_zone) == 2 and len(test_lst_str_loop) == 1) or
(len(test_lst_str_zone) == 3 and len(test_lst_str_loop) == 1) or
(len(test_lst_str_zone) == 2 and len(test_lst_str_loop) == 2)):
error(_("Test mission must be requested as PACK:MISSION[:ZONE|.LOOP], "
"got '%s' instead.") % (start_test_str))
if len(test_lst_str_zone) == 3:
pname, mname, zname = test_lst_str_zone
lname = None
elif len(test_lst_str_loop) == 2:
pname_mname, lname = test_lst_str_loop
pname, mname_lname = test_lst_str_zone
mname = mname_lname.split(".")[0]
zname = None
else:
pname, mname = test_lst_str_zone
zname, lname = None, None
if not pname:
pnames = find_mission_packs("test", pname, mname)
if len(pnames) == 0:
error(_("Mission '%s' does not exist in any test pack.") %
mname)
elif len(pnames) >= 2:
error(_("Mission '%(m)s' exists in more than one test pack: "
"%(lst)s.") %
dict(m=mname, lst=(", ".join(pnames))))
pname = pnames[0]
test_spec = (pname, mname, zname, lname)
if not path_exists("data", "src/test/%s" % pname):
error(_("There is no test '%s'.") % pname)
if not path_exists("data", "src/test/%s/%s.py" % (pname, mname)):
error(_("There is no mission '%(m)s' in test '%(t)s.") %
dict(m=mname, t=pname))
# Parse fixed time step.
fixdt = None
if options.fixed_time_step is not None:
fixed_time_step_str = options.fixed_time_step.decode(enc)
fixdt_str = fixed_time_step_str
try:
fixdt = float(fixdt_str)
except ValueError:
error(_("Time step must be a real number, "
"got '%s' instead.") % fixdt_str)
if not 0.0 < fixdt <= MAX_DT:
error(_("Time step must be in range (0.0, %(num1).3f], "
"got '%(num2).3f' instead.") %
dict(num1=MAX_DT, num2=fixdt))
# Parse random seed.
randseed = None
if options.random_seed is not None:
random_seed_str = options.random_seed.decode(enc)
rsd_lst_str = random_seed_str
if not 1 <= len(rsd_lst_str) <= 2:
error(n_("Exactly one or two random seeds can be given, "
"got %(num)d instead ('%(fmt)s').",
"Exactly one or two random seeds can be given, "
"got %(num)d instead ('%(fmt)s').",
len(rsd_lst_str)) %
dict(num=len(rsd_lst_str), fmt=random_seed_str))
rsd_lst = []
for rsd_str in rsd_lst_str:
try:
rsd = int(rsd_str)
except ValueError:
error(_("Random seed must be an integer number, "
"got '%s' instead.") % rsd_str)
rsd_lst.append(rsd)
if len(rsd_lst) == 1:
randseed = rsd_lst[0]
else:
randseed = tuple(rsd_lst)
# Parse game context.
game_context = []
for i in range(len(options.game_context)):
attr_val_str = options.game_context[i].decode(enc)
attr_val_lst_str = attr_val_str.split("=", 1)
if len(attr_val_lst_str) != 2:
error(_("Equal sign not found in game context attribute '%s'.") %
attr_val_str)
attr, val_str = attr_val_lst_str
if val_str.startswith("..") and val_str.endswith(".."):
val = val_str[2:-2]
elif val_str.startswith("'") and val_str.endswith("'"):
val = val_str[1:-1]
elif val_str.startswith("\"") and val_str.endswith("\""):
val = val_str[1:-1]
else:
try:
val = int(val_str)
except ValueError:
try:
val = float(val_str)
except ValueError:
if val_str == "True":
val = True
elif val_str == "False":
val = False
elif val_str == "None":
val = None
else:
val = val_str
game_context.append((attr, val))
report(_("Starting game.")) # also initializes logging
panda_log_real_path = rotate_logs("panda-log", "txt")
base = BaseStack(gameconf=gameconf, inputconf=inputconf,
fixdt=fixdt, randseed=randseed,
pandalog=panda_log_real_path)
# ...also automatically sets __builtin__.base.
# Random generator initialization happens after BaseStack is created,
# to be sure that nothing in BaseStack requests randomness.
# Random generator will be reinitialized on each World creation.
if isinstance(randseed, tuple):
rsd, fxrsd = randseed
elif randseed is not None:
rsd = fxrsd = randseed
else:
rsd = fxrsd = -1
reset_random(rsd)
fx_reset_random(fxrsd)
# Tool for tuning animations to work on narrowest supported screens.
NarrowAspect()
# Setup game context.
gc = AutoProps()
if game_context:
ls = []
for attr, val in game_context:
gc[attr] = val
ls.append(" gc.%s = %s" % (attr, repr(val)))
report(_("Setting game context:\n%s") % ("\n".join(ls)))
gc.save_disabled = True
if mission_spec:
gc.campaign, gc.mission, gc.zone = mission_spec
gc.save_disabled = True
elif skirmish_spec:
gc.skirmish, gc.mission, gc.zone = skirmish_spec
gc.save_disabled = True
elif test_spec:
gc.test, gc.mission, gc.zone, gc.loop = test_spec
gc.save_disabled = True
gc.game_config_file = game_config_file
gc.input_config_file = input_config_file
# Make sure user directories exists.
if not path_exists("config", "."):
os.makedirs(real_path("config", "."))
if not path_exists("save", "."):
os.makedirs(real_path("save", "."))
if not path_exists("cache", "."):
os.makedirs(real_path("cache", "."))
# Start game in task to assure that at least one engine frame has elapsed.
def startf (task):
if task.time == 0.0:
return task.cont
game = Game(gc)
try:
pygame.init()
base.taskMgr.add(startf, "startf")
base.run()
#import cProfile
#cProfile.run('base.run()', 'prof.out')
pygame.quit()
except:
pass
class GameConfError (Exception):
def __init__ (self, message=""):
self.message = message
def __str__ (self):
return self.message.encode(locale.getpreferredencoding())
def __unicode__ (self):
return self.message
class GameConf (SimpleProps):
def __init__ (self):
self.reset_to_default()
def reset_to_default (self):
pset = GameConf._make_parse_from_set
self.cpu = SimpleProps(
use_cores=2, _use_cores_p=pset([1, 2, 3], keyw=["auto"]),
)
self.video = SimpleProps(
resolution="desktop", _resolution_p=GameConf._parse_resolution,
full_screen=True, _full_screen_p=pset([True, False]),
multi_sampling_antialiasing=4, _multi_sampling_antialiasing_p=pset([0, 2, 4]),
anisotropic_filtering=16, _anisotropic_filtering_p=pset([0, 4, 8, 16]),
preload_textures=2, _preload_textures_p=pset([0, 1, 2]),
terrain_mesh="high", _terrain_mesh_p=pset(["high", "low"]),
vertical_sync=False, _vertical_sync_p=pset([True, False]),
)
self.audio = SimpleProps(
sound_system="al", _sound_system_p=pset(["none", "al", "fmod"]),
)
avail_langs = [item[:-len(".po")]
for item in list_dir_files("data", "language/po/limload")
if item.endswith(".po")]
avail_langs.append("system")
avail_langs.append("en_US")
if "sr" in avail_langs:
avail_langs.append("sr@latin") # build-time transliteration
avail_langs.sort()
self.misc = SimpleProps(
language="system", _language_p=pset(avail_langs),
frame_rate_meter=False, _frame_rate_meter_p=pset([True, False]),
)
self.path = SimpleProps(
root_path=[], _root_path_p=GameConf._parse_full_paths,
)
self.debug = SimpleProps(
output_level=0, _output_level_p=pset([0, 1, 2]),
panda_output_level="fatal", _panda_output_level_p=pset([
"fatal", "error", "warning", "info", "debug", "spam"]),
panda_pstats=False, _panda_pstats_p=pset([True, False]),
panda_verbose_timer=False, _panda_verbose_timer_p=pset([True, False]),
act_attack_type=1, _act_attack_type_p=pset([1, 2]),
act_attack_monitor=frozenset(), _act_attack_monitor_p=GameConf._parse_comma_set,
)
self.cheat = SimpleProps(
_silent=True,
adamantium_bath=False, _adamantium_bath_p=pset([True, False]),
flying_dutchman=False, _flying_dutchman_p=pset([True, False]),
guards_tanksman=False, _guards_tanksman_p=pset([True, False]),
chernobyl_liquidator=False, _chernobyl_liquidator_p=pset([True, False]),
)
@staticmethod
def _convert_type (field, valstr, valtyp):
try:
if valtyp is unicode:
value = valstr
elif valtyp is str:
enc = locale.getpreferredencoding()
value = valstr.decode(enc)
elif valtyp is bool:
if valstr.lower() == "true":
value = True
elif valstr.lower() == "false":
value = False
else:
raise ValueError
else:
value = valtyp(valstr)
except ValueError:
if valtyp is int:
valtyp_fmt = "int"
elif valtyp is float:
valtyp_fmt = "float"
elif valtyp is bool:
valtyp_fmt = "bool"
else:
raise StandardError("Cannot derive name for type %s." % valtyp)
raise GameConfError(
_("Game configuration field '%(fld)s' value '%(val)s' "
"cannot be converted to type '%(typ)s'.") %
dict(fld=field, val=valstr, typ=valtyp_fmt))
return value
@staticmethod
def _format_value (value):
if isinstance(value, bool):
if value == True:
valfmt = "true"
else:
valfmt = "false"
else:
valfmt = "%s" % value
return valfmt
@staticmethod
def _make_parse_from_set (values, keyw=()):
valtyp = type(values[0])
values_str = map(GameConf._format_value, values) + list(keyw)
valkeyw_fmt = ", ".join(values_str)
def parsef (field, valstr):
if valstr not in values_str:
raise GameConfError(
_("Game configuration field '%(fld)s' set to "
"inadmissible value '%(val)s' "
"(admissible values: %(lst)s).") %
dict(fld=field, val=valstr, lst=valkeyw_fmt))
if valstr in keyw:
value = valstr
else:
value = GameConf._convert_type(field, valstr, valtyp)
return value
return parsef
@staticmethod
def _parse_comma_set (field, valstr):
if not valstr:
return []
valstr_lst = valstr.split(",")
els = frozenset([x.strip() for x in valstr_lst])
return els
@staticmethod
def _parse_full_paths (field, valstr):
if not valstr:
return []
valstr_lst = valstr.split(":")
full_paths = []
for os_full_path in valstr_lst:
os_full_path = os.path.normpath(os_full_path)
full_path = decode_real_path(os_full_path)
full_paths.append(full_path)
return full_paths
@staticmethod
def _parse_resolution (field, valstr):
valstr_desktop = "desktop"
if valstr == valstr_desktop:
value = valstr_desktop
else:
valstr_lst = valstr.split()
if len(valstr_lst) != 2:
raise GameConfError(
_("Game configuration field '%(fld)s' "
"must have value '%(specval)s' "
"or width and height in pixels as '<width> <height>', "
"got '%(val)s' instead.") %
dict(fld=field, specval=valstr_desktop, val=valstr))
width_str, height_str = valstr_lst
width = GameConf._convert_type(field, width_str, int)
height = GameConf._convert_type(field, height_str, int)
if width > 0 and height > 0:
value = (width, height)
else:
value = valstr_desktop
return value
def read_from_file (self, path):
conf_var = {}
conf_var["base"] = encode_full_path(get_base_game_root())
real_home_dir_path = os.environ.get("HOME")
if real_home_dir_path is None:
real_home_dir_path = conf_var["base"]
conf_var["home"] = decode_real_path(real_home_dir_path)
cp = SafeConfigParser()
os_path = real_path("config", path)
fl = codecs.open(os_path, "r", "utf8")
cp.readfp(fl)
fl.close()
rp = lambda s: s.replace("-", "_")
for raw_sec_name in cp.sections():
sec_name = rp(raw_sec_name)
section = self.get(sec_name)
if section is None:
warning(
_("Unknown game configuration section '%s'.") % raw_sec_name)
continue
for raw_opt_name in cp.options(sec_name):
opt_name = rp(raw_opt_name)
option_defval = section.get(opt_name)
if option_defval is None:
warning(
_("Unknown game configuration field '%(fld)s' "
"in section '%(sec)s'.") %
dict(fld=raw_opt_name, sec=raw_sec_name))
continue
option_parse = section.get("_%s_p" % opt_name)
raw_val_str = cp.get(raw_sec_name, raw_opt_name, raw=True)
val_str = self._interp_value(raw_opt_name, raw_val_str, conf_var)
try:
opt_val = option_parse(raw_opt_name, val_str)
except GameConfError as e:
warning(e.message)
continue
section[opt_name] = opt_val
_interp_rx = re.compile(r"%([\w-]+)%", re.U)
def _interp_value (self, raw_opt_name, raw_val_str, conf_var):
val_str = raw_val_str
val_els = []
pos = 0
while True:
m = GameConf._interp_rx.search(val_str, pos)
if m is None:
val_els.append(val_str[pos:])
break
val_els.append(val_str[pos:m.start()])
var_name = m.group(1)
var_value = conf_var.get(var_name)
if var_value is not None:
val_els.append(var_value)
else:
warning(
_("Game configuration field '%(fld)s' "
"contains unknown variable '%(var)s'.") %
dict(fld=raw_opt_name, var=var_name))
val_els.append(val_str[m.start():m.end()])
pos = m.end()
val_str = "".join(val_els)
return val_str
def set_panda_config (options, gameconf):
gc = gameconf
bfmt = lambda b: ("#t" if b else "#f")
ifmt = lambda i: ("%d" % i)
pc = {}
if gc.cpu.use_cores == "auto":
use_cores = min(cpu_count(), 2)
else:
use_cores = gc.cpu.use_cores
pc["threading-model"] = {
1: "",
2: "/thread3",
3: "thread2/thread3",
}[use_cores]
pc["load-display"] = "pandagl"
pc["fullscreen"] = bfmt(gc.video.full_screen)
if gc.video.resolution == "desktop":
resolution = desktop_resolution()
else:
resolution = gc.video.resolution
pc["win-size"] = "%d %d" % resolution
pc["sync-video"] = bfmt(gc.video.vertical_sync)
pc["framebuffer-object-multisample"] = ifmt(0)
pc["framebuffer-multisample"] = bfmt(gc.video.multi_sampling_antialiasing > 0)
pc["multisamples"] = ifmt(gc.video.multi_sampling_antialiasing)
pc["texture-anisotropic-degree"] = ifmt(gc.video.anisotropic_filtering)
pc["textures-power-2"] = "none"
pc["compressed-textures"] = bfmt(True)
pc["preload-simple-textures"] = bfmt(True)
# NOTE: preload-textures does not seem to work.
pc["audio-library-name"] = {
"none": "p3fmod_none",
"al": "p3openal_audio",
"fmod": "p3fmod_audio",
}[gc.audio.sound_system]
pc["show-frame-rate-meter"] = bfmt(gc.misc.frame_rate_meter)
pc["text-encoding"] = UI_TEXT_ENC
pc["cursor-hidden"] = bfmt(True)
pc["notify-level"] = gc.debug.panda_output_level
#pc["notify-level-glxdisplay"] = "debug"
#pc["notify-level-display"] = "debug"
# Disable all caching, it is handled manually.
pc["model-cache-dir"] = full_path("cache", "panda3d") # for stragglers
pc["model-cache-models"] = bfmt(False)
pc["model-cache-textures"] = bfmt(False)
pc["model-cache-compressed-textures"] = bfmt(False)
#title = _("Limit Load") # crashes with UnicodeEncodeError
title = ""
pc["window-title"] = title
#pc["icon-filename"] = full_path("data", "src/limload.ico")
pc["want-pstats"] = bfmt(gc.debug.panda_pstats)
pc["task-timer-verbose"] = bfmt(gc.debug.panda_verbose_timer)
pc["gl-debug"] = bfmt(True)
pcstr = "".join("%s %s\n" % pv for pv in sorted(pc.items()))
loadPrcFileData("main", pcstr)
def desktop_resolution ():
# NOTE: In case of multiple monitors, this should return the resolution
# of the primary monitor, and not some aggregation of all monitors.
if os.name == "posix":
from subprocess import Popen, PIPE
cmd = ["xrandr", "-q"]
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
ret = proc.communicate()
if proc.returncode != 0:
raise StandardError("Failed to run '%s'." % "xrandr")
stdout, stderr = ret
w, h = None, None
for line in stdout.split("\n"):
m = re.search(r"(\d+)x(\d+).*\*", line)
if m is not None:
w_test, h_test = map(int, m.groups())
if w is None or w * h < w_test * h_test:
w, h = w_test, h_test
if w is None:
raise StandardError("Unexpected output from '%s'." % "xrandr")
elif os.name == "nt":
import ctypes
user32 = ctypes.windll.user32
w, h = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
return w, h
class InputConfError (Exception):
def __init__ (self, message=""):
self.message = message
def __str__ (self):
return self.message.encode(locale.getpreferredencoding())
def __unicode__ (self):
return self.message
class InputConf (object):
def __init__ (self):
ret = InputConf._default_bindings()
self.bindings, self.jsdevs = ret
@staticmethod
def _default_bindings ():
bindings = [
AutoProps(
name="pitch",
desc=p_("input command description",
"rotate plane around pitch axis"),
note=p_("input command note",
"Needed when using joystick for rotation."),
seqs=["axis2"], isaxis=True,
exponent=2.0, deadzone=0.05, minval=-1.0, maxval=1.0,
inverted=False),
AutoProps(
name="pitch-up",
desc=p_("input command description",
"rotate plane in pitch upwards"),
note=p_("input command note",
"Needed only when using keyboard for rotation, "
"which is not recommended."),
seqs=["arrow_up"]),
AutoProps(
name="pitch-down",
desc=p_("input command description",
"rotate plane in pitch downwards"),
note=p_("input command note",
"Needed only when using keyboard for rotation, "
"which is not recommended."),
seqs=["arrow_down"]),
AutoProps(
name="roll",
desc=p_("input command description",
"rotate plane around roll axis"),
note=p_("input command note",
"Needed when using joystick for rotation."),
seqs=["axis1"], isaxis=True,
exponent=2.0, deadzone=0.05, minval=-1.0, maxval=1.0,
inverted=False),
AutoProps(
name="roll-left",
desc=p_("input command description",
"rotate plane in roll to the left"),
note=p_("input command note",
"Needed only when using keyboard for rotation, "
"which is not recommended."),
seqs=["arrow_left"]),
AutoProps(
name="roll-right",
desc=p_("input command description",
"rotate plane in roll to the right"),
note=p_("input command note",
"Needed only when using keyboard for rotation, "
"which is not recommended."),
seqs=["arrow_right"]),
AutoProps(
name="throttle",
desc=p_("input command description",
"set engine throttle"),
note=p_("input command note",
"Needed when using a hardware throttle, "
"on joystick or standalone."),
seqs=[], isaxis=True,
exponent=1.0, deadzone=0.0, minval=-1.0, maxval=1.0,
inverted=False),
AutoProps(
name="throttle-up",
desc=p_("input command description",
"increase engine throttle"),
note=p_("input command note",
"Needed when using keyboard for engine control."),
seqs=["="]),
AutoProps(
name="throttle-down",
desc=p_("input command description",
"decrease engine throttle"),
note=p_("input command note",
"Needed when using keyboard for engine control."),
seqs=["-"]),
AutoProps(
name="air-brake",
desc=p_("input command description",
"deploy or retract air brake"),
note=p_("input command note",
"Use for quick airspeed decreases, such as in "
"maneuvering combat or on landing, without or "
"in addition to throttle setting."),
seqs=["b", "joy5"]),
AutoProps(
name="landing-gear",
desc=p_("input command description",
"lower or raise landing gear"),
note=p_("input command note",
"Do not forget this when landing."),
seqs=["g"]),
AutoProps(
name="next-target",
desc=p_("input command description",
"switch to next target"),
note=p_("input command note",
"Targets are switched in the HUD weapon modes and "
"waypoints are switched in the HUD navigation mode. "
"When a target is selected, the selection can be "
"cancelled either by holding this input pressed for "
"a little while longer or by pressing "
"the dedicated target deselection input."),
seqs=["tab", "joy2"]),
AutoProps(
name="deselect-target",
desc=p_("input command description",
"cancel target selection"),
note=p_("input command note",
"This can be useful to recover rotation through "
"all HUD modes, and not only through "
"weapons with which the target can be attacked."),
seqs=["z"]),
AutoProps(
name="fire-weapon",
desc=p_("input command description",
"fire currently selected weapon"),
note=p_("input command note",
"Guns and rocket pods keep firing while "
"the input is pressed."),
seqs=["space", "joy1"]),
AutoProps(
name="next-target-section",
desc=p_("input command description",
"switch to next target section"),
note=p_("input command note",
"Big targets have multiple sections which can be "
"acquired."),
seqs=["s"]),
AutoProps(
name="next-weapon",
desc=p_("input command description",
"switch to next weapon or to navigation"),
note=p_("input command note",
"Rotates through all weapon and navigation modes "
"when target is not acquired. "
"If a target is acquired, rotates only through "
"weapons with which the target can be attacked."),
seqs=["w", "joy4"]),
AutoProps(
name="previous-weapon",
desc=p_("input command description",
"switch to previous weapon or to navigation"),
#note=p_("input command note",
#"n/a"),
seqs=["q"]),
AutoProps(
name="radar-on-off",
desc=p_("input command description",
"turn on or off the radar"),
note=p_("input command note",
"Turning the radar off can be used sometimes "
"to sneak behind the enemies. "
"Passive sensors (such as IRST) keep working."),
seqs=["alt-r"]),
AutoProps(
name="radar-scale-up",
desc=p_("input command description",
"increase the scale on the radar screen"),
note=p_("input command note",
"Higher scales are useful for search and "
"engagement beyond visual range."),
seqs=["shift-r"]),
AutoProps(
name="radar-scale-down",
desc=p_("input command description",
"decrease the scale on the radar screen"),
note=p_("input command note",
"Lower scales are useful for close combat."),
seqs=["r"]),
AutoProps(
name="next-mfd-mode",
desc=p_("input command description",
"switch to next MFD mode"),
note=p_("input command note",
"Sometimes the MFD mode will switch automatically "