direct: Fix use of various deprecated APIs

This commit is contained in:
rdb 2021-03-09 19:21:26 +01:00
parent 2493c0689f
commit 3fe1780f16
14 changed files with 137 additions and 113 deletions

View File

@ -97,13 +97,13 @@ class DirectSession(DirectObject):
self.joybox = None self.joybox = None
self.radamec = None self.radamec = None
self.fastrak = [] self.fastrak = []
if base.config.GetBool('want-vrpn', 0): if ConfigVariableBool('want-vrpn', False):
from direct.directdevices import DirectDeviceManager from direct.directdevices import DirectDeviceManager
self.deviceManager = DirectDeviceManager.DirectDeviceManager() self.deviceManager = DirectDeviceManager.DirectDeviceManager()
# Automatically create any devices specified in config file # Automatically create any devices specified in config file
joybox = base.config.GetString('vrpn-joybox-device', '') joybox = ConfigVariableString('vrpn-joybox-device', '').value
radamec = base.config.GetString('vrpn-radamec-device', '') radamec = ConfigVariableString('vrpn-radamec-device', '').value
fastrak = base.config.GetString('vrpn-fastrak-device', '') fastrak = ConfigVariableString('vrpn-fastrak-device', '').value
if joybox: if joybox:
from direct.directdevices import DirectJoybox from direct.directdevices import DirectJoybox
self.joybox = DirectJoybox.DirectJoybox(joybox) self.joybox = DirectJoybox.DirectJoybox(joybox)
@ -300,7 +300,7 @@ class DirectSession(DirectObject):
self.clusterMode = clusterMode self.clusterMode = clusterMode
except NameError: except NameError:
# Has the clusterMode been set via a config variable? # Has the clusterMode been set via a config variable?
self.clusterMode = base.config.GetString("cluster-mode", '') self.clusterMode = ConfigVariableString("cluster-mode", '').value
if self.clusterMode == 'client': if self.clusterMode == 'client':
self.cluster = createClusterClient() self.cluster = createClusterClient()

View File

@ -33,7 +33,7 @@ class ClientRepositoryBase(ConnectionRepository):
ConnectionRepository.__init__(self, connectMethod, base.config, hasOwnerView = True, threadedNet = threadedNet) ConnectionRepository.__init__(self, connectMethod, base.config, hasOwnerView = True, threadedNet = threadedNet)
self.dcSuffix = dcSuffix self.dcSuffix = dcSuffix
if hasattr(self, 'setVerbose'): if hasattr(self, 'setVerbose'):
if self.config.GetBool('verbose-clientrepository'): if ConfigVariableBool('verbose-clientrepository', False):
self.setVerbose(1) self.setVerbose(1)
self.context=100000 self.context=100000
@ -42,7 +42,7 @@ class ClientRepositoryBase(ConnectionRepository):
self.deferredGenerates = [] self.deferredGenerates = []
self.deferredDoIds = {} self.deferredDoIds = {}
self.lastGenerate = 0 self.lastGenerate = 0
self.setDeferInterval(base.config.GetDouble('deferred-generate-interval', 0.2)) self.setDeferInterval(ConfigVariableDouble('deferred-generate-interval', 0.2).value)
self.noDefer = False # Set this True to temporarily disable deferring. self.noDefer = False # Set this True to temporarily disable deferring.
self.recorder = base.recorder self.recorder = base.recorder
@ -69,7 +69,7 @@ class ClientRepositoryBase(ConnectionRepository):
# Keep track of how recently we last sent a heartbeat message. # Keep track of how recently we last sent a heartbeat message.
# We want to keep these coming at heartbeatInterval seconds. # We want to keep these coming at heartbeatInterval seconds.
self.heartbeatInterval = base.config.GetDouble('heartbeat-interval', 10) self.heartbeatInterval = ConfigVariableDouble('heartbeat-interval', 10).value
self.heartbeatStarted = 0 self.heartbeatStarted = 0
self.lastHeartbeat = 0 self.lastHeartbeat = 0
@ -497,7 +497,7 @@ class ClientRepositoryBase(ConnectionRepository):
def handleServerHeartbeat(self, di): def handleServerHeartbeat(self, di):
# Got a heartbeat message from the server. # Got a heartbeat message from the server.
if base.config.GetBool('server-heartbeat-info', 1): if ConfigVariableBool('server-heartbeat-info', True):
self.notify.info("Server heartbeat.") self.notify.info("Server heartbeat.")
def handleSystemMessage(self, di): def handleSystemMessage(self, di):
@ -581,7 +581,7 @@ class ClientRepositoryBase(ConnectionRepository):
return worldNP return worldNP
def isLive(self): def isLive(self):
if base.config.GetBool('force-live', 0): if ConfigVariableBool('force-live', False):
return True return True
return not (__dev__ or launcher.isTestServer()) return not (__dev__ or launcher.isTestServer())

View File

@ -248,7 +248,7 @@ class ClockDelta(DirectObject.DirectObject):
# set movie-network-time 1, then we'll circumvent this logic # set movie-network-time 1, then we'll circumvent this logic
# and always return now. # and always return now.
if self.globalClock.getMode() == ClockObject.MNonRealTime and \ if self.globalClock.getMode() == ClockObject.MNonRealTime and \
base.config.GetBool('movie-network-time', False): ConfigVariableBool('movie-network-time', False):
return now return now
# First, determine what network time we have for 'now'. # First, determine what network time we have for 'now'.

View File

