direct: add .pylintrc, perform major code cleanup pass

Closes #989

Co-authored-by: Daniel Stokes <kupomail@gmail.com>
This commit is contained in:
rdb 2020-12-31 00:57:03 +01:00
parent cf60284ca9
commit be9dde1eee
239 changed files with 3779 additions and 3764 deletions

533
.pylintrc Normal file
View File

@ -0,0 +1,533 @@
[MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-whitelist=panda3d
# Specify a score threshold to be exceeded before program exits with error.
fail-under=10.0
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=thirdparty
# Add files or directories matching the regex patterns to the blacklist. The
# regex matches against base names, not paths.
ignore-patterns=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=1
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
confidence=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=attribute-defined-outside-init,
broad-except,
comparison-with-callable,
dangerous-default-value,
global-statement,
import-outside-toplevel,
invalid-name,
line-too-long,
misplaced-comparison-constant,
missing-class-docstring,
missing-function-docstring,
missing-module-docstring,
protected-access,
r,
raise-missing-from,
redefined-builtin,
too-many-lines,
unused-argument,
unused-variable,
unused-wildcard-import,
using-constant-test,
wildcard-import,
wrong-import-order,
wrong-import-position
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=c-extension-no-member
[REPORTS]
# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'error', 'warning', 'refactor', and 'convention'
# which contain the number of messages in each category, as well as 'statement'
# which is the total number of statements analyzed. This score is used by the
# global evaluation report (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
#msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=LF
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=100
# Maximum number of lines in a module.
max-module-lines=1000
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. Available dictionaries: none. To make it work,
# install the python-enchant package.
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local,direct.showbase.PythonUtil.ScratchPad
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis). It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
# List of decorators that change the signature of a decorated function.
signature-mutators=
[SIMILARITIES]
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
# Minimum lines number of a similarity.
min-similarity-lines=4
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=base,simbase,__dev__,onScreenDebug,globalClock,render,hidden,cluster
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored. Default to name
# with leading underscore.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
# Regular expression of note tags to take in consideration.
#notes-rgx=
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style.
#class-attribute-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style.
#variable-rgx=
[LOGGING]
# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=old
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no
# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no
[DESIGN]
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[IMPORTS]
# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=optparse,tkinter.tix
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled).
ext-import-graph=
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled).
import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Couples of modules and preferred modules, separated by a comma.
preferred-modules=
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp,
__post_init__
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=BaseException,
Exception

View File

