-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
399 lines (362 loc) · 14.8 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
import sys
if sys.version_info.major >2:
import builtins
builtins.basestring = str
else:
import __builtin__ as builtins
from direct.showbase.AppRunnerGlobal import appRunner
if appRunner: #run from binary/p3d
path=appRunner.p3dFilename.getDirname()+'/'
else: #run from python
path=''
#some options may need to be set here, but if this file is packed to a
# p3d/exe it might be hard if we don't load the values now
#some important values are set here as default values
from panda3d.core import loadPrcFileData
loadPrcFileData('', 'source-dir source')
loadPrcFileData('', 'game-mode normal')
loadPrcFileData('', 'notify-level-a4p info')
loadPrcFileData('', 'log-file None')
loadPrcFileData('', 'font-default font/DejaVuSans.ttf')
loadPrcFileData('', 'font-special font/visitor2.ttf')
loadPrcFileData('', 'textures-power-2 None')
loadPrcFileData('', 'pause-on-focus-fost True')
loadPrcFileData('', 'ui_color1 0.33 0.894 1.0 1.0')
loadPrcFileData('', 'ui_color2 0.94 0.0 0.1 1.0')
loadPrcFileData('', 'ui_color3 0.33 0.56 1.0 1.0')
loadPrcFileData('', 'window-type none')
loadPrcFileData('', 'sfx-distance-factor 10.0')
loadPrcFileData('', 'sfx-doppler-factor 1.0')
loadPrcFileData('', 'use-os-cursor False')
loadPrcFileData('', 'speakermode raw')
loadPrcFileData('', 'key-back s')
loadPrcFileData('', 'key-fire mouse1')
loadPrcFileData('', 'key-forward w')
loadPrcFileData('', 'key-gun1 1')
loadPrcFileData('', 'key-gun2 2')
loadPrcFileData('', 'key-gun3 3')
loadPrcFileData('', 'key-left a')
loadPrcFileData('', 'key-menu escape')
loadPrcFileData('', 'key-right d')
loadPrcFileData('', 'key-zoom mouse3')
loadPrcFileData('', 'sound-volume 1.0')
loadPrcFileData('', 'music-volume 0.2')
loadPrcFileData('', 'mouse-scroll-speed 0.01')
#meh, just use one config file - config.txt loaded a bit later
#if the file is lost we still have the basic valuese hardcoded here
#from panda3d.core import loadPrcFile
#loadPrcFile('base_config.prc')
#import the rest
from panda3d.core import *
from direct.showbase import ShowBase
from direct.directnotify.DirectNotify import DirectNotify
from direct.showbase.DirectObject import DirectObject
import os
import ast
import signal
from datetime import datetime
import traceback
class Configer (DirectObject):
"""
The class will load a config file, it also has a dict-like interface
"""
def __init__(self, config_file):
#a temp log is needed, we can't use the 'global' log,
#we first need to know where/what to log
#and that info is in the config file we are about to load
#solution - we store the msg and prit them later when the log system is up
self.warning=[]
self.debug=[]
self.send_events=False
self.loadConfig(config_file)
self.send_events=True
def __getitem__(self, key):
if key in self.cfg:
return self.cfg[key]
else:
v=self.getValueFromConfigVariable(key)
self.cfg[key]=v
return v
return None
def __setitem__(self, key, value):
self.cfg[key]=value
if self.send_events:
if key in ('fullscreen', 'win-size'):
messenger.send('window-reset')
elif key in ('sound-volume', 'music-volume'):
messenger.send('audio-reset-volume')
def __contains__(self, item):
return item in self.cfg
def getAllWords(self, var):
"""Returns all values of a config variable as a list
or the first value if there only is one vaue in the variable
"""
world_count=var.getNumWords()
if world_count==1:
return var.getValue()
r=[]
for i in range(world_count):
r.append(ast.literal_eval(str(var.getWord(i))))
return tuple(r)
def getValueFromConfigVariable(self, var_name):
"""Returns the config variable value or values no matter what the
type of the value is, returns list for multi word variables
"""
var_type=ConfigVariable(var_name).getValueType()
#print '(',var_type,')', var_name
if var_type ==ConfigFlags.VT_list:
l=[]
for i in range(ConfigVariableList(var_name).getNumValues()):
l.append(ConfigVariableList(var_name).getStringValue (i))
return l
elif var_type ==ConfigFlags.VT_string:
return self.getAllWords(ConfigVariableString(var_name))
elif var_type ==ConfigFlags.VT_filename:
return self.getAllWords(ConfigVariableFilename(var_name))
elif var_type ==ConfigFlags.VT_double:
return self.getAllWords(ConfigVariableDouble(var_name))
elif var_type ==ConfigFlags.VT_bool:
return self.getAllWords(ConfigVariableBool(var_name))
elif var_type ==ConfigFlags.VT_int:
return self.getAllWords(ConfigVariableInt(var_name))
elif var_type ==ConfigFlags.VT_enum:
return self.getAllWords(ConfigVariableString(var_name))
elif var_type ==ConfigFlags.VT_search_path:
return ConfigVariableSearchPath(var_name).getValue ()
elif var_type ==ConfigFlags.VT_int64:
return self.getAllWords(ConfigVariableDouble(var_name))
elif var_type ==ConfigFlags.VT_color:
return ConfigVariableColor(var_name).getValue()
else:
#the value is of unkonwn type, probably a custom value
#load them as strings and then
#try to turn them into the right type one by one
variables=self.getAllWords(ConfigVariableString(var_name, ''))
if len(variables)==0:
return None
#is it one word?
if ConfigVariableString(var_name).getNumWords()==1:
try:
return ast.literal_eval(variables)
except:
#some special strings should be converted to bool
if variables in ('false', '#f'):
return False
if variables in ('true', '#t'):
return True
return variables
r=[]
for var in variables:
try:
r.append(ast.literal_eval(var))
except:
#some special strings should be converted to bool
if variables in ('false', '#f'):
r.append(False)
elif variables in ('true', '#t'):
r.append(True)
else:
r.append(var)
return tuple(r)
return None
def loadConfig(self, config_file_name, load_all=False):
self.cfg={}
config_dict={}
self.debug.append('Loading config from: '+config_file_name)
try:
with open(config_file_name,'r') as f:
for row in f:
if not row.startswith('#'):
loadPrcFileData('',row)
if row.split():
var_name=row.split()[0]
var_value=self.getValueFromConfigVariable(var_name)
config_dict[var_name]=var_value
self.debug.append(var_name+' set to '+str(var_value))
except IOError:
self.warning.append('Could not load config file: '+config_file_name)
if load_all:
self.warning.append('Reading all known config variables!')
for i in range(ConfigVariableManager.getGlobalPtr().getNumVariables()):
var_name=ConfigVariableManager.getGlobalPtr().getVariableName(i)
var_value=self.getValueFromConfigVariable(var_name)
config_dict[var_name]=var_value
self.cfg=config_dict
def saveConfig(self, config_file, glsl_config_file=None):
log.debug('Saving config file to: '+config_file)
try:
with open(config_file, 'w') as out_file:
out_file.write('#A4P config file, edit at your own risk\n')
for key in sorted(self.cfg):
out_file.write(key+' '+self.getCfgValueAsString(key)+'\n')
except IOError:
log.warning('Could not save config file: '+config_file)
#we now also need to write a glsl configuration file
if glsl_config_file:
log.debug('Saving GLSL config file to: '+glsl_config_file)
try:
with open(glsl_config_file, 'w') as out_file:
out_file.write('//A4P config file, edit at your own risk\n')
for key, value in self.cfg.items():
if key.startswith('glsl-'):
if value == 0:
out_file.write('#define DISABLE_'+key[5:].replace('-','_').upper()+' \n')
elif value == 1:
out_file.write('#define ENABLE_'+key[5:].replace('-','_').upper()+' \n')
else:
out_file.write('#define '+key[5:].replace('-','_').upper()+' '+str(value)+' \n')
if self.send_events:
messenger.send('reload-shaders')
except IOError:
log.warning('Could not save GLSL config file: '+glsl_config_file)
def setCfgValueFromString(self, var_name, value):
if var_name in self.cfg:
v=self.cfg[var_name]
if isinstance(v, basestring): #string or unicode
self.cfg[var_name]=value
elif hasattr(v, '__iter__'): #probaly list
r=[]
for var in value.split(' '):
try:
r.append(ast.literal_eval(var))
except:
#some special strings should be converted to bool
if var in ('false', '#f'):
r.append(False)
elif var in ('true', '#t'):
r.append(True)
else:
r.append(var)
self.cfg[var_name]=r
else:
try:
self.cfg[var_name]=(ast.literal_eval(value))
except:
self.cfg[var_name]=value
else:
try:
self.cfg[var_name]=(ast.literal_eval(value))
except:
self.cfg[var_name]=value
def getCfgValueAsString(self, var_name):
if var_name not in self.cfg:
v=self.getValueFromConfigVariable(var_name)
self.cfg[var_name]=v
return self.getCfgValueAsString(var_name)
v=self.cfg[var_name]
if isinstance(v, basestring): #string or unicode
return v
elif hasattr(v, '__iter__'): #any type of sequence
temp_string=''
for item in v:
temp_string+=str(item)+' '
return temp_string.strip()
else:
return str(v)
class Logger:
"""
Prints messages to the consol and/or file and or gui element
"""
def __init__(self, gui=None, out_file=None):
self.notify = DirectNotify().newCategory('a4p')
self.gui=gui
self.out_file=None
if out_file:
self.out_file=open(path+out_file,'a')
self.out_file.write('---<Opening file on: '+str(datetime.now())+' >---\n')
self.debug('Logger is now logging')
self.debug('Logger gui is '+str(gui))
self.debug('Logger out_file is '+str(out_file))
def error(self, msg):
if self.gui:
self.gui.showMsg('Error: '+msg)
if self.out_file:
self.out_file.write('Error:'+msg+'\n')
self.notify.warning('Error: '+msg)
def warning(self, msg):
self.notify.warning(msg)
if self.gui:
self.gui.showMsg('Warning: '+msg)
if self.out_file:
self.out_file.write('Warning: '+msg+'\n')
def info(self, msg):
self.notify.info(msg)
if self.gui:
self.gui.showMsg(msg)
if self.out_file:
self.out_file.write(msg)
def debug(self, msg):
self.notify.debug(msg)
if self.gui:
self.gui.showMsg('Debug: '+msg)
if self.out_file:
self.out_file.write('Debug: '+msg+'\n')
def exception(self, msg):
if self.gui:
self.gui.showMsg('Exception: '+msg)
if self.out_file:
self.out_file.write('Exception: '+msg+'\n')
self.notify.error(msg)
def closeLogFile(self):
if self.out_file:
self.out_file.write('---<Closing file on: '+str(datetime.now())+' >---\n')
self.out_file.close()
self.out_file=None
class App():
"""
Program entry point. This class is here to init ShowBase, load config files and launch the game.
This part of the game can be packed to a p3d/exe/binary while keeping the rest of the game
as human readable python source files (py), bytecode (pyc), or a compiled extension module (pyd)
This class creates the fallowing builtins:
-log (Logger)
-app (App)
-cfg (Configer)
And anything else the ShowBase creates
"""
def __init__(self):
#init ShowBase
base = ShowBase.ShowBase()
#base.disableMouse()
#load all the config vars
builtins.cfg=Configer(path+'config.txt')
#log/print all messages
builtins.log=Logger(out_file=cfg['log-file'])
#print the msg (as needed from the configer
for msg in cfg.debug:
log.debug(msg)
for msg in cfg.warning:
log.warning(msg)
#make the path a builtin
builtins.path=path
log.debug('Curent working directory is: '+path)
if cfg['want-pstats']:
PStatClient.connect()
#config vars can also be passed as command line arguments
if len(sys.argv)>1:
names=sys.argv[1:][::2]
values=sys.argv[2:][::2]
for name, value in dict(zip(names, values)).items():
log.debug('cmd option: '+name+' '+value)
cfg.setCfgValueFromString(name, value)
log.debug(name+':'+str(cfg[name]))
#start the game
self.startGame(path+cfg['source-dir'])
def startGame(self, source_dir):
sys.path.append(source_dir)
log.debug('Importing Game from: '+source_dir)
try:
from game import Game
self.game=Game()
except:
log.error('Can not import the Game module!')
for error in traceback.format_exc().splitlines()[1:]:
log.warning(error)
self.exit()
def exit(self):
log.debug('Final message, shuting down.')
log.closeLogFile()
os._exit(1)
#os.kill(os.getpid(), signal.SIGTERM )
#base.userExit()
builtins.app=App()
base.run()