@ -4,6 +4,11 @@ from direct.fsm.FSM import FSM
from direct.interval.IntervalGlobal import * from direct.interval.IntervalGlobal import *
from direct.distributed.DistributedObject import DistributedObject from direct.distributed.DistributedObject import DistributedObject
_camera_id = ConfigVariableInt('camera-id', -1)
_aware_of_cameras = ConfigVariableInt('aware-of-cameras', 0)
class Fixture(NodePath, FSM): class Fixture(NodePath, FSM):
def __init__(self, id, parent, pos, hpr, fov): def __init__(self, id, parent, pos, hpr, fov):
NodePath.__init__(self, 'cam-%s' % id) NodePath.__init__(self, 'cam-%s' % id)
@ -60,15 +65,13 @@ class Fixture(NodePath, FSM):
def setRecordingInProgress(self, inProgress): def setRecordingInProgress(self, inProgress):
self.recordingInProgress = inProgress self.recordingInProgress = inProgress
if self.recordingInProgress and \ if self.recordingInProgress and _camera_id.value >= 0:
base.config.GetInt('camera-id', -1) >= 0:
self.hide() self.hide()
else: else:
self.show() self.show()
def show(self): def show(self):
if base.config.GetBool('aware-of-cameras',0) and \ if _aware_of_cameras and not self.recordingInProgress:
not self.recordingInProgress:
NodePath.show(self) NodePath.show(self)
def getScaleIval(self): def getScaleIval(self):
@ -99,7 +102,7 @@ class Fixture(NodePath, FSM):
def enterStandby(self): def enterStandby(self):
self.show() self.show()
if self.id == base.config.GetInt('camera-id', -1): if self.id == _camera_id.value:
self.setColorScale(3,0,0,1) self.setColorScale(3,0,0,1)
self.getScaleIval().loop() self.getScaleIval().loop()
else: else:
@ -116,7 +119,7 @@ class Fixture(NodePath, FSM):
self.scaleIval.finish() self.scaleIval.finish()
def enterRecording(self): def enterRecording(self):
if base.config.GetInt('camera-id', -1) == self.id: if _camera_id.value == self.id:
self.demand('Using') self.demand('Using')
else: else:
self.show() self.show()
@ -177,7 +180,7 @@ class DistributedCamera(DistributedObject):
DistributedObject.__init__(self, cr) DistributedObject.__init__(self, cr)
self.parent = None self.parent = None
self.fixtures = {} self.fixtures = {}
self.cameraId = base.config.GetInt('camera-id',0) self.cameraId = _camera_id.value
def __getitem__(self, index): def __getitem__(self, index):
return self.fixtures.get(index) return self.fixtures.get(index)

View File

@ -7,22 +7,21 @@ from . import DistributedNode
from . import DistributedSmoothNodeBase from . import DistributedSmoothNodeBase
from direct.task.Task import cont from direct.task.Task import cont
from direct.task.TaskManagerGlobal import taskMgr from direct.task.TaskManagerGlobal import taskMgr
from direct.showbase import DConfig as config
from direct.showbase.PythonUtil import report from direct.showbase.PythonUtil import report
# This number defines our tolerance for out-of-sync telemetry packets. # This number defines our tolerance for out-of-sync telemetry packets.
# If a packet appears to have originated from more than MaxFuture # If a packet appears to have originated from more than MaxFuture
# seconds in the future, assume we're out of sync with the other # seconds in the future, assume we're out of sync with the other
# avatar and suggest a resync for both. # avatar and suggest a resync for both.
MaxFuture = config.GetFloat("smooth-max-future", 0.2) MaxFuture = ConfigVariableDouble("smooth-max-future", 0.2)
# How frequently can we suggest a resynchronize with another client? # How frequently can we suggest a resynchronize with another client?
MinSuggestResync = config.GetFloat("smooth-min-suggest-resync", 15) MinSuggestResync = ConfigVariableDouble("smooth-min-suggest-resync", 15)
# These flags indicate whether global smoothing and/or prediction is # These flags indicate whether global smoothing and/or prediction is
# allowed or disallowed. # allowed or disallowed.
EnableSmoothing = config.GetBool("smooth-enable-smoothing", 1) EnableSmoothing = ConfigVariableBool("smooth-enable-smoothing", True)
EnablePrediction = config.GetBool("smooth-enable-prediction", 1) EnablePrediction = ConfigVariableBool("smooth-enable-prediction", True)
# These values represent the amount of time, in seconds, to delay the # These values represent the amount of time, in seconds, to delay the
# apparent position of other avatars, when non-predictive and # apparent position of other avatars, when non-predictive and
@ -30,8 +29,8 @@ EnablePrediction = config.GetBool("smooth-enable-prediction", 1)
# addition to the automatic delay of the observed average latency from # addition to the automatic delay of the observed average latency from
# each avatar, which is intended to compensate for relative clock # each avatar, which is intended to compensate for relative clock
# skew. # skew.
Lag = config.GetDouble("smooth-lag", 0.2) Lag = ConfigVariableDouble("smooth-lag", 0.2)
PredictionLag = config.GetDouble("smooth-prediction-lag", 0.0) PredictionLag = ConfigVariableDouble("smooth-prediction-lag", 0.0)
GlobalSmoothing = 0 GlobalSmoothing = 0
@ -358,10 +357,10 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
# be just slightly in the past, but it might be off by as much # be just slightly in the past, but it might be off by as much
# as this frame's amount of time forward or back. # as this frame's amount of time forward or back.
howFarFuture = local - now howFarFuture = local - now
if howFarFuture - chug >= MaxFuture: if howFarFuture - chug >= MaxFuture.value:
# Too far off; advise the other client of our clock information. # Too far off; advise the other client of our clock information.
if globalClockDelta.getUncertainty() is not None and \ if globalClockDelta.getUncertainty() is not None and \
realTime - self.lastSuggestResync >= MinSuggestResync and \ realTime - self.lastSuggestResync >= MinSuggestResync.value and \
hasattr(self.cr, 'localAvatarDoId'): hasattr(self.cr, 'localAvatarDoId'):
self.lastSuggestResync = realTime self.lastSuggestResync = realTime
timestampB = globalClockDelta.localToNetworkTime(realTime) timestampB = globalClockDelta.localToNetworkTime(realTime)
@ -527,12 +526,12 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
# Prediction and smoothing. # Prediction and smoothing.
self.smoother.setSmoothMode(SmoothMover.SMOn) self.smoother.setSmoothMode(SmoothMover.SMOn)
self.smoother.setPredictionMode(SmoothMover.PMOn) self.smoother.setPredictionMode(SmoothMover.PMOn)
self.smoother.setDelay(PredictionLag) self.smoother.setDelay(PredictionLag.value)
else: else:
# Smoothing, but no prediction. # Smoothing, but no prediction.
self.smoother.setSmoothMode(SmoothMover.SMOn) self.smoother.setSmoothMode(SmoothMover.SMOn)
self.smoother.setPredictionMode(SmoothMover.PMOff) self.smoother.setPredictionMode(SmoothMover.PMOff)
self.smoother.setDelay(Lag) self.smoother.setDelay(Lag.value)
else: else:
# No smoothing, no prediction. # No smoothing, no prediction.
self.smoother.setSmoothMode(SmoothMover.SMOff) self.smoother.setSmoothMode(SmoothMover.SMOff)