@ -163,10 +163,7 @@ class Actor(DirectObject, NodePath):
#the actor for a few frames, otherwise it has no effect
a.fixBounds()
"""
try:
self.Actor_initialized
return
except:
if not hasattr(self, 'Actor_initialized'):
self.Actor_initialized = 1
# initialize our NodePath essence
@ -252,9 +249,9 @@ class Actor(DirectObject, NodePath):
# make sure we have models
if models:
# do we have a dictionary of models?
if type(models) == dict:
if isinstance(models, dict):
# if this is a dictionary of dictionaries
if type(models[next(iter(models))]) == dict:
if isinstance(models[next(iter(models))], dict):
# then it must be a multipart actor w/LOD
self.setLODNode(node = lodNode)
# preserve numerical order for lod's
@ -271,7 +268,7 @@ class Actor(DirectObject, NodePath):
modelName, lodName, copy = copy,
okMissing = okMissing)
# then if there is a dictionary of dictionaries of anims
elif type(anims[next(iter(anims))]) == dict:
elif isinstance(anims[next(iter(anims))], dict):
# then this is a multipart actor w/o LOD
for partName in models:
# pass in each part
@ -297,10 +294,10 @@ class Actor(DirectObject, NodePath):
if anims:
if len(anims) >= 1:
# if so, does it have a dictionary of dictionaries?
if type(anims[next(iter(anims))]) == dict:
if isinstance(anims[next(iter(anims))], dict):
# are the models a dict of dicts too?
if type(models) == dict:
if type(models[next(iter(models))]) == dict:
if isinstance(models, dict):
if isinstance(models[next(iter(models))], dict):
# then we have a multi-part w/ LOD
sortedKeys = list(models.keys())
sortedKeys.sort()
@ -313,7 +310,7 @@ class Actor(DirectObject, NodePath):
# then it must be multi-part w/o LOD
for partName in anims:
self.loadAnims(anims[partName], partName)
elif type(models) == dict:
elif isinstance(models, dict):
# then we have single-part w/ LOD
sortedKeys = list(models.keys())
sortedKeys.sort()
@ -344,50 +341,46 @@ class Actor(DirectObject, NodePath):
self.__geomNode.node().setFinal(1)
def delete(self):
try:
self.Actor_deleted
return
except:
if not hasattr(self, 'Actor_deleted'):
self.Actor_deleted = 1
self.cleanup()
def copyActor(self, other, overwrite=False):
# act like a copy constructor
self.gotName = other.gotName
# act like a copy constructor
self.gotName = other.gotName
# copy the scene graph elements of other
if overwrite:
otherCopy = other.copyTo(NodePath())
otherCopy.detachNode()
# assign these elements to ourselve (overwrite)
self.assign(otherCopy)
else:
# just copy these to ourselves
otherCopy = other.copyTo(self)
# masad: check if otherCopy has a geomNode as its first child
# if actor is initialized with flattenable, then otherCopy, not
# its first child, is the geom node; check __init__, for reference
if other.getGeomNode().getName() == other.getName():
self.setGeomNode(otherCopy)
else:
self.setGeomNode(otherCopy.getChild(0))
# copy the scene graph elements of other
if overwrite:
otherCopy = other.copyTo(NodePath())
otherCopy.detachNode()
# assign these elements to ourselve (overwrite)
self.assign(otherCopy)
else:
# just copy these to ourselves
otherCopy = other.copyTo(self)
# masad: check if otherCopy has a geomNode as its first child
# if actor is initialized with flattenable, then otherCopy, not
# its first child, is the geom node; check __init__, for reference
if other.getGeomNode().getName() == other.getName():
self.setGeomNode(otherCopy)
else:
self.setGeomNode(otherCopy.getChild(0))
# copy the switches for lods
self.switches = other.switches
self.__LODNode = self.find('**/+LODNode')
self.__hasLOD = 0
if not self.__LODNode.isEmpty():
self.__hasLOD = 1
# copy the switches for lods
self.switches = other.switches
self.__LODNode = self.find('**/+LODNode')
self.__hasLOD = 0
if not self.__LODNode.isEmpty():
self.__hasLOD = 1
# copy the part dictionary from other
self.__copyPartBundles(other)
self.__copySubpartDict(other)
self.__subpartsComplete = other.__subpartsComplete
# copy the anim dictionary from other
self.__copyAnimControls(other)
# copy the part dictionary from other
self.__copyPartBundles(other)
self.__copySubpartDict(other)
self.__subpartsComplete = other.__subpartsComplete
# copy the anim dictionary from other
self.__copyAnimControls(other)
def __cmp__(self, other):
# Actor inherits from NodePath, which inherits a definition of
@ -514,7 +507,7 @@ class Actor(DirectObject, NodePath):
self.stop(None)
self.clearPythonData()
self.flush()
if(self.__geomNode):
if self.__geomNode:
self.__geomNode.removeNode()
self.__geomNode = None
if not self.isEmpty():
@ -597,12 +590,10 @@ class Actor(DirectObject, NodePath):
'l':1,
'f':0}
"""
sx = smap.get(x[0], None)
if sx is None:
self.notify.error('Invalid lodName: %s' % x)
"""
#sx = smap.get(x[0], None)
#
#if sx is None:
# self.notify.error('Invalid lodName: %s' % x)
return smap[x[0]]
else:
return int(x)
@ -1471,7 +1462,7 @@ class Actor(DirectObject, NodePath):
#iterate through for a specific part
for lodData in self.__partBundleDict.values():
partData = lodData.get(partName)
if(partData):
if partData:
char = partData.partBundleNP
char.node().update()
geomNodes = char.findAllMatches("**/+GeomNode")
@ -1693,11 +1684,20 @@ class Actor(DirectObject, NodePath):
else:
lodName = 'lodRoot'
try:
return self.__animControlDict[lodName][partName][animName].filename
except:
partDict = self.__animControlDict.get(lodName)
if partDict is None:
return None
animDict = partDict.get(partName)
if animDict is None:
return None
anim = animDict.get(animName)
if anim is None:
return None
return anim.filename
def getAnimControl(self, animName, partName=None, lodName=None,
allowAsyncBind = True):
"""
@ -1731,7 +1731,6 @@ class Actor(DirectObject, NodePath):
if anim is None:
# anim was not present
assert Actor.notify.debug("couldn't find anim: %s" % (animName))
pass
else:
# bind the animation first if we need to
if not anim.animControl:
@ -1852,7 +1851,6 @@ class Actor(DirectObject, NodePath):
if anim is None:
# anim was not present
assert Actor.notify.debug("couldn't find anim: %s" % (animName))
pass
else:
# bind the animation first if we need to
animControl = anim.animControl
@ -1987,7 +1985,7 @@ class Actor(DirectObject, NodePath):
node = bundleNP.node()
# A model loaded from disk will always have just one bundle.
assert(node.getNumBundles() == 1)
assert node.getNumBundles() == 1
bundleHandle = node.getBundleHandle(0)
if self.mergeLODBundles:
@ -2003,7 +2001,7 @@ class Actor(DirectObject, NodePath):
bundleDict[partName] = Actor.PartDef(bundleNP, bundleHandle, partModel)
def makeSubpart(self, partName, includeJoints, excludeJoints = [],
def makeSubpart(self, partName, includeJoints, excludeJoints = (),
parent="modelRoot", overlapping = False):
"""Defines a new "part" of the Actor that corresponds to the
@ -2128,10 +2126,7 @@ class Actor(DirectObject, NodePath):
lodNames = ['common']
elif lodName == 'all':
reload = False
lodNames = list(self.switches.keys())
lodNames.sort()
for i in range(0, len(lodNames)):
lodNames[i] = str(lodNames[i])
lodNames = list(map(str, sorted(self.switches.keys())))
else:
lodNames = [lodName]
@ -2140,11 +2135,10 @@ class Actor(DirectObject, NodePath):
firstLoad = True
if not reload:
try:
self.__animControlDict[lodNames[0]][partName]
if lodNames[0] in self.__animControlDict and \
partName in self.__animControlDict[lodNames[0]]:
firstLoad = False
except:
pass
for lName in lodNames:
if firstLoad:
self.__animControlDict.setdefault(lName, {})
@ -2438,7 +2432,7 @@ class Actor(DirectObject, NodePath):
bundles in our part bundle dict that have matching names, and
store the resulting anim controls in our own part bundle dict"""
assert(other.mergeLODBundles == self.mergeLODBundles)
assert other.mergeLODBundles == self.mergeLODBundles
for lodName in other.__animControlDict:
self.__animControlDict[lodName] = {}
@ -2509,11 +2503,10 @@ class Actor(DirectObject, NodePath):
for lodName, animList in self.getAnimBlends(animName, partName, lodName):
print('LOD %s:' % (lodName))
for animName, blendList in animList:
list = []
strings = []
for partName, effect in blendList:
list.append('%s:%.3f' % (partName, effect))
print(' %s: %s' % (animName, ', '.join(list)))
strings.append('%s:%.3f' % (partName, effect))
print(' %s: %s' % (animName, ', '.join(strings)))
def osdAnimBlends(self, animName=None, partName=None, lodName=None):
if not onScreenDebug.enabled:

View File

@ -8,9 +8,7 @@ from . import Actor
class DistributedActor(DistributedNode.DistributedNode, Actor.Actor):
def __init__(self, cr):
try:
self.DistributedActor_initialized
except:
if not hasattr(self, 'DistributedActor_initialized'):
self.DistributedActor_initialized = 1
Actor.Actor.__init__(self)
DistributedNode.DistributedNode.__init__(self, cr)
@ -20,14 +18,12 @@ class DistributedActor(DistributedNode.DistributedNode, Actor.Actor):
def disable(self):
# remove all anims, on all parts and all lods
if (not self.isEmpty()):
if not self.isEmpty():
Actor.Actor.unloadAnims(self, None, None, None)
DistributedNode.DistributedNode.disable(self)
def delete(self):
try:
self.DistributedActor_deleted
except:
if not hasattr(self, 'DistributedActor_deleted'):
self.DistributedActor_deleted = 1
DistributedNode.DistributedNode.delete(self)
Actor.Actor.delete(self)

View File

@ -6,6 +6,7 @@ from .ClusterConfig import *
from direct.directnotify import DirectNotifyGlobal
from direct.showbase import DirectObject
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
import os
@ -70,7 +71,7 @@ class ClusterClient(DirectObject.DirectObject):
server = DisplayConnection(
self.qcm, serverConfig.serverName,
serverConfig.serverMsgPort, self.msgHandler)
if server == None:
if server is None:
self.notify.error('Could not open %s on %s port %d' %
(serverConfig.serverConfigName,
serverConfig.serverName,
@ -138,15 +139,14 @@ class ClusterClient(DirectObject.DirectObject):
object = pair[1]
name = self.controlMappings[object][0]
serverList = self.controlMappings[object][1]
if (object in self.objectMappings):
if object in self.objectMappings:
self.moveObject(self.objectMappings[object],name,serverList,
self.controlOffsets[object], self.objectHasColor[object])
self.sendNamedMovementDone()
return Task.cont
def sendNamedMovementDone(self, serverList = None):
if (serverList == None):
if serverList is None:
serverList = range(len(self.serverList))
for server in serverList:
@ -155,7 +155,6 @@ class ClusterClient(DirectObject.DirectObject):
def redoSortedPriorities(self):
self.sortedControlMappings = []
for key in self.controlMappings:
self.sortedControlMappings.append([self.controlPriorities[key],
@ -169,7 +168,7 @@ class ClusterClient(DirectObject.DirectObject):
hpr = nodePath.getHpr(render)
scale = nodePath.getScale(render)
hidden = nodePath.isHidden()
if (hasColor):
if hasColor:
color = nodePath.getColor()
else:
color = [1,1,1,1]
@ -193,7 +192,7 @@ class ClusterClient(DirectObject.DirectObject):
def moveSelectedTask(self, state):
# Update cluster if current display is a cluster client
if (last is not None):
if last is not None:
self.notify.debug('moving selected node path')
xyz = Point3(0)
hpr = VBase3(0)
@ -204,24 +203,24 @@ class ClusterClient(DirectObject.DirectObject):
return Task.cont
def addNamedObjectMapping(self,object,name,hasColor = True):
if (name not in self.objectMappings):
def addNamedObjectMapping(self, object, name, hasColor = True):
if name not in self.objectMappings:
self.objectMappings[name] = object
self.objectHasColor[name] = hasColor
else:
self.notify.debug('attempt to add duplicate named object: '+name)
def removeObjectMapping(self,name):
if (name in self.objectMappings):
if name in self.objectMappings:
self.objectMappings.pop(name)
def addControlMapping(self,objectName,controlledName, serverList = None,
def addControlMapping(self, objectName, controlledName, serverList = None,
offset = None, priority = 0):
if (objectName not in self.controlMappings):
if (serverList == None):
if objectName not in self.controlMappings:
if serverList is None:
serverList = range(len(self.serverList))
if (offset == None):
if offset is None:
offset = Vec3(0,0,0)
self.controlMappings[objectName] = [controlledName,serverList]
@ -233,30 +232,29 @@ class ClusterClient(DirectObject.DirectObject):
for item in oldList:
mergedList.append(item)
for item in serverList:
if (item not in mergedList):
if item not in mergedList:
mergedList.append(item)
self.redoSortedPriorities()
#self.notify.debug('attempt to add duplicate controlled object: '+name)
def setControlMappingOffset(self,objectName,offset):
if (objectName in self.controlMappings):
def setControlMappingOffset(self, objectName, offset):
if objectName in self.controlMappings:
self.controlOffsets[objectName] = offset
def removeControlMapping(self,name, serverList = None):
if (name in self.controlMappings):
if (serverList == None):
def removeControlMapping(self, name, serverList = None):
if name in self.controlMappings:
if serverList is None:
self.controlMappings.pop(name)
self.controlPriorities.pop(name)
else:
list = self.controlMappings[key][1]
oldList = self.controlMappings[key][1]
newList = []
for server in list:
if (server not in serverList):
for server in oldList:
if server not in serverList:
newList.append(server)
self.controlMappings[key][1] = newList
if (len(newList) == 0):
if len(newList) == 0:
self.controlMappings.pop(name)
self.controlPriorities.pop(name)
self.redoSortedPriorities()
@ -303,7 +301,7 @@ class ClusterClient(DirectObject.DirectObject):
tag = self.taggedObjects[name]
function = tag["selectFunction"]
args = tag["selectArgs"]
if (function != None):
if function is not None:
function(*args)
else:
self(self.getNodePathFindCmd(nodePath) + '.select()', 0)
@ -315,7 +313,7 @@ class ClusterClient(DirectObject.DirectObject):
tag = self.taggedObjects[name]
function = tag["deselectFunction"]
args = tag["deselectArgs"]
if (function != None):
if function is not None:
function(*args)
self.startMoveSelectedTask()
self(self.getNodePathFindCmd(nodePath) + '.deselect()', 0)
@ -348,24 +346,23 @@ class ClusterClient(DirectObject.DirectObject):
def handleDatagram(self,dgi,type,server):
if (type == CLUSTER_NONE):
if type == CLUSTER_NONE:
pass
elif (type == CLUSTER_NAMED_OBJECT_MOVEMENT):
elif type == CLUSTER_NAMED_OBJECT_MOVEMENT:
self.serverQueues[server].append(self.msgHandler.parseNamedMovementDatagram(dgi))
#self.handleNamedMovement(dgi)
# when we recieve a 'named movement done' packet from a server we handle
# all of its messages
elif (type == CLUSTER_NAMED_MOVEMENT_DONE):
elif type == CLUSTER_NAMED_MOVEMENT_DONE:
self.handleMessageQueue(server)
else:
self.notify.warning("Received unsupported packet type:" % type)
return type
def handleMessageQueue(self,server):
list = self.serverQueues[server]
queue = self.serverQueues[server]
# handle all messages in the queue
for data in list:
for data in queue:
#print dgi
self.handleNamedMovement(data)
@ -378,14 +375,14 @@ class ClusterClient(DirectObject.DirectObject):
(name,x, y, z, h, p, r, sx, sy, sz,red,g,b,a, hidden) = data
#print "name"
#if (name == "camNode"):
#if name == "camNode":
# print x,y,z,h,p,r, sx, sy, sz,red,g,b,a, hidden
if (name in self.objectMappings):
if name in self.objectMappings:
self.objectMappings[name].setPosHpr(render, x, y, z, h, p, r)
self.objectMappings[name].setScale(render,sx,sy,sz)
if (self.objectHasColor[name]):
if self.objectHasColor[name]:
self.objectMappings[name].setColor(red,g,b,a)
if (hidden):
if hidden:
self.objectMappings[name].hide()
else:
self.objectMappings[name].show()
@ -451,7 +448,7 @@ class DisplayConnection:
self.tcpConn = qcm.openTCPClientConnection(
serverName, port, gameServerTimeoutMs)
# Test for bad connection
if self.tcpConn == None:
if self.tcpConn is None:
return None
else:
self.tcpConn.setNoDelay(1)
@ -680,5 +677,3 @@ class DummyClusterClient(DirectObject.DirectObject):
if fLocally:
# Execute locally
exec(commandString, __builtins__)

View File

@ -165,4 +165,3 @@ ClientConfigs = {
}
],
}

View File

@ -59,17 +59,17 @@ class ClusterMsgHandler:
if qcr.dataAvailable():
datagram = NetDatagram()
if qcr.getData(datagram):
(dgi, type) = self.readHeader(datagram)
(dgi, dtype) = self.readHeader(datagram)
else:
dgi = None
type = CLUSTER_NONE
dtype = CLUSTER_NONE
self.notify.warning("getData returned false")
else:
datagram = None
dgi = None
type = CLUSTER_NONE
dtype = CLUSTER_NONE
# Note, return datagram to keep a handle on the data
return (datagram, dgi, type)
return (datagram, dgi, dtype)
def blockingRead(self, qcr):
"""
@ -85,19 +85,19 @@ class ClusterMsgHandler:
# Data is available, create a datagram iterator
datagram = NetDatagram()
if qcr.getData(datagram):
(dgi, type) = self.readHeader(datagram)
(dgi, dtype) = self.readHeader(datagram)
else:
(dgi, type) = (None, CLUSTER_NONE)
(dgi, dtype) = (None, CLUSTER_NONE)
self.notify.warning("getData returned false")
# Note, return datagram to keep a handle on the data
return (datagram, dgi, type)
return (datagram, dgi, dtype)
def readHeader(self, datagram):
dgi = PyDatagramIterator(datagram)
number = dgi.getUint32()
type = dgi.getUint8()
self.notify.debug("Packet %d type %d received" % (number, type))
return (dgi, type)
dtype = dgi.getUint8()
self.notify.debug("Packet %d type %d received" % (number, dtype))
return (dgi, dtype)
def makeCamOffsetDatagram(self, xyz, hpr):
datagram = PyDatagram()
@ -298,12 +298,3 @@ class ClusterMsgHandler:
dt=dgi.getFloat32()
self.notify.debug('time data=%f %f' % (frameTime, dt))
return (frameCount, frameTime, dt)

View File

@ -4,6 +4,7 @@ from direct.distributed.MsgTypes import *
from direct.directnotify import DirectNotifyGlobal
from direct.showbase import DirectObject
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
# NOTE: This assumes the following variables are set via bootstrap command line
# arguments on server startup:
@ -100,16 +101,16 @@ class ClusterServer(DirectObject.DirectObject):
return Task.cont
def addNamedObjectMapping(self,object,name,hasColor = True,
def addNamedObjectMapping(self, object, name, hasColor = True,
priority = 0):
if (name not in self.objectMappings):
if name not in self.objectMappings:
self.objectMappings[name] = object
self.objectHasColor[name] = hasColor
else:
self.notify.debug('attempt to add duplicate named object: '+name)
def removeObjectMapping(self,name):
if (name in self.objectMappings):
def removeObjectMapping(self, name):
if name in self.objectMappings:
self.objectMappings.pop(name)
@ -123,11 +124,11 @@ class ClusterServer(DirectObject.DirectObject):
self.sortedControlMappings.sort()
def addControlMapping(self,objectName,controlledName, offset = None,
def addControlMapping(self, objectName, controlledName, offset = None,
priority = 0):
if (objectName not in self.controlMappings):
if objectName not in self.controlMappings:
self.controlMappings[objectName] = controlledName
if (offset == None):
if offset is None:
offset = Vec3(0,0,0)
self.controlOffsets[objectName] = offset
self.controlPriorities[objectName] = priority
@ -135,13 +136,13 @@ class ClusterServer(DirectObject.DirectObject):
else:
self.notify.debug('attempt to add duplicate controlled object: '+name)
def setControlMappingOffset(self,objectName,offset):
if (objectName in self.controlMappings):
def setControlMappingOffset(self, objectName, offset):
if objectName in self.controlMappings:
self.controlOffsets[objectName] = offset
def removeControlMapping(self,name):
if (name in self.controlMappings):
def removeControlMapping(self, name):
if name in self.controlMappings:
self.controlMappings.pop(name)
self.controlPriorities.pop(name)
self.redoSortedPriorities()
@ -156,7 +157,7 @@ class ClusterServer(DirectObject.DirectObject):
for pair in self.sortedControlPriorities:
object = pair[1]
name = self.controlMappings[object]
if (object in self.objectMappings):
if object in self.objectMappings:
self.moveObject(self.objectMappings[object],name,self.controlOffsets[object],
self.objectHasColor[object])
@ -165,7 +166,6 @@ class ClusterServer(DirectObject.DirectObject):
def sendNamedMovementDone(self):
self.notify.debug("named movement done")
datagram = self.msgHandler.makeNamedMovementDone()
self.cw.send(datagram,self.lastConnection)
@ -176,7 +176,7 @@ class ClusterServer(DirectObject.DirectObject):
xyz = nodePath.getPos(render) + offset
hpr = nodePath.getHpr(render)
scale = nodePath.getScale(render)
if (hasColor):
if hasColor:
color = nodePath.getColor()
else:
color = [1,1,1,1]
@ -243,34 +243,34 @@ class ClusterServer(DirectObject.DirectObject):
def handleDatagram(self, dgi, type):
""" Process a datagram depending upon type flag """
if (type == CLUSTER_NONE):
if type == CLUSTER_NONE:
pass
elif (type == CLUSTER_EXIT):
elif type == CLUSTER_EXIT:
print('GOT EXIT')
import sys
sys.exit()
elif (type == CLUSTER_CAM_OFFSET):
elif type == CLUSTER_CAM_OFFSET:
self.handleCamOffset(dgi)
elif (type == CLUSTER_CAM_FRUSTUM):
elif type == CLUSTER_CAM_FRUSTUM:
self.handleCamFrustum(dgi)
elif (type == CLUSTER_CAM_MOVEMENT):
elif type == CLUSTER_CAM_MOVEMENT:
self.handleCamMovement(dgi)
elif (type == CLUSTER_SELECTED_MOVEMENT):
elif type == CLUSTER_SELECTED_MOVEMENT:
self.handleSelectedMovement(dgi)
elif (type == CLUSTER_COMMAND_STRING):
elif type == CLUSTER_COMMAND_STRING:
self.handleCommandString(dgi)
elif (type == CLUSTER_SWAP_READY):
elif type == CLUSTER_SWAP_READY:
pass
elif (type == CLUSTER_SWAP_NOW):
elif type == CLUSTER_SWAP_NOW:
self.notify.debug('swapping')
base.graphicsEngine.flipFrame()
elif (type == CLUSTER_TIME_DATA):
elif type == CLUSTER_TIME_DATA:
self.notify.debug('time data')
self.handleTimeData(dgi)
elif (type == CLUSTER_NAMED_OBJECT_MOVEMENT):
elif type == CLUSTER_NAMED_OBJECT_MOVEMENT:
self.messageQueue.append(self.msgHandler.parseNamedMovementDatagram(dgi))
#self.handleNamedMovement(dgi)
elif (type == CLUSTER_NAMED_MOVEMENT_DONE):
elif type == CLUSTER_NAMED_MOVEMENT_DONE:
#print "got done",self.messageQueue
#if (len(self.messageQueue) > 0):
# print self.messageQueue[0]
@ -297,11 +297,11 @@ class ClusterServer(DirectObject.DirectObject):
def handleNamedMovement(self, data):
""" Update cameraJig position to reflect latest position """
(name,x, y, z, h, p, r,sx,sy,sz, red, g, b, a, hidden) = data
if (name in self.objectMappings):
if name in self.objectMappings:
self.objectMappings[name].setPosHpr(render, x, y, z, h, p, r)
self.objectMappings[name].setScale(render,sx,sy,sz)
self.objectMappings[name].setColor(red,g,b,a)
if (hidden):
if hidden:
self.objectMappings[name].hide()
else:
self.objectMappings[name].show()
@ -346,5 +346,3 @@ class ClusterServer(DirectObject.DirectObject):
exec(command, __builtins__)
except:
pass

View File

@ -1,5 +1,6 @@
from direct.showbase.InputStateGlobal import inputState
from direct.showbase.MessengerGlobal import messenger
from direct.task.Task import Task
from panda3d.core import *
from . import GravityWalker
@ -54,7 +55,7 @@ class BattleWalker(GravityWalker.GravityWalker):
debugRunning = inputState.isSet("debugRunning")
if(debugRunning):
if debugRunning:
self.speed*=base.debugRunningMultiplier
self.slideSpeed*=base.debugRunningMultiplier
self.rotationSpeed*=1.25
@ -139,150 +140,3 @@ class BattleWalker(GravityWalker.GravityWalker):
if self.moving or jump:
messenger.send("avatarMoving")
return Task.cont
if 0:
def handleAvatarControls(self, task):
# If targetNp is not available, revert back to GravityWalker.handleAvatarControls.
# This situation occurs when the target dies, but we aren't switched out of
# battle walker control mode.
targetNp = self.avatarNodePath.currentTarget
if not BattleStrafe or targetNp == None or targetNp.isEmpty():
return GravityWalker.GravityWalker.handleAvatarControls(self, task)
# get the button states:
run = inputState.isSet("run")
forward = inputState.isSet("forward")
reverse = inputState.isSet("reverse")
turnLeft = inputState.isSet("turnLeft")
turnRight = inputState.isSet("turnRight")
slide = inputState.isSet("slide")
jump = inputState.isSet("jump")
# Determine what the speeds are based on the buttons:
self.advanceSpeed=(forward and self.avatarControlForwardSpeed or
reverse and -self.avatarControlReverseSpeed)
if run and self.advanceSpeed>0.0:
self.advanceSpeed*=2.0 #*#
# Should fSlide be renamed slideButton?
self.slideSpeed=.15*(turnLeft and -self.avatarControlForwardSpeed or
turnRight and self.avatarControlForwardSpeed)
print('slideSpeed: %s' % self.slideSpeed)
self.rotationSpeed=0
self.speed=0
debugRunning = inputState.isSet("debugRunning")
if debugRunning:
self.advanceSpeed*=4.0
self.slideSpeed*=4.0
self.rotationSpeed*=1.25
if self.needToDeltaPos:
self.setPriorParentVector()
self.needToDeltaPos = 0
if self.wantDebugIndicator:
self.displayDebugInfo()
if self.lifter.isOnGround():
if self.isAirborne:
self.isAirborne = 0
assert self.debugPrint("isAirborne 0 due to isOnGround() true")
impact = self.lifter.getImpactVelocity()
if impact < -30.0:
messenger.send("jumpHardLand")
self.startJumpDelay(0.3)
else:
messenger.send("jumpLand")
if impact < -5.0:
self.startJumpDelay(0.2)
# else, ignore the little potholes.
assert self.isAirborne == 0
self.priorParent = Vec3.zero()
if jump and self.mayJump:
# The jump button is down and we're close
# enough to the ground to jump.
self.lifter.addVelocity(self.avatarControlJumpForce)
messenger.send("jumpStart")
self.isAirborne = 1
assert self.debugPrint("isAirborne 1 due to jump")
else:
if self.isAirborne == 0:
assert self.debugPrint("isAirborne 1 due to isOnGround() false")
self.isAirborne = 1
self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
# How far did we move based on the amount of time elapsed?
self.__oldDt = ClockObject.getGlobalClock().getDt()
dt=self.__oldDt
# Before we do anything with position or orientation, make the avatar
# face it's target. Only allow rMax degrees rotation per frame, so
# we don't get an unnatural spinning effect
curH = self.avatarNodePath.getH()
self.avatarNodePath.headsUp(targetNp)
newH = self.avatarNodePath.getH()
delH = reduceAngle(newH-curH)
rMax = 10
if delH < -rMax:
self.avatarNodePath.setH(curH-rMax)
self.rotationSpeed=-self.avatarControlRotateSpeed
elif delH > rMax:
self.avatarNodePath.setH(curH+rMax)
self.rotationSpeed=self.avatarControlRotateSpeed
# Check to see if we're moving at all:
self.moving = self.speed or self.slideSpeed or self.rotationSpeed or (self.priorParent!=Vec3.zero())
if self.moving:
distance = dt * self.speed
slideDistance = dt * self.slideSpeed
print('slideDistance: %s' % slideDistance)
rotation = dt * self.rotationSpeed
# Take a step in the direction of our previous heading.
self.vel=Vec3(Vec3.forward() * distance +
Vec3.right() * slideDistance)
if self.vel != Vec3.zero() or self.priorParent != Vec3.zero():
if 1:
# rotMat is the rotation matrix corresponding to
# our previous heading.
rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
step=(self.priorParent * dt) + rotMat.xform(self.vel)
self.avatarNodePath.setFluidPos(Point3(
self.avatarNodePath.getPos()+step))
self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
else:
self.vel.set(0.0, 0.0, 0.0)
"""
# Check to see if we're moving at all:
self.moving = self.advanceSpeed or self.slideSpeed or self.rotationSpeed or (self.priorParent!=Vec3.zero())
if self.moving:
distance = dt * self.advanceSpeed
slideDistance = dt * self.slideSpeed
rotation = dt * self.rotationSpeed
# Prevent avatar from getting too close to target
d = self.avatarNodePath.getPos(targetNp)
# TODO: make min distance adjust for current weapon
if (d[0]*d[0]+d[1]*d[1] < 6.0 and distance > 0):
# move the avatar sideways instead of forward
slideDistance += .2
distance = 0
# Take a step in the direction of our previous heading.
self.vel=Vec3(Vec3.forward() * distance +
Vec3.right() * slideDistance)
if self.vel != Vec3.zero() or self.priorParent != Vec3.zero():
# rotMat is the rotation matrix corresponding to
# our previous heading.
rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
step=rotMat.xform(self.vel) + (self.priorParent * dt)
self.avatarNodePath.setFluidPos(Point3(
self.avatarNodePath.getPos()+step))
self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
else:
self.vel.set(0.0, 0.0, 0.0)
"""
if self.moving or jump:
messenger.send("avatarMoving")
return Task.cont

View File

@ -1,5 +1,6 @@
from direct.showbase.InputStateGlobal import inputState
from direct.showbase.MessengerGlobal import messenger
#from DirectGui import *
#from PythonUtil import *
#from IntervalGlobal import *
@ -292,18 +293,18 @@ class ControlManager:
self.forceAvJumpToken.release()
self.forceAvJumpToken = None
def monitor(self, foo):
def monitor(self, _):
#assert self.debugPrint("monitor()")
#if 1:
# airborneHeight=self.avatar.getAirborneHeight()
# onScreenDebug.add("airborneHeight", "% 10.4f"%(airborneHeight,))
if 0:
onScreenDebug.add("InputState forward", "%d"%(inputState.isSet("forward")))
onScreenDebug.add("InputState reverse", "%d"%(inputState.isSet("reverse")))
onScreenDebug.add("InputState turnLeft", "%d"%(inputState.isSet("turnLeft")))
onScreenDebug.add("InputState turnRight", "%d"%(inputState.isSet("turnRight")))
onScreenDebug.add("InputState slideLeft", "%d"%(inputState.isSet("slideLeft")))
onScreenDebug.add("InputState slideRight", "%d"%(inputState.isSet("slideRight")))
#if 0:
# onScreenDebug.add("InputState forward", "%d"%(inputState.isSet("forward")))
# onScreenDebug.add("InputState reverse", "%d"%(inputState.isSet("reverse")))
# onScreenDebug.add("InputState turnLeft", "%d"%(inputState.isSet("turnLeft")))
# onScreenDebug.add("InputState turnRight", "%d"%(inputState.isSet("turnRight")))
# onScreenDebug.add("InputState slideLeft", "%d"%(inputState.isSet("slideLeft")))
# onScreenDebug.add("InputState slideRight", "%d"%(inputState.isSet("slideRight")))
return Task.cont
def setWASDTurn(self, turn):
@ -343,4 +344,3 @@ class ControlManager:
inputState.set("turnLeft", False, inputSource=inputState.WASD)
inputState.set("turnRight", False, inputSource=inputState.WASD)

View File

@ -19,7 +19,9 @@ animations based on walker events.
from direct.showbase.InputStateGlobal import inputState
from direct.directnotify import DirectNotifyGlobal
from direct.showbase import DirectObject
from direct.showbase.MessengerGlobal import messenger
from direct.task.Task import Task
from direct.task.TaskManagerGlobal import taskMgr
from panda3d.core import *

View File

@ -19,10 +19,12 @@ from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase import DirectObject
from direct.controls.ControlManager import CollisionHandlerRayStart
from direct.showbase.InputStateGlobal import inputState
from direct.showbase.MessengerGlobal import messenger
from direct.task.Task import Task
from panda3d.core import *
from direct.task.TaskManagerGlobal import taskMgr
from direct.extensions_native import VBase3_extensions
from direct.extensions_native import VBase4_extensions
from panda3d.core import *
import math
@ -142,7 +144,7 @@ class GravityWalker(DirectObject.DirectObject):
cSphereNode.setIntoCollideMask(BitMask32.allOff())
# set up collision mechanism
if config.GetBool('want-fluid-pusher', 0):
if ConfigVariableBool('want-fluid-pusher', 0):
self.pusher = CollisionHandlerFluidPusher()
else:
self.pusher = CollisionHandlerPusher()
@ -284,11 +286,11 @@ class GravityWalker(DirectObject.DirectObject):
# make sure we have a shadow traverser
base.initShadowTrav()
if active:
if 1:
# Please let skyler or drose know if this is causing a problem
# This is a bit of a hack fix:
self.avatarNodePath.setP(0.0)
self.avatarNodePath.setR(0.0)
# Please let skyler or drose know if this is causing a problem
# This is a bit of a hack fix:
self.avatarNodePath.setP(0.0)
self.avatarNodePath.setR(0.0)
self.cTrav.addCollider(self.cWallSphereNodePath, self.pusher)
if self.wantFloorSphere:
self.cTrav.addCollider(self.cFloorSphereNodePath, self.pusherFloor)
@ -440,7 +442,7 @@ class GravityWalker(DirectObject.DirectObject):
self.slideSpeed *= GravityWalker.DiagonalFactor
debugRunning = inputState.isSet("debugRunning")
if(debugRunning):
if debugRunning:
self.speed*=base.debugRunningMultiplier
self.slideSpeed*=base.debugRunningMultiplier
self.rotationSpeed*=1.25

View File

@ -1,6 +1,8 @@
from direct.directnotify import DirectNotifyGlobal
from direct.showbase import DirectObject
from direct.showbase.PythonUtil import SerialNumGen
from direct.showbase.MessengerGlobal import messenger
# internal class, don't create these on your own
class InputStateToken:

View File

@ -20,7 +20,9 @@ from direct.directnotify import DirectNotifyGlobal
from direct.showbase import DirectObject
from direct.controls.ControlManager import CollisionHandlerRayStart
from direct.showbase.InputStateGlobal import inputState
from direct.showbase.MessengerGlobal import messenger
from direct.task.Task import Task
from direct.task.TaskManagerGlobal import taskMgr
from panda3d.core import *
class NonPhysicsWalker(DirectObject.DirectObject):
@ -184,7 +186,7 @@ class NonPhysicsWalker(DirectObject.DirectObject):
tempCTrav = CollisionTraverser("oneTimeCollide")
tempCTrav.addCollider(self.cSphereNodePath, self.pusher)
tempCTrav.addCollider(self.cRayNodePath, self.lifter)
tempCTrav.traverse(render)
tempCTrav.traverse(base.render)
def addBlastForce(self, vector):
pass
@ -268,12 +270,12 @@ class NonPhysicsWalker(DirectObject.DirectObject):
else:
self.vel.set(0.0, 0.0, 0.0)
self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
self.__oldPosDelta = self.avatarNodePath.getPosDelta(base.render)
self.__oldDt = dt
try:
self.worldVelocity = self.__oldPosDelta*(1/self.__oldDt)
except:
if self.__oldDt != 0:
self.worldVelocity = self.__oldPosDelta * (1 / self.__oldDt)
else:
# divide by zero
self.worldVelocity = 0

View File

@ -31,9 +31,6 @@ class ObserverWalker(NonPhysicsWalker.NonPhysicsWalker):
"""
Set up the avatar for collisions
"""
"""
Set up the avatar for collisions
"""
assert not avatarNodePath.isEmpty()
self.cTrav = collisionTraverser
@ -102,11 +99,9 @@ class ObserverWalker(NonPhysicsWalker.NonPhysicsWalker):
Activate the arrow keys, etc.
"""
assert self.debugPrint("enableAvatarControls")
pass
def disableAvatarControls(self):
"""
Ignore the arrow keys, etc.
"""
assert self.debugPrint("disableAvatarControls")
pass

View File

@ -20,12 +20,14 @@ from direct.directnotify import DirectNotifyGlobal
from direct.showbase import DirectObject
from direct.controls.ControlManager import CollisionHandlerRayStart
from direct.showbase.InputStateGlobal import inputState
from direct.showbase.MessengerGlobal import messenger
from direct.task.Task import Task
from panda3d.core import *
from panda3d.physics import *
from direct.task.TaskManagerGlobal import taskMgr
from direct.extensions_native import Mat3_extensions
from direct.extensions_native import VBase3_extensions
from direct.extensions_native import VBase4_extensions
from panda3d.core import *
from panda3d.physics import *
import math
#import LineStream
@ -131,11 +133,6 @@ class PhysicsWalker(DirectObject.DirectObject):
assert onScreenDebug.add("height", height.getZ())
return height.getZ() - self.floorOffset
else: # useCollisionHandlerQueue
"""
returns the height of the avatar above the ground.
If there is no floor below the avatar, 0.0 is returned.
aka get airborne height.
"""
height = 0.0
#*#self.cRayTrav.traverse(render)
if self.cRayQueue.getNumEntries() != 0:
@ -239,7 +236,7 @@ class PhysicsWalker(DirectObject.DirectObject):
self.floorOffset = floorOffset = 7.0
self.avatarNodePath = self.setupPhysics(avatarNodePath)
if 0 or self.useHeightRay:
if self.useHeightRay:
#self.setupRay(floorBitmask, avatarRadius)
self.setupRay(floorBitmask, 0.0)
self.setupSphere(wallBitmask|floorBitmask, avatarRadius)
@ -257,14 +254,14 @@ class PhysicsWalker(DirectObject.DirectObject):
self.cSphereNodePath.show()
if indicator:
# Indicator Node:
change=render.attachNewNode("change")
change = render.attachNewNode("change")
#change.setPos(Vec3(1.0, 1.0, 1.0))
#change.setHpr(0.0, 0.0, 0.0)
change.setScale(0.1)
#change.setColor(Vec4(1.0, 1.0, 1.0, 1.0))
indicator.reparentTo(change)
indicatorNode=render.attachNewNode("physVelocityIndicator")
indicatorNode = render.attachNewNode("physVelocityIndicator")
#indicatorNode.setScale(0.1)
#indicatorNode.setP(90.0)
indicatorNode.setPos(self.avatarNodePath, 0.0, 0.0, 6.0)
@ -273,7 +270,7 @@ class PhysicsWalker(DirectObject.DirectObject):
self.physVelocityIndicator=indicatorNode
# Contact Node:
contactIndicatorNode=render.attachNewNode("physContactIndicator")
contactIndicatorNode = render.attachNewNode("physContactIndicator")
contactIndicatorNode.setScale(0.25)
contactIndicatorNode.setP(90.0)
contactIndicatorNode.setPos(self.avatarNodePath, 0.0, 0.0, 5.0)
@ -472,137 +469,103 @@ class PhysicsWalker(DirectObject.DirectObject):
onScreenDebug.add("posDelta1",
self.avatarNodePath.getPosDelta(render).pPrintValues())
if 0:
onScreenDebug.add("posDelta3",
render.getRelativeVector(
self.avatarNodePath,
self.avatarNodePath.getPosDelta(render)).pPrintValues())
#onScreenDebug.add("posDelta3",
# render.getRelativeVector(
# self.avatarNodePath,
# self.avatarNodePath.getPosDelta(render)).pPrintValues())
if 0:
onScreenDebug.add("gravity",
self.gravity.getLocalVector().pPrintValues())
onScreenDebug.add("priorParent",
self.priorParent.getLocalVector().pPrintValues())
onScreenDebug.add("avatarViscosity",
"% 10.4f"%(self.avatarViscosity.getCoef(),))
#onScreenDebug.add("gravity",
# self.gravity.getLocalVector().pPrintValues())
#onScreenDebug.add("priorParent",
# self.priorParent.getLocalVector().pPrintValues())
#onScreenDebug.add("avatarViscosity",
# "% 10.4f"%(self.avatarViscosity.getCoef(),))
#
#onScreenDebug.add("physObject pos",
# physObject.getPosition().pPrintValues())
#onScreenDebug.add("physObject hpr",
# physObject.getOrientation().getHpr().pPrintValues())
#onScreenDebug.add("physObject orien",
# physObject.getOrientation().pPrintValues())
onScreenDebug.add("physObject pos",
physObject.getPosition().pPrintValues())
onScreenDebug.add("physObject hpr",
physObject.getOrientation().getHpr().pPrintValues())
onScreenDebug.add("physObject orien",
physObject.getOrientation().pPrintValues())
onScreenDebug.add("physObject vel",
physObject.getVelocity().pPrintValues())
onScreenDebug.add("physObject len",
"% 10.4f"%physObject.getVelocity().length())
if 1:
onScreenDebug.add("physObject vel",
physObject.getVelocity().pPrintValues())
onScreenDebug.add("physObject len",
"% 10.4f"%physObject.getVelocity().length())
#onScreenDebug.add("posDelta4",
# self.priorParentNp.getRelativeVector(
# render,
# self.avatarNodePath.getPosDelta(render)).pPrintValues())
if 0:
onScreenDebug.add("posDelta4",
self.priorParentNp.getRelativeVector(
render,
self.avatarNodePath.getPosDelta(render)).pPrintValues())
onScreenDebug.add("priorParent",
self.priorParent.getLocalVector().pPrintValues())
if 1:
onScreenDebug.add("priorParent",
self.priorParent.getLocalVector().pPrintValues())
#onScreenDebug.add("priorParent po",
# self.priorParent.getVector(physObject).pPrintValues())
if 0:
onScreenDebug.add("priorParent po",
self.priorParent.getVector(physObject).pPrintValues())
#onScreenDebug.add("__posDelta",
# self.__oldPosDelta.pPrintValues())
if 0:
onScreenDebug.add("__posDelta",
self.__oldPosDelta.pPrintValues())
onScreenDebug.add("contact",
contact.pPrintValues())
#onScreenDebug.add("airborneHeight", "% 10.4f"%(
# self.getAirborneHeight(),))
if 1:
onScreenDebug.add("contact",
contact.pPrintValues())
#onScreenDebug.add("airborneHeight", "% 10.4f"%(
# self.getAirborneHeight(),))
if 0:
onScreenDebug.add("__oldContact",
contact.pPrintValues())
onScreenDebug.add("__oldAirborneHeight", "% 10.4f"%(
self.getAirborneHeight(),))
airborneHeight=self.getAirborneHeight()
#onScreenDebug.add("__oldContact",
# contact.pPrintValues())
#onScreenDebug.add("__oldAirborneHeight", "% 10.4f"%(
# self.getAirborneHeight(),))
airborneHeight = self.getAirborneHeight()
if airborneHeight > self.highMark:
self.highMark = airborneHeight
if __debug__:
onScreenDebug.add("highMark", "% 10.4f"%(self.highMark,))
#if airborneHeight < 0.1: #contact!=Vec3.zero():
if 1:
if (airborneHeight > self.avatarRadius*0.5
or physObject.getVelocity().getZ() > 0.0
): # Check stair angles before changing this.
# ...the avatar is airborne (maybe a lot or a tiny amount).
self.isAirborne = 1
else:
# ...the avatar is very close to the ground (close enough to be
# considered on the ground).
if self.isAirborne and physObject.getVelocity().getZ() <= 0.0:
# ...the avatar has landed.
contactLength = contact.length()
if contactLength>self.__hardLandingForce:
#print "jumpHardLand"
messenger.send("jumpHardLand")
else:
#print "jumpLand"
messenger.send("jumpLand")
self.priorParent.setVector(Vec3.zero())
self.isAirborne = 0
elif jump:
#print "jump"
#self.__jumpButton=0
messenger.send("jumpStart")
if 0:
# ...jump away from walls and with with the slope normal.
jumpVec=Vec3(contact+Vec3.up())
#jumpVec=Vec3(rotAvatarToPhys.xform(jumpVec))
jumpVec.normalize()
else:
# ...jump straight up, even if next to a wall.
jumpVec=Vec3.up()
jumpVec*=self.avatarControlJumpForce
physObject.addImpulse(Vec3(jumpVec))
self.isAirborne = 1 # Avoid double impulse before fully airborne.
else:
self.isAirborne = 0
if __debug__:
onScreenDebug.add("isAirborne", "%d"%(self.isAirborne,))
if (airborneHeight > self.avatarRadius*0.5
or physObject.getVelocity().getZ() > 0.0
): # Check stair angles before changing this.
# ...the avatar is airborne (maybe a lot or a tiny amount).
self.isAirborne = 1
else:
if contact!=Vec3.zero():
# ...the avatar has touched something (but might not be on the ground).
# ...the avatar is very close to the ground (close enough to be
# considered on the ground).
if self.isAirborne and physObject.getVelocity().getZ() <= 0.0:
# ...the avatar has landed.
contactLength = contact.length()
contact.normalize()
angle=contact.dot(Vec3.up())
if angle>self.__standableGround:
# ...avatar is on standable ground.
if self.__oldContact==Vec3.zero():
#if self.__oldAirborneHeight > 0.1: #self.__oldContact==Vec3.zero():
# ...avatar was airborne.
self.jumpCount-=1
if contactLength>self.__hardLandingForce:
messenger.send("jumpHardLand")
else:
messenger.send("jumpLand")
elif jump:
self.jumpCount+=1
#self.__jumpButton=0
messenger.send("jumpStart")
jump=Vec3(contact+Vec3.up())
#jump=Vec3(rotAvatarToPhys.xform(jump))
jump.normalize()
jump*=self.avatarControlJumpForce
physObject.addImpulse(Vec3(jump))
if contactLength>self.__hardLandingForce:
#print "jumpHardLand"
messenger.send("jumpHardLand")
else:
#print "jumpLand"
messenger.send("jumpLand")
self.priorParent.setVector(Vec3.zero())
self.isAirborne = 0
elif jump:
#print "jump"
#self.__jumpButton = 0
messenger.send("jumpStart")
if contact!=self.__oldContact:
## ...jump away from walls and with with the slope normal.
#jumpVec=Vec3(contact+Vec3.up())
##jumpVec=Vec3(rotAvatarToPhys.xform(jumpVec))
#jumpVec.normalize()
# ...jump straight up, even if next to a wall.
jumpVec=Vec3.up()
jumpVec *= self.avatarControlJumpForce
physObject.addImpulse(Vec3(jumpVec))
self.isAirborne = 1 # Avoid double impulse before fully airborne.
else:
self.isAirborne = 0
if __debug__:
onScreenDebug.add("isAirborne", "%d"%(self.isAirborne,))
if contact != self.__oldContact:
# We must copy the vector to preserve it:
self.__oldContact=Vec3(contact)
self.__oldAirborneHeight=airborneHeight
self.__oldContact = Vec3(contact)
self.__oldAirborneHeight = airborneHeight
moveToGround = Vec3.zero()
if not self.useHeightRay or self.isAirborne:
@ -741,7 +704,7 @@ class PhysicsWalker(DirectObject.DirectObject):
if __debug__:
def setupAvatarPhysicsIndicator(self):
if self.wantDebugIndicator:
indicator=loader.loadModel('phase_5/models/props/dagger')
indicator = base.loader.loadModel('phase_5/models/props/dagger')
#self.walkControls.setAvatarPhysicsIndicator(indicator)
def debugPrint(self, message):

View File

@ -3,6 +3,7 @@ TwoDWalker.py is for controlling the avatars in a 2D scroller game environment.
"""
from .GravityWalker import *
from direct.showbase.MessengerGlobal import messenger
from panda3d.core import ConfigVariableBool

View File

@ -7,22 +7,9 @@ from direct.showbase import ShowBase
base = ShowBase.ShowBase()
# Put an axis in the world:
loader.loadModel("models/misc/xyzAxis").reparentTo(render)
base.loader.loadModel("models/misc/xyzAxis").reparentTo(render)
if 0:
# Hack:
# Enable drive mode but turn it off, and reset the camera
# This is here because ShowBase sets up a drive interface, this
# can be removed if ShowBase is changed to not set that up.
base.useDrive()
base.disableMouse()
if base.mouseInterface:
base.mouseInterface.reparentTo(base.dataUnused)
if base.mouse2cam:
base.mouse2cam.reparentTo(base.dataUnused)
# end of hack.
camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
base.camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
base.camLens.setFov(52.0)
base.camLens.setNearFar(1.0, 10000.0)

View File

@ -5,25 +5,13 @@ from panda3d.core import *
from direct.showbase.PythonUtil import *
from direct.showbase import ThreeUpShow
ThreeUpShow.ThreeUpShow()
base = ThreeUpShow.ThreeUpShow()
# Put an axis in the world:
loader.loadModel("models/misc/xyzAxis").reparentTo(render)
base.loader.loadModel("models/misc/xyzAxis").reparentTo(render)
if 0:
# Hack:
# Enable drive mode but turn it off, and reset the camera
# This is here because ShowBase sets up a drive interface, this
# can be removed if ShowBase is changed to not set that up.
base.useDrive()
base.disableMouse()
if base.mouseInterface:
base.mouseInterface.reparentTo(base.dataUnused)
if base.mouse2cam:
base.mouse2cam.reparentTo(base.dataUnused)
# end of hack.
camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
base.camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
base.camLens.setFov(52.0)
base.camLens.setNearFar(1.0, 10000.0)

View File

@ -14,7 +14,7 @@ class DirectDeviceManager(VrpnClient, DirectObject):
def __init__(self, server = None):
# Determine which server to use
if server != None:
if server is not None:
# One given as constructor argument
self.server = server
else:
@ -77,10 +77,10 @@ class DirectButtons(ButtonNode, DirectObject):
return self.nodePath
def __repr__(self):
str = self.name + ': '
string = self.name + ': '
for val in self:
str = str + '%d' % val + ' '
return str
string = string + '%d' % val + ' '
return string
class DirectAnalogs(AnalogNode, DirectObject):
analogCount = 0
@ -149,12 +149,12 @@ class DirectAnalogs(AnalogNode, DirectObject):
aMin = self.analogMin
center = self.analogCenter
deadband = self.analogDeadband
range = self.analogRange
# Zero out values in deadband
if (abs(rawValue-center) <= deadband):
if abs(rawValue - center) <= deadband:
return 0.0
# Clamp value between aMin and aMax and scale around center
if (rawValue >= center):
if rawValue >= center:
# Convert positive values to range 0 to 1
val = min(rawValue * sf, aMax)
percentVal = ((val - (center + deadband))/
@ -165,7 +165,7 @@ class DirectAnalogs(AnalogNode, DirectObject):
percentVal = -((val - (center - deadband))/
float(aMin - (center - deadband)))
# Normalize values to given minVal and maxVal range
return (((maxVal - minVal) * ((percentVal + 1)/2.0)) + minVal)
return ((maxVal - minVal) * ((percentVal + 1)/2.0)) + minVal
def normalizeChannel(self, chan, minVal = -1, maxVal = 1, sf = 1.0):
try:
@ -180,13 +180,14 @@ class DirectAnalogs(AnalogNode, DirectObject):
return self.nodePath
def __repr__(self):
str = self.name + ': '
string = self.name + ': '
for val in self:
str = str + '%.3f' % val + ' '
return str
string = string + '%.3f' % val + ' '
return string
class DirectTracker(TrackerNode, DirectObject):
trackerCount = 0
def __init__(self, vrpnClient, device):
# Keep track of number of trackers created
DirectTracker.trackerCount += 1
@ -257,10 +258,10 @@ class DirectDials(DialNode, DirectObject):
return self.nodePath
def __repr__(self):
str = self.name + ': '
string = self.name + ': '
for i in range(self.getNumDials()):
str = str + '%.3f' % self[i] + ' '
return str
string = string + '%.3f' % self[i] + ' '
return string
class DirectTimecodeReader(AnalogNode, DirectObject):
timecodeReaderCount = 0
@ -316,5 +317,5 @@ class DirectTimecodeReader(AnalogNode, DirectObject):
self.totalSeconds)
def __repr__(self):
str = ('%s: %d:%d:%d:%d' % ((self.name,) + self.getTime()[:-1]))
return str
string = ('%s: %d:%d:%d:%d' % ((self.name,) + self.getTime()[:-1]))
return string

View File

@ -1,14 +1,12 @@
""" Class used to create and control radamec device """
from math import *
from direct.showbase.DirectObject import DirectObject
from direct.task.Task import Task
from direct.task.TaskManagerGlobal import taskMgr
from .DirectDeviceManager import *
from direct.directnotify import DirectNotifyGlobal
"""
TODO:
Handle interaction between widget, followSelectedTask and updateTask
"""
#TODO: Handle interaction between widget, followSelectedTask and updateTask
# ANALOGS
NULL_AXIS = -1
@ -65,4 +63,3 @@ class DirectFastrak(DirectObject):
3.280839895013123 * pos[1],
3.280839895013123 * pos[0])
self.notify.debug("Tracker(%d) Pos = %s" % (self.deviceNo, repr(self.trackerPos)))

View File

@ -4,12 +4,10 @@ from .DirectDeviceManager import *
from direct.directtools.DirectUtil import *
from direct.gui import OnscreenText
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
import math
"""
TODO:
Handle interaction between widget, followSelectedTask and updateTask
"""
#TODO: Handle interaction between widget, followSelectedTask and updateTask
# BUTTONS
L_STICK = 0
@ -39,10 +37,11 @@ class DirectJoybox(DirectObject):
joyboxCount = 0
xyzMultiplier = 1.0
hprMultiplier = 1.0
def __init__(self, device = 'CerealBox', nodePath = base.direct.camera,
headingNP = base.direct.camera):
# See if device manager has been initialized
if base.direct.deviceManager == None:
if base.direct.deviceManager is None:
base.direct.deviceManager = DirectDeviceManager()
# Set name
DirectJoybox.joyboxCount += 1
@ -172,12 +171,12 @@ class DirectJoybox(DirectObject):
for chan in range(len(self.analogs)):
val = self.analogs.getControlState(chan)
# Zero out values in deadband
if (val < 0):
if val < 0:
val = min(val + ANALOG_DEADBAND, 0.0)
else:
val = max(val - ANALOG_DEADBAND, 0.0)
# Scale up rotating knob values
if (chan == L_TWIST) or (chan == R_TWIST):
if chan == L_TWIST or chan == R_TWIST:
val *= 3.0
# Now clamp value between minVal and maxVal
val = CLAMP(val, JOYBOX_MIN, JOYBOX_MAX)
@ -240,7 +239,7 @@ class DirectJoybox(DirectObject):
def joyboxFly(self):
# Do nothing if no nodePath selected
if self.nodePath == None:
if self.nodePath is None:
return
hprScale = ((self.aList[L_SLIDE] + 1.0) *
50.0 * DirectJoybox.hprMultiplier)
@ -264,14 +263,14 @@ class DirectJoybox(DirectObject):
# if we are using a heading nodepath, we want
# to drive in the direction we are facing,
# however, we don't want the z component to change
if (self.useHeadingNP and self.headingNP != None):
if self.useHeadingNP and self.headingNP is not None:
oldZ = pos.getZ()
pos = self.nodePath.getRelativeVector(self.headingNP,
pos)
pos.setZ(oldZ)
# if we are using a heading NP we might want to rotate
# in place around that NP
if (self.rotateInPlace):
if self.rotateInPlace:
parent = self.nodePath.getParent()
self.floatingNP.reparentTo(parent)
self.floatingNP.setPos(self.headingNP,0,0,0)
@ -389,7 +388,7 @@ class DirectJoybox(DirectObject):
def spaceFly(self):
# Do nothing if no nodePath selected
if self.nodePath == None:
if self.nodePath is None:
return
hprScale = (self.normalizeChannel(L_SLIDE, 0.1, 100) *
DirectJoybox.hprMultiplier)
@ -408,7 +407,7 @@ class DirectJoybox(DirectObject):
def planetFly(self):
# Do nothing if no nodePath selected
if self.nodePath == None:
if self.nodePath is None:
return
hprScale = (self.normalizeChannel(L_SLIDE, 0.1, 100) *
DirectJoybox.hprMultiplier)
@ -459,7 +458,7 @@ class DirectJoybox(DirectObject):
def orbitFly(self):
# Do nothing if no nodePath selected
if self.nodePath == None:
if self.nodePath is None:
return
hprScale = (self.normalizeChannel(L_SLIDE, 0.1, 100) *
DirectJoybox.hprMultiplier)
@ -502,7 +501,7 @@ class DirectJoybox(DirectObject):
# correct the ranges of the two twist axes of the joybox.
def normalizeChannel(self, chan, minVal = -1, maxVal = 1):
try:
if (chan == L_TWIST) or (chan == R_TWIST):
if chan == L_TWIST or chan == R_TWIST:
# These channels have reduced range
return self.analogs.normalize(
self.analogs.getControlState(chan), minVal, maxVal, 3.0)
@ -511,5 +510,3 @@ class DirectJoybox(DirectObject):
self.analogs.getControlState(chan), minVal, maxVal)
except IndexError:
return 0.0

View File

@ -1,15 +1,13 @@
""" Class used to create and control radamec device """
from math import *
from direct.showbase.DirectObject import DirectObject
from direct.task.Task import Task
from direct.task.TaskManagerGlobal import taskMgr
from .DirectDeviceManager import *
from direct.directnotify import DirectNotifyGlobal
"""
TODO:
Handle interaction between widget, followSelectedTask and updateTask
"""
#TODO: Handle interaction between widget, followSelectedTask and updateTask
# ANALOGS
RAD_PAN = 0
@ -23,7 +21,7 @@ class DirectRadamec(DirectObject):
def __init__(self, device = 'Analog0', nodePath = None):
# See if device manager has been initialized
if base.direct.deviceManager == None:
if base.direct.deviceManager is None:
base.direct.deviceManager = DirectDeviceManager()
# Set name
self.name = 'Radamec-' + repr(DirectRadamec.radamecCount)
@ -73,11 +71,12 @@ class DirectRadamec(DirectObject):
# Normalize to the range [-minVal, maxVal] based on some hard-coded
# max/min numbers of the Radamec device
def normalizeChannel(self, chan, minVal = -1, maxVal = 1):
try:
maxRange = self.maxRange[chan]
minRange = self.minRange[chan]
except IndexError:
if chan < 0 or chan >= min(len(self.maxRange), len(self.minRange)):
raise RuntimeError("can't normalize this channel (channel %d)" % chan)
range = maxRange - minRange
clampedVal = CLAMP(self.aList[chan], minRange, maxRange)
return ((maxVal - minVal) * (clampedVal - minRange) / range) + minVal
maxRange = self.maxRange[chan]
minRange = self.minRange[chan]
diff = maxRange - minRange
clampedVal = max(min(self.aList[chan], maxRange), maxRange)
return ((maxVal - minVal) * (clampedVal - minRange) / diff) + minVal

View File

@ -41,17 +41,17 @@ class DirectNotify:
"""getCategory(self, string)
Return the category with given name if present, None otherwise
"""
return (self.__categories.get(categoryName, None))
return self.__categories.get(categoryName, None)
def newCategory(self, categoryName, logger=None):
"""newCategory(self, string)
Make a new notify category named categoryName. Return new category
if no such category exists, else return existing category
"""
if (categoryName not in self.__categories):
if categoryName not in self.__categories:
self.__categories[categoryName] = Notifier.Notifier(categoryName, logger)
self.setDconfigLevel(categoryName)
return (self.getCategory(categoryName))
return self.getCategory(categoryName)
def setDconfigLevel(self, categoryName):
"""

View File

@ -4,6 +4,7 @@
import time
import math
class Logger:
def __init__(self, fileName="log"):
"""
@ -14,18 +15,17 @@ class Logger:
self.__logFile = None
self.__logFileName = fileName
def setTimeStamp(self, bool):
def setTimeStamp(self, enable):
"""
Toggle time stamp printing with log entries on and off
"""
self.__timeStamp = bool
self.__timeStamp = enable
def getTimeStamp(self):
"""
Return whether or not we are printing time stamps with log entries
"""
return(self.__timeStamp)
return self.__timeStamp
# logging control
@ -38,13 +38,12 @@ class Logger:
def log(self, entryString):
"""log(self, string)
Print the given string to the log file"""
if (self.__logFile == None):
if self.__logFile is None:
self.__openLogFile()
if (self.__timeStamp):
if self.__timeStamp:
self.__logFile.write(self.__getTimeStamp())
self.__logFile.write(entryString + '\n')
# logging functions
def __openLogFile(self):
@ -61,7 +60,7 @@ class Logger:
"""
Close the error/warning output file
"""
if (self.__logFile != None):
if self.__logFile is not None:
self.__logFile.close()
def __getTimeStamp(self):
@ -70,22 +69,8 @@ class Logger:
"""
t = time.time()
dt = t - self.__startTime
if (dt >= 86400):
days = int(math.floor(dt/86400))
dt = dt%86400
else:
days = 0
if (dt >= 3600):
hours = int(math.floor(dt/3600))
dt = dt%3600
else:
hours = 0
if (dt >= 60):
minutes = int(math.floor(dt/60))
dt = dt%60
else:
minutes = 0
days, dt = divmod(dt, 86400)
hours, dt = divmod(dt, 3600)
minutes, dt = divmod(dt, 60)
seconds = int(math.ceil(dt))
return("%02d:%02d:%02d:%02d: " % (days, hours, minutes, seconds))
return "%02d:%02d:%02d:%02d: " % (days, hours, minutes, seconds)

View File

@ -32,7 +32,7 @@ class Notifier:
"""
self.__name = name
if (logger==None):
if logger is None:
self.__logger = defaultLogger
else:
self.__logger = logger
@ -144,17 +144,17 @@ class Notifier:
self.__print(string)
return 1 # to allow assert myNotify.warning("blah")
def setWarning(self, bool):
def setWarning(self, enable):
"""
Enable/Disable the printing of warning messages
"""
self.__warning = bool
self.__warning = enable
def getWarning(self):
"""
Return whether the printing of warning messages is on or off
"""
return(self.__warning)
return self.__warning
# debug funcs
def debug(self, debugString):
@ -171,11 +171,11 @@ class Notifier:
self.__print(string)
return 1 # to allow assert myNotify.debug("blah")
def setDebug(self, bool):
def setDebug(self, enable):
"""
Enable/Disable the printing of debug messages
"""
self.__debug = bool
self.__debug = enable
def getDebug(self):
"""
@ -204,11 +204,11 @@ class Notifier:
"""
return self.__info
def setInfo(self, bool):
def setInfo(self, enable):
"""
Enable/Disable informational message printing
"""
self.__info = bool
self.__info = enable
# log funcs
def __log(self, logEntry):
@ -222,13 +222,13 @@ class Notifier:
"""
Return 1 if logging enabled, 0 otherwise
"""
return (self.__logging)
return self.__logging
def setLogging(self, bool):
def setLogging(self, enable):
"""
Set the logging flag to int (1=on, 0=off)
"""
self.__logging = bool
self.__logging = enable
def __print(self, string):
"""
@ -297,4 +297,3 @@ class Notifier:
self.__log(string)
self.__print(string)
return 1 # to allow assert self.notify.debugCall("blah")

View File

@ -8,7 +8,9 @@
#
##############################################################################
import os,sys,gc
import os
import sys
import gc
from panda3d.core import *
class EggCacher:
@ -18,7 +20,7 @@ class EggCacher:
self.bamcache = BamCache.getGlobalPtr()
self.pandaloader = Loader()
self.loaderopts = LoaderOptions(LoaderOptions.LF_no_ram_cache)
if (self.bamcache.getActive() == 0):
if not self.bamcache.getActive():
print("The model cache is not currently active.")
print("You must set a model-cache-dir in your config file.")
sys.exit(1)
@ -29,42 +31,44 @@ class EggCacher:
def parseArgs(self, args):
self.concise = 0
self.pzkeep = 0
while len(args):
if (args[0]=="--concise"):
while len(args) > 0:
if args[0] == "--concise":
self.concise = 1
args = args[1:]
elif (args[0]=="--pzkeep"):
elif args[0] == "--pzkeep":
self.pzkeep = 1
args = args[1:]
else:
break
if (len(args) < 1):
if len(args) < 1:
print("Usage: eggcacher options file-or-directory")
sys.exit(1)
self.paths = args
def scanPath(self, eggs, path):
if (os.path.exists(path)==0):
if not os.path.exists(path):
print("No such file or directory: " + path)
return
if (os.path.isdir(path)):
if os.path.isdir(path):
for f in os.listdir(path):
self.scanPath(eggs, os.path.join(path,f))
return
if (path.endswith(".egg")):
if path.endswith(".egg"):
size = os.path.getsize(path)
eggs.append((path,size))
return
if (path.endswith(".egg.pz") or path.endswith(".egg.gz")):
if path.endswith(".egg.pz") or path.endswith(".egg.gz"):
size = os.path.getsize(path)
if (self.pzkeep): eggs.append((path,size))
else: eggs.append((path[:-3],size))
if self.pzkeep:
eggs.append((path, size))
else:
eggs.append((path[:-3], size))
def scanPaths(self, paths):
eggs = []
for path in paths:
abs = os.path.abspath(path)
self.scanPath(eggs,path)
#abs = os.path.abspath(path)
self.scanPath(eggs, path)
return eggs
def processFiles(self, files):
@ -72,15 +76,16 @@ class EggCacher:
for (path, size) in files:
total += size
progress = 0
for (path,size) in files:
for (path, size) in files:
fn = Filename.fromOsSpecific(path)
cached = self.bamcache.lookup(fn, "bam")
percent = (progress * 100) / total
report = path
if (self.concise): report = os.path.basename(report)
if self.concise:
report = os.path.basename(report)
print("Preprocessing Models %2d%% %s" % (percent, report))
sys.stdout.flush()
if (cached) and (cached.hasData()==0):
if cached and not cached.hasData():
self.pandaloader.loadSync(fn, self.loaderopts)
gc.collect()
ModelPool.releaseAllModels()

View File

@ -10,8 +10,8 @@ from __future__ import print_function
__all__ = []
import os
from distutils import sysconfig
import panda3d, pandac
import panda3d
import pandac
from panda3d.interrogatedb import *

View File

@ -6,6 +6,7 @@ from .DirectSelection import SelectionRay
from direct.interval.IntervalGlobal import Sequence, Func
from direct.directnotify import DirectNotifyGlobal
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
CAM_MOVE_DURATION = 1.2
COA_MARKER_SF = 0.0075
@ -22,7 +23,7 @@ class DirectCameraControl(DirectObject):
self.orthoViewRoll = 0.0
self.lastView = 0
self.coa = Point3(0, 100, 0)
self.coaMarker = loader.loadModel('models/misc/sphere')
self.coaMarker = base.loader.loadModel('models/misc/sphere')
self.coaMarker.setName('DirectCameraCOAMarker')
self.coaMarker.setTransparency(1)
self.coaMarker.setColor(1, 0, 0, 0)
@ -150,7 +151,7 @@ class DirectCameraControl(DirectObject):
def __startManipulateCamera(self, func = None, task = None, ival = None):
self.__stopManipulateCamera()
if func:
assert(task is None)
assert task is None
task = Task.Task(func)
if task:
self.manipulateCameraTask = taskMgr.add(task, 'manipulateCamera')
@ -366,7 +367,7 @@ class DirectCameraControl(DirectObject):
moveDir[2],
hVal,
0.0, 0.0)
if (self.lockRoll == True):
if self.lockRoll:
# flatten roll
base.direct.camera.setR(0)
@ -449,7 +450,7 @@ class DirectCameraControl(DirectObject):
(deltaX * base.direct.dr.fovH),
(-deltaY * base.direct.dr.fovV),
0.0)
if (self.lockRoll == True):
if self.lockRoll:
# flatten roll
base.direct.camera.setR(0)
self.camManipRef.setPos(self.coaMarkerPos)
@ -466,7 +467,7 @@ class DirectCameraControl(DirectObject):
(deltaY * 180.0),
0.0)
if (self.lockRoll == True):
if self.lockRoll:
# flatten roll
self.camManipRef.setR(0)
base.direct.camera.setTransform(self.camManipRef, wrt)
@ -491,7 +492,7 @@ class DirectCameraControl(DirectObject):
deltaAngle = angle - state.lastAngle
state.lastAngle = angle
self.camManipRef.setHpr(self.camManipRef, 0, 0, deltaAngle)
if (self.lockRoll == True):
if self.lockRoll:
# flatten roll
self.camManipRef.setR(0)
base.direct.camera.setTransform(self.camManipRef, wrt)
@ -576,7 +577,7 @@ class DirectCameraControl(DirectObject):
if not coaDist:
coaDist = Vec3(self.coa - ZERO_POINT).length()
# Place the marker in render space
if ref == None:
if ref is None:
# KEH: use the current display region
# ref = base.cam
ref = base.direct.drList.getCurrentDr().cam
@ -892,4 +893,3 @@ class DirectCameraControl(DirectObject):
def removeManipulateCameraTask(self):
self.__stopManipulateCamera()

View File

@ -163,7 +163,7 @@ def getCrankAngle(center):
# origin) in screen space
x = base.direct.dr.mouseX - center[0]
y = base.direct.dr.mouseY - center[2]
return (180 + rad2Deg(math.atan2(y, x)))
return 180 + rad2Deg(math.atan2(y, x))
def relHpr(nodePath, base, h, p, r):
# Compute nodePath2newNodePath relative to base coordinate system
@ -205,9 +205,9 @@ def qSlerp(startQuat, endQuat, t):
startQ.setJ(-1 * startQ.getJ())
startQ.setK(-1 * startQ.getK())
startQ.setR(-1 * startQ.getR())
if ((1.0 + cosOmega) > Q_EPSILON):
if (1.0 + cosOmega) > Q_EPSILON:
# usual case
if ((1.0 - cosOmega) > Q_EPSILON):
if (1.0 - cosOmega) > Q_EPSILON:
# usual case
omega = math.acos(cosOmega)
sinOmega = math.sin(omega)
@ -240,4 +240,3 @@ def qSlerp(startQuat, endQuat, t):
destQuat.setK(startScale * startQ.getK() +
endScale * endQuat.getK())
return destQuat

View File

@ -59,4 +59,3 @@ def LE_showInOneCam(nodePath, thisCamName):
for camName in LE_CAM_MASKS:
if camName != thisCamName:
nodePath.hide(LE_CAM_MASKS[camName])

View File

@ -4,6 +4,7 @@ from direct.showbase.DirectObject import DirectObject
from .DirectUtil import *
from .DirectGeometry import *
class DirectGrid(NodePath, DirectObject):
def __init__(self,gridSize=100.0,gridSpacing=5.0,planeColor=(0.5,0.5,0.5,0.5),parent = None):
# Initialize superclass
@ -13,7 +14,7 @@ class DirectGrid(NodePath, DirectObject):
# Load up grid parts to initialize grid object
# Polygon used to mark grid plane
self.gridBack = loader.loadModel('models/misc/gridBack')
self.gridBack = base.loader.loadModel('models/misc/gridBack')
self.gridBack.reparentTo(self)
self.gridBack.setColor(*planeColor)
@ -35,7 +36,7 @@ class DirectGrid(NodePath, DirectObject):
self.centerLines.setThickness(3)
# Small marker to hilight snap-to-grid point
self.snapMarker = loader.loadModel('models/misc/sphere')
self.snapMarker = base.loader.loadModel('models/misc/sphere')
self.snapMarker.node().setName('gridSnapMarker')
self.snapMarker.reparentTo(self)
self.snapMarker.setColor(1, 0, 0, 1)
@ -107,7 +108,7 @@ class DirectGrid(NodePath, DirectObject):
center.create()
minor.create()
major.create()
if (self.gridBack):
if self.gridBack:
self.gridBack.setScale(scaledSize)
def setXyzSnap(self, fSnap):

View File

@ -1,5 +1,7 @@
from panda3d.core import *
from direct.showbase.MessengerGlobal import messenger
class DirectLight(NodePath):
def __init__(self, light, parent):
@ -58,21 +60,21 @@ class DirectLights(NodePath):
nameList.sort()
return nameList
def create(self, type):
type = type.lower()
if type == 'ambient':
def create(self, ltype):
ltype = ltype.lower()
if ltype == 'ambient':
self.ambientCount += 1
light = AmbientLight('ambient-' + repr(self.ambientCount))
light.setColor(VBase4(.3, .3, .3, 1))
elif type == 'directional':
elif ltype == 'directional':
self.directionalCount += 1
light = DirectionalLight('directional-' + repr(self.directionalCount))
light.setColor(VBase4(1))
elif type == 'point':
elif ltype == 'point':
self.pointCount += 1
light = PointLight('point-' + repr(self.pointCount))
light.setColor(VBase4(1))
elif type == 'spot':
elif ltype == 'spot':
self.spotCount += 1
light = Spotlight('spot-' + repr(self.spotCount))
light.setColor(VBase4(1))
@ -130,6 +132,3 @@ class DirectLights(NodePath):
Turn off the given directLight
"""
render.clearLight(directLight)

View File

@ -1,4 +1,5 @@
from direct.showbase.DirectObject import DirectObject
from direct.showbase.MessengerGlobal import messenger
from .DirectGlobals import *
from .DirectUtil import *
from .DirectGeometry import *
@ -6,6 +7,7 @@ from .DirectSelection import SelectionRay
from direct.task import Task
from copy import deepcopy
class DirectManipulationControl(DirectObject):
def __init__(self):
# Create the grid
@ -201,7 +203,7 @@ class DirectManipulationControl(DirectObject):
((abs (endY - startY)) < 0.01)):
return
self.marquee = LineNodePath(render2d, 'marquee', 0.5, VBase4(.8, .6, .6, 1))
self.marquee = LineNodePath(base.render2d, 'marquee', 0.5, VBase4(.8, .6, .6, 1))
self.marqueeInfo = (startX, startY, endX, endY)
self.marquee.drawLines([
[(startX, 0, startY), (startX, 0, endY)],
@ -252,7 +254,7 @@ class DirectManipulationControl(DirectObject):
lens.extrude((endX, endY), nlr, flr)
lens.extrude((startX, endY), nll, fll)
marqueeFrustum = BoundingHexahedron(fll, flr, fur, ful, nll, nlr, nur, nul);
marqueeFrustum = BoundingHexahedron(fll, flr, fur, ful, nll, nlr, nur, nul)
marqueeFrustum.xform(base.direct.cam.getNetTransform().getMat())
base.marqueeFrustum = marqueeFrustum
@ -273,13 +275,13 @@ class DirectManipulationControl(DirectObject):
## elif (skipFlags & SKIP_BACKFACE) and base.direct.iRay.isEntryBackfacing():
## # Skip, if backfacing poly
## pass
elif ((skipFlags & SKIP_CAMERA) and
(camera in geom.getAncestors())):
elif (skipFlags & SKIP_CAMERA) and \
(base.camera in geom.getAncestors()):
# Skip if parented to a camera.
continue
# Can pick unpickable, use the first visible node
elif ((skipFlags & SKIP_UNPICKABLE) and
(geom.getName() in base.direct.iRay.unpickable)):
elif (skipFlags & SKIP_UNPICKABLE) and \
(geom.getName() in base.direct.iRay.unpickable):
# Skip if in unpickable list
continue
@ -486,7 +488,7 @@ class DirectManipulationControl(DirectObject):
for tag in self.unmovableTagList:
for selected in objects:
unmovableTag = selected.getTag(tag)
if (unmovableTag):
if unmovableTag:
# check value of unmovableTag to see if it is
# completely uneditable or if it allows only certain
# types of editing
@ -498,7 +500,7 @@ class DirectManipulationControl(DirectObject):
selectedList = base.direct.selected.getSelectedAsList()
# See if any of the selected are completely uneditable
editTypes = self.getEditTypes(selectedList)
if (editTypes & EDIT_TYPE_UNEDITABLE == EDIT_TYPE_UNEDITABLE):
if (editTypes & EDIT_TYPE_UNEDITABLE) == EDIT_TYPE_UNEDITABLE:
return
self.currEditTypes = editTypes
if selectedList:
@ -633,7 +635,7 @@ class DirectManipulationControl(DirectObject):
base.direct.widget.getMat(base.direct.selected.last))
else:
# Move the objects with the widget
base.direct.selected.moveWrtWidgetAll()
base.direct.selected.moveWrtWidgetAll()
# Continue
return Task.cont
@ -811,11 +813,11 @@ class DirectManipulationControl(DirectObject):
widgetAxis.normalize()
if type == 'top?':
# Check sign of angle between two vectors
return (widgetDir.dot(widgetAxis) < 0.)
return widgetDir.dot(widgetAxis) < 0.
elif type == 'edge?':
# Checking to see if we are viewing edge-on
# Check angle between two vectors
return(abs(widgetDir.dot(widgetAxis)) < .2)
return abs(widgetDir.dot(widgetAxis)) < .2
### FREE MANIPULATION METHODS ###
def xlateCamXZ(self, state):
@ -1043,7 +1045,7 @@ class DirectManipulationControl(DirectObject):
entry = base.direct.iRay.pickGeom(
skipFlags = SKIP_HIDDEN | SKIP_BACKFACE | SKIP_CAMERA)
# MRM: Need to handle moving COA
if (entry != None) and (base.direct.selected.last != None):
if entry is not None and base.direct.selected.last is not None:
# Record undo point
base.direct.pushUndo(base.direct.selected)
# Record wrt matrix
@ -1064,7 +1066,7 @@ class ObjectHandles(NodePath, DirectObject):
NodePath.__init__(self)
# Load up object handles model and assign it to self
self.assign(loader.loadModel('models/misc/objectHandles'))
self.assign(base.loader.loadModel('models/misc/objectHandles'))
self.setName(name)
self.scalingNode = self.getChild(0)
self.scalingNode.setName('ohScalingNode')
@ -1206,7 +1208,7 @@ class ObjectHandles(NodePath, DirectObject):
self.reparentTo(hidden)
def enableHandles(self, handles):
if type(handles) == list:
if isinstance(handles, list):
for handle in handles:
self.enableHandle(handle)
elif handles == 'x':
@ -1255,7 +1257,7 @@ class ObjectHandles(NodePath, DirectObject):
self.zScaleGroup.reparentTo(self.zHandles)
def disableHandles(self, handles):
if type(handles) == list:
if isinstance(handles, list):
for handle in handles:
self.disableHandle(handle)
elif handles == 'x':
@ -1640,7 +1642,7 @@ class ObjectHandles(NodePath, DirectObject):
# by comparing lineDir with plane normals. The plane with the
# largest dotProduct is most "normal"
if axis == 'x':
if (abs(lineDir.dot(Y_AXIS)) > abs(lineDir.dot(Z_AXIS))):
if abs(lineDir.dot(Y_AXIS)) > abs(lineDir.dot(Z_AXIS)):
self.hitPt.assign(
planeIntersect(lineOrigin, lineDir, ORIGIN, Y_AXIS))
else:
@ -1650,7 +1652,7 @@ class ObjectHandles(NodePath, DirectObject):
self.hitPt.setY(0)
self.hitPt.setZ(0)
elif axis == 'y':
if (abs(lineDir.dot(X_AXIS)) > abs(lineDir.dot(Z_AXIS))):
if abs(lineDir.dot(X_AXIS)) > abs(lineDir.dot(Z_AXIS)):
self.hitPt.assign(
planeIntersect(lineOrigin, lineDir, ORIGIN, X_AXIS))
else:
@ -1660,7 +1662,7 @@ class ObjectHandles(NodePath, DirectObject):
self.hitPt.setX(0)
self.hitPt.setZ(0)
elif axis == 'z':
if (abs(lineDir.dot(X_AXIS)) > abs(lineDir.dot(Y_AXIS))):
if abs(lineDir.dot(X_AXIS)) > abs(lineDir.dot(Y_AXIS)):
self.hitPt.assign(
planeIntersect(lineOrigin, lineDir, ORIGIN, X_AXIS))
else:
@ -1731,40 +1733,39 @@ class ObjectHandles(NodePath, DirectObject):
return self.hitPt
def drawBox(lines, center, sideLength):
l = sideLength * 0.5
lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
l = sideLength * 0.5
lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
lines.moveTo(center[0] - l, center[1] + l, center[2] + l)
lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
lines.moveTo(center[0] - l, center[1] + l, center[2] + l)
lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
lines.moveTo(center[0] + l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
lines.moveTo(center[0] + l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
lines.moveTo(center[0] + l, center[1] + l, center[2] + l)
lines.drawTo(center[0] - l, center[1] + l, center[2] + l)
lines.drawTo(center[0] - l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] - l, center[2] + l)
lines.drawTo(center[0] + l, center[1] + l, center[2] + l)
lines.moveTo(center[0] + l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
lines.drawTo(center[0] + l, center[1] + l, center[2] - l)
lines.moveTo(center[0] + l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] + l, center[2] - l)
lines.drawTo(center[0] - l, center[1] - l, center[2] - l)
lines.drawTo(center[0] + l, center[1] - l, center[2] - l)
lines.drawTo(center[0] + l, center[1] + l, center[2] - l)

View File

@ -1,4 +1,5 @@
from direct.showbase.DirectObject import DirectObject
from direct.showbase.MessengerGlobal import messenger
from .DirectGlobals import *
from .DirectUtil import *
from .DirectGeometry import *
@ -95,7 +96,7 @@ class SelectedNodePaths(DirectObject):
dnp = self.getDeselectedDict(id)
if dnp:
# Remove it from the deselected dictionary
del(self.deselectedDict[id])
del self.deselectedDict[id]
# Show its bounding box
dnp.highlight()
else:
@ -125,7 +126,7 @@ class SelectedNodePaths(DirectObject):
# Hide its bounding box
dnp.dehighlight()
# Remove it from the selected dictionary
del(self.selectedDict[id])
del self.selectedDict[id]
if dnp in self.selectedList: # [gjeon]
self.selectedList.remove(dnp)
# And keep track of it in the deselected dictionary
@ -308,7 +309,7 @@ class DirectBoundingBox:
# Create a line segments object for the bbox
lines = LineNodePath(hidden)
lines.node().setName('bboxLines')
if (bboxColor):
if bboxColor:
lines.setColor(VBase4(*bboxColor))
else:
lines.setColor(VBase4(1., 0., 0., 1.))
@ -352,7 +353,7 @@ class DirectBoundingBox:
return lines
def setBoxColorScale(self, r, g, b, a):
if (self.lines):
if self.lines:
self.lines.reset()
self.lines = None
self.lines = self.createBBoxLines((r, g, b, a))
@ -564,13 +565,13 @@ class SelectionQueue(CollisionHandlerQueue):
elif (skipFlags & SKIP_BACKFACE) and self.isEntryBackfacing(entry):
# Skip, if backfacing poly
pass
elif ((skipFlags & SKIP_CAMERA) and
(camera in nodePath.getAncestors())):
elif (skipFlags & SKIP_CAMERA) and \
(base.camera in nodePath.getAncestors()):
# Skip if parented to a camera.
pass
# Can pick unpickable, use the first visible node
elif ((skipFlags & SKIP_UNPICKABLE) and
(nodePath.getName() in self.unpickable)):
elif (skipFlags & SKIP_UNPICKABLE) and\
(nodePath.getName() in self.unpickable):
# Skip if in unpickable list
pass
elif base.direct and\
@ -793,4 +794,3 @@ class SelectionSphere(SelectionQueue):
targetNodePath = render
self.collideWithBitMask(bitMask)
return self.pick(targetNodePath, skipFlags)

View File

@ -4,6 +4,7 @@ from panda3d.core import *
from .DirectUtil import *
from direct.showbase.DirectObject import DirectObject
from direct.showbase.BulletinBoardGlobal import bulletinBoard as bboard
from direct.task import Task
from .DirectGlobals import DIRECT_NO_MOD
@ -291,9 +292,8 @@ class DirectSession(DirectObject):
self.passThroughKeys = ['v','b','l','p', 'r', 'shift-r', 's', 't','shift-a', 'w']
if base.wantTk:
from direct.showbase import TkGlobal
from direct.tkpanels import DirectSessionPanel
self.panel = DirectSessionPanel.DirectSessionPanel(parent = tkroot)
self.panel = DirectSessionPanel.DirectSessionPanel(parent = base.tkRoot)
try:
# Has the clusterMode been set externally (i.e. via the
# bootstrap application?
@ -385,14 +385,12 @@ class DirectSession(DirectObject):
def oobe(self):
# If oobeMode was never set, set it to false and create the
# structures we need to implement OOBE.
try:
self.oobeMode
except:
if not hasattr(self, 'oobeMode'):
self.oobeMode = 0
self.oobeCamera = hidden.attachNewNode('oobeCamera')
self.oobeVis = loader.loadModel('models/misc/camera')
self.oobeVis = base.loader.loadModel('models/misc/camera')
if self.oobeVis:
self.oobeVis.node().setFinal(1)
@ -710,7 +708,7 @@ class DirectSession(DirectObject):
else:
self.widget.showWidget()
editTypes = self.manipulationControl.getEditTypes([dnp])
if (editTypes & EDIT_TYPE_UNEDITABLE == EDIT_TYPE_UNEDITABLE):
if (editTypes & EDIT_TYPE_UNEDITABLE) == EDIT_TYPE_UNEDITABLE:
self.manipulationControl.disableWidgetMove()
else:
self.manipulationControl.enableWidgetMove()
@ -1071,8 +1069,10 @@ class DirectSession(DirectObject):
for iRay in self.iRayList:
iRay.removeUnpickable(item)
class DisplayRegionContext(DirectObject):
regionCount = 0
def __init__(self, cam):
self.cam = cam
self.camNode = self.cam.node()
@ -1093,10 +1093,7 @@ class DisplayRegionContext(DirectObject):
# one display region per camera, since we are defining a
# display region on a per-camera basis. See note in
# DisplayRegionList.__init__()
try:
self.dr = self.camNode.getDr(0)
except:
self.dr = self.camNode.getDisplayRegion(0)
self.dr = self.camNode.getDisplayRegion(0)
left = self.dr.getLeft()
right = self.dr.getRight()
bottom = self.dr.getBottom()

View File

@ -2,6 +2,7 @@
from .DirectGlobals import *
from panda3d.core import VBase4
from direct.task.Task import Task
from direct.task.TaskManagerGlobal import taskMgr
# Routines to adjust values
def ROUND_TO(value, divisor):
@ -84,4 +85,3 @@ def getFileData(filename, separator = ','):
data = [s.strip() for s in l.split(separator)]
fileData.append(data)
return fileData

View File

@ -2,8 +2,10 @@
from direct.distributed import DistributedObject
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.MessengerGlobal import messenger
from . import LargeBlobSenderConsts
class DistributedLargeBlobSender(DistributedObject.DistributedObject):
"""DistributedLargeBlobSender: for sending large chunks of data through
the DC system"""

View File

@ -50,7 +50,7 @@ class DistributedLargeBlobSenderAI(DistributedObjectAI.DistributedObjectAI):
'setFilename', [filename])
else:
chunkSize = LargeBlobSenderConsts.ChunkSize
while len(s):
while len(s) > 0:
self.sendUpdateToAvatarId(self.targetAvId,
'setChunk', [s[:chunkSize]])
s = s[chunkSize:]

View File

@ -1,4 +1,5 @@
from direct.showbase.DirectObject import DirectObject
from direct.showbase.MessengerGlobal import messenger
from direct.directtools.DirectGeometry import *
from panda3d.core import NodePath, LineSegs
@ -8,7 +9,7 @@ class Mopath(DirectObject):
nameIndex = 1
def __init__(self, name = None, fluid = 1, objectToLoad = None, upVectorNodePath = None, reverseUpVector = False):
if (name == None):
if name is None:
name = 'mopath%d' % self.nameIndex
self.nameIndex = self.nameIndex + 1
self.name = name
@ -35,24 +36,23 @@ class Mopath(DirectObject):
return self.maxT * self.timeScale
def loadFile(self, filename, fReset = 1):
nodePath = loader.loadModel(filename)
nodePath = base.loader.loadModel(filename)
if nodePath:
self.loadNodePath(nodePath)
nodePath.removeNode()
else:
print('Mopath: no data in file: %s' % filename)
def loadNodePath(self, nodePath, fReset = 1):
if fReset:
self.reset()
self.__extractCurves(nodePath)
if (self.tNurbsCurve != []):
if self.tNurbsCurve != []:
self.maxT = self.tNurbsCurve[-1].getMaxT()
elif (self.xyzNurbsCurve != None):
elif self.xyzNurbsCurve is not None:
self.maxT = self.xyzNurbsCurve.getMaxT()
elif (self.hprNurbsCurve != None):
elif self.hprNurbsCurve is not None:
self.maxT = self.hprNurbsCurve.getMaxT()
else:
print('Mopath: no valid curves in nodePath: %s' % nodePath)
@ -74,11 +74,11 @@ class Mopath(DirectObject):
elif node.getCurveType() == PCTHPR:
self.hprNurbsCurve = node
elif node.getCurveType() == PCTNONE:
if (self.xyzNurbsCurve == None):
if self.xyzNurbsCurve is None:
self.xyzNurbsCurve = node
else:
print('Mopath: got a PCT_NONE curve and an XYZ Curve in nodePath: %s' % nodePath)
elif (node.getCurveType() == PCTT):
elif node.getCurveType() == PCTT:
self.tNurbsCurve.append(node)
else:
# Iterate over children if any
@ -97,29 +97,29 @@ class Mopath(DirectObject):
def getFinalState(self):
pos = Point3(0)
if (self.xyzNurbsCurve != None):
if self.xyzNurbsCurve is not None:
self.xyzNurbsCurve.getPoint(self.maxT, pos)
hpr = Point3(0)
if (self.hprNurbsCurve != None):
if self.hprNurbsCurve is not None:
self.hprNurbsCurve.getPoint(self.maxT, hpr)
return (pos, hpr)
def goTo(self, node, time):
if (self.xyzNurbsCurve == None) and (self.hprNurbsCurve == None):
if self.xyzNurbsCurve is None and self.hprNurbsCurve is None:
print('Mopath: Mopath has no curves')
return
time /= self.timeScale
self.playbackTime = self.calcTime(CLAMP(time, 0.0, self.maxT))
if (self.xyzNurbsCurve != None):
if self.xyzNurbsCurve is not None:
self.xyzNurbsCurve.getPoint(self.playbackTime, self.posPoint)
if self.fluid:
node.setFluidPos(self.posPoint)
else:
node.setPos(self.posPoint)
if (self.hprNurbsCurve != None):
if self.hprNurbsCurve is not None:
self.hprNurbsCurve.getPoint(self.playbackTime, self.hprPoint)
node.setHpr(self.hprPoint)
elif (self.fFaceForward and (self.xyzNurbsCurve != None)):
elif self.fFaceForward and self.xyzNurbsCurve is not None:
if self.faceForwardDelta:
# Look at a point a bit ahead in parametric time.
t = min(self.playbackTime + self.faceForwardDelta, self.xyzNurbsCurve.getMaxT())
@ -133,18 +133,18 @@ class Mopath(DirectObject):
# use the self.upVectorNodePath position if it exists to
# create an up vector for lookAt
if (self.upVectorNodePath is None):
if self.upVectorNodePath is None:
node.lookAt(lookPoint)
else:
if (self.reverseUpVector == False):
node.lookAt(lookPoint,
self.upVectorNodePath.getPos() - self.posPoint)
if not self.reverseUpVector:
node.lookAt(lookPoint,
self.upVectorNodePath.getPos() - self.posPoint)
else:
node.lookAt(lookPoint,
self.posPoint - self.upVectorNodePath.getPos())
node.lookAt(lookPoint,
self.posPoint - self.upVectorNodePath.getPos())
def play(self, node, time = 0.0, loop = 0):
if (self.xyzNurbsCurve == None) and (self.hprNurbsCurve == None):
if self.xyzNurbsCurve is None and self.hprNurbsCurve is None:
print('Mopath: Mopath has no curves')
return
self.node = node
@ -161,11 +161,11 @@ class Mopath(DirectObject):
time = globalClock.getFrameTime()
dTime = time - task.lastTime
task.lastTime = time
if (self.loop):
if self.loop:
cTime = (task.currentTime + dTime) % self.getMaxT()
else:
cTime = task.currentTime + dTime
if ((self.loop == 0) and (cTime > self.getMaxT())):
if self.loop == 0 and cTime > self.getMaxT():
self.stop()
messenger.send(self.name + '-done')
self.node = None
@ -187,4 +187,3 @@ class Mopath(DirectObject):
ls.drawTo(p)
return NodePath(ls.create())

View File

@ -165,23 +165,23 @@ class CompilationEnvironment:
if self.platform.startswith('win'):
self.Python = sysconf.PREFIX
if ('VCINSTALLDIR' in os.environ):
if 'VCINSTALLDIR' in os.environ:
self.MSVC = os.environ['VCINSTALLDIR']
elif (Filename('/c/Program Files/Microsoft Visual Studio 9.0/VC').exists()):
elif Filename('/c/Program Files/Microsoft Visual Studio 9.0/VC').exists():
self.MSVC = Filename('/c/Program Files/Microsoft Visual Studio 9.0/VC').toOsSpecific()
elif (Filename('/c/Program Files (x86)/Microsoft Visual Studio 9.0/VC').exists()):
elif Filename('/c/Program Files (x86)/Microsoft Visual Studio 9.0/VC').exists():
self.MSVC = Filename('/c/Program Files (x86)/Microsoft Visual Studio 9.0/VC').toOsSpecific()
elif (Filename('/c/Program Files/Microsoft Visual Studio .NET 2003/Vc7').exists()):
elif Filename('/c/Program Files/Microsoft Visual Studio .NET 2003/Vc7').exists():
self.MSVC = Filename('/c/Program Files/Microsoft Visual Studio .NET 2003/Vc7').toOsSpecific()
else:
print('Could not locate Microsoft Visual C++ Compiler! Try running from the Visual Studio Command Prompt.')
sys.exit(1)
if ('WindowsSdkDir' in os.environ):
if 'WindowsSdkDir' in os.environ:
self.PSDK = os.environ['WindowsSdkDir']
elif (platform.architecture()[0] == '32bit' and Filename('/c/Program Files/Microsoft Platform SDK for Windows Server 2003 R2').exists()):
elif platform.architecture()[0] == '32bit' and Filename('/c/Program Files/Microsoft Platform SDK for Windows Server 2003 R2').exists():
self.PSDK = Filename('/c/Program Files/Microsoft Platform SDK for Windows Server 2003 R2').toOsSpecific()
elif (os.path.exists(os.path.join(self.MSVC, 'PlatformSDK'))):
elif os.path.exists(os.path.join(self.MSVC, 'PlatformSDK')):
self.PSDK = os.path.join(self.MSVC, 'PlatformSDK')
else:
print('Could not locate the Microsoft Windows Platform SDK! Try running from the Visual Studio Command Prompt.')
@ -199,7 +199,7 @@ class CompilationEnvironment:
self.suffix64 = '\\amd64'
# If it is run by makepanda, it handles the MSVC and PlatformSDK paths itself.
if ('MAKEPANDA' in os.environ):
if 'MAKEPANDA' in os.environ:
self.compileObjExe = 'cl /wd4996 /Fo%(basename)s.obj /nologo /c %(MD)s /Zi /O2 /Ob2 /EHsc /Zm300 /W3 /I"%(pythonIPath)s" %(filename)s'
self.compileObjDll = self.compileObjExe
self.linkExe = 'link /nologo /MAP:NUL /FIXED:NO /OPT:REF /STACK:4194304 /INCREMENTAL:NO /LIBPATH:"%(python)s\\libs" /out:%(basename)s.exe %(basename)s.obj'
@ -237,7 +237,7 @@ class CompilationEnvironment:
self.linkExe = "%(CC)s -o %(basename)s %(basename)s.o -L/usr/local/lib -lpython%(pythonVersion)s"
self.linkDll = "%(LDSHARED)s -o %(basename)s.so %(basename)s.o -L/usr/local/lib -lpython%(pythonVersion)s"
if (os.path.isdir("/usr/PCBSD/local/lib")):
if os.path.isdir("/usr/PCBSD/local/lib"):
self.linkExe += " -L/usr/PCBSD/local/lib"
self.linkDll += " -L/usr/PCBSD/local/lib"
@ -1009,8 +1009,8 @@ class Freezer:
if not newName:
newName = moduleName
assert(moduleName.endswith('.*'))
assert(newName.endswith('.*'))
assert moduleName.endswith('.*')
assert newName.endswith('.*')
mdefs = {}
@ -1020,7 +1020,7 @@ class Freezer:
parentNames = [(parentName, newParentName)]
if parentName.endswith('.*'):
assert(newParentName.endswith('.*'))
assert newParentName.endswith('.*')
# Another special case. The parent name "*" means to
# return all possible directories within a particular
# directory.
@ -1353,7 +1353,7 @@ class Freezer:
for moduleName, module in list(self.mf.modules.items()):
if module.__code__:
co = self.mf.replace_paths_in_code(module.__code__)
module.__code__ = co;
module.__code__ = co
def __addPyc(self, multifile, filename, code, compressionLevel):
if code:
@ -2226,7 +2226,7 @@ class Freezer:
strings = macho_data[stroff:stroff+strsize]
for i in range(nsyms):
for j in range(nsyms):
strx, type, sect, desc, value = struct.unpack_from(nlist_struct, macho_data, symoff)
symoff += nlist_size
name = strings[strx : strings.find(b'\0', strx)]
@ -2539,8 +2539,10 @@ class PandaModuleFinder(modulefinder.ModuleFinder):
if "*" in fromlist:
have_star = 1
fromlist = [f for f in fromlist if f != "*"]
if what == "absolute_import": level = 0
else: level = -1
if what == "absolute_import":
level = 0
else:
level = -1
self._safe_import_hook(name, m, fromlist, level=level)
if have_star:
# We've encountered an "import *". If it is a Python module,

View File

@ -16,7 +16,6 @@ import stat
import struct
import imp
import string
import time
import tempfile
import setuptools
@ -500,11 +499,7 @@ class build_apps(setuptools.Command):
icon.makeICNS(os.path.join(resdir, 'iconfile.icns'))
with open(os.path.join(contentsdir, 'Info.plist'), 'wb') as f:
if hasattr(plistlib, 'dump'):
plistlib.dump(plist, f)
else:
plistlib.writePlist(plist, f)
plistlib.dump(plist, f)
def build_runtimes(self, platform, use_wheels):
""" Builds the distributions for the given platform. """

View File

@ -150,7 +150,7 @@ class Icon:
# ICO files only support resolutions up to 256x256.
count = 0
for size in self.images.keys():
for size in self.images:
if size < 256:
count += 1
if size <= 256:

View File

@ -170,4 +170,3 @@ def create_nsis(command, basename, build_dir):
)
cmd.append(nsifile.to_os_specific())
subprocess.check_call(cmd)

View File

@ -487,6 +487,8 @@ class ResourceTable(object):
entry.data = data
entry.code_page = code_page
return entry
class PEFile(object):

View File

@ -105,7 +105,7 @@ def main(args=None):
elif opt == '-h':
usage(0)
else:
print('illegal option: ' + flag)
print('illegal option: ' + opt)
sys.exit(1)
if not basename:

View File

@ -1,6 +1,7 @@
#from otp.ai.AIBaseGlobal import *
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.DirectObject import DirectObject
from direct.showbase.MessengerGlobal import messenger
from .ConnectionRepository import *
from panda3d.core import ConfigVariableDouble, ConfigVariableInt, ConfigVariableBool
@ -254,7 +255,8 @@ class AsyncRequest(DirectObject):
print("\n\nself.avatarId =", self.avatarId)
print("\nself.neededObjects =", self.neededObjects)
print("\ntimed out after %s seconds.\n\n"%(task.delayTime,))
import pdb; pdb.set_trace()
import pdb
pdb.set_trace()
self.delete()
return Task.done

View File

@ -1,8 +1,11 @@
"""CRCache module: contains the CRCache class"""
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.MessengerGlobal import messenger
from direct.showbase.PythonUtil import safeRepr, itype
from . import DistributedObject
class CRCache:
notify = DirectNotifyGlobal.directNotify.newCategory("CRCache")
@ -41,7 +44,7 @@ class CRCache:
for distObj in delayDeleted:
if distObj.getDelayDeleteCount() != 0:
delayDeleteLeaks.append(distObj)
if len(delayDeleteLeaks):
if len(delayDeleteLeaks) > 0:
s = 'CRCache.flush:'
for obj in delayDeleteLeaks:
s += ('\n could not delete %s (%s), delayDeletes=%s' %
@ -76,7 +79,7 @@ class CRCache:
# if the cache is full, pop the oldest item
oldestDistObj = self.fifo.pop(0)
# and remove it from the dictionary
del(self.dict[oldestDistObj.getDoId()])
del self.dict[oldestDistObj.getDoId()]
# and delete it
oldestDistObj.deleteOrDelay()
if oldestDistObj.getDelayDeleteCount() <= 0:
@ -93,7 +96,7 @@ class CRCache:
# Find the object
distObj = self.dict[doId]
# Remove it from the dictionary
del(self.dict[doId])
del self.dict[doId]
# Remove it from the fifo
self.fifo.remove(distObj)
# return the distObj
@ -111,7 +114,7 @@ class CRCache:
# Look it up
distObj = self.dict[doId]
# Remove it from the dict and fifo
del(self.dict[doId])
del self.dict[doId]
self.fifo.remove(distObj)
# and delete it
distObj.deleteOrDelay()

View File

@ -114,4 +114,3 @@ if __debug__:
dc._stopMemLeakCheck()
dc.destroy()
del dc

View File

@ -29,8 +29,8 @@ class CartesianGridBase:
# Compute which zone we are in
zoneId = int(self.startingZone + ((row * self.gridSize) + col))
if (wantRowAndCol):
return (zoneId,col,row)
if wantRowAndCol:
return (zoneId, col, row)
else:
return zoneId
@ -113,9 +113,9 @@ class CartesianGridBase:
else:
# in a middle column, only look at top and bottom rows
possibleRows = []
if (topOffset == radius):
if topOffset == radius:
possibleRows.append(0)
if (bottomOffset == radius):
if bottomOffset == radius:
possibleRows.append(bottomOffset + topOffset)
#print "on column %s and looking at rows %s"%(currCol,possibleRows)
for currRow in possibleRows:

View File

@ -2,10 +2,11 @@
from .ClientRepositoryBase import ClientRepositoryBase
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.MessengerGlobal import messenger
from .MsgTypesCMU import *
from .PyDatagram import PyDatagram
from .PyDatagramIterator import PyDatagramIterator
from panda3d.core import UniqueIdAllocator
from panda3d.core import UniqueIdAllocator, Notify
class ClientRepository(ClientRepositoryBase):
@ -68,7 +69,7 @@ class ClientRepository(ClientRepositoryBase):
zone = di.getUint32()
for obj in self.doId2do.values():
if obj.zoneId == zone:
if (self.isLocalId(obj.doId)):
if self.isLocalId(obj.doId):
self.resendGenerate(obj)
def resendGenerate(self, obj):
@ -114,12 +115,12 @@ class ClientRepository(ClientRepositoryBase):
# repeat-generate, synthesized for the benefit of someone
# else who just entered the zone. Accept the new updates,
# but don't make a formal generate.
assert(self.notify.debug("performing generate-update for %s %s" % (dclass.getName(), doId)))
assert self.notify.debug("performing generate-update for %s %s" % (dclass.getName(), doId))
dclass.receiveUpdateBroadcastRequired(distObj, di)
dclass.receiveUpdateOther(distObj, di)
return
assert(self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId)))
assert self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId))
dclass.startGenerate()
# Create a new distributed object, and put it in the dictionary
distObj = self.generateWithRequiredOtherFields(dclass, doId, di, 0, zoneId)
@ -200,7 +201,7 @@ class ClientRepository(ClientRepositoryBase):
if not dclass:
self.notify.error("Unknown distributed class: %s" % (distObj.__class__))
classDef = dclass.getClassDef()
if classDef == None:
if classDef is None:
self.notify.error("Could not create an undefined %s object." % (
dclass.getName()))
@ -289,13 +290,13 @@ class ClientRepository(ClientRepositoryBase):
""" Returns true if this doId is one that we're the owner of,
false otherwise. """
return ((doId >= self.doIdBase) and (doId < self.doIdLast))
return doId >= self.doIdBase and doId < self.doIdLast
def haveCreateAuthority(self):
""" Returns true if this client has been assigned a range of
doId's it may use to create objects, false otherwise. """
return (self.doIdLast > self.doIdBase)
return self.doIdLast > self.doIdBase
def getAvatarIdFromSender(self):
""" Returns the doIdBase of the client that originally sent
@ -306,7 +307,7 @@ class ClientRepository(ClientRepositoryBase):
def handleDatagram(self, di):
if self.notify.getDebug():
print("ClientRepository received datagram:")
di.getDatagram().dumpHex(ostream)
di.getDatagram().dumpHex(Notify.out())
msgType = self.getMsgType()
self.currentSenderId = None

View File

@ -1,16 +1,18 @@
from panda3d.core import *
from panda3d.direct import *
from .MsgTypes import *
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
from direct.directnotify import DirectNotifyGlobal
from . import CRCache
from direct.distributed.CRDataCache import CRDataCache
from direct.distributed.ConnectionRepository import ConnectionRepository
from direct.showbase import PythonUtil
from direct.showbase.PythonUtil import safeRepr, itype, makeList
from direct.showbase.MessengerGlobal import messenger
from .MsgTypes import *
from . import CRCache
from . import ParentMgr
from . import RelatedObjectMgr
import time
from .ClockDelta import *
import time
class ClientRepositoryBase(ConnectionRepository):
@ -155,7 +157,7 @@ class ClientRepositoryBase(ConnectionRepository):
# Look up the dclass
assert parentId == self.GameGlobalsId or parentId in self.doId2do
dclass = self.dclassesByNumber[classId]
assert(self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId)))
assert self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId))
dclass.startGenerate()
# Create a new distributed object, and put it in the dictionary
distObj = self.generateWithRequiredOtherFields(dclass, doId, di, parentId, zoneId)
@ -189,7 +191,7 @@ class ClientRepositoryBase(ConnectionRepository):
for dg, di in updates:
# non-DC updates that need to be played back in-order are
# stored as (msgType, (dg, di))
if type(di) is tuple:
if isinstance(di, tuple):
msgType = dg
dg, di = di
self.replayDeferredGenerate(msgType, (dg, di))
@ -248,7 +250,7 @@ class ClientRepositoryBase(ConnectionRepository):
# ...it is not in the dictionary or the cache.
# Construct a new one
classDef = dclass.getClassDef()
if classDef == None:
if classDef is None:
self.notify.error("Could not create an undefined %s object." % (dclass.getName()))
distObj = classDef(self)
distObj.dclass = dclass
@ -296,7 +298,7 @@ class ClientRepositoryBase(ConnectionRepository):
# ...it is not in the dictionary or the cache.
# Construct a new one
classDef = dclass.getClassDef()
if classDef == None:
if classDef is None:
self.notify.error("Could not create an undefined %s object." % (dclass.getName()))
distObj = classDef(self)
distObj.dclass = dclass
@ -339,7 +341,7 @@ class ClientRepositoryBase(ConnectionRepository):
# ...it is not in the dictionary or the cache.
# Construct a new one
classDef = dclass.getOwnerClassDef()
if classDef == None:
if classDef is None:
self.notify.error("Could not create an undefined %s object. Have you created an owner view?" % (dclass.getName()))
distObj = classDef(self)
distObj.dclass = dclass
@ -452,7 +454,7 @@ class ClientRepositoryBase(ConnectionRepository):
# a dict and adding the avatar handles to that dict when they are created
# then change/remove the old method. I didn't do that because I couldn't think
# of a use for it. -JML
try :
try:
handle = self.identifyAvatar(doId)
if handle:
dclass = self.dclassesByName[handle.dclassName]
@ -477,7 +479,7 @@ class ClientRepositoryBase(ConnectionRepository):
def handleGoGetLost(self, di):
# The server told us it's about to drop the connection on us.
# Get ready!
if (di.getRemainingSize() > 0):
if di.getRemainingSize() > 0:
self.bootedIndex = di.getUint16()
self.bootedText = di.getString()

View File

@ -78,7 +78,7 @@ class ClockDelta(DirectObject.DirectObject):
# representing infinite uncertainty, if we have never received
# a time measurement.
if self.uncertainty == None:
if self.uncertainty is None:
return None
now = self.globalClock.getRealTime()
@ -190,7 +190,7 @@ class ClockDelta(DirectObject.DirectObject):
the new measurement was used, false if it was discarded.
"""
oldUncertainty = self.getUncertainty()
if oldUncertainty != None:
if oldUncertainty is not None:
self.notify.info(
'previous delta at %.3f s, +/- %.3f s.' %
(self.delta, oldUncertainty))
@ -241,7 +241,7 @@ class ClockDelta(DirectObject.DirectObject):
minutes of the current local time given in now, or
getRealTime() if now is not specified.
"""
if now == None:
if now is None:
now = self.globalClock.getRealTime()
# Are we in non-real-time mode (i.e. filming a movie)? If you

View File

@ -1,10 +1,12 @@
from panda3d.core import *
from panda3d.direct import *
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.distributed.DoInterestManager import DoInterestManager
from direct.distributed.DoCollectionManager import DoCollectionManager
from direct.showbase import GarbageReport
from direct.showbase.MessengerGlobal import messenger
from .PyDatagramIterator import PyDatagramIterator
import inspect
@ -175,7 +177,7 @@ class ConnectionRepository(
def applyFieldValues(distObj, dclass, values):
for i in range(dclass.getNumInheritedFields()):
field = dclass.getInheritedField(i)
if field.asMolecularField() == None:
if field.asMolecularField() is None:
value = values.get(field.getName(), None)
if value is None and field.isRequired():
# Gee, this could be better. What would really be
@ -214,7 +216,7 @@ class ConnectionRepository(
# Construct a new one
classDef = dclass.getClassDef()
if classDef == None:
if classDef is None:
self.notify.error("Could not create an undefined %s object."%(
dclass.getName()))
distObj = classDef(self)
@ -252,7 +254,7 @@ class ConnectionRepository(
dcFileNames = [dcFileNames]
dcImports = {}
if dcFileNames == None:
if dcFileNames is None:
readResult = dcFile.readAll()
if not readResult:
self.notify.error("Could not read dc file.")
@ -322,7 +324,7 @@ class ConnectionRepository(
classDef = dcImports.get(className)
# Also try it without the dcSuffix.
if classDef == None:
if classDef is None:
className = dclass.getName()
classDef = dcImports.get(className)
if classDef is None:
@ -379,7 +381,7 @@ class ConnectionRepository(
# in the DC file.
for i in range(dcFile.getNumClasses()):
dclass = dcFile.getClass(i)
if ((dclass.getName()+ownerDcSuffix) in ownerImportSymbols):
if (dclass.getName()+ownerDcSuffix) in ownerImportSymbols:
number = dclass.getNumber()
className = dclass.getName() + ownerDcSuffix
@ -583,7 +585,7 @@ class ConnectionRepository(
# available. Returns the HTTPClient (also self.http), or None
# if not set.
if self.http == None:
if self.http is None:
try:
self.http = HTTPClient()
except:
@ -662,7 +664,7 @@ class ConnectionRepository(
self.setSimulatedDisconnect(0)
def uniqueName(self, idString):
return ("%s-%s" % (idString, self.uniqueId))
return "%s-%s" % (idString, self.uniqueId)
class GCTrigger:
# used to trigger garbage collection

View File

@ -12,7 +12,7 @@ class Fixture(NodePath, FSM):
self.lens = PerspectiveLens()
self.lens.setFov(base.camLens.getFov())
model = loader.loadModel('models/misc/camera', okMissing = True)
model = base.loader.loadModel('models/misc/camera', okMissing = True)
model.reparentTo(self)
self.reparentTo(parent)
@ -129,8 +129,8 @@ class Fixture(NodePath, FSM):
def enterUsing(self, args = []):
localAvatar.b_setGameState('Camera')
camera.setPosHpr(0,0,0,0,0,0)
camera.reparentTo(self)
base.camera.setPosHpr(0,0,0,0,0,0)
base.camera.reparentTo(self)
self.hide()
base.cam.node().setLens(self.lens)

View File

@ -81,7 +81,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
def handleChildArrive(self, child, zoneId):
DistributedNode.handleChildArrive(self, child, zoneId)
if (zoneId >= self.startingZone):
if zoneId >= self.startingZone:
if not child.gridParent:
child.gridParent = GridParent(child)
child.gridParent.setGridParent(self, zoneId)
@ -91,7 +91,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
def handleChildArriveZone(self, child, zoneId):
DistributedNode.handleChildArrive(self, child, zoneId)
if (zoneId >= self.startingZone):
if zoneId >= self.startingZone:
if not child.gridParent:
child.gridParent = GridParent(child)
child.gridParent.setGridParent(self, zoneId)
@ -150,21 +150,21 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
# sometimes we also need to remove vis avatar from
# my parent if it is also a grid
if (clearAll):
if clearAll:
if event is not None:
parentEvent = eventGroup.newEvent('%s.parent.removeInterest' % self.doId)
else:
parentEvent = None
##HACK BANDAID FOR PVP INSTANCES
if(hasattr(self.cr.doId2do[self.parentId],"worldGrid")):
if hasattr(self.cr.doId2do[self.parentId], "worldGrid"):
self.cr.doId2do[self.parentId].worldGrid.stopProcessVisibility(event=parentEvent)
def processVisibility(self, task):
if self.visAvatar == None:
if self.visAvatar is None:
# no avatar to process visibility for
return Task.done
if(self.visAvatar.isDisabled()):
if self.visAvatar.isDisabled():
self.visAvatar = None
return Task.done
if self.visAvatar.gameFSM.state == 'Cutscene':
@ -192,7 +192,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
zoneId = int(self.startingZone + ((row * self.gridSize) + col))
assert self.notify.debug("processVisibility: %s: row: %s col: %s zoneId: %s" %
(self.doId, row, col, zoneId))
if (zoneId == self.visZone):
if zoneId == self.visZone:
assert self.notify.debug(
"processVisibility: %s: interest did not change" % (self.doId))
if self.visDirty:
@ -314,7 +314,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
# Load up grid parts to initialize grid object
# Polygon used to mark grid plane
# self.gridBack = loader.loadModel('models/misc/gridBack')
# self.gridBack = base.loader.loadModel('models/misc/gridBack')
# self.gridBack.reparentTo(self)
# self.gridBack.setColor(0.2, 0.2, 0.2, 0.5)
@ -397,7 +397,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
dx = self.cellWidth * self.gridSize * .5
for i in range(self.gridSize):
for j in range(self.gridSize):
marker = loader.loadModel("models/misc/smiley")
marker = base.loader.loadModel("models/misc/smiley")
marker.reparentTo(self.markerParent)
marker.setPos(i * self.cellWidth - dx,
j * self.cellWidth - dx,

View File

@ -3,6 +3,7 @@ from panda3d.core import *
from panda3d.direct import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
@ -56,7 +57,7 @@ class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
# Put the avatar on the grid
self.handleAvatarZoneChange(av, useZoneId)
if (not self.updateTaskStarted) and startAutoUpdate:
if startAutoUpdate and not self.updateTaskStarted:
self.startUpdateGridTask()
def removeObjectFromGrid(self, av):
@ -100,24 +101,24 @@ class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
for avId in list(self.gridObjects.keys()):
av = self.gridObjects[avId]
# handle a missing object after it is already gone?
if (av.isEmpty()):
if av.isEmpty():
task.setDelay(1.0)
del self.gridObjects[avId]
continue
pos = av.getPos()
if ((pos[0] < 0 or pos[1] < 0) or
(pos[0] > self.cellWidth or pos[1] > self.cellWidth)):
if (pos[0] < 0 or pos[1] < 0) or \
(pos[0] > self.cellWidth or pos[1] > self.cellWidth):
# we are out of the bounds of this current cell
self.handleAvatarZoneChange(av)
# Do this every second, not every frame
if (task):
if task:
task.setDelay(1.0)
return Task.again
def handleAvatarZoneChange(self, av, useZoneId=-1):
# Calculate zone id
# Get position of av relative to this grid
if (useZoneId == -1):
if useZoneId == -1:
pos = av.getPos(self)
zoneId = self.getZoneFromXYZ(pos)
else:
@ -137,9 +138,8 @@ class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
def handleSetLocation(self, av, parentId, zoneId):
pass
#if (av.parentId != parentId):
#if av.parentId != parentId:
# parent changed, need to look up instance tree
# to see if avatar's named area location information
# changed
#av.requestRegionUpdateTask(regionegionUid)

View File

@ -9,9 +9,7 @@ class DistributedNode(DistributedObject.DistributedObject, NodePath):
"""Distributed Node class:"""
def __init__(self, cr):
try:
self.DistributedNode_initialized
except:
if not hasattr(self, 'DistributedNode_initialized'):
self.DistributedNode_initialized = 1
self.gotStringParentToken = 0
DistributedObject.DistributedObject.__init__(self, cr)
@ -28,9 +26,7 @@ class DistributedNode(DistributedObject.DistributedObject, NodePath):
DistributedObject.DistributedObject.disable(self)
def delete(self):
try:
self.DistributedNode_deleted
except:
if not hasattr(self, 'DistributedNode_deleted'):
self.DistributedNode_deleted = 1
if not self.isEmpty():
self.removeNode()
@ -78,7 +74,7 @@ class DistributedNode(DistributedObject.DistributedObject, NodePath):
### setParent ###
def b_setParent(self, parentToken):
if type(parentToken) == str:
if isinstance(parentToken, str):
self.setParentStr(parentToken)
else:
self.setParent(parentToken)
@ -86,7 +82,7 @@ class DistributedNode(DistributedObject.DistributedObject, NodePath):
self.d_setParent(parentToken)
def d_setParent(self, parentToken):
if type(parentToken) == str:
if isinstance(parentToken, str):
self.sendUpdate("setParentStr", [parentToken])
else:
self.sendUpdate("setParent", [parentToken])

View File

@ -6,9 +6,7 @@ from . import GridParent
class DistributedNodeAI(DistributedObjectAI.DistributedObjectAI, NodePath):
def __init__(self, air, name=None):
# Be careful not to create multiple NodePath objects
try:
self.DistributedNodeAI_initialized
except:
if not hasattr(self, 'DistributedNodeAI_initialized'):
self.DistributedNodeAI_initialized = 1
DistributedObjectAI.DistributedObjectAI.__init__(self, air)
if name is None:
@ -47,14 +45,14 @@ class DistributedNodeAI(DistributedObjectAI.DistributedObjectAI, NodePath):
### setParent ###
def b_setParent(self, parentToken):
if type(parentToken) == str:
if isinstance(parentToken, str):
self.setParentStr(parentToken)
else:
self.setParent(parentToken)
self.d_setParent(parentToken)
def d_setParent(self, parentToken):
if type(parentToken) == type(''):
if isinstance(parentToken, str):
self.sendUpdate("setParentStr", [parentToken])
else:
self.sendUpdate("setParent", [parentToken])

View File

@ -3,23 +3,21 @@ from .DistributedObjectUD import DistributedObjectUD
class DistributedNodeUD(DistributedObjectUD):
def __init__(self, air, name=None):
# Be careful not to create multiple NodePath objects
try:
self.DistributedNodeUD_initialized
except:
if not hasattr(self, 'DistributedNodeUD_initialized'):
self.DistributedNodeUD_initialized = 1
DistributedObjectUD.__init__(self, air)
if name is None:
name = self.__class__.__name__
def b_setParent(self, parentToken):
if type(parentToken) == str:
if isinstance(parentToken, str):
self.setParentStr(parentToken)
else:
self.setParent(parentToken)
self.d_setParent(parentToken)
def d_setParent(self, parentToken):
if type(parentToken) == type(''):
if isinstance(parentToken, str):
self.sendUpdate("setParentStr", [parentToken])
else:
self.sendUpdate("setParent", [parentToken])

View File

@ -2,6 +2,7 @@
from panda3d.core import *
from panda3d.direct import *
from direct.showbase.MessengerGlobal import messenger
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.distributed.DistributedObjectBase import DistributedObjectBase
#from PyDatagram import PyDatagram
@ -43,9 +44,7 @@ class DistributedObject(DistributedObjectBase):
def __init__(self, cr):
assert self.notify.debugStateCall(self)
try:
self.DistributedObject_initialized
except:
if not hasattr(self, 'DistributedObject_initialized'):
self.DistributedObject_initialized = 1
DistributedObjectBase.__init__(self, cr)
@ -96,7 +95,7 @@ class DistributedObject(DistributedObjectBase):
flags.append("cacheable")
flagStr = ""
if len(flags):
if len(flags) > 0:
flagStr = " (%s)" % (" ".join(flags))
print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
@ -156,25 +155,25 @@ class DistributedObject(DistributedObjectBase):
self._cachedData = self.cr.doDataCache.popCachedData(self.doId)
def setCachedData(self, name, data):
assert type(name) == type('')
assert isinstance(name, str)
# ownership of the data passes to the repository data cache
self.cr.doDataCache.setCachedData(self.doId, name, data)
def hasCachedData(self, name):
assert type(name) == type('')
assert isinstance(name, str)
if not hasattr(self, '_cachedData'):
return False
return name in self._cachedData
def getCachedData(self, name):
assert type(name) == type('')
assert isinstance(name, str)
# ownership of the data passes to the caller of this method
data = self._cachedData[name]
del self._cachedData[name]
return data
def flushCachedData(self, name):
assert type(name) == type('')
assert isinstance(name, str)
# call this to throw out cached data from a previous instantiation
self._cachedData[name].flush()
@ -278,14 +277,13 @@ class DistributedObject(DistributedObjectBase):
Inheritors should redefine this to take appropriate action on disable
"""
assert self.notify.debug('disable(): %s' % (self.doId))
pass
def isDisabled(self):
"""
Returns true if the object has been disabled and/or deleted,
or if it is brand new and hasn't yet been generated.
"""
return (self.activeState < ESGenerating)
return self.activeState < ESGenerating
def isGenerated(self):
"""
@ -293,17 +291,14 @@ class DistributedObject(DistributedObjectBase):
and not yet disabled.
"""
assert self.notify.debugStateCall(self)
return (self.activeState == ESGenerated)
return self.activeState == ESGenerated
def delete(self):
"""
Inheritors should redefine this to take appropriate action on delete
"""
assert self.notify.debug('delete(): %s' % (self.doId))
try:
self.DistributedObject_deleted
except:
self.DistributedObject_deleted = 1
self.DistributedObject_deleted = 1
def generate(self):
"""
@ -374,10 +369,10 @@ class DistributedObject(DistributedObjectBase):
self.cr.sendDeleteMsg(self.doId)
def taskName(self, taskString):
return ("%s-%s" % (taskString, self.doId))
return "%s-%s" % (taskString, self.doId)
def uniqueName(self, idString):
return ("%s-%s" % (idString, self.doId))
return "%s-%s" % (idString, self.doId)
def getCallbackContext(self, callback, extraArgs = []):
# Some objects implement a back-and-forth handshake operation
@ -429,7 +424,7 @@ class DistributedObject(DistributedObjectBase):
if tuple:
callback, extraArgs = tuple
completeArgs = args + extraArgs
if callback != None:
if callback is not None:
callback(*completeArgs)
del self.__callbacks[context]
else:
@ -470,9 +465,9 @@ class DistributedObject(DistributedObjectBase):
# doneBarrier() twice, or we have not received a barrier
# context from the AI. I think in either case it's ok to
# silently ignore the error.
if self.__barrierContext != None:
if self.__barrierContext is not None:
context, aiName = self.__barrierContext
if name == None or name == aiName:
if name is None or name == aiName:
assert self.notify.debug('doneBarrier(%s, %s)' % (context, aiName))
self.sendUpdate("setBarrierReady", [context])
self.__barrierContext = None

View File

@ -2,6 +2,7 @@
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.distributed.DistributedObjectBase import DistributedObjectBase
from direct.showbase.MessengerGlobal import messenger
from direct.showbase import PythonUtil
from panda3d.core import *
from panda3d.direct import *
@ -13,9 +14,7 @@ class DistributedObjectAI(DistributedObjectBase):
QuietZone = 1
def __init__(self, air):
try:
self.DistributedObjectAI_initialized
except:
if not hasattr(self, 'DistributedObjectAI_initialized'):
self.DistributedObjectAI_initialized = 1
DistributedObjectBase.__init__(self, air)
@ -66,11 +65,11 @@ class DistributedObjectAI(DistributedObjectBase):
flags = []
if self.__generated:
flags.append("generated")
if self.air == None:
if self.air is None:
flags.append("deleted")
flagStr = ""
if len(flags):
if len(flags) > 0:
flagStr = " (%s)" % (" ".join(flags))
print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
@ -119,24 +118,23 @@ class DistributedObjectAI(DistributedObjectBase):
# self.doId may not exist. The __dict__ syntax works around that.
assert self.notify.debug('delete(): %s' % (self.__dict__.get("doId")))
if not self._DOAI_requestedDelete:
# this logs every delete that was not requested by us.
# TODO: this currently prints warnings for deletes of objects
# that we did not create. We need to add a 'locally created'
# flag to every object to filter these out.
"""
DistributedObjectAI.notify.warning(
'delete() called but requestDelete never called for %s: %s'
% (self.__dict__.get('doId'), self.__class__.__name__))
"""
"""
# print a stack trace so we can detect whether this is the
# result of a network msg.
# this is slow.
from direct.showbase.PythonUtil import StackTrace
DistributedObjectAI.notify.warning(
'stack trace: %s' % StackTrace())
"""
#if not self._DOAI_requestedDelete:
# # this logs every delete that was not requested by us.
# # TODO: this currently prints warnings for deletes of objects
# # that we did not create. We need to add a 'locally created'
# # flag to every object to filter these out.
#
# DistributedObjectAI.notify.warning(
# 'delete() called but requestDelete never called for %s: %s'
# % (self.__dict__.get('doId'), self.__class__.__name__))
#
# # print a stack trace so we can detect whether this is the
# # result of a network msg.
# # this is slow.
# from direct.showbase.PythonUtil import StackTrace
# DistributedObjectAI.notify.warning(
# 'stack trace: %s' % StackTrace())
self._DOAI_requestedDelete = False
self.releaseZoneData()
@ -167,7 +165,7 @@ class DistributedObjectAI(DistributedObjectBase):
Returns true if the object has been deleted,
or if it is brand new and hasnt yet been generated.
"""
return self.air == None
return self.air is None
def isGenerated(self):
"""
@ -195,7 +193,6 @@ class DistributedObjectAI(DistributedObjectBase):
Called after the object has been generated and all
of its required fields filled in. Overwrite when needed.
"""
pass
def b_setLocation(self, parentId, zoneId):
self.d_setLocation(parentId, zoneId)
@ -206,14 +203,13 @@ class DistributedObjectAI(DistributedObjectBase):
def setLocation(self, parentId, zoneId):
# Prevent Duplicate SetLocations for being Called
if (self.parentId == parentId) and (self.zoneId == zoneId):
if self.parentId == parentId and self.zoneId == zoneId:
return
oldParentId = self.parentId
oldZoneId = self.zoneId
self.air.storeObjectLocation(self, parentId, zoneId)
if ((oldParentId != parentId) or
(oldZoneId != zoneId)):
if oldParentId != parentId or oldZoneId != zoneId:
self.releaseZoneData()
messenger.send(self.getZoneChangeEvent(), [zoneId, oldZoneId])
# if we are not going into the quiet zone, send a 'logical' zone
@ -476,10 +472,10 @@ class DistributedObjectAI(DistributedObjectBase):
self._DOAI_requestedDelete = True
def taskName(self, taskString):
return ("%s-%s" % (taskString, self.doId))
return "%s-%s" % (taskString, self.doId)
def uniqueName(self, idString):
return ("%s-%s" % (idString, self.doId))
return "%s-%s" % (idString, self.doId)
def validate(self, avId, bool, msg):
if not bool:
@ -542,7 +538,7 @@ class DistributedObjectAI(DistributedObjectBase):
avId = self.air.getAvatarIdFromSender()
assert self.notify.debug('setBarrierReady(%s, %s)' % (context, avId))
barrier = self.__barriers.get(context)
if barrier == None:
if barrier is None:
# This may be None if a client was slow and missed an
# earlier timeout. Too bad.
return
@ -569,7 +565,6 @@ class DistributedObjectAI(DistributedObjectBase):
def _retrieveCachedData(self):
""" This is a no-op on the AI. """
pass
def setAI(self, aiChannel):
self.air.setAI(self.doId, aiChannel)

View File

@ -49,7 +49,6 @@ class DistributedObjectBase(DirectObject):
"""
assert self.notify.debugCall()
# Inheritors should override
pass
def handleChildArriveZone(self, childObj, zoneId):
"""
@ -60,7 +59,6 @@ class DistributedObjectBase(DirectObject):
"""
assert self.notify.debugCall()
# Inheritors should override
pass
def handleChildLeave(self, childObj, zoneId):
"""
@ -69,7 +67,6 @@ class DistributedObjectBase(DirectObject):
"""
assert self.notify.debugCall()
# Inheritors should override
pass
def handleChildLeaveZone(self, childObj, zoneId):
"""
@ -79,12 +76,10 @@ class DistributedObjectBase(DirectObject):
"""
assert self.notify.debugCall()
# Inheritors should override
pass
def handleQueryObjectChildrenLocalDone(self, context):
assert self.notify.debugCall()
# Inheritors should override
pass
def getParentObj(self):
if self.parentId is None:
@ -92,12 +87,10 @@ class DistributedObjectBase(DirectObject):
return self.cr.doId2do.get(self.parentId)
def hasParentingRules(self):
return self.dclass.getFieldByName('setParentingRules') != None
return self.dclass.getFieldByName('setParentingRules') is not None
def delete(self):
"""
Override this to handle cleanup right before this object
gets deleted.
"""
pass

View File

@ -21,4 +21,3 @@ class DistributedObjectGlobal(DistributedObject):
DistributedObject.__init__(self, cr)
self.parentId = 0
self.zoneId = 0

View File

@ -18,15 +18,14 @@ class DistributedObjectGlobalAI(DistributedObjectAI):
if not self.doNotListenToChannel:
self.air.registerForChannel(self.doId)
except AttributeError:
self.air.registerForChannel(self.doId)
self.air.registerForChannel(self.doId)
return False
def delete(self):
DistributedObjectAI.delete(self)
try:
DistributedObjectAI.delete(self)
try:
if not self.doNotListenToChannel:
self.air.unregisterForChannel(self.doId)
except AttributeError:
self.air.unregisterForChannel(self.doId)
self.air.unregisterForChannel(self.doId)
except AttributeError:
self.air.unregisterForChannel(self.doId)
## self.air.removeDOFromTables(self)

View File

@ -1,5 +1,4 @@
from panda3d.core import ConfigVariableInt
from .DistributedObjectUD import DistributedObjectUD
from direct.directnotify.DirectNotifyGlobal import directNotify
@ -25,7 +24,8 @@ class DistributedObjectGlobalUD(DistributedObjectUD):
DistributedObjectUD.delete(self)
def execCommand(self, command, mwMgrId, avId, zoneId):
text = str(self.__execMessage(command))[:config.GetInt("ai-debug-length",300)]
length = ConfigVariableInt("ai-debug-length", 300)
text = str(self.__execMessage(command))[:length.value]
self.notify.info(text)
def __execMessage(self, message):

View File

@ -1,6 +1,7 @@
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.distributed.DistributedObjectBase import DistributedObjectBase
from direct.showbase.MessengerGlobal import messenger
#from PyDatagram import PyDatagram
#from PyDatagramIterator import PyDatagramIterator
@ -23,9 +24,7 @@ class DistributedObjectOV(DistributedObjectBase):
def __init__(self, cr):
assert self.notify.debugStateCall(self)
try:
self.DistributedObjectOV_initialized
except:
if not hasattr(self, 'DistributedObjectOV_initialized'):
self.DistributedObjectOV_initialized = 1
DistributedObjectBase.__init__(self, cr)
@ -51,7 +50,7 @@ class DistributedObjectOV(DistributedObjectBase):
flags.append("disabled")
flagStr = ""
if len(flags):
if len(flags) > 0:
flagStr = " (%s)" % (" ".join(flags))
print("%sfrom DistributedObjectOV doId:%s, parent:%s, zone:%s%s" % (
@ -103,7 +102,7 @@ class DistributedObjectOV(DistributedObjectBase):
Returns true if the object has been disabled and/or deleted,
or if it is brand new and hasn't yet been generated.
"""
return (self.activeState < ESGenerating)
return self.activeState < ESGenerating
def isGenerated(self):
"""
@ -111,16 +110,14 @@ class DistributedObjectOV(DistributedObjectBase):
and not yet disabled.
"""
assert self.notify.debugStateCall(self)
return (self.activeState == ESGenerated)
return self.activeState == ESGenerated
def delete(self):
"""
Inheritors should redefine this to take appropriate action on delete
"""
assert self.notify.debug('delete(): %s' % (self.doId))
try:
self.DistributedObjectOV_deleted
except:
if not hasattr(self, 'DistributedObjectOV_deleted'):
self.DistributedObjectOV_deleted = 1
self.cr = None
self.dclass = None
@ -186,7 +183,7 @@ class DistributedObjectOV(DistributedObjectBase):
self.notify.warning("sendUpdate failed, because self.cr is not set")
def taskName(self, taskString):
return ('%s-%s-OV' % (taskString, self.getDoId()))
return '%s-%s-OV' % (taskString, self.getDoId())
def uniqueName(self, idString):
return ('%s-%s-OV' % (idString, self.getDoId()))
return '%s-%s-OV' % (idString, self.getDoId())

View File

@ -2,6 +2,7 @@
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.distributed.DistributedObjectBase import DistributedObjectBase
from direct.showbase.MessengerGlobal import messenger
from direct.showbase import PythonUtil
from panda3d.core import *
from panda3d.direct import *
@ -13,9 +14,7 @@ class DistributedObjectUD(DistributedObjectBase):
QuietZone = 1
def __init__(self, air):
try:
self.DistributedObjectUD_initialized
except:
if not hasattr(self, 'DistributedObjectUD_initialized'):
self.DistributedObjectUD_initialized = 1
DistributedObjectBase.__init__(self, air)
@ -64,11 +63,11 @@ class DistributedObjectUD(DistributedObjectBase):
flags = []
if self.__generated:
flags.append("generated")
if self.air == None:
if self.air is None:
flags.append("deleted")
flagStr = ""
if len(flags):
if len(flags) > 0:
flagStr = " (%s)" % (" ".join(flags))
print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
@ -103,24 +102,23 @@ class DistributedObjectUD(DistributedObjectBase):
# self.doId may not exist. The __dict__ syntax works around that.
assert self.notify.debug('delete(): %s' % (self.__dict__.get("doId")))
if not self._DOUD_requestedDelete:
# this logs every delete that was not requested by us.
# TODO: this currently prints warnings for deletes of objects
# that we did not create. We need to add a 'locally created'
# flag to every object to filter these out.
"""
DistributedObjectUD.notify.warning(
'delete() called but requestDelete never called for %s: %s'
% (self.__dict__.get('doId'), self.__class__.__name__))
"""
"""
# print a stack trace so we can detect whether this is the
# result of a network msg.
# this is slow.
from direct.showbase.PythonUtil import StackTrace
DistributedObjectUD.notify.warning(
'stack trace: %s' % StackTrace())
"""
#if not self._DOUD_requestedDelete:
# # this logs every delete that was not requested by us.
# # TODO: this currently prints warnings for deletes of objects
# # that we did not create. We need to add a 'locally created'
# # flag to every object to filter these out.
#
# DistributedObjectUD.notify.warning(
# 'delete() called but requestDelete never called for %s: %s'
# % (self.__dict__.get('doId'), self.__class__.__name__))
#
# # print a stack trace so we can detect whether this is the
# # result of a network msg.
# # this is slow.
# from direct.showbase.PythonUtil import StackTrace
# DistributedObjectUD.notify.warning(
# 'stack trace: %s' % StackTrace())
self._DOUD_requestedDelete = False
# Clean up all the pending barriers.
@ -143,7 +141,7 @@ class DistributedObjectUD(DistributedObjectBase):
Returns true if the object has been deleted,
or if it is brand new and hasnt yet been generated.
"""
return self.air == None
return self.air is None
def isGenerated(self):
"""
@ -409,10 +407,10 @@ class DistributedObjectUD(DistributedObjectBase):
self._DOUD_requestedDelete = True
def taskName(self, taskString):
return ("%s-%s" % (taskString, self.doId))
return "%s-%s" % (taskString, self.doId)
def uniqueName(self, idString):
return ("%s-%s" % (idString, self.doId))
return "%s-%s" % (idString, self.doId)
def validate(self, avId, bool, msg):
if not bool:
@ -475,7 +473,7 @@ class DistributedObjectUD(DistributedObjectBase):
avId = self.air.getAvatarIdFromSender()
assert self.notify.debug('setBarrierReady(%s, %s)' % (context, avId))
barrier = self.__barriers.get(context)
if barrier == None:
if barrier is None:
# This may be None if a client was slow and missed an
# earlier timeout. Too bad.
return

View File

@ -6,7 +6,9 @@ from .ClockDelta import *
from . import DistributedNode
from . import DistributedSmoothNodeBase
from direct.task.Task import cont
from direct.task.TaskManagerGlobal import taskMgr
from direct.showbase import DConfig as config
from direct.showbase.PythonUtil import report
# This number defines our tolerance for out-of-sync telemetry packets.
# If a packet appears to have originated from more than MaxFuture
@ -62,9 +64,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
"""
def __init__(self, cr):
try:
self.DistributedSmoothNode_initialized
except:
if not hasattr(self, 'DistributedSmoothNode_initialized'):
self.DistributedSmoothNode_initialized = 1
DistributedNode.DistributedNode.__init__(self, cr)
DistributedSmoothNodeBase.DistributedSmoothNodeBase.__init__(self)
@ -181,22 +181,22 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
self.smoother.setPhonyTimestamp()
self.smoother.markPosition()
def _checkResume(self,timestamp):
def _checkResume(self, timestamp):
"""
Determine if we were previously stopped and now need to
resume movement by making sure any old stored positions
reflect the node's current position
"""
if (self.stopped):
if self.stopped:
currTime = globalClock.getFrameTime()
now = currTime - self.smoother.getExpectedBroadcastPeriod()
last = self.smoother.getMostRecentTimestamp()
if (now > last):
if now > last:
# only set a new timestamp postion if we still have
# a position being smoothed to (so we don't interrupt
# any current smoothing and only do this if the object
# is actually locally stopped)
if (timestamp == None):
if timestamp is None:
# no timestamp, use current time
local = 0.0
else:
@ -302,7 +302,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
self.smoother.setR(r)
@report(types = ['args'], dConfigParam = 'smoothnode')
def setComponentL(self, l):
if (l != self.zoneId):
if l != self.zoneId:
# only perform set location if location is different
self.setLocation(self.parentId,l)
@report(types = ['args'], dConfigParam = 'smoothnode')
@ -360,7 +360,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
howFarFuture = local - now
if howFarFuture - chug >= MaxFuture:
# Too far off; advise the other client of our clock information.
if globalClockDelta.getUncertainty() != None and \
if globalClockDelta.getUncertainty() is not None and \
realTime - self.lastSuggestResync >= MinSuggestResync and \
hasattr(self.cr, 'localAvatarDoId'):
self.lastSuggestResync = realTime
@ -457,9 +457,9 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
result = self.peerToPeerResync(
avId, timestampA, serverTime, uncertainty)
if result >= 0 and \
globalClockDelta.getUncertainty() != None:
globalClockDelta.getUncertainty() is not None:
other = self.cr.doId2do.get(avId)
if (not other):
if not other:
assert self.notify.info(
"Warning: couldn't find the avatar %d" % (avId))
elif hasattr(other, "d_returnResync") and \
@ -498,7 +498,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
# If we didn't get anything useful from the other client,
# maybe our clock is just completely hosed. Go ask the AI.
if not gotSync:
if self.cr.timeManager != None:
if self.cr.timeManager is not None:
self.cr.timeManager.synchronize("suggested by %d" % (avId))
return gotSync

View File

@ -98,11 +98,10 @@ class DistributedSmoothNodeAI(DistributedNodeAI.DistributedNodeAI,
def getComponentR(self):
return self.getR()
def getComponentL(self):
if (self.zoneId):
if self.zoneId:
return self.zoneId
else:
# we can't send None over the wire which self.zoneId can sometimes be
return 0
def getComponentT(self):
return 0

View File

@ -2,6 +2,7 @@
from .ClockDelta import *
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
from direct.showbase.PythonUtil import randFloat, Enum
from panda3d.direct import CDistributedSmoothNodeBase
@ -58,13 +59,13 @@ class DistributedSmoothNodeBase:
self.d_broadcastPosHpr = None
def posHprBroadcastStarted(self):
return self.d_broadcastPosHpr != None
return self.d_broadcastPosHpr is not None
def wantSmoothPosBroadcastTask(self):
return True
def startPosHprBroadcast(self, period=.2, stagger=0, type=None):
if self.cnode == None:
if self.cnode is None:
self.initializeCnode()
BT = DistributedSmoothNodeBase.BroadcastTypes
@ -117,4 +118,3 @@ class DistributedSmoothNodeBase:
if self.d_broadcastPosHpr is None:
self.cnode.initialize(self, self.dclass, self.doId)
self.cnode.sendEverything()

View File

@ -113,7 +113,7 @@ class DoCollectionManager:
return 1
if dist2 is None:
return -1
if (dist1 < dist2):
if dist1 < dist2:
return -1
return 1
@ -270,7 +270,7 @@ class DoCollectionManager:
def deleteDistributedObjects(self):
# Get rid of all the distributed objects
for doId, do in list(self.doId2do.items()):
for do in list(self.doId2do.values()):
self.deleteDistObject(do)
# Get rid of everything that manages distributed objects
@ -314,14 +314,14 @@ class DoCollectionManager:
def storeObjectLocation(self, object, parentId, zoneId):
oldParentId = object.parentId
oldZoneId = object.zoneId
if (oldParentId != parentId):
if oldParentId != parentId:
# notify any existing parent that we're moving away
oldParentObj = self.doId2do.get(oldParentId)
if oldParentObj is not None:
oldParentObj.handleChildLeave(object, oldZoneId)
self.deleteObjectLocation(object, oldParentId, oldZoneId)
elif (oldZoneId != zoneId):
elif oldZoneId != zoneId:
# Remove old location
oldParentObj = self.doId2do.get(oldParentId)
if oldParentObj is not None:
@ -331,8 +331,7 @@ class DoCollectionManager:
# object is already at that parent and zone
return
if ((parentId is None) or (zoneId is None) or
(parentId == zoneId == 0)):
if parentId is None or zoneId is None or (parentId == zoneId == 0):
# Do not store null values
object.parentId = None
object.zoneId = None
@ -418,10 +417,10 @@ class DoCollectionManager:
#assert do.doId in self.doId2do
location = do.getLocation()
if location:
oldParentId, oldZoneId = location
oldParentObj = self.doId2do.get(oldParentId)
if oldParentObj:
oldParentObj.handleChildLeave(do, oldZoneId)
oldParentId, oldZoneId = location
oldParentObj = self.doId2do.get(oldParentId)
if oldParentObj:
oldParentObj.handleChildLeave(do, oldZoneId)
self.deleteObjectLocation(do, do.parentId, do.zoneId)
## location = do.getLocation()
## if location is not None:

View File

@ -13,7 +13,7 @@ class DoHierarchy:
self._allDoIds = set()
def isEmpty(self):
assert ((len(self._table) == 0) == (len(self._allDoIds) == 0))
assert (len(self._table) == 0) == (len(self._allDoIds) == 0)
return len(self._table) == 0 and len(self._allDoIds) == 0
def __len__(self):
@ -77,7 +77,7 @@ class DoHierarchy:
'deleteObjectLocation(%s %s) not in _allDoIds; duplicate delete()? or invalid previous location on a new object?' % (
do.__class__.__name__, do.doId))
# jbutler: temp hack to get by the assert, this will be fixed soon
if (doId not in self._allDoIds):
if doId not in self._allDoIds:
return
parentZoneDict = self._table.get(parentId)
if parentZoneDict is not None:

View File

@ -12,6 +12,7 @@ from panda3d.direct import *
from .MsgTypes import *
from direct.showbase.PythonUtil import *
from direct.showbase import DirectObject
from direct.showbase.MessengerGlobal import messenger
from .PyDatagram import PyDatagram
from direct.directnotify.DirectNotifyGlobal import directNotify
import types
@ -375,7 +376,7 @@ class DoInterestManager(DirectObject.DirectObject):
return
autoInterests = obj.getAutoInterests()
obj._autoInterestHandle = None
if not len(autoInterests):
if len(autoInterests) == 0:
return
obj._autoInterestHandle = self.addAutoInterest(obj.doId, autoInterests, '%s-autoInterest' % obj.__class__.__name__)
def closeAutoInterests(self, obj):
@ -658,7 +659,8 @@ if __debug__:
if failed:
self.stream.write("failures=%d" % failed)
if errored:
if failed: self.stream.write(", ")
if failed:
self.stream.write(", ")
self.stream.write("errors=%d" % errored)
self.stream.writeln(")")
else:

View File

@ -1,5 +1,7 @@
from direct.distributed.DistributedSmoothNodeBase import DistributedSmoothNodeBase
from direct.distributed.GridParent import GridParent
from direct.showbase.PythonUtil import report
class GridChild:
"""
@ -56,7 +58,6 @@ class GridChild:
for currGridId, interestInfo in self._gridInterests.items():
self.cr.removeTaggedInterest(interestInfo[0])
#self.__clearGridInterest()
pass
def isOnAGrid(self):
return self._gridParent is not None

View File

@ -96,7 +96,5 @@ class GridParent:
else:
self.av.reparentTo(self.cellOrigin)
#print "gridParent: reparent to %s" % self.av
#print "gridParent: pos = %s, %s" % (self.av.getPos(), self.av.getParent().getPos())
#print("gridParent: reparent to %s" % self.av)
#print("gridParent: pos = %s, %s" % (self.av.getPos(), self.av.getParent().getPos()))

View File

@ -1,6 +1,8 @@
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.DirectObject import DirectObject
from direct.showbase.EventGroup import EventGroup
from direct.showbase.MessengerGlobal import messenger
class InterestWatcher(DirectObject):
"""Object that observes all interests adds/removes over a period of time,
@ -66,11 +68,9 @@ class InterestWatcher(DirectObject):
def _handleInterestCloseEvent(self, event, parentId, zoneIdList):
self._gotEvent = True
self._eGroup.addEvent(event)
"""
if self._recurse:
# this interest is in the process of closing. If an interest
# underneath any objects in that interest close, we need to know
# about it.
self.closingParent2zones.setdefault(parentId, set())
self.closingParent2zones[parentId].union(set(zoneIdList))
"""
#if self._recurse:
# # this interest is in the process of closing. If an interest
# # underneath any objects in that interest close, we need to know
# # about it.
# self.closingParent2zones.setdefault(parentId, set())
# self.closingParent2zones[parentId].union(set(zoneIdList))

View File

@ -90,5 +90,3 @@ class NetMessenger(Messenger):
else:
(message, sentArgs) = loads(pickleData)
Messenger.send(self, message, sentArgs=sentArgs)

View File

@ -90,7 +90,7 @@ class ParentMgr:
if isDefaultValue(token):
self.notify.error('parent token (for %s) cannot be a default value (%s)' % (repr(parent), token))
if type(token) is int:
if isinstance(token, int):
if token > 0xFFFFFFFF:
self.notify.error('parent token %s (for %s) is out of uint32 range' % (token, repr(parent)))

View File

@ -50,7 +50,7 @@ class PyDatagram(Datagram):
self.addUint16(code)
def putArg(self, arg, subatomicType, divisor=1):
if (divisor == 1):
if divisor == 1:
funcSpecs = self.FuncDict.get(subatomicType)
if funcSpecs:
addFunc, argFunc = funcSpecs

View File

@ -2,8 +2,10 @@
# from direct.showbase.ShowBaseGlobal import *
from direct.showbase import DirectObject
from direct.task.TaskManagerGlobal import taskMgr
from direct.directnotify import DirectNotifyGlobal
class RelatedObjectMgr(DirectObject.DirectObject):
"""
This class manages a relationship between DistributedObjects that
@ -104,7 +106,7 @@ class RelatedObjectMgr(DirectObject.DirectObject):
doIdList = doIdList[:]
doLaterName = None
if timeout != None:
if timeout is not None:
doLaterName = "RelatedObject-%s" % (RelatedObjectMgr.doLaterSequence)
assert self.notify.debug("doLaterName = %s" % (doLaterName))
@ -115,7 +117,7 @@ class RelatedObjectMgr(DirectObject.DirectObject):
for doId in doIdsPending:
pendingList = self.pendingObjects.get(doId)
if pendingList == None:
if pendingList is None:
pendingList = []
self.pendingObjects[doId] = pendingList
self.__listenFor(doId)
@ -171,7 +173,6 @@ class RelatedObjectMgr(DirectObject.DirectObject):
assert self.notify.debug("timeout expired for %s (remaining: %s)" % (doIdList, doIdsPending))
self.__removePending(tuple, doIdsPending)
if timeoutCallback:
timeoutCallback(doIdList)
else:
@ -248,10 +249,9 @@ class RelatedObjectMgr(DirectObject.DirectObject):
if doId:
object = self.cr.doId2do.get(doId)
objects.append(object)
if object == None:
if object is None:
doIdsPending.append(doId)
else:
objects.append(None)
return objects, doIdsPending

View File

@ -4,6 +4,7 @@ from panda3d.core import *
from panda3d.direct import *
from direct.distributed.MsgTypesCMU import *
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.PyDatagram import PyDatagram
@ -84,7 +85,7 @@ class ServerRepository:
threadedNet = None):
if threadedNet is None:
# Default value.
threadedNet = config.GetBool('threaded-net', False)
threadedNet = ConfigVariableBool('threaded-net', False).value
# Set up networking interfaces.
numThreads = 0
@ -217,7 +218,7 @@ class ServerRepository:
self.hashVal = 0
dcImports = {}
if dcFileNames == None:
if dcFileNames is None:
readResult = dcFile.readAll()
if not readResult:
self.notify.error("Could not read dc file.")
@ -269,11 +270,11 @@ class ServerRepository:
classDef = dcImports.get(className)
# Also try it without the dcSuffix.
if classDef == None:
if classDef is None:
className = dclass.getName()
classDef = dcImports.get(className)
if classDef == None:
if classDef is None:
self.notify.debug("No class definition for %s." % (className))
else:
if inspect.ismodule(classDef):
@ -458,7 +459,7 @@ class ServerRepository:
return
dcfield = object.dclass.getFieldByIndex(fieldId)
if dcfield == None:
if dcfield is None:
self.notify.warning(
"Ignoring update for field %s on object %s from client %s; no such field for class %s." % (
fieldId, doId, client.doIdBase, object.dclass.getName()))

