forked from panda3d/panda3d
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShowBase.py
More file actions
3266 lines (2718 loc) · 126 KB
/
ShowBase.py
File metadata and controls
3266 lines (2718 loc) · 126 KB
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
""" This module contains ShowBase, an application framework responsible
for opening a graphical display, setting up input devices and creating
the scene graph.
The simplest way to open a ShowBase instance is to execute this code:
.. code-block:: python
from direct.showbase.ShowBase import ShowBase
base = ShowBase()
base.run()
A common approach is to create your own subclass inheriting from ShowBase.
Built-in global variables
-------------------------
Some key variables used in all Panda3D scripts are actually attributes of the
ShowBase instance. When creating an instance of this class, it will write many
of these variables to the built-in scope of the Python interpreter, so that
they are accessible to any Python module.
While these are handy for prototyping, we do not recommend using them in bigger
projects, as it can make the code confusing to read to other Python developers,
to whom it may not be obvious where these variables are originating.
Some of these built-in variables are documented further in the
:mod:`~direct.showbase.ShowBaseGlobal` module.
"""
__all__ = ['ShowBase', 'WindowControls']
# This module redefines the builtin import function with one
# that prints out every import it does in a hierarchical form
# Annoying and very noisy, but sometimes useful
#import VerboseImport
from panda3d.core import *
from panda3d.direct import throw_new_frame, init_app_for_gui
from panda3d.direct import storeAccessibilityShortcutKeys, allowAccessibilityShortcutKeys
from . import DConfig
# Register the extension methods for NodePath.
from direct.extensions_native import NodePath_extensions
# This needs to be available early for DirectGUI imports
import sys
import builtins
builtins.config = DConfig
from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify
from .MessengerGlobal import messenger
from .BulletinBoardGlobal import bulletinBoard
from direct.task.TaskManagerGlobal import taskMgr
from .JobManagerGlobal import jobMgr
from .EventManagerGlobal import eventMgr
#from PythonUtil import *
from direct.interval import IntervalManager
from direct.showbase.BufferViewer import BufferViewer
from direct.task import Task
from . import Loader
import time
import atexit
import importlib
from direct.showbase import ExceptionVarDump
from . import DirectObject
from . import SfxPlayer
if __debug__:
from direct.showbase import GarbageReport
from direct.directutil import DeltaProfiler
from . import OnScreenDebug
@atexit.register
def exitfunc():
if getattr(builtins, 'base', None) is not None:
builtins.base.destroy()
# Now ShowBase is a DirectObject. We need this so ShowBase can hang
# hooks on messages, particularly on window-event. This doesn't
# *seem* to cause anyone any problems.
class ShowBase(DirectObject.DirectObject):
config = DConfig
notify = directNotify.newCategory("ShowBase")
def __init__(self, fStartDirect=True, windowType=None):
"""Opens a window, sets up a 3-D and several 2-D scene graphs, and
everything else needed to render the scene graph to the window.
To prevent a window from being opened, set windowType to the string
'none' (or 'offscreen' to create an offscreen buffer). If this is not
specified, the default value is taken from the 'window-type'
configuration variable.
This constructor will add various things to the Python builtins scope,
including this instance itself (under the name ``base``).
"""
self.__dev__ = self.config.GetBool('want-dev', __debug__)
builtins.__dev__ = self.__dev__
logStackDump = (self.config.GetBool('log-stack-dump', False) or
self.config.GetBool('client-log-stack-dump', False))
uploadStackDump = self.config.GetBool('upload-stack-dump', False)
if logStackDump or uploadStackDump:
ExceptionVarDump.install(logStackDump, uploadStackDump)
if __debug__:
self.__autoGarbageLogging = self.__dev__ and self.config.GetBool('auto-garbage-logging', False)
## The directory containing the main Python file of this application.
self.mainDir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
self.main_dir = self.mainDir
## This contains the global appRunner instance, as imported from
## AppRunnerGlobal. This will be None if we are not running in the
## runtime environment (ie. from a .p3d file).
self.appRunner = None
self.app_runner = self.appRunner
#debug running multiplier
self.debugRunningMultiplier = 4
# [gjeon] to disable sticky keys
if self.config.GetBool('disable-sticky-keys', 0):
storeAccessibilityShortcutKeys()
allowAccessibilityShortcutKeys(False)
self.printEnvDebugInfo()
vfs = VirtualFileSystem.getGlobalPtr()
self.nextWindowIndex = 1
self.__directStarted = False
self.__deadInputs = 0
# Store dconfig variables
self.sfxActive = self.config.GetBool('audio-sfx-active', 1)
self.musicActive = self.config.GetBool('audio-music-active', 1)
self.wantFog = self.config.GetBool('want-fog', 1)
self.wantRender2dp = self.config.GetBool('want-render2dp', 1)
self.screenshotExtension = self.config.GetString('screenshot-extension', 'jpg')
self.musicManager = None
self.musicManagerIsValid = None
self.sfxManagerList = []
self.sfxManagerIsValidList = []
self.wantStats = self.config.GetBool('want-pstats', 0)
self.wantTk = False
self.wantWx = False
## Fill this in with a function to invoke when the user "exits"
## the program by closing the main window.
self.exitFunc = None
## Add final-exit callbacks to this list. These will be called
## when sys.exit() is called, after Panda has unloaded, and
## just before Python is about to shut down.
self.finalExitCallbacks = []
# Set up the TaskManager to reset the PStats clock back
# whenever we resume from a pause. This callback function is
# a little hacky, but we can't call it directly from within
# the TaskManager because he doesn't know about PStats (and
# has to run before libpanda is even loaded).
taskMgr.resumeFunc = PStatClient.resumeAfterPause
if self.__dev__:
self.__setupProfile()
# If the aspect ratio is 0 or None, it means to infer the
# aspect ratio from the window size.
# If you need to know the actual aspect ratio call base.getAspectRatio()
self.__configAspectRatio = ConfigVariableDouble('aspect-ratio', 0).getValue()
# This variable is used to see if the aspect ratio has changed when
# we get a window-event.
self.__oldAspectRatio = None
## This is set to the value of the window-type config variable, but may
## optionally be overridden in the Showbase constructor. Should either be
## 'onscreen' (the default), 'offscreen' or 'none'.
self.windowType = windowType
if self.windowType is None:
self.windowType = self.config.GetString('window-type', 'onscreen')
self.requireWindow = self.config.GetBool('require-window', 1)
## This is the main, or only window; see winList for a list of *all* windows.
self.win = None
self.frameRateMeter = None
self.sceneGraphAnalyzerMeter = None
self.winList = []
self.winControls = []
self.mainWinMinimized = 0
self.mainWinForeground = 0
self.pipe = None
self.pipeList = []
self.mouse2cam = None
self.buttonThrowers = None
self.mouseWatcher = None
self.mouseWatcherNode = None
self.pointerWatcherNodes = None
self.mouseInterface = None
self.drive = None
self.trackball = None
self.texmem = None
self.showVertices = None
self.deviceButtonThrowers = []
## This is a NodePath pointing to the Camera object set up for the 3D scene.
## This is usually a child of self.camera.
self.cam = None
self.cam2d = None
self.cam2dp = None
## This is the NodePath that should be used to manipulate the camera. This
## is the node to which the default camera is attached.
self.camera = None
self.camera2d = None
self.camera2dp = None
## This is a list of all cameras created with makeCamera, including base.cam.
self.camList = []
## Convenience accessor for base.cam.node()
self.camNode = None
## Convenience accessor for base.camNode.get_lens()
self.camLens = None
self.camFrustumVis = None
self.direct = None
## This is used to store the wx.Application object used when want-wx is
## set or base.startWx() is called.
self.wxApp = None
self.wxAppCreated = False
self.tkRoot = None
self.tkRootCreated = False
# This is used for syncing multiple PCs in a distributed cluster
try:
# Has the cluster sync variable been set externally?
self.clusterSyncFlag = clusterSyncFlag
except NameError:
# Has the clusterSyncFlag been set via a config variable
self.clusterSyncFlag = self.config.GetBool('cluster-sync', 0)
# We've already created aspect2d in ShowBaseGlobal, for the
# benefit of creating DirectGui elements before ShowBase.
from . import ShowBaseGlobal
self.hidden = ShowBaseGlobal.hidden
## The global graphics engine, ie. GraphicsEngine.getGlobalPtr()
self.graphicsEngine = GraphicsEngine.getGlobalPtr()
self.graphics_engine = self.graphicsEngine
self.setupRender()
self.setupRender2d()
self.setupDataGraph()
if self.wantRender2dp:
self.setupRender2dp()
## This is a placeholder for a CollisionTraverser. If someone
## stores a CollisionTraverser pointer here, we'll traverse it
## in the collisionLoop task.
self.cTrav = 0
self.shadowTrav = 0
self.cTravStack = Stack()
# Ditto for an AppTraverser.
self.appTrav = 0
# This is the DataGraph traverser, which we might as well
# create now.
self.dgTrav = DataGraphTraverser()
# Maybe create a RecorderController to record and/or play back
# the user session.
self.recorder = None
playbackSession = self.config.GetString('playback-session', '')
recordSession = self.config.GetString('record-session', '')
if playbackSession:
self.recorder = RecorderController()
self.recorder.beginPlayback(Filename.fromOsSpecific(playbackSession))
elif recordSession:
self.recorder = RecorderController()
self.recorder.beginRecord(Filename.fromOsSpecific(recordSession))
if self.recorder:
# If we're either playing back or recording, pass the
# random seed into the system so each session will have
# the same random seed.
import random #, whrandom
seed = self.recorder.getRandomSeed()
random.seed(seed)
#whrandom.seed(seed & 0xff, (seed >> 8) & 0xff, (seed >> 16) & 0xff)
# For some reason, wx needs to be initialized before the graphics window
if sys.platform == "darwin":
if self.config.GetBool("want-wx", 0):
wx = importlib.import_module('wx')
self.wxApp = wx.App()
# Same goes for Tk, which uses a conflicting NSApplication
if self.config.GetBool("want-tk", 0):
Pmw = importlib.import_module('Pmw')
self.tkRoot = Pmw.initialise()
# Open the default rendering window.
if self.windowType != 'none':
props = WindowProperties.getDefault()
if (self.config.GetBool('read-raw-mice', 0)):
props.setRawMice(1)
self.openDefaultWindow(startDirect = False, props=props)
# The default is trackball mode, which is more convenient for
# ad-hoc development in Python using ShowBase. Applications
# can explicitly call base.useDrive() if they prefer a drive
# interface.
self.mouseInterface = self.trackball
self.useTrackball()
self.loader = Loader.Loader(self)
self.graphicsEngine.setDefaultLoader(self.loader.loader)
## The global event manager, as imported from EventManagerGlobal.
self.eventMgr = eventMgr
## The global messenger, as imported from MessengerGlobal.
self.messenger = messenger
## The global bulletin board, as imported from BulletinBoardGlobal.
self.bboard = bulletinBoard
## The global task manager, as imported from TaskManagerGlobal.
self.taskMgr = taskMgr
self.task_mgr = taskMgr
## The global job manager, as imported from JobManagerGlobal.
self.jobMgr = jobMgr
## Particle manager
self.particleMgr = None
self.particleMgrEnabled = 0
## Physics manager
self.physicsMgr = None
self.physicsMgrEnabled = 0
self.physicsMgrAngular = 0
## This is the global input device manager, which keeps track of
## connected input devices.
self.devices = InputDeviceManager.getGlobalPtr()
self.__inputDeviceNodes = {}
self.createStats()
self.AppHasAudioFocus = 1
# Get a pointer to Panda's global ClockObject, used for
# synchronizing events between Python and C.
globalClock = ClockObject.getGlobalClock()
# Since we have already started up a TaskManager, and probably
# a number of tasks; and since the TaskManager had to use the
# TrueClock to tell time until this moment, make sure the
# globalClock object is exactly in sync with the TrueClock.
trueClock = TrueClock.getGlobalPtr()
globalClock.setRealTime(trueClock.getShortTime())
globalClock.tick()
# Now we can make the TaskManager start using the new globalClock.
taskMgr.globalClock = globalClock
# client CPU affinity is determined by, in order:
# - client-cpu-affinity-mask config
# - pcalt-# (# is CPU number, 0-based)
# - client-cpu-affinity config
# - auto-single-cpu-affinity config
affinityMask = self.config.GetInt('client-cpu-affinity-mask', -1)
if affinityMask != -1:
TrueClock.getGlobalPtr().setCpuAffinity(affinityMask)
else:
# this is useful on machines that perform better with each process
# assigned to a single CPU
autoAffinity = self.config.GetBool('auto-single-cpu-affinity', 0)
affinity = None
if autoAffinity and hasattr(builtins, 'clientIndex'):
affinity = abs(int(builtins.clientIndex))
else:
affinity = self.config.GetInt('client-cpu-affinity', -1)
if (affinity in (None, -1)) and autoAffinity:
affinity = 0
if affinity not in (None, -1):
# Windows XP supports a 32-bit affinity mask
TrueClock.getGlobalPtr().setCpuAffinity(1 << (affinity % 32))
# Make sure we're not making more than one ShowBase.
if hasattr(builtins, 'base'):
raise Exception("Attempt to spawn multiple ShowBase instances!")
# DO NOT ADD TO THIS LIST. We're trying to phase out the use of
# built-in variables by ShowBase. Use a Global module if necessary.
builtins.base = self
builtins.render2d = self.render2d
builtins.aspect2d = self.aspect2d
builtins.pixel2d = self.pixel2d
builtins.render = self.render
builtins.hidden = self.hidden
builtins.camera = self.camera
builtins.loader = self.loader
builtins.taskMgr = self.taskMgr
builtins.jobMgr = self.jobMgr
builtins.eventMgr = self.eventMgr
builtins.messenger = self.messenger
builtins.bboard = self.bboard
# Config needs to be defined before ShowBase is constructed
#builtins.config = self.config
builtins.ostream = Notify.out()
builtins.directNotify = directNotify
builtins.giveNotify = giveNotify
builtins.globalClock = globalClock
builtins.vfs = vfs
builtins.cpMgr = ConfigPageManager.getGlobalPtr()
builtins.cvMgr = ConfigVariableManager.getGlobalPtr()
builtins.pandaSystem = PandaSystem.getGlobalPtr()
if __debug__:
builtins.deltaProfiler = DeltaProfiler.DeltaProfiler("ShowBase")
self.onScreenDebug = OnScreenDebug.OnScreenDebug()
builtins.onScreenDebug = self.onScreenDebug
if self.wantRender2dp:
builtins.render2dp = self.render2dp
builtins.aspect2dp = self.aspect2dp
builtins.pixel2dp = self.pixel2dp
# Now add this instance to the ShowBaseGlobal module scope.
from . import ShowBaseGlobal
builtins.run = ShowBaseGlobal.run
ShowBaseGlobal.base = self
ShowBaseGlobal.__dev__ = self.__dev__
if self.__dev__:
ShowBase.notify.debug('__dev__ == %s' % self.__dev__)
else:
ShowBase.notify.info('__dev__ == %s' % self.__dev__)
self.createBaseAudioManagers()
if self.__dev__ and self.config.GetBool('track-gui-items', False):
# dict of guiId to gui item, for tracking down leaks
if not hasattr(ShowBase, 'guiItems'):
ShowBase.guiItems = {}
# optionally restore the default gui sounds from 1.7.2 and earlier
if ConfigVariableBool('orig-gui-sounds', False).getValue():
from direct.gui import DirectGuiGlobals as DGG
DGG.setDefaultClickSound(self.loader.loadSfx("audio/sfx/GUI_click.wav"))
DGG.setDefaultRolloverSound(self.loader.loadSfx("audio/sfx/GUI_rollover.wav"))
# Now hang a hook on the window-event from Panda. This allows
# us to detect when the user resizes, minimizes, or closes the
# main window.
self.__prevWindowProperties = None
self.accept('window-event', self.windowEvent)
# Transition effects (fade, iris, etc)
from . import Transitions
self.transitions = Transitions.Transitions(self.loader)
if self.win:
# Setup the window controls - handy for multiwindow applications
self.setupWindowControls()
# Client sleep
sleepTime = self.config.GetFloat('client-sleep', 0.0)
self.clientSleep = 0.0
self.setSleep(sleepTime)
# Extra sleep for running 4+ clients on a single machine
# adds a sleep right after the main render in igloop
# tends to even out the frame rate and keeps it from going
# to zero in the out of focus windows
if self.config.GetBool('multi-sleep', 0):
self.multiClientSleep = 1
else:
self.multiClientSleep = 0
# Offscreen buffer viewing utility.
# This needs to be allocated even if the viewer is off.
if self.wantRender2dp:
self.bufferViewer = BufferViewer(self.win, self.render2dp)
else:
self.bufferViewer = BufferViewer(self.win, self.render2d)
if self.windowType != 'none':
if fStartDirect: # [gjeon] if this is False let them start direct manually
self.__doStartDirect()
if self.config.GetBool('show-tex-mem', False):
if not self.texmem or self.texmem.cleanedUp:
self.toggleTexMem()
taskMgr.finalInit()
# Start IGLOOP
self.restart()
# add a collision traverser via pushCTrav and remove it via popCTrav
# that way the owner of the new cTrav doesn't need to hold onto the
# previous one in order to put it back
def pushCTrav(self, cTrav):
self.cTravStack.push(self.cTrav)
self.cTrav = cTrav
def popCTrav(self):
self.cTrav = self.cTravStack.pop()
def __setupProfile(self):
""" Sets up the Python profiler, if available, according to
some Panda config settings. """
try:
profile = importlib.import_module('profile')
pstats = importlib.import_module('pstats')
except ImportError:
return
profile.Profile.bias = float(self.config.GetString("profile-bias","0"))
def f8(x):
return ("%" + "8.%df" % self.config.GetInt("profile-decimals", 3)) % x
pstats.f8 = f8
# temp; see ToonBase.py
def getExitErrorCode(self):
return 0
def printEnvDebugInfo(self):
"""Print some information about the environment that we are running
in. Stuff like the model paths and other paths. Feel free to
add stuff to this.
"""
if self.config.GetBool('want-env-debug-info', 0):
print("\n\nEnvironment Debug Info {")
print("* model path:")
print(getModelPath())
#print "* dna path:"
#print getDnaPath()
print("}")
def destroy(self):
""" Call this function to destroy the ShowBase and stop all
its tasks, freeing all of the Panda resources. Normally, you
should not need to call it explicitly, as it is bound to the
exitfunc and will be called at application exit time
automatically.
This function is designed to be safe to call multiple times."""
for cb in self.finalExitCallbacks[:]:
cb()
# Remove the built-in base reference
if getattr(builtins, 'base', None) is self:
del builtins.run
del builtins.base
del builtins.loader
del builtins.taskMgr
ShowBaseGlobal = sys.modules.get('direct.showbase.ShowBaseGlobal', None)
if ShowBaseGlobal:
del ShowBaseGlobal.base
self.aspect2d.node().removeAllChildren()
self.render2d.node().removeAllChildren()
self.aspect2d.reparent_to(self.render2d)
# [gjeon] restore sticky key settings
if self.config.GetBool('disable-sticky-keys', 0):
allowAccessibilityShortcutKeys(True)
self.ignoreAll()
self.shutdown()
if getattr(self, 'musicManager', None):
self.musicManager.shutdown()
self.musicManager = None
for sfxManager in self.sfxManagerList:
sfxManager.shutdown()
self.sfxManagerList = []
if getattr(self, 'loader', None):
self.loader.destroy()
self.loader = None
if getattr(self, 'graphicsEngine', None):
self.graphicsEngine.removeAllWindows()
try:
self.direct.panel.destroy()
except:
pass
if hasattr(self, 'win'):
del self.win
del self.winList
del self.pipe
def makeDefaultPipe(self, printPipeTypes = None):
"""
Creates the default GraphicsPipe, which will be used to make
windows unless otherwise specified.
"""
assert self.pipe == None
if printPipeTypes is None:
# When the user didn't specify an explicit setting, take the value
# from the config variable. We could just omit the parameter, however
# this way we can keep backward compatibility.
printPipeTypes = ConfigVariableBool("print-pipe-types", True)
selection = GraphicsPipeSelection.getGlobalPtr()
if printPipeTypes:
selection.printPipeTypes()
self.pipe = selection.makeDefaultPipe()
if not self.pipe:
self.notify.error(
"No graphics pipe is available!\n"
"Your Config.prc file must name at least one valid panda display\n"
"library via load-display or aux-display.")
self.notify.info("Default graphics pipe is %s (%s)." % (
self.pipe.getType().getName(), self.pipe.getInterfaceName()))
self.pipeList.append(self.pipe)
def makeModulePipe(self, moduleName):
"""
Returns a GraphicsPipe from the indicated module,
e.g. 'pandagl' or 'pandadx9'. Does not affect base.pipe or
base.pipeList.
"""
selection = GraphicsPipeSelection.getGlobalPtr()
return selection.makeModulePipe(moduleName)
def makeAllPipes(self):
"""
Creates all GraphicsPipes that the system knows about and fill up
self.pipeList with them.
"""
selection = GraphicsPipeSelection.getGlobalPtr()
selection.loadAuxModules()
# First, we should make sure the default pipe exists.
if self.pipe == None:
self.makeDefaultPipe()
# Now go through the list of known pipes, and make each one if
# we don't have one already.
numPipeTypes = selection.getNumPipeTypes()
for i in range(numPipeTypes):
pipeType = selection.getPipeType(i)
# Do we already have a pipe of this type on the list?
# This operation is n-squared, but presumably there won't
# be more than a handful of pipe types, so who cares.
already = 0
for pipe in self.pipeList:
if pipe.getType() == pipeType:
already = 1
if not already:
pipe = selection.makePipe(pipeType)
if pipe:
self.notify.info("Got aux graphics pipe %s (%s)." % (
pipe.getType().getName(), pipe.getInterfaceName()))
self.pipeList.append(pipe)
else:
self.notify.info("Could not make graphics pipe %s." % (
pipeType.getName()))
def openWindow(self, props = None, fbprops = None, pipe = None, gsg = None,
host = None, type = None, name = None, size = None,
aspectRatio = None, makeCamera = True, keepCamera = False,
scene = None, stereo = None, unexposedDraw = None,
callbackWindowDict = None, requireWindow = None):
"""
Creates a window and adds it to the list of windows that are
to be updated every frame.
props is the WindowProperties that describes the window.
type is either 'onscreen', 'offscreen', or 'none'.
If keepCamera is true, the existing base.cam is set up to
render into the new window.
If keepCamera is false but makeCamera is true, a new camera is
set up to render into the new window.
If unexposedDraw is not None, it specifies the initial value
of GraphicsWindow.setUnexposedDraw().
If callbackWindowDict is not None, a CallbackGraphicWindow is
created instead, which allows the caller to create the actual
window with its own OpenGL context, and direct Panda's
rendering into that window.
If requireWindow is true, it means that the function should
raise an exception if the window fails to open correctly.
"""
# Save this lambda here for convenience; we'll use it to call
# down to the underlying _doOpenWindow() with all of the above
# parameters.
func = lambda : self._doOpenWindow(
props = props, fbprops = fbprops, pipe = pipe, gsg = gsg,
host = host, type = type, name = name, size = size,
aspectRatio = aspectRatio, makeCamera = makeCamera,
keepCamera = keepCamera, scene = scene, stereo = stereo,
unexposedDraw = unexposedDraw,
callbackWindowDict = callbackWindowDict)
if self.win:
# If we've already opened a window before, this is just a
# pass-through to _doOpenWindow().
win = func()
self.graphicsEngine.openWindows()
return win
if type is None:
type = self.windowType
if requireWindow is None:
requireWindow = self.requireWindow
win = func()
# Give the window a chance to truly open.
self.graphicsEngine.openWindows()
if win != None and not win.isValid():
self.notify.info("Window did not open, removing.")
self.closeWindow(win)
win = None
if win == None and pipe == None:
# Try a little harder if the window wouldn't open.
self.makeAllPipes()
try:
self.pipeList.remove(self.pipe)
except ValueError:
pass
while self.win == None and self.pipeList:
self.pipe = self.pipeList[0]
self.notify.info("Trying pipe type %s (%s)" % (
self.pipe.getType(), self.pipe.getInterfaceName()))
win = func()
self.graphicsEngine.openWindows()
if win != None and not win.isValid():
self.notify.info("Window did not open, removing.")
self.closeWindow(win)
win = None
if win == None:
self.pipeList.remove(self.pipe)
if win == None:
self.notify.warning("Unable to open '%s' window." % (type))
if requireWindow:
# Unless require-window is set to false, it is an
# error not to open a window.
raise Exception('Could not open window.')
else:
self.notify.info("Successfully opened window of type %s (%s)" % (
win.getType(), win.getPipe().getInterfaceName()))
return win
def _doOpenWindow(self, props = None, fbprops = None, pipe = None,
gsg = None, host = None, type = None, name = None,
size = None, aspectRatio = None,
makeCamera = True, keepCamera = False,
scene = None, stereo = None, unexposedDraw = None,
callbackWindowDict = None):
if pipe == None:
pipe = self.pipe
if pipe == None:
self.makeDefaultPipe()
pipe = self.pipe
if pipe == None:
# We couldn't get a pipe.
return None
if isinstance(gsg, GraphicsOutput):
# If the gsg is a window or buffer, it means to use the
# GSG from that buffer.
host = gsg
gsg = gsg.getGsg()
# If we are using DirectX, force a new GSG to be created,
# since at the moment DirectX seems to misbehave if we do
# not do this. This will cause a delay while all textures
# etc. are reloaded, so we should revisit this later if we
# can fix the underlying bug in our DirectX support.
if pipe.getType().getName().startswith('wdx'):
gsg = None
if type == None:
type = self.windowType
if props == None:
props = WindowProperties.getDefault()
if fbprops == None:
fbprops = FrameBufferProperties.getDefault()
if size != None:
# If we were given an explicit size, use it; otherwise,
# the size from the properties is used.
props = WindowProperties(props)
props.setSize(size[0], size[1])
if name == None:
name = 'window%s' % (self.nextWindowIndex)
self.nextWindowIndex += 1
win = None
flags = GraphicsPipe.BFFbPropsOptional
if type == 'onscreen':
flags = flags | GraphicsPipe.BFRequireWindow
elif type == 'offscreen':
flags = flags | GraphicsPipe.BFRefuseWindow
if callbackWindowDict:
flags = flags | GraphicsPipe.BFRequireCallbackWindow
if host:
assert host.isValid()
win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
props, flags, host.getGsg(), host)
elif gsg:
win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
props, flags, gsg)
else:
win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
props, flags)
if win == None:
# Couldn't create a window!
return None
if unexposedDraw is not None and hasattr(win, 'setUnexposedDraw'):
win.setUnexposedDraw(unexposedDraw)
if callbackWindowDict:
# If we asked for (and received) a CallbackGraphicsWindow,
# we now have to assign the callbacks, before we start
# trying to do anything with the window.
for callbackName in ['Events', 'Properties', 'Render']:
func = callbackWindowDict.get(callbackName, None)
if not func:
continue
setCallbackName = 'set%sCallback' % (callbackName)
setCallback = getattr(win, setCallbackName)
setCallback(PythonCallbackObject(func))
# We also need to set up the mouse/keyboard objects.
for inputName in callbackWindowDict.get('inputDevices', ['mouse']):
win.createInputDevice(inputName)
if hasattr(win, "requestProperties"):
win.requestProperties(props)
mainWindow = False
if self.win is None:
mainWindow = True
self.win = win
if hasattr(self, 'bufferViewer'):
self.bufferViewer.win = win
self.winList.append(win)
# Set up a 3-d camera for the window by default.
if keepCamera:
self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
stereo = stereo, useCamera = self.cam)
elif makeCamera:
self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
stereo = stereo)
messenger.send('open_window', [win, mainWindow])
if mainWindow:
messenger.send('open_main_window')
return win
def closeWindow(self, win, keepCamera = False, removeWindow = True):
"""
Closes the indicated window and removes it from the list of
windows. If it is the main window, clears the main window
pointer to None.
"""
win.setActive(False)
# First, remove all of the cameras associated with display
# regions on the window.
numRegions = win.getNumDisplayRegions()
for i in range(numRegions):
dr = win.getDisplayRegion(i)
# [gjeon] remove drc in base.direct.drList
if self.direct is not None:
for drc in self.direct.drList:
if drc.cam == dr.getCamera():
self.direct.drList.displayRegionList.remove(drc)
break
cam = NodePath(dr.getCamera())
dr.setCamera(NodePath())
if not cam.isEmpty() and \
cam.node().getNumDisplayRegions() == 0 and \
not keepCamera:
# If the camera is used by no other DisplayRegions,
# remove it.
if self.camList.count(cam) != 0:
self.camList.remove(cam)
# Don't throw away self.camera; we want to
# preserve it for reopening the window.
if cam == self.cam:
self.cam = None
if cam == self.cam2d:
self.cam2d = None
if cam == self.cam2dp:
self.cam2dp = None
cam.removeNode()
# [gjeon] remove winControl
for winCtrl in self.winControls:
if winCtrl.win == win:
self.winControls.remove(winCtrl)
break
# Now we can actually close the window.
if removeWindow:
self.graphicsEngine.removeWindow(win)
self.winList.remove(win)
mainWindow = False
if win == self.win:
mainWindow = True
self.win = None
if self.frameRateMeter:
self.frameRateMeter.clearWindow()
self.frameRateMeter = None
if self.sceneGraphAnalyzerMeter:
self.sceneGraphAnalyzerMeter.clearWindow()
self.sceneGraphAnalyzerMeter = None
messenger.send('close_window', [win, mainWindow])
if mainWindow:
messenger.send('close_main_window')
if not self.winList:
# Give the window(s) a chance to actually close before we
# continue.
self.graphicsEngine.renderFrame()
def openDefaultWindow(self, *args, **kw):
# Creates the main window for the first time, without being
# too particular about the kind of graphics API that is
# chosen. The suggested window type from the load-display
# config variable is tried first; if that fails, the first
# window type that can be successfully opened at all is
# accepted. Returns true on success, false otherwise.
#
# This is intended to be called only once, at application
# startup. It is normally called automatically unless
# window-type is configured to 'none'.
startDirect = kw.get('startDirect', True)
if 'startDirect' in kw:
del kw['startDirect']
self.openMainWindow(*args, **kw)
if startDirect:
self.__doStartDirect()
return self.win != None
def openMainWindow(self, *args, **kw):
"""
Creates the initial, main window for the application, and sets
up the mouse and render2d structures appropriately for it. If
this method is called a second time, it will close the
previous main window and open a new one, preserving the lens
properties in base.camLens.
The return value is true on success, or false on failure (in
which case base.win may be either None, or the previous,
closed window).
"""
keepCamera = kw.get('keepCamera', False)