View File

@ -11,6 +11,9 @@ from direct.distributed.PyDatagram import PyDatagram
import inspect import inspect
_server_doid_range = ConfigVariableInt('server-doid-range', 1000000)
class ServerRepository: class ServerRepository:
""" This maintains the server-side connection with a Panda server. """ This maintains the server-side connection with a Panda server.
@ -134,7 +137,7 @@ class ServerRepository:
# The number of doId's to assign to each client. Must remain # The number of doId's to assign to each client. Must remain
# constant during server lifetime. # constant during server lifetime.
self.doIdRange = base.config.GetInt('server-doid-range', 1000000) self.doIdRange = _server_doid_range.value
# An allocator object that assigns the next doIdBase to each # An allocator object that assigns the next doIdBase to each
# client. # client.

View File

@ -102,6 +102,8 @@ from direct.task.TaskManagerGlobal import taskMgr
guiObjectCollector = PStatCollector("Client::GuiObjects") guiObjectCollector = PStatCollector("Client::GuiObjects")
_track_gui_items = ConfigVariableBool('track-gui-items', False)
class DirectGuiBase(DirectObject.DirectObject): class DirectGuiBase(DirectObject.DirectObject):
"""Base class of all DirectGUI widgets.""" """Base class of all DirectGUI widgets."""
@ -638,7 +640,7 @@ class DirectGuiBase(DirectObject.DirectObject):
""" """
# Need to tack on gui item specific id # Need to tack on gui item specific id
gEvent = event + self.guiId gEvent = event + self.guiId
if ShowBaseGlobal.config.GetBool('debug-directgui-msgs', False): if ConfigVariableBool('debug-directgui-msgs', False):
from direct.showbase.PythonUtil import StackTrace from direct.showbase.PythonUtil import StackTrace
print(gEvent) print(gEvent)
print(StackTrace()) print(StackTrace())
@ -667,7 +669,7 @@ class DirectGuiWidget(DirectGuiBase, NodePath):
# Determine the default initial state for inactive (or # Determine the default initial state for inactive (or
# unclickable) components. If we are in edit mode, these are # unclickable) components. If we are in edit mode, these are
# actually clickable by default. # actually clickable by default.
guiEdit = ShowBaseGlobal.config.GetBool('direct-gui-edit', False) guiEdit = ConfigVariableBool('direct-gui-edit', False)
if guiEdit: if guiEdit:
inactiveInitState = DGG.NORMAL inactiveInitState = DGG.NORMAL
else: else:
@ -733,7 +735,7 @@ class DirectGuiWidget(DirectGuiBase, NodePath):
guiObjectCollector.addLevel(1) guiObjectCollector.addLevel(1)
guiObjectCollector.flushLevel() guiObjectCollector.flushLevel()
# track gui items by guiId for tracking down leaks # track gui items by guiId for tracking down leaks
if ShowBaseGlobal.config.GetBool('track-gui-items', False): if _track_gui_items:
if not hasattr(ShowBase, 'guiItems'): if not hasattr(ShowBase, 'guiItems'):
ShowBase.guiItems = {} ShowBase.guiItems = {}
if self.guiId in ShowBase.guiItems: if self.guiId in ShowBase.guiItems:

View File

@ -542,10 +542,18 @@ class OnscreenText(NodePath):
for option, value in kw.items(): for option, value in kw.items():
# Use option string to access setter function # Use option string to access setter function
try: try:
setter = getattr(self, 'set' + option[0].upper() + option[1:]) if option == 'pos':
if setter == self.setPos: self.setTextPos(value[0], value[1])
setter(value[0], value[1]) elif option == 'roll':
self.setTextR(-value)
elif option == 'scale':
self.setTextScale(value)
elif option == 'x':
self.setTextX(value)
elif option == 'y':
self.setTextY(value)
else: else:
setter = getattr(self, 'set' + option[0].upper() + option[1:])
setter(value) setter(value)
except AttributeError: except AttributeError:
print('OnscreenText.configure: invalid option: %s' % option) print('OnscreenText.configure: invalid option: %s' % option)
@ -557,6 +565,17 @@ class OnscreenText(NodePath):
def cget(self, option): def cget(self, option):
# Get current configuration setting. # Get current configuration setting.
# This is for compatibility with DirectGui functions # This is for compatibility with DirectGui functions
if option == 'pos':
return self.__pos
elif option == 'roll':
return self.__roll
elif option == 'scale':
return self.__scale
elif option == 'x':
return self.__pos[0]
elif option == 'y':
return self.__pos[1]
getter = getattr(self, 'get' + option[0].upper() + option[1:]) getter = getattr(self, 'get' + option[0].upper() + option[1:])
return getter() return getter()