View File

@ -61,4 +61,3 @@ class StagedObject:
def isOffStage(self):
return self.__state == StagedObject.OFF

View File

@ -1,6 +1,7 @@
from direct.showbase.DirectObject import *
from panda3d.core import *
from direct.showbase.DirectObject import *
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
from direct.distributed import DistributedObject
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.ClockDelta import globalClockDelta
@ -144,7 +145,6 @@ class TimeManager(DistributedObject.DistributedObject):
return 1
def serverTime(self, context, timestamp):
"""serverTime(self, int8 context, int32 timestamp)
@ -184,4 +184,3 @@ class TimeManager(DistributedObject.DistributedObject):
messenger.send("gotTimeSync", taskChain = 'default')
messenger.send(self.cr.uniqueName("gotTimeSync"), taskChain = 'default')

View File

@ -1,5 +1,5 @@
from direct.distributed.ClockDelta import *
from panda3d.core import *
from direct.distributed.ClockDelta import *
from direct.distributed import DistributedObjectAI
class TimeManagerAI(DistributedObjectAI.DistributedObjectAI):

View File

@ -67,7 +67,7 @@ def popupControls(self, tl = None):
EntryScale = importlib.import_module('direct.tkwidgets.EntryScale')
tkinter = importlib.import_module('tkinter')
if tl == None:
if tl is None:
tl = tkinter.Toplevel()
tl.title('Interval Controls')
outerFrame = tkinter.Frame(tl)

View File

@ -6,10 +6,6 @@
from panda3d import core
from .extension_native_helpers import Dtool_funcToMethod
"""
HTTPChannel-extensions module: contains methods to extend functionality
of the HTTPChannel class
"""
def spawnTask(self, name = None, callback = None, extraArgs = []):
"""Spawns a task to service the download recently requested
@ -23,6 +19,7 @@ def spawnTask(self, name = None, callback = None, extraArgs = []):
if not name:
name = str(self.getUrl())
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
task = Task.Task(self.doTask)
task.callback = callback
task.callbackArgs = extraArgs

View File

@ -12,11 +12,11 @@ from panda3d.core import Mat3
from .extension_native_helpers import Dtool_funcToMethod
def pPrintValues(self):
"""
Pretty print
"""
return "\n%s\n%s\n%s" % (
self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintValues())
"""
Pretty print
"""
return "\n%s\n%s\n%s" % (
self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintValues())
Dtool_funcToMethod(pPrintValues, Mat3)
del pPrintValues
#####################################################################

View File

@ -105,6 +105,7 @@ def remove(self):
print("Warning: NodePath.remove() is deprecated. Use remove_node() instead.")
# Send message in case anyone needs to do something
# before node is deleted
from direct.showbase.MessengerGlobal import messenger
messenger.send('preRemoveNodePath', [self])
# Remove nodePath
self.removeNode()
@ -315,7 +316,7 @@ def printTransform(self, other = None, sd = 2, fRecursive = 0):
from panda3d.core import Vec3
fmtStr = '%%0.%df' % sd
name = self.getName()
if other == None:
if other is None:
transform = self.getTransform()
else:
transform = self.getTransform(other)
@ -464,7 +465,7 @@ def showCS(self, mask = None):
npc = self.findAllMatches('**/+CollisionNode')
for p in range(0, npc.getNumPaths()):
np = npc[p]
if (mask == None or (np.node().getIntoCollideMask() & mask).getWord()):
if (mask is None or (np.node().getIntoCollideMask() & mask).getWord()):
np.show()
Dtool_funcToMethod(showCS, NodePath)
@ -482,7 +483,7 @@ def hideCS(self, mask = None):
npc = self.findAllMatches('**/+CollisionNode')
for p in range(0, npc.getNumPaths()):
np = npc[p]
if (mask == None or (np.node().getIntoCollideMask() & mask).getWord()):
if (mask is None or (np.node().getIntoCollideMask() & mask).getWord()):
np.hide()
Dtool_funcToMethod(hideCS, NodePath)
@ -639,15 +640,15 @@ def flattenMultitex(self, stateFrom = None, target = None,
useGeom = 0, allowTexMat = 0, win = None):
from panda3d.core import MultitexReducer
mr = MultitexReducer()
if target != None:
if target is not None:
mr.setTarget(target)
mr.setUseGeom(useGeom)
mr.setAllowTexMat(allowTexMat)
if win == None:
if win is None:
win = base.win
if stateFrom == None:
if stateFrom is None:
mr.scan(self)
else:
mr.scan(self, stateFrom)
@ -664,7 +665,7 @@ def removeNonCollisions(self):
# remove anything that is not collision-related
print("NodePath.removeNonCollisions() is deprecated")
stack = [self]
while len(stack):
while len(stack) > 0:
np = stack.pop()
# if there are no CollisionNodes under this node, remove it
if np.find('**/+CollisionNode').isEmpty():
@ -706,22 +707,44 @@ def r_subdivideCollisions(self, solids, numSolidsInLeaves):
if len(solids) <= numSolidsInLeaves:
return solids
origins = []
avgX = 0; avgY = 0; avgZ = 0
minX = None; minY = None; minZ = None
maxX = None; maxY = None; maxZ = None
avgX = 0
avgY = 0
avgZ = 0
minX = None
minY = None
minZ = None
maxX = None
maxY = None
maxZ = None
for solid in solids:
origin = solid.getCollisionOrigin()
origins.append(origin)
x = origin.getX(); y = origin.getY(); z = origin.getZ()
avgX += x; avgY += y; avgZ += z
x = origin.getX()
y = origin.getY()
z = origin.getZ()
avgX += x
avgY += y
avgZ += z
if minX is None:
minX = x; minY = y; minZ = z
maxX = x; maxY = y; maxZ = z
minX = x
minY = y
minZ = z
maxX = x
maxY = y
maxZ = z
else:
minX = min(x, minX); minY = min(y, minY); minZ = min(z, minZ)
maxX = max(x, maxX); maxY = max(y, maxY); maxZ = max(z, maxZ)
avgX /= len(solids); avgY /= len(solids); avgZ /= len(solids)
extentX = maxX - minX; extentY = maxY - minY; extentZ = maxZ - minZ
minX = min(x, minX)
minY = min(y, minY)
minZ = min(z, minZ)
maxX = max(x, maxX)
maxY = max(y, maxY)
maxZ = max(z, maxZ)
avgX /= len(solids)
avgY /= len(solids)
avgZ /= len(solids)
extentX = maxX - minX
extentY = maxY - minY
extentZ = maxZ - minZ
maxExtent = max(max(extentX, extentY), extentZ)
# sparse octree
xyzSolids = []
@ -738,60 +761,62 @@ def r_subdivideCollisions(self, solids, numSolidsInLeaves):
# throw out axes that are not close to the max axis extent; try and keep
# the divisions square/spherical
if extentX < (maxExtent * .75) or extentX > (maxExtent * 1.25):
midX += maxExtent
midX += maxExtent
if extentY < (maxExtent * .75) or extentY > (maxExtent * 1.25):
midY += maxExtent
midY += maxExtent
if extentZ < (maxExtent * .75) or extentZ > (maxExtent * 1.25):
midZ += maxExtent
for i in range(len(solids)):
origin = origins[i]
x = origin.getX(); y = origin.getY(); z = origin.getZ()
if x < midX:
if y < midY:
if z < midZ:
xyzSolids.append(solids[i])
else:
xyZSolids.append(solids[i])
else:
if z < midZ:
xYzSolids.append(solids[i])
else:
xYZSolids.append(solids[i])
midZ += maxExtent
for i, solid in enumerate(solids):
origin = origins[i]
x = origin.getX()
y = origin.getY()
z = origin.getZ()
if x < midX:
if y < midY:
if z < midZ:
xyzSolids.append(solids[i])
else:
xyZSolids.append(solids[i])
else:
if y < midY:
if z < midZ:
XyzSolids.append(solids[i])
else:
XyZSolids.append(solids[i])
else:
if z < midZ:
XYzSolids.append(solids[i])
else:
XYZSolids.append(solids[i])
if z < midZ:
xYzSolids.append(solids[i])
else:
xYZSolids.append(solids[i])
else:
if y < midY:
if z < midZ:
XyzSolids.append(solids[i])
else:
XyZSolids.append(solids[i])
else:
if z < midZ:
XYzSolids.append(solids[i])
else:
XYZSolids.append(solids[i])
newSolids = []
if len(xyzSolids):
newSolids.append(self.r_subdivideCollisions(xyzSolids, numSolidsInLeaves))
if len(XyzSolids):
newSolids.append(self.r_subdivideCollisions(XyzSolids, numSolidsInLeaves))
if len(xYzSolids):
newSolids.append(self.r_subdivideCollisions(xYzSolids, numSolidsInLeaves))
if len(XYzSolids):
newSolids.append(self.r_subdivideCollisions(XYzSolids, numSolidsInLeaves))
if len(xyZSolids):
newSolids.append(self.r_subdivideCollisions(xyZSolids, numSolidsInLeaves))
if len(XyZSolids):
newSolids.append(self.r_subdivideCollisions(XyZSolids, numSolidsInLeaves))
if len(xYZSolids):
newSolids.append(self.r_subdivideCollisions(xYZSolids, numSolidsInLeaves))
if len(XYZSolids):
newSolids.append(self.r_subdivideCollisions(XYZSolids, numSolidsInLeaves))
if len(xyzSolids) > 0:
newSolids.append(self.r_subdivideCollisions(xyzSolids, numSolidsInLeaves))
if len(XyzSolids) > 0:
newSolids.append(self.r_subdivideCollisions(XyzSolids, numSolidsInLeaves))
if len(xYzSolids) > 0:
newSolids.append(self.r_subdivideCollisions(xYzSolids, numSolidsInLeaves))
if len(XYzSolids) > 0:
newSolids.append(self.r_subdivideCollisions(XYzSolids, numSolidsInLeaves))
if len(xyZSolids) > 0:
newSolids.append(self.r_subdivideCollisions(xyZSolids, numSolidsInLeaves))
if len(XyZSolids) > 0:
newSolids.append(self.r_subdivideCollisions(XyZSolids, numSolidsInLeaves))
if len(xYZSolids) > 0:
newSolids.append(self.r_subdivideCollisions(xYZSolids, numSolidsInLeaves))
if len(XYZSolids) > 0:
newSolids.append(self.r_subdivideCollisions(XYZSolids, numSolidsInLeaves))
#import pdb;pdb.set_trace()
return newSolids
def r_constructCollisionTree(self, solidTree, parentNode, colName):
from panda3d.core import CollisionNode
for item in solidTree:
if type(item[0]) == type([]):
if isinstance(item[0], list):
newNode = parentNode.attachNewNode('%s-branch' % colName)
self.r_constructCollisionTree(item, newNode, colName)
else:

View File

@ -16,6 +16,13 @@ clunky approach. - Josh
"""
from panda3d.core import LVecBase4, LPoint2
from panda3d.core import AuxBitplaneAttrib
from panda3d.core import Texture, Shader, ATSNone
from panda3d.core import FrameBufferProperties
from direct.task.TaskManagerGlobal import taskMgr
from .FilterManager import FilterManager
from .filterBloomI import BLOOM_I
from .filterBloomX import BLOOM_X
@ -24,14 +31,8 @@ from .filterBlurX import BLUR_X
from .filterBlurY import BLUR_Y
from .filterCopy import COPY
from .filterDown4 import DOWN_4
from panda3d.core import LVecBase4, LPoint2
from panda3d.core import Filename
from panda3d.core import AuxBitplaneAttrib
from panda3d.core import Texture, Shader, ATSNone
from panda3d.core import FrameBufferProperties
import os
CARTOON_BODY="""
CARTOON_BODY = """
float4 cartoondelta = k_cartoonseparation * texpix_txaux.xwyw;
float4 cartoon_c0 = tex2D(k_txaux, %(texcoord)s + cartoondelta.xy);
float4 cartoon_c1 = tex2D(k_txaux, %(texcoord)s - cartoondelta.xy);
@ -48,7 +49,7 @@ o_color = lerp(o_color, k_cartooncolor, cartoon_thresh);
# We fill in the actual value of numsamples in the loop limit
# when the shader is configured.
#
SSAO_BODY="""//Cg
SSAO_BODY = """//Cg
void vshader(float4 vtx_position : POSITION,
out float4 l_position : POSITION,
@ -100,8 +101,8 @@ void fshader(out float4 o_color : COLOR,
class FilterConfig:
pass
class CommonFilters:
class CommonFilters:
""" Class CommonFilters implements certain common image postprocessing
filters. The constructor requires a filter builder as a parameter. """
@ -118,20 +119,19 @@ class CommonFilters:
self.bloom = []
self.blur = []
self.ssao = []
if self.task != None:
taskMgr.remove(self.task)
self.task = None
if self.task is not None:
taskMgr.remove(self.task)
self.task = None
def reconfigure(self, fullrebuild, changed):
""" Reconfigure is called whenever any configuration change is made. """
configuration = self.configuration
if (fullrebuild):
if fullrebuild:
self.cleanup()
if (len(configuration) == 0):
if len(configuration) == 0:
return
if not self.manager.win.gsg.getSupportsBasicShaders():
@ -141,12 +141,12 @@ class CommonFilters:
needtex = set(["color"])
needtexcoord = set(["color"])
if ("CartoonInk" in configuration):
if "CartoonInk" in configuration:
needtex.add("aux")
auxbits |= AuxBitplaneAttrib.ABOAuxNormal
needtexcoord.add("aux")
if ("AmbientOcclusion" in configuration):
if "AmbientOcclusion" in configuration:
needtex.add("depth")
needtex.add("ssao0")
needtex.add("ssao1")
@ -155,12 +155,12 @@ class CommonFilters:
auxbits |= AuxBitplaneAttrib.ABOAuxNormal
needtexcoord.add("ssao2")
if ("BlurSharpen" in configuration):
if "BlurSharpen" in configuration:
needtex.add("blur0")
needtex.add("blur1")
needtexcoord.add("blur1")
if ("Bloom" in configuration):
if "Bloom" in configuration:
needtex.add("bloom0")
needtex.add("bloom1")
needtex.add("bloom2")
@ -168,10 +168,10 @@ class CommonFilters:
auxbits |= AuxBitplaneAttrib.ABOGlow
needtexcoord.add("bloom3")
if ("ViewGlow" in configuration):
if "ViewGlow" in configuration:
auxbits |= AuxBitplaneAttrib.ABOGlow
if ("VolumetricLighting" in configuration):
if "VolumetricLighting" in configuration:
needtex.add(configuration["VolumetricLighting"].source)
for tex in needtex:
@ -188,47 +188,47 @@ class CommonFilters:
clamping = False
self.finalQuad = self.manager.renderSceneInto(textures = self.textures, auxbits=auxbits, fbprops=fbprops, clamping=clamping)
if (self.finalQuad == None):
if self.finalQuad is None:
self.cleanup()
return False
if ("BlurSharpen" in configuration):
blur0=self.textures["blur0"]
blur1=self.textures["blur1"]
self.blur.append(self.manager.renderQuadInto("filter-blur0", colortex=blur0,div=2))
if "BlurSharpen" in configuration:
blur0 = self.textures["blur0"]
blur1 = self.textures["blur1"]
self.blur.append(self.manager.renderQuadInto("filter-blur0", colortex=blur0, div=2))
self.blur.append(self.manager.renderQuadInto("filter-blur1", colortex=blur1))
self.blur[0].setShaderInput("src", self.textures["color"])
self.blur[0].setShader(Shader.make(BLUR_X, Shader.SL_Cg))
self.blur[1].setShaderInput("src", blur0)
self.blur[1].setShader(Shader.make(BLUR_Y, Shader.SL_Cg))
if ("AmbientOcclusion" in configuration):
ssao0=self.textures["ssao0"]
ssao1=self.textures["ssao1"]
ssao2=self.textures["ssao2"]
if "AmbientOcclusion" in configuration:
ssao0 = self.textures["ssao0"]
ssao1 = self.textures["ssao1"]
ssao2 = self.textures["ssao2"]
self.ssao.append(self.manager.renderQuadInto("filter-ssao0", colortex=ssao0))
self.ssao.append(self.manager.renderQuadInto("filter-ssao1", colortex=ssao1,div=2))
self.ssao.append(self.manager.renderQuadInto("filter-ssao1", colortex=ssao1, div=2))
self.ssao.append(self.manager.renderQuadInto("filter-ssao2", colortex=ssao2))
self.ssao[0].setShaderInput("depth", self.textures["depth"])
self.ssao[0].setShaderInput("normal", self.textures["aux"])
self.ssao[0].setShaderInput("random", loader.loadTexture("maps/random.rgb"))
self.ssao[0].setShaderInput("random", base.loader.loadTexture("maps/random.rgb"))
self.ssao[0].setShader(Shader.make(SSAO_BODY % configuration["AmbientOcclusion"].numsamples, Shader.SL_Cg))
self.ssao[1].setShaderInput("src", ssao0)
self.ssao[1].setShader(Shader.make(BLUR_X, Shader.SL_Cg))
self.ssao[2].setShaderInput("src", ssao1)
self.ssao[2].setShader(Shader.make(BLUR_Y, Shader.SL_Cg))
if ("Bloom" in configuration):
if "Bloom" in configuration:
bloomconf = configuration["Bloom"]
bloom0=self.textures["bloom0"]
bloom1=self.textures["bloom1"]
bloom2=self.textures["bloom2"]
bloom3=self.textures["bloom3"]
if (bloomconf.size == "large"):
bloom0 = self.textures["bloom0"]
bloom1 = self.textures["bloom1"]
bloom2 = self.textures["bloom2"]
bloom3 = self.textures["bloom3"]
if bloomconf.size == "large":
scale=8
downsamplerName="filter-down4"
downsampler=DOWN_4
elif (bloomconf.size == "medium"):
elif bloomconf.size == "medium":
scale=4
downsamplerName="filter-copy"
downsampler=COPY
@ -282,7 +282,7 @@ class CommonFilters:
for texcoord, padTex in texcoordPadding.items():
if padTex is not None:
text += " uniform float4 texpad_tx%s,\n" % (padTex)
if ("HalfPixelShift" in configuration):
if "HalfPixelShift" in configuration:
text += " uniform float4 texpix_tx%s,\n" % (padTex)
for i, name in texcoordSets:
@ -298,7 +298,7 @@ class CommonFilters:
else:
text += " %s = (vtx_position.xz * texpad_tx%s.xy) + texpad_tx%s.xy;\n" % (texcoord, padTex, padTex)
if ("HalfPixelShift" in configuration):
if "HalfPixelShift" in configuration:
text += " %s += texpix_tx%s.xy * 0.5;\n" % (texcoord, padTex)
text += "}\n"
@ -311,37 +311,37 @@ class CommonFilters:
for key in self.textures:
text += " uniform sampler2D k_tx" + key + ",\n"
if ("CartoonInk" in configuration):
if "CartoonInk" in configuration:
text += " uniform float4 k_cartoonseparation,\n"
text += " uniform float4 k_cartooncolor,\n"
text += " uniform float4 texpix_txaux,\n"
if ("BlurSharpen" in configuration):
if "BlurSharpen" in configuration:
text += " uniform float4 k_blurval,\n"
if ("VolumetricLighting" in configuration):
if "VolumetricLighting" in configuration:
text += " uniform float4 k_casterpos,\n"
text += " uniform float4 k_vlparams,\n"
if ("ExposureAdjust" in configuration):
if "ExposureAdjust" in configuration:
text += " uniform float k_exposure,\n"
text += " out float4 o_color : COLOR)\n"
text += "{\n"
text += " o_color = tex2D(k_txcolor, %s);\n" % (texcoords["color"])
if ("CartoonInk" in configuration):
if "CartoonInk" in configuration:
text += CARTOON_BODY % {"texcoord" : texcoords["aux"]}
if ("AmbientOcclusion" in configuration):
if "AmbientOcclusion" in configuration:
text += " o_color *= tex2D(k_txssao2, %s).r;\n" % (texcoords["ssao2"])
if ("BlurSharpen" in configuration):
if "BlurSharpen" in configuration:
text += " o_color = lerp(tex2D(k_txblur1, %s), o_color, k_blurval.x);\n" % (texcoords["blur1"])
if ("Bloom" in configuration):
text += " o_color = saturate(o_color);\n";
if "Bloom" in configuration:
text += " o_color = saturate(o_color);\n"
text += " float4 bloom = 0.5 * tex2D(k_txbloom3, %s);\n" % (texcoords["bloom3"])
text += " o_color = 1-((1-bloom)*(1-o_color));\n"
if ("ViewGlow" in configuration):
if "ViewGlow" in configuration:
text += " o_color.r = o_color.a;\n"
if ("VolumetricLighting" in configuration):
if "VolumetricLighting" in configuration:
text += " float decay = 1.0f;\n"
text += " float2 curcoord = %s;\n" % (texcoords["color"])
text += " float2 lightdir = curcoord - k_casterpos.xy;\n"
@ -357,15 +357,15 @@ class CommonFilters:
text += " }\n"
text += " o_color += float4(vlcolor * k_vlparams.z, 1);\n"
if ("ExposureAdjust" in configuration):
if "ExposureAdjust" in configuration:
text += " o_color.rgb *= k_exposure;\n"
# With thanks to Stephen Hill!
if ("HighDynamicRange" in configuration):
if "HighDynamicRange" in configuration:
text += " float3 aces_color = mul(aces_input_mat, o_color.rgb);\n"
text += " o_color.rgb = saturate(mul(aces_output_mat, (aces_color * (aces_color + 0.0245786f) - 0.000090537f) / (aces_color * (0.983729f * aces_color + 0.4329510f) + 0.238081f)));\n"
if ("GammaAdjust" in configuration):
if "GammaAdjust" in configuration:
gamma = configuration["GammaAdjust"]
if gamma == 0.5:
text += " o_color.rgb = sqrt(o_color.rgb);\n"
@ -374,12 +374,12 @@ class CommonFilters:
elif gamma != 1.0:
text += " o_color.rgb = pow(o_color.rgb, %ff);\n" % (gamma)
if ("SrgbEncode" in configuration):
if "SrgbEncode" in configuration:
text += " o_color.r = (o_color.r < 0.0031308) ? (o_color.r * 12.92) : (1.055 * pow(o_color.r, 0.41666) - 0.055);\n"
text += " o_color.g = (o_color.g < 0.0031308) ? (o_color.g * 12.92) : (1.055 * pow(o_color.g, 0.41666) - 0.055);\n"
text += " o_color.b = (o_color.b < 0.0031308) ? (o_color.b * 12.92) : (1.055 * pow(o_color.b, 0.41666) - 0.055);\n"
if ("Inverted" in configuration):
if "Inverted" in configuration:
text += " o_color = float4(1, 1, 1, 1) - o_color;\n"
text += "}\n"
@ -392,19 +392,19 @@ class CommonFilters:
self.task = taskMgr.add(self.update, "common-filters-update")
if (changed == "CartoonInk") or fullrebuild:
if ("CartoonInk" in configuration):
if changed == "CartoonInk" or fullrebuild:
if "CartoonInk" in configuration:
c = configuration["CartoonInk"]
self.finalQuad.setShaderInput("cartoonseparation", LVecBase4(c.separation, 0, c.separation, 0))
self.finalQuad.setShaderInput("cartooncolor", c.color)
if (changed == "BlurSharpen") or fullrebuild:
if ("BlurSharpen" in configuration):
if changed == "BlurSharpen" or fullrebuild:
if "BlurSharpen" in configuration:
blurval = configuration["BlurSharpen"]
self.finalQuad.setShaderInput("blurval", LVecBase4(blurval, blurval, blurval, blurval))
if (changed == "Bloom") or fullrebuild:
if ("Bloom" in configuration):
if changed == "Bloom" or fullrebuild:
if "Bloom" in configuration:
bloomconf = configuration["Bloom"]
intensity = bloomconf.intensity * 3.0
self.bloom[0].setShaderInput("blend", bloomconf.blendx, bloomconf.blendy, bloomconf.blendz, bloomconf.blendw * 2.0)
@ -412,20 +412,20 @@ class CommonFilters:
self.bloom[0].setShaderInput("desat", bloomconf.desat)
self.bloom[3].setShaderInput("intensity", intensity, intensity, intensity, intensity)
if (changed == "VolumetricLighting") or fullrebuild:
if ("VolumetricLighting" in configuration):
if changed == "VolumetricLighting" or fullrebuild:
if "VolumetricLighting" in configuration:
config = configuration["VolumetricLighting"]
tcparam = config.density / float(config.numsamples)
self.finalQuad.setShaderInput("vlparams", tcparam, config.decay, config.exposure, 0.0)
if (changed == "AmbientOcclusion") or fullrebuild:
if ("AmbientOcclusion" in configuration):
if changed == "AmbientOcclusion" or fullrebuild:
if "AmbientOcclusion" in configuration:
config = configuration["AmbientOcclusion"]
self.ssao[0].setShaderInput("params1", config.numsamples, -float(config.amount) / config.numsamples, config.radius, 0)
self.ssao[0].setShaderInput("params2", config.strength, config.falloff, 0, 0)
if (changed == "ExposureAdjust") or fullrebuild:
if ("ExposureAdjust" in configuration):
if changed == "ExposureAdjust" or fullrebuild:
if "ExposureAdjust" in configuration:
stops = configuration["ExposureAdjust"]
self.finalQuad.setShaderInput("exposure", 2 ** stops)
@ -441,11 +441,11 @@ class CommonFilters:
casterpos = LPoint2()
self.manager.camera.node().getLens().project(caster.getPos(self.manager.camera), casterpos)
self.finalQuad.setShaderInput("casterpos", LVecBase4(casterpos.getX() * 0.5 + 0.5, (casterpos.getY() * 0.5 + 0.5), 0, 0))
if task != None:
if task is not None:
return task.cont
def setCartoonInk(self, separation=1, color=(0, 0, 0, 1)):
fullrebuild = (("CartoonInk" in self.configuration) == False)
fullrebuild = ("CartoonInk" not in self.configuration)
newconfig = FilterConfig()
newconfig.separation = separation
newconfig.color = color
@ -453,24 +453,30 @@ class CommonFilters:
return self.reconfigure(fullrebuild, "CartoonInk")
def delCartoonInk(self):
if ("CartoonInk" in self.configuration):
if "CartoonInk" in self.configuration:
del self.configuration["CartoonInk"]
return self.reconfigure(True, "CartoonInk")
return True
def setBloom(self, blend=(0.3,0.4,0.3,0.0), mintrigger=0.6, maxtrigger=1.0, desat=0.6, intensity=1.0, size="medium"):
if (size==0): size="off"
elif (size==1): size="small"
elif (size==2): size="medium"
elif (size==3): size="large"
if (size=="off"):
if size == 0 or size == "off":
self.delBloom()
return
if (maxtrigger==None): maxtrigger=mintrigger+0.8
elif size == 1:
size = "small"
elif size == 2:
size = "medium"
elif size == 3:
size = "large"
if maxtrigger is None:
maxtrigger = mintrigger + 0.8
oldconfig = self.configuration.get("Bloom", None)
fullrebuild = True
if (oldconfig) and (oldconfig.size == size):
if oldconfig and oldconfig.size == size:
fullrebuild = False
newconfig = FilterConfig()
(newconfig.blendx, newconfig.blendy, newconfig.blendz, newconfig.blendw) = blend
newconfig.maxtrigger = maxtrigger
@ -482,40 +488,40 @@ class CommonFilters:
return self.reconfigure(fullrebuild, "Bloom")
def delBloom(self):
if ("Bloom" in self.configuration):
if "Bloom" in self.configuration:
del self.configuration["Bloom"]
return self.reconfigure(True, "Bloom")
return True
def setHalfPixelShift(self):
fullrebuild = (("HalfPixelShift" in self.configuration) == False)
fullrebuild = ("HalfPixelShift" not in self.configuration)
self.configuration["HalfPixelShift"] = 1
return self.reconfigure(fullrebuild, "HalfPixelShift")
def delHalfPixelShift(self):
if ("HalfPixelShift" in self.configuration):
if "HalfPixelShift" in self.configuration:
del self.configuration["HalfPixelShift"]
return self.reconfigure(True, "HalfPixelShift")
return True
def setViewGlow(self):
fullrebuild = (("ViewGlow" in self.configuration) == False)
fullrebuild = ("ViewGlow" not in self.configuration)
self.configuration["ViewGlow"] = 1
return self.reconfigure(fullrebuild, "ViewGlow")
def delViewGlow(self):
if ("ViewGlow" in self.configuration):
if "ViewGlow" in self.configuration:
del self.configuration["ViewGlow"]
return self.reconfigure(True, "ViewGlow")
return True
def setInverted(self):
fullrebuild = (("Inverted" in self.configuration) == False)
fullrebuild = ("Inverted" not in self.configuration)
self.configuration["Inverted"] = 1
return self.reconfigure(fullrebuild, "Inverted")
def delInverted(self):
if ("Inverted" in self.configuration):
if "Inverted" in self.configuration:
del self.configuration["Inverted"]
return self.reconfigure(True, "Inverted")
return True
@ -523,7 +529,7 @@ class CommonFilters:
def setVolumetricLighting(self, caster, numsamples = 32, density = 5.0, decay = 0.1, exposure = 0.1, source = "color"):
oldconfig = self.configuration.get("VolumetricLighting", None)
fullrebuild = True
if (oldconfig) and (oldconfig.source == source) and (oldconfig.numsamples == int(numsamples)):
if oldconfig and oldconfig.source == source and oldconfig.numsamples == int(numsamples):
fullrebuild = False
newconfig = FilterConfig()
newconfig.caster = caster
@ -536,7 +542,7 @@ class CommonFilters:
return self.reconfigure(fullrebuild, "VolumetricLighting")
def delVolumetricLighting(self):
if ("VolumetricLighting" in self.configuration):
if "VolumetricLighting" in self.configuration:
del self.configuration["VolumetricLighting"]
return self.reconfigure(True, "VolumetricLighting")
return True
@ -544,20 +550,20 @@ class CommonFilters:
def setBlurSharpen(self, amount=0.0):
"""Enables the blur/sharpen filter. If the 'amount' parameter is 1.0, it will not have effect.
A value of 0.0 means fully blurred, and a value higher than 1.0 sharpens the image."""
fullrebuild = (("BlurSharpen" in self.configuration) == False)
fullrebuild = ("BlurSharpen" not in self.configuration)
self.configuration["BlurSharpen"] = amount
return self.reconfigure(fullrebuild, "BlurSharpen")
def delBlurSharpen(self):
if ("BlurSharpen" in self.configuration):
if "BlurSharpen" in self.configuration:
del self.configuration["BlurSharpen"]
return self.reconfigure(True, "BlurSharpen")
return True
def setAmbientOcclusion(self, numsamples = 16, radius = 0.05, amount = 2.0, strength = 0.01, falloff = 0.000002):
fullrebuild = (("AmbientOcclusion" in self.configuration) == False)
fullrebuild = ("AmbientOcclusion" not in self.configuration)
if (not fullrebuild):
if not fullrebuild:
fullrebuild = (numsamples != self.configuration["AmbientOcclusion"].numsamples)
newconfig = FilterConfig()
@ -570,7 +576,7 @@ class CommonFilters:
return self.reconfigure(fullrebuild, "AmbientOcclusion")
def delAmbientOcclusion(self):
if ("AmbientOcclusion" in self.configuration):
if "AmbientOcclusion" in self.configuration:
del self.configuration["AmbientOcclusion"]
return self.reconfigure(True, "AmbientOcclusion")
return True
@ -584,7 +590,7 @@ class CommonFilters:
return True
def delGammaAdjust(self):
if ("GammaAdjust" in self.configuration):
if "GammaAdjust" in self.configuration:
old_gamma = self.configuration["GammaAdjust"]
del self.configuration["GammaAdjust"]
return self.reconfigure((old_gamma != 1.0), "GammaAdjust")
@ -610,7 +616,7 @@ class CommonFilters:
def delSrgbEncode(self):
""" Reverses the effects of setSrgbEncode. """
if ("SrgbEncode" in self.configuration):
if "SrgbEncode" in self.configuration:
old_enable = self.configuration["SrgbEncode"]
del self.configuration["SrgbEncode"]
return self.reconfigure(old_enable, "SrgbEncode")
@ -632,7 +638,7 @@ class CommonFilters:
return self.reconfigure(fullrebuild, "HighDynamicRange")
def delHighDynamicRange(self):
if ("HighDynamicRange" in self.configuration):
if "HighDynamicRange" in self.configuration:
del self.configuration["HighDynamicRange"]
return self.reconfigure(True, "HighDynamicRange")
return True
@ -652,7 +658,7 @@ class CommonFilters:
return True
def delExposureAdjust(self):
if ("ExposureAdjust" in self.configuration):
if "ExposureAdjust" in self.configuration:
del self.configuration["ExposureAdjust"]
return self.reconfigure(True, "ExposureAdjust")
return True

View File

@ -56,7 +56,7 @@ class FilterManager(DirectObject):
if region is None:
self.notify.error('Could not find appropriate DisplayRegion to filter')
return False
return
# Instance Variables.
@ -78,13 +78,13 @@ class FilterManager(DirectObject):
self.accept("window-event", self.windowEvent)
def getClears(self,region):
def getClears(self, region):
clears = []
for i in range(GraphicsOutput.RTPCOUNT):
clears.append((region.getClearActive(i), region.getClearValue(i)))
return clears
def setClears(self,region,clears):
def setClears(self, region, clears):
for i in range(GraphicsOutput.RTPCOUNT):
(active, value) = clears[i]
region.setClearActive(i, active)
@ -94,7 +94,7 @@ class FilterManager(DirectObject):
clears = []
for i in range(GraphicsOutput.RTPCOUNT):
(active, value) = clears0[i]
if (active == 0):
if not active:
(active, value) = clears1[i]
region.setClearActive(i, active)
region.setClearValue(i, value)
@ -107,13 +107,14 @@ class FilterManager(DirectObject):
(self.region.getTop() == 1.0))
def getScaledSize(self, mul, div, align):
""" Calculate the size of the desired window. Not public. """
winx = self.forcex
winy = self.forcey
if winx == 0: winx = self.win.getXSize()
if winy == 0: winy = self.win.getYSize()
if winx == 0:
winx = self.win.getXSize()
if winy == 0:
winy = self.win.getYSize()
if div != 1:
winx = ((winx+align-1) // align) * align
@ -168,7 +169,7 @@ class FilterManager(DirectObject):
scene. It is assumed that the user will replace the shader
on the quad with a more interesting filter. """
if (textures):
if textures:
colortex = textures.get("color", None)
depthtex = textures.get("depth", None)
auxtex = textures.get("aux", None)
@ -178,7 +179,7 @@ class FilterManager(DirectObject):
auxtex0 = auxtex
auxtex1 = None
if (colortex == None):
if colortex is None:
colortex = Texture("filter-base-color")
colortex.setWrapU(Texture.WMClamp)
colortex.setWrapV(Texture.WMClamp)
@ -193,7 +194,7 @@ class FilterManager(DirectObject):
else:
buffer = self.createBuffer("filter-base", winx, winy, texgroup)
if (buffer == None):
if buffer is None:
return None
cm = CardMaker("filter-base-quad")
@ -208,7 +209,7 @@ class FilterManager(DirectObject):
cs.setState(self.camstate)
# Do we really need to turn on the Shader Generator?
#cs.setShaderAuto()
if (auxbits):
if auxbits:
cs.setAttrib(AuxBitplaneAttrib.make(auxbits))
if clamping is False:
# Disables clamping in the shader generator.
@ -226,13 +227,13 @@ class FilterManager(DirectObject):
self.region.setCamera(quadcam)
self.setStackedClears(buffer, self.rclears, self.wclears)
if (auxtex0):
if auxtex0:
buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1)
buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0))
if (auxtex1):
if auxtex1:
buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1)
self.region.disableClears()
if (self.isFullscreen()):
if self.isFullscreen():
self.win.disableClears()
dr = buffer.makeDisplayRegion()
@ -257,14 +258,14 @@ class FilterManager(DirectObject):
winx, winy = self.getScaledSize(mul, div, align)
depthbits = bool(depthtex != None)
depthbits = int(depthtex is not None)
if fbprops is not None:
buffer = self.createBuffer(name, winx, winy, texgroup, depthbits, fbprops=fbprops)
else:
buffer = self.createBuffer(name, winx, winy, texgroup, depthbits)
if (buffer == None):
if buffer is None:
return None
cm = CardMaker("filter-stage-quad")
@ -313,23 +314,23 @@ class FilterManager(DirectObject):
props.addProperties(fbprops)
depthtex, colortex, auxtex0, auxtex1 = texgroup
if (auxtex0 != None):
if auxtex0 is not None:
props.setAuxRgba(1)
if (auxtex1 != None):
if auxtex1 is not None:
props.setAuxRgba(2)
buffer=base.graphicsEngine.makeOutput(
self.win.getPipe(), name, -1,
props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable,
self.win.getGsg(), self.win)
if (buffer == None):
if buffer is None:
return buffer
if (depthtex):
if depthtex:
buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth)
if (colortex):
if colortex:
buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)
if (auxtex0):
if auxtex0:
buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0)
if (auxtex1):
if auxtex1:
buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1)
buffer.setSort(self.nextsort)
buffer.disableClears()