View File

@ -64,7 +64,7 @@ class ObjectMgrBase:
# [gjeon] to solve the problem of unproper $USERNAME # [gjeon] to solve the problem of unproper $USERNAME
userId = os.path.basename(os.path.expandvars('$USERNAME')) userId = os.path.basename(os.path.expandvars('$USERNAME'))
if userId == '': if userId == '':
userId = base.config.GetString("le-user-id") userId = ConfigVariableString("le-user-id").value
if userId == '': if userId == '':
userId = 'unknown' userId = 'unknown'
newUid = str(time.time()) + userId newUid = str(time.time()) + userId

View File

@ -7,6 +7,9 @@ from direct.directnotify.DirectNotifyGlobal import directNotify
import warnings import warnings
_want_python_motion_trails = ConfigVariableBool('want-python-motion-trails', False)
def remove_task(): def remove_task():
if MotionTrail.task_added: if MotionTrail.task_added:
total_motion_trails = len(MotionTrail.motion_trail_list) total_motion_trails = len(MotionTrail.motion_trail_list)
@ -134,7 +137,7 @@ class MotionTrail(NodePath, DirectObject):
self.cmotion_trail.setGeomNode(self.geom_node) self.cmotion_trail.setGeomNode(self.geom_node)
self.modified_vertices = True self.modified_vertices = True
if base.config.GetBool('want-python-motion-trails', 0): if _want_python_motion_trails:
self.use_python_version = True self.use_python_version = True
else: else:
self.use_python_version = False self.use_python_version = False

View File

@ -1,3 +1,4 @@
from panda3d.core import ConfigVariableString
from panda3d.physics import SpriteParticleRenderer from panda3d.physics import SpriteParticleRenderer
@ -18,8 +19,8 @@ class SpriteParticleRendererExt(SpriteParticleRenderer):
def getSourceTextureName(self): def getSourceTextureName(self):
if self.sourceTextureName is None: if self.sourceTextureName is None:
SpriteParticleRendererExt.sourceTextureName = base.config.GetString( SpriteParticleRendererExt.sourceTextureName = ConfigVariableString(
'particle-sprite-texture', 'maps/lightbulb.rgb') 'particle-sprite-texture', 'maps/lightbulb.rgb').value
# Return instance copy of class variable # Return instance copy of class variable
return self.sourceTextureName return self.sourceTextureName
@ -57,8 +58,8 @@ class SpriteParticleRendererExt(SpriteParticleRenderer):
def getSourceFileName(self): def getSourceFileName(self):
if self.sourceFileName is None: if self.sourceFileName is None:
SpriteParticleRendererExt.sourceFileName = base.config.GetString( SpriteParticleRendererExt.sourceFileName = ConfigVariableString(
'particle-sprite-model', 'models/misc/smiley') 'particle-sprite-model', 'models/misc/smiley').value
# Return instance copy of class variable # Return instance copy of class variable
return self.sourceFileName return self.sourceFileName
@ -68,8 +69,8 @@ class SpriteParticleRendererExt(SpriteParticleRenderer):
def getSourceNodeName(self): def getSourceNodeName(self):
if self.sourceNodeName is None: if self.sourceNodeName is None:
SpriteParticleRendererExt.sourceNodeName = base.config.GetString( SpriteParticleRendererExt.sourceNodeName = ConfigVariableString(
'particle-sprite-node', '**/*') 'particle-sprite-node', '**/*').value
# Return instance copy of class variable # Return instance copy of class variable
return self.sourceNodeName return self.sourceNodeName

View File

@ -641,9 +641,7 @@ if __debug__:
def _profiled(*args, **kArgs): def _profiled(*args, **kArgs):
name = '(%s) %s from %s' % (category, f.__name__, f.__module__) name = '(%s) %s from %s' % (category, f.__name__, f.__module__)
# showbase might not be loaded yet, so don't use if category is None or ConfigVariableBool('want-profile-%s' % category, False).value:
# base.config. Instead, query the ConfigVariableBool.
if (category is None) or ConfigVariableBool('want-profile-%s' % category, 0).getValue():
return profileFunc(Functor(f, *args, **kArgs), name, terse) return profileFunc(Functor(f, *args, **kArgs), name, terse)
else: else:
return f(*args, **kArgs) return f(*args, **kArgs)
@ -1990,7 +1988,7 @@ def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigPara
return f return f
try: try:
if not (__dev__ or config.GetBool('force-reports', 0)): if not __dev__ and not ConfigVariableBool('force-reports', False):
return decorator return decorator
# determine whether we should use the decorator # determine whether we should use the decorator
@ -2006,7 +2004,7 @@ def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigPara
dConfigParams = dConfigParam dConfigParams = dConfigParam
dConfigParamList = [param for param in dConfigParams \ dConfigParamList = [param for param in dConfigParams \
if config.GetBool('want-%s-report' % (param,), 0)] if ConfigVariableBool('want-%s-report' % (param,), False)]
doPrint = bool(dConfigParamList) doPrint = bool(dConfigParamList)
@ -2256,12 +2254,12 @@ if __debug__:
def quickProfile(name="unnamed"): def quickProfile(name="unnamed"):
import pstats import pstats
def profileDecorator(f): def profileDecorator(f):
if not config.GetBool("use-profiler", False): if not ConfigVariableBool("use-profiler", False):
return f return f
def _profiled(*args, **kArgs): def _profiled(*args, **kArgs):
# must do this in here because we don't have base/simbase # must do this in here because we don't have base/simbase
# at the time that PythonUtil is loaded # at the time that PythonUtil is loaded
if not config.GetBool("profile-debug", False): if not ConfigVariableBool("profile-debug", False):
#dumb timings #dumb timings
st=globalClock.getRealTime() st=globalClock.getRealTime()
f(*args,**kArgs) f(*args,**kArgs)