View File

@ -9,6 +9,7 @@ __all__ = ['ClassicFSM']
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.DirectObject import DirectObject
from direct.showbase.MessengerGlobal import messenger
import weakref
if __debug__:
@ -83,7 +84,7 @@ class ClassicFSM(DirectObject):
self.__internalStateInFlux = 0
if __debug__:
global _debugFsms
_debugFsms[name]=weakref.ref(self)
_debugFsms[name] = weakref.ref(self)
# I know this isn't how __repr__ is supposed to be used, but it
# is nice and convenient.
@ -107,7 +108,7 @@ class ClassicFSM(DirectObject):
if self.__currentState == self.__initialState:
return
assert self.__currentState == None
assert self.__currentState is None
self.__internalStateInFlux = 1
self.__enter(self.__initialState, argList)
assert not self.__internalStateInFlux
@ -115,7 +116,7 @@ class ClassicFSM(DirectObject):
# setters and getters
def getName(self):
return(self.__name)
return self.__name
def setName(self, name):
self.__name = name
@ -134,13 +135,13 @@ class ClassicFSM(DirectObject):
self.__states[state.getName()] = state
def getInitialState(self):
return(self.__initialState)
return self.__initialState
def setInitialState(self, initialStateName):
self.__initialState = self.getStateNamed(initialStateName)
def getFinalState(self):
return(self.__finalState)
return self.__finalState
def setFinalState(self, finalStateName):
self.__finalState = self.getStateNamed(finalStateName)
@ -149,7 +150,7 @@ class ClassicFSM(DirectObject):
self.request(self.getFinalState().getName())
def getCurrentState(self):
return(self.__currentState)
return self.__currentState
# lookup funcs
@ -198,7 +199,7 @@ class ClassicFSM(DirectObject):
"""
assert self.__internalStateInFlux
stateName = aState.getName()
if (stateName in self.__states):
if stateName in self.__states:
assert ClassicFSM.notify.debug("[%s]: entering %s" % (self.__name, stateName))
self.__currentState = aState
# Only send the state change event if we are inspecting it
@ -257,7 +258,7 @@ class ClassicFSM(DirectObject):
aState = aStateName
aStateName = aState.getName()
if aState == None:
if aState is None:
ClassicFSM.notify.error("[%s]: request: %s, no such state" %
(self.__name, aStateName))
@ -282,8 +283,8 @@ class ClassicFSM(DirectObject):
exitArgList)
return 1
# We can implicitly always transition to our final state.
elif (aStateName == self.__finalState.getName()):
if (self.__currentState == self.__finalState):
elif aStateName == self.__finalState.getName():
if self.__currentState == self.__finalState:
# Do not do the transition if we are already in the
# final state
assert ClassicFSM.notify.debug(
@ -300,7 +301,7 @@ class ClassicFSM(DirectObject):
exitArgList)
return 1
# are we already in this state?
elif (aStateName == self.__currentState.getName()):
elif aStateName == self.__currentState.getName():
assert ClassicFSM.notify.debug(
"[%s]: already in state %s and no self transition" %
(self.__name, aStateName))
@ -348,7 +349,7 @@ class ClassicFSM(DirectObject):
aState = aStateName
aStateName = aState.getName()
if aState == None:
if aState is None:
ClassicFSM.notify.error("[%s]: request: %s, no such state" %
(self.__name, aStateName))
@ -375,11 +376,3 @@ class ClassicFSM(DirectObject):
def isInternalStateInFlux(self):
return self.__internalStateInFlux

View File

@ -9,8 +9,9 @@ __all__ = ['FSMException', 'FSM']
from direct.showbase.DirectObject import DirectObject
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.MessengerGlobal import messenger
from direct.showbase import PythonUtil
from direct.directnotify import DirectNotifyGlobal
from direct.stdpy.threading import RLock
@ -239,7 +240,7 @@ class FSM(DirectObject):
def isInTransition(self):
self.fsmLock.acquire()
try:
return self.state == None
return self.state is None
finally:
self.fsmLock.release()
@ -339,12 +340,10 @@ class FSM(DirectObject):
def defaultEnter(self, *args):
""" This is the default function that is called if there is no
enterState() method for a particular state name. """
pass
def defaultExit(self):
""" This is the default function that is called if there is no
exitState() method for a particular state name. """
pass
def defaultFilter(self, request, args):
"""This is the function that is called if there is no
@ -485,8 +484,6 @@ class FSM(DirectObject):
if not self.__callFromToFunc(self.oldState, self.newState, *args):
self.__callExitFunc(self.oldState)
self.__callEnterFunc(self.newState, *args)
pass
pass
except:
# If we got an exception during the enter or exit methods,
# go directly to state "InternalError" and raise up the
@ -513,7 +510,7 @@ class FSM(DirectObject):
def __callEnterFunc(self, name, *args):
# Calls the appropriate enter function when transitioning into
# a new state, if it exists.
assert self.state == None and self.newState == name
assert self.state is None and self.newState == name
func = getattr(self, "enter" + name, None)
if not func:
@ -525,7 +522,7 @@ class FSM(DirectObject):
def __callFromToFunc(self, oldState, newState, *args):
# Calls the appropriate fromTo function when transitioning into
# a new state, if it exists.
assert self.state == None and self.oldState == oldState and self.newState == newState
assert self.state is None and self.oldState == oldState and self.newState == newState
func = getattr(self, "from%sTo%s" % (oldState,newState), None)
if func:
@ -536,7 +533,7 @@ class FSM(DirectObject):
def __callExitFunc(self, name):
# Calls the appropriate exit function when leaving a
# state, if it exists.
assert self.state == None and self.oldState == name
assert self.state is None and self.oldState == name
func = getattr(self, "exit" + name, None)
if not func:

View File

@ -212,4 +212,3 @@ class FourState:
"""for debugging"""
return self.notify.debug("%d (%d) %s"%(
id(self), self.stateIndex==4, message))

View File

@ -7,6 +7,7 @@ from direct.directnotify import DirectNotifyGlobal
from . import ClassicFSM
from . import State
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
class FourStateAI:
@ -268,4 +269,3 @@ class FourStateAI:
"""for debugging"""
return self.notify.debug("%d (%d) %s"%(
id(self), self.stateIndex==4, message))

View File

@ -4,6 +4,7 @@ __all__ = ['ClassicStyle', 'NewStyle', 'ToonEyes']
from . import FSM
from direct.task import Task
from direct.task.TaskManagerGlobal import taskMgr
class ClassicStyle(FSM.FSM):

View File

@ -21,21 +21,21 @@ class State(DirectObject):
States = weakref.WeakKeyDictionary()
@classmethod
def replaceMethod(self, oldFunction, newFunction):
def replaceMethod(cls, oldFunction, newFunction):
import types
count = 0
for state in self.States:
for state in cls.States:
# Note: you can only replace methods currently
enterFunc = state.getEnterFunc()
exitFunc = state.getExitFunc()
# print 'testing: ', state, enterFunc, exitFunc, oldFunction
if type(enterFunc) == types.MethodType:
if isinstance(enterFunc, types.MethodType):
if enterFunc.__func__ == oldFunction:
# print 'found: ', enterFunc, oldFunction
state.setEnterFunc(types.MethodType(newFunction,
enterFunc.__self__))
count += 1
if type(exitFunc) == types.MethodType:
if isinstance(exitFunc, types.MethodType):
if exitFunc.__func__ == oldFunction:
# print 'found: ', exitFunc, oldFunction
state.setExitFunc(types.MethodType(newFunction,
@ -62,19 +62,19 @@ class State(DirectObject):
# setters and getters
def getName(self):
return(self.__name)
return self.__name
def setName(self, stateName):
self.__name = stateName
def getEnterFunc(self):
return(self.__enterFunc)
return self.__enterFunc
def setEnterFunc(self, stateEnterFunc):
self.__enterFunc = stateEnterFunc
def getExitFunc(self):
return(self.__exitFunc)
return self.__exitFunc
def setExitFunc(self, stateExitFunc):
self.__exitFunc = stateExitFunc
@ -99,9 +99,9 @@ class State(DirectObject):
return 1
# if we're given a state object, get its name instead
if type(otherState) != type(''):
if not isinstance(otherState, str):
otherState = otherState.getName()
return (otherState in self.__transitions)
return otherState in self.__transitions
def setTransitions(self, stateTransitions):
"""setTransitions(self, string[])"""
@ -119,7 +119,7 @@ class State(DirectObject):
if __debug__:
def getInspectorPos(self):
"""getInspectorPos(self)"""
return(self.__inspectorPos)
return self.__inspectorPos
def setInspectorPos(self, inspectorPos):
"""setInspectorPos(self, [x, y])"""
@ -131,7 +131,7 @@ class State(DirectObject):
"""
Return the list of child FSMs
"""
return(self.__FSMList)
return self.__FSMList
def setChildren(self, FSMList):
"""setChildren(self, ClassicFSM[])
@ -196,7 +196,7 @@ class State(DirectObject):
# state that is safe to enter
self.__enterChildren(argList)
if (self.__enterFunc != None):
if self.__enterFunc is not None:
self.__enterFunc(*argList)
def exit(self, argList=[]):
@ -207,7 +207,7 @@ class State(DirectObject):
self.__exitChildren(argList)
# call exit function if it exists
if (self.__exitFunc != None):
if self.__exitFunc is not None:
self.__exitFunc(*argList)
def __str__(self):

View File

@ -408,6 +408,7 @@ class AttrSetter(StateChangeNode):
StateChangeNode._handleStateChange(self)
if __debug__:
from direct.showbase.PythonUtil import ScratchPad
o = ScratchPad()
svar = StateVar(0)
aset = AttrSetter(svar, o, 'testAttr')

View File

@ -126,5 +126,3 @@ class DirectButton(DirectFrame):
self.guiItem.setSound(DGG.ENTER + self.guiId, rolloverSound)
else:
self.guiItem.clearSound(DGG.ENTER + self.guiId)

View File

@ -56,4 +56,3 @@ class DirectCheckBox(DirectButton):
if self['command']:
# Pass any extra args to command
self['command'](*[self['isChecked']] + self['extraArgs'])

View File

@ -61,12 +61,12 @@ class DirectCheckButton(DirectButton):
# Call option initialization functions
self.initialiseoptions(DirectCheckButton)
# After initialization with X giving it the correct size, put back space
if self['boxImage'] == None:
if self['boxImage'] is None:
self.indicator['text'] = (' ', '*')
self.indicator['text_pos'] = (0, -.2)
else:
self.indicator['text'] = (' ', ' ')
if self['boxImageColor'] != None and self['boxImage'] != None:
if self['boxImageColor'] is not None and self['boxImage'] is not None:
self.colors = [VBase4(0, 0, 0, 0), self['boxImageColor']]
self.component('indicator')['image_color'] = VBase4(0, 0, 0, 0)
@ -84,7 +84,7 @@ class DirectCheckButton(DirectButton):
else:
# Use ready state to compute bounds
frameType = self.frameStyle[0].getType()
if fClearFrame and (frameType != PGFrameStyle.TNone):
if fClearFrame and frameType != PGFrameStyle.TNone:
self.frameStyle[0].setType(PGFrameStyle.TNone)
self.guiItem.setFrameStyle(0, self.frameStyle[0])
# To force an update of the button
@ -92,7 +92,7 @@ class DirectCheckButton(DirectButton):
# Clear out frame before computing bounds
self.getBounds()
# Restore frame style if necessary
if (frameType != PGFrameStyle.TNone):
if frameType != PGFrameStyle.TNone:
self.frameStyle[0].setType(frameType)
self.guiItem.setFrameStyle(0, self.frameStyle[0])
@ -170,7 +170,7 @@ class DirectCheckButton(DirectButton):
def commandFunc(self, event):
self['indicatorValue'] = 1 - self['indicatorValue']
if self.colors != None:
if self.colors is not None:
self.component('indicator')['image_color'] = self.colors[self['indicatorValue']]
if self['command']:
@ -179,12 +179,5 @@ class DirectCheckButton(DirectButton):
def setIndicatorValue(self):
self.component('indicator').guiItem.setState(self['indicatorValue'])
if self.colors != None:
if self.colors is not None:
self.component('indicator')['image_color'] = self.colors[self['indicatorValue']]

Some files were not shown because too many files have changed in this diff Show More