View File

@ -101,19 +101,21 @@ class ShowBase(DirectObject.DirectObject):
including this instance itself (under the name ``base``). including this instance itself (under the name ``base``).
""" """
from . import ShowBaseGlobal
#: Set if the want-dev Config.prc variable is enabled. By default, it #: Set if the want-dev Config.prc variable is enabled. By default, it
#: is set to True except when using Python with the -O flag. #: is set to True except when using Python with the -O flag.
self.__dev__ = self.config.GetBool('want-dev', __debug__) self.__dev__ = ShowBaseGlobal.__dev__
builtins.__dev__ = self.__dev__ builtins.__dev__ = self.__dev__
logStackDump = (self.config.GetBool('log-stack-dump', False) or logStackDump = (ConfigVariableBool('log-stack-dump', False).value or
self.config.GetBool('client-log-stack-dump', False)) ConfigVariableBool('client-log-stack-dump', False).value)
uploadStackDump = self.config.GetBool('upload-stack-dump', False) uploadStackDump = ConfigVariableBool('upload-stack-dump', False).value
if logStackDump or uploadStackDump: if logStackDump or uploadStackDump:
ExceptionVarDump.install(logStackDump, uploadStackDump) ExceptionVarDump.install(logStackDump, uploadStackDump)
if __debug__: if __debug__:
self.__autoGarbageLogging = self.__dev__ and self.config.GetBool('auto-garbage-logging', False) self.__autoGarbageLogging = self.__dev__ and ConfigVariableBool('auto-garbage-logging', False)
#: The directory containing the main Python file of this application. #: The directory containing the main Python file of this application.
self.mainDir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR") self.mainDir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
@ -128,9 +130,12 @@ class ShowBase(DirectObject.DirectObject):
self.debugRunningMultiplier = 4 self.debugRunningMultiplier = 4
# [gjeon] to disable sticky keys # [gjeon] to disable sticky keys
if self.config.GetBool('disable-sticky-keys', 0): if ConfigVariableBool('disable-sticky-keys', False):
storeAccessibilityShortcutKeys() storeAccessibilityShortcutKeys()
allowAccessibilityShortcutKeys(False) allowAccessibilityShortcutKeys(False)
self.__disabledStickyKeys = True
else:
self.__disabledStickyKeys = False
self.printEnvDebugInfo() self.printEnvDebugInfo()
vfs = VirtualFileSystem.getGlobalPtr() vfs = VirtualFileSystem.getGlobalPtr()
@ -140,18 +145,18 @@ class ShowBase(DirectObject.DirectObject):
self.__deadInputs = 0 self.__deadInputs = 0
# Store dconfig variables # Store dconfig variables
self.sfxActive = self.config.GetBool('audio-sfx-active', 1) self.sfxActive = ConfigVariableBool('audio-sfx-active', True).value
self.musicActive = self.config.GetBool('audio-music-active', 1) self.musicActive = ConfigVariableBool('audio-music-active', True).value
self.wantFog = self.config.GetBool('want-fog', 1) self.wantFog = ConfigVariableBool('want-fog', True).value
self.wantRender2dp = self.config.GetBool('want-render2dp', 1) self.wantRender2dp = ConfigVariableBool('want-render2dp', True).value
self.screenshotExtension = self.config.GetString('screenshot-extension', 'jpg') self.screenshotExtension = ConfigVariableString('screenshot-extension', 'jpg').value
self.musicManager = None self.musicManager = None
self.musicManagerIsValid = None self.musicManagerIsValid = None
self.sfxManagerList = [] self.sfxManagerList = []
self.sfxManagerIsValidList = [] self.sfxManagerIsValidList = []
self.wantStats = self.config.GetBool('want-pstats', 0) self.wantStats = ConfigVariableBool('want-pstats', False).value
self.wantTk = False self.wantTk = False
self.wantWx = False self.wantWx = False
self.wantDirect = False self.wantDirect = False
@ -178,7 +183,7 @@ class ShowBase(DirectObject.DirectObject):
# If the aspect ratio is 0 or None, it means to infer the # If the aspect ratio is 0 or None, it means to infer the
# aspect ratio from the window size. # aspect ratio from the window size.
# If you need to know the actual aspect ratio call base.getAspectRatio() # If you need to know the actual aspect ratio call base.getAspectRatio()
self.__configAspectRatio = ConfigVariableDouble('aspect-ratio', 0).getValue() self.__configAspectRatio = ConfigVariableDouble('aspect-ratio', 0).value
# This variable is used to see if the aspect ratio has changed when # This variable is used to see if the aspect ratio has changed when
# we get a window-event. # we get a window-event.
self.__oldAspectRatio = None self.__oldAspectRatio = None
@ -188,8 +193,8 @@ class ShowBase(DirectObject.DirectObject):
#: be 'onscreen' (the default), 'offscreen' or 'none'. #: be 'onscreen' (the default), 'offscreen' or 'none'.
self.windowType = windowType self.windowType = windowType
if self.windowType is None: if self.windowType is None:
self.windowType = self.config.GetString('window-type', 'onscreen') self.windowType = ConfigVariableString('window-type', 'onscreen').value
self.requireWindow = self.config.GetBool('require-window', 1) self.requireWindow = ConfigVariableBool('require-window', True).value
#: This is the main, or only window; see `winList` for a list of *all* windows. #: This is the main, or only window; see `winList` for a list of *all* windows.
self.win = None self.win = None
@ -262,11 +267,10 @@ class ShowBase(DirectObject.DirectObject):
self.clusterSyncFlag = clusterSyncFlag self.clusterSyncFlag = clusterSyncFlag
except NameError: except NameError:
# Has the clusterSyncFlag been set via a config variable # Has the clusterSyncFlag been set via a config variable
self.clusterSyncFlag = self.config.GetBool('cluster-sync', 0) self.clusterSyncFlag = ConfigVariableBool('cluster-sync', False)
# We've already created aspect2d in ShowBaseGlobal, for the # We've already created aspect2d in ShowBaseGlobal, for the
# benefit of creating DirectGui elements before ShowBase. # benefit of creating DirectGui elements before ShowBase.
from . import ShowBaseGlobal
self.hidden = ShowBaseGlobal.hidden self.hidden = ShowBaseGlobal.hidden
#: The global :class:`~panda3d.core.GraphicsEngine`, as returned by #: The global :class:`~panda3d.core.GraphicsEngine`, as returned by
@ -298,14 +302,14 @@ class ShowBase(DirectObject.DirectObject):
# Maybe create a RecorderController to record and/or play back # Maybe create a RecorderController to record and/or play back
# the user session. # the user session.
self.recorder = None self.recorder = None
playbackSession = self.config.GetString('playback-session', '') playbackSession = ConfigVariableFilename('playback-session', '')
recordSession = self.config.GetString('record-session', '') recordSession = ConfigVariableFilename('record-session', '')
if playbackSession: if not playbackSession.empty():
self.recorder = RecorderController() self.recorder = RecorderController()
self.recorder.beginPlayback(Filename.fromOsSpecific(playbackSession)) self.recorder.beginPlayback(playbackSession.value)
elif recordSession: elif not recordSession.empty():
self.recorder = RecorderController() self.recorder = RecorderController()
self.recorder.beginRecord(Filename.fromOsSpecific(recordSession)) self.recorder.beginRecord(recordSession.value)
if self.recorder: if self.recorder:
# If we're either playing back or recording, pass the # If we're either playing back or recording, pass the
@ -319,19 +323,19 @@ class ShowBase(DirectObject.DirectObject):
# For some reason, wx needs to be initialized before the graphics window # For some reason, wx needs to be initialized before the graphics window
if sys.platform == "darwin": if sys.platform == "darwin":
if self.config.GetBool("want-wx", 0): if ConfigVariableBool("want-wx", False):
wx = importlib.import_module('wx') wx = importlib.import_module('wx')
self.wxApp = wx.App() self.wxApp = wx.App()
# Same goes for Tk, which uses a conflicting NSApplication # Same goes for Tk, which uses a conflicting NSApplication
if self.config.GetBool("want-tk", 0): if ConfigVariableBool("want-tk", False):
Pmw = importlib.import_module('Pmw') Pmw = importlib.import_module('Pmw')
self.tkRoot = Pmw.initialise() self.tkRoot = Pmw.initialise()
# Open the default rendering window. # Open the default rendering window.
if self.windowType != 'none': if self.windowType != 'none':
props = WindowProperties.getDefault() props = WindowProperties.getDefault()
if self.config.GetBool('read-raw-mice', 0): if ConfigVariableBool('read-raw-mice', False):
props.setRawMice(1) props.setRawMice(1)
self.openDefaultWindow(startDirect = False, props=props) self.openDefaultWindow(startDirect = False, props=props)
@ -398,18 +402,18 @@ class ShowBase(DirectObject.DirectObject):
# - pcalt-# (# is CPU number, 0-based) # - pcalt-# (# is CPU number, 0-based)
# - client-cpu-affinity config # - client-cpu-affinity config
# - auto-single-cpu-affinity config # - auto-single-cpu-affinity config
affinityMask = self.config.GetInt('client-cpu-affinity-mask', -1) affinityMask = ConfigVariableInt('client-cpu-affinity-mask', -1).value
if affinityMask != -1: if affinityMask != -1:
TrueClock.getGlobalPtr().setCpuAffinity(affinityMask) TrueClock.getGlobalPtr().setCpuAffinity(affinityMask)
else: else:
# this is useful on machines that perform better with each process # this is useful on machines that perform better with each process
# assigned to a single CPU # assigned to a single CPU
autoAffinity = self.config.GetBool('auto-single-cpu-affinity', 0) autoAffinity = ConfigVariableBool('auto-single-cpu-affinity', False).value
affinity = None affinity = None
if autoAffinity and hasattr(builtins, 'clientIndex'): if autoAffinity and hasattr(builtins, 'clientIndex'):
affinity = abs(int(builtins.clientIndex)) affinity = abs(int(builtins.clientIndex))
else: else:
affinity = self.config.GetInt('client-cpu-affinity', -1) affinity = ConfigVariableInt('client-cpu-affinity', -1).value
if (affinity in (None, -1)) and autoAffinity: if (affinity in (None, -1)) and autoAffinity:
affinity = 0 affinity = 0
if affinity not in (None, -1): if affinity not in (None, -1):
@ -467,13 +471,13 @@ class ShowBase(DirectObject.DirectObject):
self.createBaseAudioManagers() self.createBaseAudioManagers()
if self.__dev__ and self.config.GetBool('track-gui-items', False): if self.__dev__ and ConfigVariableBool('track-gui-items', False):
# dict of guiId to gui item, for tracking down leaks # dict of guiId to gui item, for tracking down leaks
if not hasattr(ShowBase, 'guiItems'): if not hasattr(ShowBase, 'guiItems'):
ShowBase.guiItems = {} ShowBase.guiItems = {}
# optionally restore the default gui sounds from 1.7.2 and earlier # optionally restore the default gui sounds from 1.7.2 and earlier
if ConfigVariableBool('orig-gui-sounds', False).getValue(): if ConfigVariableBool('orig-gui-sounds', False).value:
from direct.gui import DirectGuiGlobals as DGG from direct.gui import DirectGuiGlobals as DGG
DGG.setDefaultClickSound(self.loader.loadSfx("audio/sfx/GUI_click.wav")) DGG.setDefaultClickSound(self.loader.loadSfx("audio/sfx/GUI_click.wav"))
DGG.setDefaultRolloverSound(self.loader.loadSfx("audio/sfx/GUI_rollover.wav")) DGG.setDefaultRolloverSound(self.loader.loadSfx("audio/sfx/GUI_rollover.wav"))
@ -495,18 +499,15 @@ class ShowBase(DirectObject.DirectObject):
self.setupWindowControls() self.setupWindowControls()
# Client sleep # Client sleep
sleepTime = self.config.GetFloat('client-sleep', 0.0) sleepTime = ConfigVariableDouble('client-sleep', 0.0)
self.clientSleep = 0.0 self.clientSleep = 0.0
self.setSleep(sleepTime) self.setSleep(sleepTime.value)
# Extra sleep for running 4+ clients on a single machine # Extra sleep for running 4+ clients on a single machine
# adds a sleep right after the main render in igloop # adds a sleep right after the main render in igloop
# tends to even out the frame rate and keeps it from going # tends to even out the frame rate and keeps it from going
# to zero in the out of focus windows # to zero in the out of focus windows
if self.config.GetBool('multi-sleep', 0): self.multiClientSleep = ConfigVariableBool('multi-sleep', False)
self.multiClientSleep = 1
else:
self.multiClientSleep = 0
#: Utility for viewing offscreen buffers, see :mod:`.BufferViewer`. #: Utility for viewing offscreen buffers, see :mod:`.BufferViewer`.
self.bufferViewer = BufferViewer(self.win, self.render2dp if self.wantRender2dp else self.render2d) self.bufferViewer = BufferViewer(self.win, self.render2dp if self.wantRender2dp else self.render2d)
@ -515,7 +516,7 @@ class ShowBase(DirectObject.DirectObject):
if fStartDirect: # [gjeon] if this is False let them start direct manually if fStartDirect: # [gjeon] if this is False let them start direct manually
self.__doStartDirect() self.__doStartDirect()
if self.config.GetBool('show-tex-mem', False): if ConfigVariableBool('show-tex-mem', False):
if not self.texmem or self.texmem.cleanedUp: if not self.texmem or self.texmem.cleanedUp:
self.toggleTexMem() self.toggleTexMem()
@ -543,10 +544,10 @@ class ShowBase(DirectObject.DirectObject):
except ImportError: except ImportError:
return return
profile.Profile.bias = float(self.config.GetString("profile-bias","0")) profile.Profile.bias = ConfigVariableDouble("profile-bias", 0.0).value
def f8(x): def f8(x):
return ("%" + "8.%df" % self.config.GetInt("profile-decimals", 3)) % x return ("%" + "8.%df" % ConfigVariableInt("profile-decimals", 3)) % x
pstats.f8 = f8 pstats.f8 = f8
# temp; see ToonBase.py # temp; see ToonBase.py
@ -558,7 +559,7 @@ class ShowBase(DirectObject.DirectObject):
in. Stuff like the model paths and other paths. Feel free to in. Stuff like the model paths and other paths. Feel free to
add stuff to this. add stuff to this.
""" """
if self.config.GetBool('want-env-debug-info', 0): if ConfigVariableBool('want-env-debug-info', False):
print("\n\nEnvironment Debug Info {") print("\n\nEnvironment Debug Info {")
print("* model path:") print("* model path:")
print(getModelPath()) print(getModelPath())
@ -593,8 +594,9 @@ class ShowBase(DirectObject.DirectObject):
self.aspect2d.reparent_to(self.render2d) self.aspect2d.reparent_to(self.render2d)
# [gjeon] restore sticky key settings # [gjeon] restore sticky key settings
if self.config.GetBool('disable-sticky-keys', 0): if self.__disabledStickyKeys:
allowAccessibilityShortcutKeys(True) allowAccessibilityShortcutKeys(True)
self.__disabledStickyKeys = False
self.ignoreAll() self.ignoreAll()
self.shutdown() self.shutdown()
@ -1076,16 +1078,10 @@ class ShowBase(DirectObject.DirectObject):
self.win.setClearStencilActive(oldClearStencilActive) self.win.setClearStencilActive(oldClearStencilActive)
self.win.setClearStencil(oldClearStencil) self.win.setClearStencil(oldClearStencil)
flag = self.config.GetBool('show-frame-rate-meter', False) flag = ConfigVariableBool('show-frame-rate-meter', False)
if self.appRunner is not None and self.appRunner.allowPythonDev: self.setFrameRateMeter(flag.value)
# In an allow_python_dev p3d application, we always flag = ConfigVariableBool('show-scene-graph-analyzer-meter', False)
# start up with the frame rate meter enabled, to self.setSceneGraphAnalyzerMeter(flag.value)
# provide a visual reminder that this flag has been
# set.
flag = True
self.setFrameRateMeter(flag)
flag = self.config.GetBool('show-scene-graph-analyzer-meter', False)
self.setSceneGraphAnalyzerMeter(flag)
return success return success
def setSleep(self, amount): def setSleep(self, amount):
@ -2240,7 +2236,7 @@ class ShowBase(DirectObject.DirectObject):
# between collisionLoop and igLoop # between collisionLoop and igLoop
self.taskMgr.add(self.__collisionLoop, 'collisionLoop', sort = 30) self.taskMgr.add(self.__collisionLoop, 'collisionLoop', sort = 30)
if ConfigVariableBool('garbage-collect-states').getValue(): if ConfigVariableBool('garbage-collect-states').value:
self.taskMgr.add(self.__garbageCollectStates, 'garbageCollectStates', sort = 46) self.taskMgr.add(self.__garbageCollectStates, 'garbageCollectStates', sort = 46)
# give the igLoop task a reasonably "late" sort, # give the igLoop task a reasonably "late" sort,
# so that it will get run after most tasks # so that it will get run after most tasks
@ -2508,7 +2504,7 @@ class ShowBase(DirectObject.DirectObject):
# Make the spots round, so there's less static in the display. # Make the spots round, so there's less static in the display.
# This forces software point generation on many drivers, so # This forces software point generation on many drivers, so
# it's not on by default. # it's not on by default.
if self.config.GetBool('round-show-vertices', False): if ConfigVariableBool('round-show-vertices', False):
spot = PNMImage(256, 256, 1) spot = PNMImage(256, 256, 1)
spot.renderSpot((1, 1, 1, 1), (0, 0, 0, 0), 0.8, 1) spot.renderSpot((1, 1, 1, 1), (0, 0, 0, 0), 0.8, 1)
tex = Texture('spot') tex = Texture('spot')
@ -3134,7 +3130,7 @@ class ShowBase(DirectObject.DirectObject):
# Set a timer to run the Panda frame 60 times per second. # Set a timer to run the Panda frame 60 times per second.
wxFrameRate = ConfigVariableDouble('wx-frame-rate', 60.0) wxFrameRate = ConfigVariableDouble('wx-frame-rate', 60.0)
self.wxTimer = wx.Timer(self.wxApp) self.wxTimer = wx.Timer(self.wxApp)
self.wxTimer.Start(1000.0 / wxFrameRate.getValue()) self.wxTimer.Start(1000.0 / wxFrameRate.value)
self.wxApp.Bind(wx.EVT_TIMER, self.__wxTimerCallback) self.wxApp.Bind(wx.EVT_TIMER, self.__wxTimerCallback)
# wx is now the main loop, not us any more. # wx is now the main loop, not us any more.
@ -3221,7 +3217,7 @@ class ShowBase(DirectObject.DirectObject):
# Set a timer to run the Panda frame 60 times per second. # Set a timer to run the Panda frame 60 times per second.
tkFrameRate = ConfigVariableDouble('tk-frame-rate', 60.0) tkFrameRate = ConfigVariableDouble('tk-frame-rate', 60.0)
self.tkDelay = int(1000.0 / tkFrameRate.getValue()) self.tkDelay = int(1000.0 / tkFrameRate.value)
self.tkRoot.after(self.tkDelay, self.__tkTimerCallback) self.tkRoot.after(self.tkDelay, self.__tkTimerCallback)
# wx is now the main loop, not us any more. # wx is now the main loop, not us any more.
@ -3301,11 +3297,11 @@ class ShowBase(DirectObject.DirectObject):
self.__directStarted = False self.__directStarted = False
# Start Tk, Wx and DIRECT if specified by Config.prc # Start Tk, Wx and DIRECT if specified by Config.prc
fTk = self.config.GetBool('want-tk', 0) fTk = ConfigVariableBool('want-tk', False).value
fWx = self.config.GetBool('want-wx', 0) fWx = ConfigVariableBool('want-wx', False).value
# Start DIRECT if specified in Config.prc or in cluster mode # Start DIRECT if specified in Config.prc or in cluster mode
fDirect = (self.config.GetBool('want-directtools', 0) or fDirect = (ConfigVariableBool('want-directtools', 0).value or
(self.config.GetString("cluster-mode", '') != '')) (not ConfigVariableString("cluster-mode", '').empty()))
# Set fWantTk to 0 to avoid starting Tk with this call # Set fWantTk to 0 to avoid starting Tk with this call
self.startDirect(fWantDirect = fDirect, fWantTk = fTk, fWantWx = fWx) self.startDirect(fWantDirect = fDirect, fWantTk = fTk, fWantWx = fWx)

View File

@ -16,12 +16,12 @@ __all__ = []
from .ShowBase import ShowBase, WindowControls # pylint: disable=unused-import from .ShowBase import ShowBase, WindowControls # pylint: disable=unused-import
from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify # pylint: disable=unused-import from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify # pylint: disable=unused-import
from panda3d.core import VirtualFileSystem, Notify, ClockObject, PandaSystem from panda3d.core import VirtualFileSystem, Notify, ClockObject, PandaSystem
from panda3d.core import ConfigPageManager, ConfigVariableManager from panda3d.core import ConfigPageManager, ConfigVariableManager, ConfigVariableBool
from panda3d.core import NodePath, PGTop from panda3d.core import NodePath, PGTop
from . import DConfig as config from . import DConfig as config
import warnings import warnings
__dev__ = config.GetBool('want-dev', __debug__) __dev__ = ConfigVariableBool('want-dev', __debug__).value
#: The global instance of the :ref:`virtual-file-system`, as obtained using #: The global instance of the :ref:`virtual-file-system`, as obtained using
#: :meth:`panda3d.core.VirtualFileSystem.getGlobalPtr()`. #: :meth:`panda3d.core.VirtualFileSystem.getGlobalPtr()`.