diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000000..7a7400e831 --- /dev/null +++ b/.pylintrc @@ -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*(# )??$ + +# 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 diff --git a/direct/src/actor/Actor.py b/direct/src/actor/Actor.py index 9cd05f13c7..806706d2b8 100644 --- a/direct/src/actor/Actor.py +++ b/direct/src/actor/Actor.py @@ -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: diff --git a/direct/src/actor/DistributedActor.py b/direct/src/actor/DistributedActor.py index c46a8863c4..1e45113032 100644 --- a/direct/src/actor/DistributedActor.py +++ b/direct/src/actor/DistributedActor.py @@ -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) diff --git a/direct/src/cluster/ClusterClient.py b/direct/src/cluster/ClusterClient.py index 969ba9e860..2908cee1b9 100644 --- a/direct/src/cluster/ClusterClient.py +++ b/direct/src/cluster/ClusterClient.py @@ -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__) - - diff --git a/direct/src/cluster/ClusterConfig.py b/direct/src/cluster/ClusterConfig.py index a22e98b7db..25095f4090 100644 --- a/direct/src/cluster/ClusterConfig.py +++ b/direct/src/cluster/ClusterConfig.py @@ -165,4 +165,3 @@ ClientConfigs = { } ], } - diff --git a/direct/src/cluster/ClusterMsgs.py b/direct/src/cluster/ClusterMsgs.py index 7de69420b9..a1e4fa8816 100644 --- a/direct/src/cluster/ClusterMsgs.py +++ b/direct/src/cluster/ClusterMsgs.py @@ -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) - - - - - - - - - diff --git a/direct/src/cluster/ClusterServer.py b/direct/src/cluster/ClusterServer.py index 511dc84cef..943bbb129c 100644 --- a/direct/src/cluster/ClusterServer.py +++ b/direct/src/cluster/ClusterServer.py @@ -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 - - diff --git a/direct/src/controls/BattleWalker.py b/direct/src/controls/BattleWalker.py index 104dc3e55b..10d51e01c1 100755 --- a/direct/src/controls/BattleWalker.py +++ b/direct/src/controls/BattleWalker.py @@ -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 - - diff --git a/direct/src/controls/ControlManager.py b/direct/src/controls/ControlManager.py index db5d6654fb..18e0fec0f3 100755 --- a/direct/src/controls/ControlManager.py +++ b/direct/src/controls/ControlManager.py @@ -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) - diff --git a/direct/src/controls/DevWalker.py b/direct/src/controls/DevWalker.py index 460b6c83f6..da6f139185 100755 --- a/direct/src/controls/DevWalker.py +++ b/direct/src/controls/DevWalker.py @@ -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 * diff --git a/direct/src/controls/GravityWalker.py b/direct/src/controls/GravityWalker.py index 28d047d6f0..6d5e78ffd9 100755 --- a/direct/src/controls/GravityWalker.py +++ b/direct/src/controls/GravityWalker.py @@ -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 diff --git a/direct/src/controls/InputState.py b/direct/src/controls/InputState.py index 1be5d6fbfe..72939032d6 100755 --- a/direct/src/controls/InputState.py +++ b/direct/src/controls/InputState.py @@ -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: diff --git a/direct/src/controls/NonPhysicsWalker.py b/direct/src/controls/NonPhysicsWalker.py index 0b9c67f5e6..871dcf69d8 100755 --- a/direct/src/controls/NonPhysicsWalker.py +++ b/direct/src/controls/NonPhysicsWalker.py @@ -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 diff --git a/direct/src/controls/ObserverWalker.py b/direct/src/controls/ObserverWalker.py index 3fbdaeaed6..040971a538 100755 --- a/direct/src/controls/ObserverWalker.py +++ b/direct/src/controls/ObserverWalker.py @@ -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 diff --git a/direct/src/controls/PhysicsWalker.py b/direct/src/controls/PhysicsWalker.py index 3743f25ac9..1710550606 100755 --- a/direct/src/controls/PhysicsWalker.py +++ b/direct/src/controls/PhysicsWalker.py @@ -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): diff --git a/direct/src/controls/TwoDWalker.py b/direct/src/controls/TwoDWalker.py index 58fa913959..11319ee273 100644 --- a/direct/src/controls/TwoDWalker.py +++ b/direct/src/controls/TwoDWalker.py @@ -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 diff --git a/direct/src/directbase/TestStart.py b/direct/src/directbase/TestStart.py index 7cb8ae37c7..b89526b210 100755 --- a/direct/src/directbase/TestStart.py +++ b/direct/src/directbase/TestStart.py @@ -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) diff --git a/direct/src/directbase/ThreeUpStart.py b/direct/src/directbase/ThreeUpStart.py index 87158c937a..a9fc95a1f0 100644 --- a/direct/src/directbase/ThreeUpStart.py +++ b/direct/src/directbase/ThreeUpStart.py @@ -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) diff --git a/direct/src/directdevices/DirectDeviceManager.py b/direct/src/directdevices/DirectDeviceManager.py index 1ee3be6507..4e1228418b 100644 --- a/direct/src/directdevices/DirectDeviceManager.py +++ b/direct/src/directdevices/DirectDeviceManager.py @@ -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 diff --git a/direct/src/directdevices/DirectFastrak.py b/direct/src/directdevices/DirectFastrak.py index adc275ca0b..1fda9f74cb 100644 --- a/direct/src/directdevices/DirectFastrak.py +++ b/direct/src/directdevices/DirectFastrak.py @@ -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))) - diff --git a/direct/src/directdevices/DirectJoybox.py b/direct/src/directdevices/DirectJoybox.py index 60c4c4211b..75bb83cbd6 100644 --- a/direct/src/directdevices/DirectJoybox.py +++ b/direct/src/directdevices/DirectJoybox.py @@ -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 - - diff --git a/direct/src/directdevices/DirectRadamec.py b/direct/src/directdevices/DirectRadamec.py index 3f74162b9b..7cb62bdc7d 100644 --- a/direct/src/directdevices/DirectRadamec.py +++ b/direct/src/directdevices/DirectRadamec.py @@ -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 diff --git a/direct/src/directnotify/DirectNotify.py b/direct/src/directnotify/DirectNotify.py index 14a712bd40..97419ac67a 100644 --- a/direct/src/directnotify/DirectNotify.py +++ b/direct/src/directnotify/DirectNotify.py @@ -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): """ diff --git a/direct/src/directnotify/Logger.py b/direct/src/directnotify/Logger.py index 844dead3d5..0c5aeaab04 100644 --- a/direct/src/directnotify/Logger.py +++ b/direct/src/directnotify/Logger.py @@ -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) diff --git a/direct/src/directnotify/Notifier.py b/direct/src/directnotify/Notifier.py index 571d7f43b0..156723ed93 100644 --- a/direct/src/directnotify/Notifier.py +++ b/direct/src/directnotify/Notifier.py @@ -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") - diff --git a/direct/src/directscripts/eggcacher.py b/direct/src/directscripts/eggcacher.py index 6dcee8e2d3..ee01a24b06 100644 --- a/direct/src/directscripts/eggcacher.py +++ b/direct/src/directscripts/eggcacher.py @@ -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() diff --git a/direct/src/directscripts/extract_docs.py b/direct/src/directscripts/extract_docs.py index 68f3671193..e7d0a08c47 100644 --- a/direct/src/directscripts/extract_docs.py +++ b/direct/src/directscripts/extract_docs.py @@ -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 * diff --git a/direct/src/directtools/DirectCameraControl.py b/direct/src/directtools/DirectCameraControl.py index 7870fb09f5..66d3aa0928 100644 --- a/direct/src/directtools/DirectCameraControl.py +++ b/direct/src/directtools/DirectCameraControl.py @@ -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() - diff --git a/direct/src/directtools/DirectGeometry.py b/direct/src/directtools/DirectGeometry.py index 2c69a8d8d5..b97031dc50 100644 --- a/direct/src/directtools/DirectGeometry.py +++ b/direct/src/directtools/DirectGeometry.py @@ -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 - diff --git a/direct/src/directtools/DirectGlobals.py b/direct/src/directtools/DirectGlobals.py index 9d10a3f691..719e60dc39 100644 --- a/direct/src/directtools/DirectGlobals.py +++ b/direct/src/directtools/DirectGlobals.py @@ -59,4 +59,3 @@ def LE_showInOneCam(nodePath, thisCamName): for camName in LE_CAM_MASKS: if camName != thisCamName: nodePath.hide(LE_CAM_MASKS[camName]) - diff --git a/direct/src/directtools/DirectGrid.py b/direct/src/directtools/DirectGrid.py index 80d8280ec0..15182e0ad7 100644 --- a/direct/src/directtools/DirectGrid.py +++ b/direct/src/directtools/DirectGrid.py @@ -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): diff --git a/direct/src/directtools/DirectLights.py b/direct/src/directtools/DirectLights.py index f20f08aca7..62c2685731 100644 --- a/direct/src/directtools/DirectLights.py +++ b/direct/src/directtools/DirectLights.py @@ -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) - - - diff --git a/direct/src/directtools/DirectManipulation.py b/direct/src/directtools/DirectManipulation.py index 8a07b14702..0607e42bf4 100644 --- a/direct/src/directtools/DirectManipulation.py +++ b/direct/src/directtools/DirectManipulation.py @@ -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) diff --git a/direct/src/directtools/DirectSelection.py b/direct/src/directtools/DirectSelection.py index 3352705544..2e0848ab81 100644 --- a/direct/src/directtools/DirectSelection.py +++ b/direct/src/directtools/DirectSelection.py @@ -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) - diff --git a/direct/src/directtools/DirectSession.py b/direct/src/directtools/DirectSession.py index 087348dfad..607171cf49 100644 --- a/direct/src/directtools/DirectSession.py +++ b/direct/src/directtools/DirectSession.py @@ -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() diff --git a/direct/src/directtools/DirectUtil.py b/direct/src/directtools/DirectUtil.py index 43d46831cb..1d7cc60015 100644 --- a/direct/src/directtools/DirectUtil.py +++ b/direct/src/directtools/DirectUtil.py @@ -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 - diff --git a/direct/src/directutil/DistributedLargeBlobSender.py b/direct/src/directutil/DistributedLargeBlobSender.py index 35b46761a7..42ed01b36f 100755 --- a/direct/src/directutil/DistributedLargeBlobSender.py +++ b/direct/src/directutil/DistributedLargeBlobSender.py @@ -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""" diff --git a/direct/src/directutil/DistributedLargeBlobSenderAI.py b/direct/src/directutil/DistributedLargeBlobSenderAI.py index 514033face..aed6d7054d 100755 --- a/direct/src/directutil/DistributedLargeBlobSenderAI.py +++ b/direct/src/directutil/DistributedLargeBlobSenderAI.py @@ -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:] diff --git a/direct/src/directutil/Mopath.py b/direct/src/directutil/Mopath.py index 05e437d34d..08a9363211 100644 --- a/direct/src/directutil/Mopath.py +++ b/direct/src/directutil/Mopath.py @@ -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()) - diff --git a/direct/src/dist/FreezeTool.py b/direct/src/dist/FreezeTool.py index 95d94c2ced..bb06c69fe1 100644 --- a/direct/src/dist/FreezeTool.py +++ b/direct/src/dist/FreezeTool.py @@ -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, diff --git a/direct/src/dist/commands.py b/direct/src/dist/commands.py index 191a5c019a..9da0a06cfa 100644 --- a/direct/src/dist/commands.py +++ b/direct/src/dist/commands.py @@ -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. """ diff --git a/direct/src/dist/icon.py b/direct/src/dist/icon.py index 2fbe38841a..8e062b3cd1 100644 --- a/direct/src/dist/icon.py +++ b/direct/src/dist/icon.py @@ -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: diff --git a/direct/src/dist/installers.py b/direct/src/dist/installers.py index 3d84fd4306..f1234d3ad1 100644 --- a/direct/src/dist/installers.py +++ b/direct/src/dist/installers.py @@ -170,4 +170,3 @@ def create_nsis(command, basename, build_dir): ) cmd.append(nsifile.to_os_specific()) subprocess.check_call(cmd) - diff --git a/direct/src/dist/pefile.py b/direct/src/dist/pefile.py index 9ab9071eb6..002c758d2d 100755 --- a/direct/src/dist/pefile.py +++ b/direct/src/dist/pefile.py @@ -487,6 +487,8 @@ class ResourceTable(object): entry.data = data entry.code_page = code_page + return entry + class PEFile(object): diff --git a/direct/src/dist/pfreeze.py b/direct/src/dist/pfreeze.py index 112dbcca0b..1f71744ba2 100755 --- a/direct/src/dist/pfreeze.py +++ b/direct/src/dist/pfreeze.py @@ -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: diff --git a/direct/src/distributed/AsyncRequest.py b/direct/src/distributed/AsyncRequest.py index 10e00f3765..533cedf9bf 100755 --- a/direct/src/distributed/AsyncRequest.py +++ b/direct/src/distributed/AsyncRequest.py @@ -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 diff --git a/direct/src/distributed/CRCache.py b/direct/src/distributed/CRCache.py index b256c4f13e..b35220814d 100644 --- a/direct/src/distributed/CRCache.py +++ b/direct/src/distributed/CRCache.py @@ -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() diff --git a/direct/src/distributed/CRDataCache.py b/direct/src/distributed/CRDataCache.py index b28453c0a3..43c87a015b 100755 --- a/direct/src/distributed/CRDataCache.py +++ b/direct/src/distributed/CRDataCache.py @@ -114,4 +114,3 @@ if __debug__: dc._stopMemLeakCheck() dc.destroy() del dc - diff --git a/direct/src/distributed/CartesianGridBase.py b/direct/src/distributed/CartesianGridBase.py index f5e9d90339..07e63ae941 100755 --- a/direct/src/distributed/CartesianGridBase.py +++ b/direct/src/distributed/CartesianGridBase.py @@ -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: diff --git a/direct/src/distributed/ClientRepository.py b/direct/src/distributed/ClientRepository.py index b3745c1355..e0866af4b7 100644 --- a/direct/src/distributed/ClientRepository.py +++ b/direct/src/distributed/ClientRepository.py @@ -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 diff --git a/direct/src/distributed/ClientRepositoryBase.py b/direct/src/distributed/ClientRepositoryBase.py index 5aa7c3fa94..5b8336f397 100644 --- a/direct/src/distributed/ClientRepositoryBase.py +++ b/direct/src/distributed/ClientRepositoryBase.py @@ -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() diff --git a/direct/src/distributed/ClockDelta.py b/direct/src/distributed/ClockDelta.py index 3a3705d5eb..544e2f644f 100644 --- a/direct/src/distributed/ClockDelta.py +++ b/direct/src/distributed/ClockDelta.py @@ -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 diff --git a/direct/src/distributed/ConnectionRepository.py b/direct/src/distributed/ConnectionRepository.py index d77802c7ff..be50ebd96a 100644 --- a/direct/src/distributed/ConnectionRepository.py +++ b/direct/src/distributed/ConnectionRepository.py @@ -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 diff --git a/direct/src/distributed/DistributedCamera.py b/direct/src/distributed/DistributedCamera.py index 8c9b076338..43a492ea45 100755 --- a/direct/src/distributed/DistributedCamera.py +++ b/direct/src/distributed/DistributedCamera.py @@ -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) diff --git a/direct/src/distributed/DistributedCartesianGrid.py b/direct/src/distributed/DistributedCartesianGrid.py index 3942f3a154..9f124521a9 100755 --- a/direct/src/distributed/DistributedCartesianGrid.py +++ b/direct/src/distributed/DistributedCartesianGrid.py @@ -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, diff --git a/direct/src/distributed/DistributedCartesianGridAI.py b/direct/src/distributed/DistributedCartesianGridAI.py index 370906cccc..e8516ee4ba 100755 --- a/direct/src/distributed/DistributedCartesianGridAI.py +++ b/direct/src/distributed/DistributedCartesianGridAI.py @@ -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) - diff --git a/direct/src/distributed/DistributedNode.py b/direct/src/distributed/DistributedNode.py index 1a88fcc02a..85cd78de3e 100644 --- a/direct/src/distributed/DistributedNode.py +++ b/direct/src/distributed/DistributedNode.py @@ -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]) diff --git a/direct/src/distributed/DistributedNodeAI.py b/direct/src/distributed/DistributedNodeAI.py index f119ee6a93..8fb607c6e6 100644 --- a/direct/src/distributed/DistributedNodeAI.py +++ b/direct/src/distributed/DistributedNodeAI.py @@ -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]) diff --git a/direct/src/distributed/DistributedNodeUD.py b/direct/src/distributed/DistributedNodeUD.py index 2c83b21c07..484441e3a1 100755 --- a/direct/src/distributed/DistributedNodeUD.py +++ b/direct/src/distributed/DistributedNodeUD.py @@ -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]) diff --git a/direct/src/distributed/DistributedObject.py b/direct/src/distributed/DistributedObject.py index 84870b890c..5ddd900fa3 100644 --- a/direct/src/distributed/DistributedObject.py +++ b/direct/src/distributed/DistributedObject.py @@ -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 diff --git a/direct/src/distributed/DistributedObjectAI.py b/direct/src/distributed/DistributedObjectAI.py index 32b2374fc5..9b3878a6ff 100644 --- a/direct/src/distributed/DistributedObjectAI.py +++ b/direct/src/distributed/DistributedObjectAI.py @@ -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) diff --git a/direct/src/distributed/DistributedObjectBase.py b/direct/src/distributed/DistributedObjectBase.py index 066466df1d..aa0647a96a 100755 --- a/direct/src/distributed/DistributedObjectBase.py +++ b/direct/src/distributed/DistributedObjectBase.py @@ -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 diff --git a/direct/src/distributed/DistributedObjectGlobal.py b/direct/src/distributed/DistributedObjectGlobal.py index 6414f70990..0298f19d5f 100755 --- a/direct/src/distributed/DistributedObjectGlobal.py +++ b/direct/src/distributed/DistributedObjectGlobal.py @@ -21,4 +21,3 @@ class DistributedObjectGlobal(DistributedObject): DistributedObject.__init__(self, cr) self.parentId = 0 self.zoneId = 0 - diff --git a/direct/src/distributed/DistributedObjectGlobalAI.py b/direct/src/distributed/DistributedObjectGlobalAI.py index 28ce8d2c7d..11bee0df72 100755 --- a/direct/src/distributed/DistributedObjectGlobalAI.py +++ b/direct/src/distributed/DistributedObjectGlobalAI.py @@ -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) - diff --git a/direct/src/distributed/DistributedObjectGlobalUD.py b/direct/src/distributed/DistributedObjectGlobalUD.py index 34cfa3a213..6000978c20 100755 --- a/direct/src/distributed/DistributedObjectGlobalUD.py +++ b/direct/src/distributed/DistributedObjectGlobalUD.py @@ -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): diff --git a/direct/src/distributed/DistributedObjectOV.py b/direct/src/distributed/DistributedObjectOV.py index 52ed2d13be..aafba0dbda 100755 --- a/direct/src/distributed/DistributedObjectOV.py +++ b/direct/src/distributed/DistributedObjectOV.py @@ -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()) diff --git a/direct/src/distributed/DistributedObjectUD.py b/direct/src/distributed/DistributedObjectUD.py index 99762cc1d3..24f18bd2b2 100755 --- a/direct/src/distributed/DistributedObjectUD.py +++ b/direct/src/distributed/DistributedObjectUD.py @@ -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 diff --git a/direct/src/distributed/DistributedSmoothNode.py b/direct/src/distributed/DistributedSmoothNode.py index 282ec5b88d..372a3b281e 100644 --- a/direct/src/distributed/DistributedSmoothNode.py +++ b/direct/src/distributed/DistributedSmoothNode.py @@ -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 diff --git a/direct/src/distributed/DistributedSmoothNodeAI.py b/direct/src/distributed/DistributedSmoothNodeAI.py index fe8ec19b1c..d2071fd8e0 100755 --- a/direct/src/distributed/DistributedSmoothNodeAI.py +++ b/direct/src/distributed/DistributedSmoothNodeAI.py @@ -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 - diff --git a/direct/src/distributed/DistributedSmoothNodeBase.py b/direct/src/distributed/DistributedSmoothNodeBase.py index 8f7d1c31e4..affd8d609e 100755 --- a/direct/src/distributed/DistributedSmoothNodeBase.py +++ b/direct/src/distributed/DistributedSmoothNodeBase.py @@ -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() - diff --git a/direct/src/distributed/DoCollectionManager.py b/direct/src/distributed/DoCollectionManager.py index f36aedb6d9..21eeb10751 100755 --- a/direct/src/distributed/DoCollectionManager.py +++ b/direct/src/distributed/DoCollectionManager.py @@ -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: diff --git a/direct/src/distributed/DoHierarchy.py b/direct/src/distributed/DoHierarchy.py index c7283f4ac2..a1248e697a 100755 --- a/direct/src/distributed/DoHierarchy.py +++ b/direct/src/distributed/DoHierarchy.py @@ -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: diff --git a/direct/src/distributed/DoInterestManager.py b/direct/src/distributed/DoInterestManager.py index 08a2f21657..382abc48dd 100755 --- a/direct/src/distributed/DoInterestManager.py +++ b/direct/src/distributed/DoInterestManager.py @@ -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: diff --git a/direct/src/distributed/GridChild.py b/direct/src/distributed/GridChild.py index 462c4d841e..c9f986f2c5 100755 --- a/direct/src/distributed/GridChild.py +++ b/direct/src/distributed/GridChild.py @@ -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 diff --git a/direct/src/distributed/GridParent.py b/direct/src/distributed/GridParent.py index 5d5d47b8e5..c17d980c27 100755 --- a/direct/src/distributed/GridParent.py +++ b/direct/src/distributed/GridParent.py @@ -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())) diff --git a/direct/src/distributed/InterestWatcher.py b/direct/src/distributed/InterestWatcher.py index 094be3a677..b6b541e86e 100755 --- a/direct/src/distributed/InterestWatcher.py +++ b/direct/src/distributed/InterestWatcher.py @@ -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)) diff --git a/direct/src/distributed/NetMessenger.py b/direct/src/distributed/NetMessenger.py index 818c49f819..5dab015fb5 100755 --- a/direct/src/distributed/NetMessenger.py +++ b/direct/src/distributed/NetMessenger.py @@ -90,5 +90,3 @@ class NetMessenger(Messenger): else: (message, sentArgs) = loads(pickleData) Messenger.send(self, message, sentArgs=sentArgs) - - diff --git a/direct/src/distributed/ParentMgr.py b/direct/src/distributed/ParentMgr.py index 6e52b1097b..056c6e8f0e 100644 --- a/direct/src/distributed/ParentMgr.py +++ b/direct/src/distributed/ParentMgr.py @@ -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))) diff --git a/direct/src/distributed/PyDatagram.py b/direct/src/distributed/PyDatagram.py index 1f1f56ad16..98d4ed8504 100755 --- a/direct/src/distributed/PyDatagram.py +++ b/direct/src/distributed/PyDatagram.py @@ -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 diff --git a/direct/src/distributed/RelatedObjectMgr.py b/direct/src/distributed/RelatedObjectMgr.py index a2c00b2ea0..09a3fddc51 100644 --- a/direct/src/distributed/RelatedObjectMgr.py +++ b/direct/src/distributed/RelatedObjectMgr.py @@ -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 - diff --git a/direct/src/distributed/ServerRepository.py b/direct/src/distributed/ServerRepository.py index 6e0ef837a0..757a7c392f 100644 --- a/direct/src/distributed/ServerRepository.py +++ b/direct/src/distributed/ServerRepository.py @@ -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())) diff --git a/direct/src/distributed/StagedObject.py b/direct/src/distributed/StagedObject.py index 3127bd6e06..e96e6540b7 100755 --- a/direct/src/distributed/StagedObject.py +++ b/direct/src/distributed/StagedObject.py @@ -61,4 +61,3 @@ class StagedObject: def isOffStage(self): return self.__state == StagedObject.OFF - diff --git a/direct/src/distributed/TimeManager.py b/direct/src/distributed/TimeManager.py index 714abd7f7d..8b5d228c79 100644 --- a/direct/src/distributed/TimeManager.py +++ b/direct/src/distributed/TimeManager.py @@ -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') - diff --git a/direct/src/distributed/TimeManagerAI.py b/direct/src/distributed/TimeManagerAI.py index 2e235523ce..fab2e8090f 100644 --- a/direct/src/distributed/TimeManagerAI.py +++ b/direct/src/distributed/TimeManagerAI.py @@ -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): diff --git a/direct/src/extensions_native/CInterval_extensions.py b/direct/src/extensions_native/CInterval_extensions.py index 5435eab962..09429970a1 100644 --- a/direct/src/extensions_native/CInterval_extensions.py +++ b/direct/src/extensions_native/CInterval_extensions.py @@ -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) diff --git a/direct/src/extensions_native/HTTPChannel_extensions.py b/direct/src/extensions_native/HTTPChannel_extensions.py index 3d87a97bc9..f078eaceba 100644 --- a/direct/src/extensions_native/HTTPChannel_extensions.py +++ b/direct/src/extensions_native/HTTPChannel_extensions.py @@ -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 diff --git a/direct/src/extensions_native/Mat3_extensions.py b/direct/src/extensions_native/Mat3_extensions.py index 28e862ca78..8bc175c190 100644 --- a/direct/src/extensions_native/Mat3_extensions.py +++ b/direct/src/extensions_native/Mat3_extensions.py @@ -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 ##################################################################### diff --git a/direct/src/extensions_native/NodePath_extensions.py b/direct/src/extensions_native/NodePath_extensions.py index ffb55daceb..b3cf352b71 100644 --- a/direct/src/extensions_native/NodePath_extensions.py +++ b/direct/src/extensions_native/NodePath_extensions.py @@ -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: diff --git a/direct/src/filter/CommonFilters.py b/direct/src/filter/CommonFilters.py index 26601ced2e..f31c9803df 100644 --- a/direct/src/filter/CommonFilters.py +++ b/direct/src/filter/CommonFilters.py @@ -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 diff --git a/direct/src/filter/FilterManager.py b/direct/src/filter/FilterManager.py index e670a36125..2a0dfb2852 100644 --- a/direct/src/filter/FilterManager.py +++ b/direct/src/filter/FilterManager.py @@ -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() diff --git a/direct/src/fsm/ClassicFSM.py b/direct/src/fsm/ClassicFSM.py index 18c0bd6a4d..ef44692138 100644 --- a/direct/src/fsm/ClassicFSM.py +++ b/direct/src/fsm/ClassicFSM.py @@ -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 - - - - - - - - diff --git a/direct/src/fsm/FSM.py b/direct/src/fsm/FSM.py index 8236b64a75..93d11df21e 100644 --- a/direct/src/fsm/FSM.py +++ b/direct/src/fsm/FSM.py @@ -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: diff --git a/direct/src/fsm/FourState.py b/direct/src/fsm/FourState.py index 65a5b5b807..8322273d27 100755 --- a/direct/src/fsm/FourState.py +++ b/direct/src/fsm/FourState.py @@ -212,4 +212,3 @@ class FourState: """for debugging""" return self.notify.debug("%d (%d) %s"%( id(self), self.stateIndex==4, message)) - diff --git a/direct/src/fsm/FourStateAI.py b/direct/src/fsm/FourStateAI.py index 09c83e7486..284d3b3cb8 100755 --- a/direct/src/fsm/FourStateAI.py +++ b/direct/src/fsm/FourStateAI.py @@ -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)) - diff --git a/direct/src/fsm/SampleFSM.py b/direct/src/fsm/SampleFSM.py index 9db513afa2..6a60c18b32 100644 --- a/direct/src/fsm/SampleFSM.py +++ b/direct/src/fsm/SampleFSM.py @@ -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): diff --git a/direct/src/fsm/State.py b/direct/src/fsm/State.py index 8c53d205fd..f80507a538 100644 --- a/direct/src/fsm/State.py +++ b/direct/src/fsm/State.py @@ -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): diff --git a/direct/src/fsm/StatePush.py b/direct/src/fsm/StatePush.py index fe0f496158..fe90d45f5d 100755 --- a/direct/src/fsm/StatePush.py +++ b/direct/src/fsm/StatePush.py @@ -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') diff --git a/direct/src/gui/DirectButton.py b/direct/src/gui/DirectButton.py index 5cf8a91e9e..f1fd744af6 100644 --- a/direct/src/gui/DirectButton.py +++ b/direct/src/gui/DirectButton.py @@ -126,5 +126,3 @@ class DirectButton(DirectFrame): self.guiItem.setSound(DGG.ENTER + self.guiId, rolloverSound) else: self.guiItem.clearSound(DGG.ENTER + self.guiId) - - diff --git a/direct/src/gui/DirectCheckBox.py b/direct/src/gui/DirectCheckBox.py index 26b561edaf..adaf11258d 100755 --- a/direct/src/gui/DirectCheckBox.py +++ b/direct/src/gui/DirectCheckBox.py @@ -56,4 +56,3 @@ class DirectCheckBox(DirectButton): if self['command']: # Pass any extra args to command self['command'](*[self['isChecked']] + self['extraArgs']) - diff --git a/direct/src/gui/DirectCheckButton.py b/direct/src/gui/DirectCheckButton.py index ed74c3eef7..22f7a88f93 100644 --- a/direct/src/gui/DirectCheckButton.py +++ b/direct/src/gui/DirectCheckButton.py @@ -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']] - - - - - - - diff --git a/direct/src/gui/DirectDialog.py b/direct/src/gui/DirectDialog.py index b6401c7a7a..7e9fce72a7 100644 --- a/direct/src/gui/DirectDialog.py +++ b/direct/src/gui/DirectDialog.py @@ -14,7 +14,6 @@ from direct.showbase import ShowBaseGlobal from . import DirectGuiGlobals as DGG from .DirectFrame import * from .DirectButton import * -import types def findDialog(uniqueName): @@ -191,8 +190,7 @@ class DirectDialog(DirectFrame): bindList = zip(self.buttonList, self['buttonHotKeyList'], self['buttonValueList']) for button, hotKey, value in bindList: - if ((type(hotKey) == list) or - (type(hotKey) == tuple)): + if isinstance(hotKey, (list, tuple)): for key in hotKey: button.bind('press-' + key + '-', self.buttonCommand, extraArgs = [value]) @@ -278,13 +276,10 @@ class DirectDialog(DirectFrame): # Must compensate for scale scale = self['button_scale'] # Can either be a Vec3 or a tuple of 3 values - if (isinstance(scale, Vec3) or - (type(scale) == list) or - (type(scale) == tuple)): + if isinstance(scale, (VBase3, list, tuple)): sx = scale[0] sz = scale[2] - elif ((type(scale) == int) or - (type(scale) == float)): + elif isinstance(scale, (int, float)): sx = sz = scale else: sx = sz = 1 @@ -426,4 +421,3 @@ class RetryCancelDialog(DirectDialog): self.defineoptions(kw, optiondefs) DirectDialog.__init__(self, parent) self.initialiseoptions(RetryCancelDialog) - diff --git a/direct/src/gui/DirectEntry.py b/direct/src/gui/DirectEntry.py index 1c20141a14..cc402d853e 100644 --- a/direct/src/gui/DirectEntry.py +++ b/direct/src/gui/DirectEntry.py @@ -89,7 +89,7 @@ class DirectEntry(DirectFrame): # Initialize superclasses DirectFrame.__init__(self, parent) - if self['entryFont'] == None: + if self['entryFont'] is None: font = DGG.getDefaultFont() else: font = self['entryFont'] @@ -241,13 +241,13 @@ class DirectEntry(DirectFrame): if wasNonWordChar: # first letter of a word, capitalize it unconditionally; capitalize = True - elif (character == character.upper() and - len(self.autoCapitalizeAllowPrefixes) and - wordSoFar in self.autoCapitalizeAllowPrefixes): + elif character == character.upper() and \ + len(self.autoCapitalizeAllowPrefixes) > 0 and \ + wordSoFar in self.autoCapitalizeAllowPrefixes: # first letter after one of the prefixes, allow it to be capitalized capitalize = True - elif (len(self.autoCapitalizeForcePrefixes) and - wordSoFar in self.autoCapitalizeForcePrefixes): + elif len(self.autoCapitalizeForcePrefixes) > 0 and \ + wordSoFar in self.autoCapitalizeForcePrefixes: # first letter after one of the force prefixes, force it to be capitalized capitalize = True if capitalize: @@ -304,7 +304,7 @@ class DirectEntry(DirectFrame): return self.guiItem.getCursorPosition() def setCursorPosition(self, pos): - if (pos < 0): + if pos < 0: self.guiItem.setCursorPosition(self.guiItem.getNumCharacters() + pos) else: self.guiItem.setCursorPosition(pos) diff --git a/direct/src/gui/DirectEntryScroll.py b/direct/src/gui/DirectEntryScroll.py index fd369b2716..10fc2f6c9d 100644 --- a/direct/src/gui/DirectEntryScroll.py +++ b/direct/src/gui/DirectEntryScroll.py @@ -60,7 +60,8 @@ class DirectEntryScroll(DirectFrame): detaches and unbinds the entry from the scroll frame and its events. You'll be responsible for destroying it. """ - if self.entry is None: return + if self.entry is None: + return self.entry.unbind(DGG.CURSORMOVE) self.entry.detachNode() self.entry = None @@ -136,4 +137,3 @@ class DirectEntryScroll(DirectFrame): def resetCanvas(self): self.canvas.setPos(0,0,0) - diff --git a/direct/src/gui/DirectGui.py b/direct/src/gui/DirectGui.py index 4b6d62b9db..81080475d1 100644 --- a/direct/src/gui/DirectGui.py +++ b/direct/src/gui/DirectGui.py @@ -1,6 +1,6 @@ """Imports all of the :ref:`directgui` classes.""" -from . import DirectGuiGlobals as DGG +from . import DirectGuiGlobals as DGG # pylint: disable=unused-import from .OnscreenText import * from .OnscreenGeom import * from .OnscreenImage import * diff --git a/direct/src/gui/DirectGuiBase.py b/direct/src/gui/DirectGuiBase.py index 21c2b3acd5..6502883976 100644 --- a/direct/src/gui/DirectGuiBase.py +++ b/direct/src/gui/DirectGuiBase.py @@ -90,6 +90,7 @@ __all__ = ['DirectGuiBase', 'DirectGuiWidget'] from panda3d.core import * from direct.showbase import ShowBaseGlobal from direct.showbase.ShowBase import ShowBase +from direct.showbase.MessengerGlobal import messenger from . import DirectGuiGlobals as DGG from .OnscreenText import * from .OnscreenGeom import * @@ -97,6 +98,7 @@ from .OnscreenImage import * from direct.directtools.DirectUtil import ROUND_TO from direct.showbase import DirectObject from direct.task import Task +from direct.task.TaskManagerGlobal import taskMgr guiObjectCollector = PStatCollector("Client::GuiObjects") @@ -433,7 +435,7 @@ class DirectGuiBase(DirectObject.DirectObject): info = optionInfo[option] func = info[DGG._OPT_FUNCTION] if func is not None: - func() + func() # Allow index style references def __setitem__(self, key, value): @@ -557,7 +559,7 @@ class DirectGuiBase(DirectObject.DirectObject): if widgetClass is None: return None # Get arguments for widget constructor - if len(widgetArgs) == 1 and type(widgetArgs[0]) == tuple: + if len(widgetArgs) == 1 and isinstance(widgetArgs[0], tuple): # Arguments to the constructor can be specified as either # multiple trailing arguments to createcomponent() or as a # single tuple argument. @@ -818,7 +820,7 @@ class DirectGuiWidget(DirectGuiBase, NodePath): def editStart(self, event): taskMgr.remove('guiEditTask') - vWidget2render2d = self.getPos(render2d) + vWidget2render2d = self.getPos(ShowBaseGlobal.render2d) vMouse2render2d = Point3(event.getMouse()[0], 0, event.getMouse()[1]) editVec = Vec3(vWidget2render2d - vMouse2render2d) if base.mouseWatcherNode.getModifierButtons().isDown( @@ -844,7 +846,7 @@ class DirectGuiWidget(DirectGuiBase, NodePath): if mwn.hasMouse(): vMouse2render2d = Point3(mwn.getMouse()[0], 0, mwn.getMouse()[1]) newPos = vMouse2render2d + state.editVec - self.setPos(render2d, newPos) + self.setPos(ShowBaseGlobal.render2d, newPos) if DirectGuiWidget.snapToGrid: newPos = self.getPos() newPos.set( @@ -858,9 +860,9 @@ class DirectGuiWidget(DirectGuiBase, NodePath): taskMgr.remove('guiEditTask') def setState(self): - if type(self['state']) == type(0): + if isinstance(self['state'], int): self.guiItem.setActive(self['state']) - elif (self['state'] == DGG.NORMAL) or (self['state'] == 'normal'): + elif self['state'] == DGG.NORMAL or self['state'] == 'normal': self.guiItem.setActive(1) else: self.guiItem.setActive(0) @@ -879,7 +881,7 @@ class DirectGuiWidget(DirectGuiBase, NodePath): bw = (0, 0) else: - 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 @@ -887,12 +889,12 @@ class DirectGuiWidget(DirectGuiBase, NodePath): # 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]) - if ((frameType != PGFrameStyle.TNone) and - (frameType != PGFrameStyle.TFlat)): + if frameType != PGFrameStyle.TNone and \ + frameType != PGFrameStyle.TFlat: bw = self['borderWidth'] else: bw = (0, 0) @@ -952,7 +954,7 @@ class DirectGuiWidget(DirectGuiBase, NodePath): def setRelief(self, fSetStyle = 1): relief = self['relief'] # Convert None, and string arguments - if relief == None: + if relief is None: relief = PGFrameStyle.TNone elif isinstance(relief, str): # Convert string to frame style int @@ -979,8 +981,7 @@ class DirectGuiWidget(DirectGuiBase, NodePath): def setFrameColor(self): # this might be a single color or a list of colors colors = self['frameColor'] - if type(colors[0]) == int or \ - type(colors[0]) == float: + if isinstance(colors[0], (int, float)): colors = (colors,) for i in range(self['numStates']): if i >= len(colors): @@ -993,9 +994,8 @@ class DirectGuiWidget(DirectGuiBase, NodePath): def setFrameTexture(self): # this might be a single texture or a list of textures textures = self['frameTexture'] - if textures == None or \ - isinstance(textures, Texture) or \ - isinstance(textures, str): + if textures is None or \ + isinstance(textures, (Texture, str)): textures = (textures,) * self['numStates'] for i in range(self['numStates']): if i >= len(textures): @@ -1003,7 +1003,7 @@ class DirectGuiWidget(DirectGuiBase, NodePath): else: texture = textures[i] if isinstance(texture, str): - texture = loader.loadTexture(texture) + texture = base.loader.loadTexture(texture) if texture: self.frameStyle[i].setTexture(texture) else: @@ -1077,10 +1077,10 @@ class DirectGuiWidget(DirectGuiBase, NodePath): self[key] = value[1] def taskName(self, idString): - return (idString + "-" + str(self.guiId)) + return idString + "-" + str(self.guiId) def uniqueName(self, idString): - return (idString + "-" + str(self.guiId)) + return idString + "-" + str(self.guiId) def setProp(self, propString, value): """ diff --git a/direct/src/gui/DirectGuiGlobals.py b/direct/src/gui/DirectGuiGlobals.py index 78bf1040e3..7cb985e972 100644 --- a/direct/src/gui/DirectGuiGlobals.py +++ b/direct/src/gui/DirectGuiGlobals.py @@ -123,7 +123,7 @@ def setDefaultClickSound(newSound): def getDefaultFont(): global defaultFont - if defaultFont == None: + if defaultFont is None: defaultFont = defaultFontFunc() return defaultFont diff --git a/direct/src/gui/DirectGuiTest.py b/direct/src/gui/DirectGuiTest.py index c68c705b0e..2a33d1600b 100644 --- a/direct/src/gui/DirectGuiTest.py +++ b/direct/src/gui/DirectGuiTest.py @@ -5,6 +5,7 @@ __all__ = [] if __name__ == "__main__": from direct.showbase.ShowBase import ShowBase + from direct.task.TaskManagerGlobal import taskMgr from . import DirectGuiGlobals from .DirectGui import * #from whrandom import * @@ -14,7 +15,7 @@ if __name__ == "__main__": # EXAMPLE CODE # Load a model - smiley = loader.loadModel('models/misc/smiley') + smiley = base.loader.loadModel('models/misc/smiley') # Here we specify the button's command def dummyCmd(index): diff --git a/direct/src/gui/DirectOptionMenu.py b/direct/src/gui/DirectOptionMenu.py index fe417cfd9f..2adf21cf69 100644 --- a/direct/src/gui/DirectOptionMenu.py +++ b/direct/src/gui/DirectOptionMenu.py @@ -104,7 +104,7 @@ class DirectOptionMenu(DirectButton): Create new popup menu to reflect specified set of items """ # Remove old component if it exits - if self.popupMenu != None: + if self.popupMenu is not None: self.destroycomponent('popupMenu') # Create new component self.popupMenu = self.createcomponent('popupMenu', (), None, @@ -127,19 +127,19 @@ class DirectOptionMenu(DirectButton): text = item, text_align = TextNode.ALeft, command = lambda i = itemIndex: self.set(i)) bounds = c.getBounds() - if self.minX == None: + if self.minX is None: self.minX = bounds[0] elif bounds[0] < self.minX: self.minX = bounds[0] - if self.maxX == None: + if self.maxX is None: self.maxX = bounds[1] elif bounds[1] > self.maxX: self.maxX = bounds[1] - if self.minZ == None: + if self.minZ is None: self.minZ = bounds[2] elif bounds[2] < self.minZ: self.minZ = bounds[2] - if self.maxZ == None: + if self.maxZ is None: self.maxZ = bounds[3] elif bounds[3] > self.maxZ: self.maxZ = bounds[3] @@ -308,4 +308,3 @@ class DirectOptionMenu(DirectButton): Override popup menu button's command func Command is executed in response to selecting menu items """ - pass diff --git a/direct/src/gui/DirectRadioButton.py b/direct/src/gui/DirectRadioButton.py index c679eff334..cbc16698b9 100755 --- a/direct/src/gui/DirectRadioButton.py +++ b/direct/src/gui/DirectRadioButton.py @@ -77,14 +77,14 @@ class DirectRadioButton(DirectButton): self.initialiseoptions(DirectRadioButton) # After initialization with X giving it the correct size, put back space if self['boxGeom'] is None: - if not 'boxRelief' in kw and self['boxImage'] is None: + if 'boxRelief' not in kw and self['boxImage'] is None: self.indicator['relief'] = DGG.SUNKEN self.indicator['text'] = (' ', '*') self.indicator['text_pos'] = (0, -.25) else: self.indicator['text'] = (' ', ' ') - if self['boxGeomColor'] != None and self['boxGeom'] != None: + if self['boxGeomColor'] is not None and self['boxGeom'] is not None: self.colors = [VBase4(1, 1, 1, 0), self['boxGeomColor']] self.component('indicator')['geom_color'] = VBase4(1, 1, 1, 0) @@ -120,7 +120,7 @@ class DirectRadioButton(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]) @@ -160,8 +160,7 @@ class DirectRadioButton(DirectButton): self.bounds[3] += indicatorHeight + (2*self['boxBorder']) # Set frame to new dimensions - if ((frameType != PGFrameStyle.TNone) and - (frameType != PGFrameStyle.TFlat)): + if frameType != PGFrameStyle.TNone and frameType != PGFrameStyle.TFlat: bw = self['borderWidth'] else: bw = (0, 0) @@ -219,10 +218,10 @@ class DirectRadioButton(DirectButton): def uncheck(self): self['indicatorValue'] = 0 - if self.colors != None: + if self.colors is not None: self.component('indicator')['geom_color'] = self.colors[self['indicatorValue']] def setIndicatorValue(self): self.component('indicator').guiItem.setState(self['indicatorValue']) - if self.colors != None: + if self.colors is not None: self.component('indicator')['geom_color'] = self.colors[self['indicatorValue']] diff --git a/direct/src/gui/DirectScrollBar.py b/direct/src/gui/DirectScrollBar.py index 822cb5b3a6..e9540529f2 100644 --- a/direct/src/gui/DirectScrollBar.py +++ b/direct/src/gui/DirectScrollBar.py @@ -11,11 +11,6 @@ from . import DirectGuiGlobals as DGG from .DirectFrame import * from .DirectButton import * -""" -import DirectScrollBar -d = DirectScrollBar(borderWidth=(0, 0)) - -""" class DirectScrollBar(DirectFrame): """ @@ -72,7 +67,7 @@ class DirectScrollBar(DirectFrame): DirectButton, (self,), borderWidth = self['borderWidth']) - if self.decButton['frameSize'] == None and \ + if self.decButton['frameSize'] is None and \ self.decButton.bounds == [0.0, 0.0, 0.0, 0.0]: f = self['frameSize'] if self['orientation'] == DGG.HORIZONTAL: @@ -80,7 +75,7 @@ class DirectScrollBar(DirectFrame): else: self.decButton['frameSize'] = (f[0], f[1], f[2]*0.05, f[3]*0.05) - if self.incButton['frameSize'] == None and \ + if self.incButton['frameSize'] is None and \ self.incButton.bounds == [0.0, 0.0, 0.0, 0.0]: f = self['frameSize'] if self['orientation'] == DGG.HORIZONTAL: @@ -196,4 +191,3 @@ class DirectScrollBar(DirectFrame): if self['command']: self['command'](*self['extraArgs']) - diff --git a/direct/src/gui/DirectScrolledFrame.py b/direct/src/gui/DirectScrolledFrame.py index c860797b74..73e35c9440 100644 --- a/direct/src/gui/DirectScrolledFrame.py +++ b/direct/src/gui/DirectScrolledFrame.py @@ -11,10 +11,6 @@ from . import DirectGuiGlobals as DGG from .DirectFrame import * from .DirectScrollBar import * -""" -import DirectScrolledFrame -d = DirectScrolledFrame(borderWidth=(0, 0)) -""" class DirectScrolledFrame(DirectFrame): """ @@ -77,7 +73,8 @@ class DirectScrolledFrame(DirectFrame): self.initialiseoptions(DirectScrolledFrame) def setScrollBarWidth(self): - if self.fInit: return + if self.fInit: + return w = self['scrollBarWidth'] self.verticalScroll["frameSize"] = (-w / 2.0, w / 2.0, self.verticalScroll["frameSize"][2], self.verticalScroll["frameSize"][3]) diff --git a/direct/src/gui/DirectScrolledList.py b/direct/src/gui/DirectScrolledList.py index ffe43ab3e7..70331e67f1 100644 --- a/direct/src/gui/DirectScrolledList.py +++ b/direct/src/gui/DirectScrolledList.py @@ -11,6 +11,7 @@ from direct.showbase import ShowBaseGlobal from . import DirectGuiGlobals as DGG from direct.directnotify import DirectNotifyGlobal from direct.task.Task import Task +from direct.task.TaskManagerGlobal import taskMgr from .DirectFrame import * from .DirectButton import * @@ -159,9 +160,9 @@ class DirectScrolledList(DirectFrame): def selectListItem(self, item): assert self.notify.debugStateCall(self) if hasattr(self, "currentSelected"): - self.currentSelected['state']=DGG.NORMAL - item['state']=DGG.DISABLED - self.currentSelected=item + self.currentSelected['state'] = DGG.NORMAL + item['state'] = DGG.DISABLED + self.currentSelected = item def scrollBy(self, delta): assert self.notify.debugStateCall(self) @@ -181,7 +182,7 @@ class DirectScrolledList(DirectFrame): return 0 for i in range(len(self["items"])): - if(self["items"][i].itemID == itemID): + if self["items"][i].itemID == itemID: return i self.notify.warning("getItemIndexForItemID: item not found!") return 0 @@ -203,27 +204,27 @@ class DirectScrolledList(DirectFrame): numItemsVisible = self["numItemsVisible"] numItemsTotal = len(self["items"]) - if(centered): + if centered: self.index = index - (numItemsVisible // 2) else: self.index = index # Not enough items to even worry about scrolling, # just disable the buttons and do nothing - if (len(self["items"]) <= numItemsVisible): + if len(self["items"]) <= numItemsVisible: self.incButton['state'] = DGG.DISABLED self.decButton['state'] = DGG.DISABLED # Hmm.. just reset self.index to 0 and bail out self.index = 0 ret = 0 else: - if (self.index <= 0): + if self.index <= 0: self.index = 0 #print "at list start, ", len(self["items"])," ", self["numItemsVisible"] self.decButton['state'] = DGG.DISABLED self.incButton['state'] = DGG.NORMAL ret = 0 - elif (self.index >= (numItemsTotal - numItemsVisible)): + elif self.index >= (numItemsTotal - numItemsVisible): self.index = numItemsTotal - numItemsVisible #print "at list end, ", len(self["items"])," ", self["numItemsVisible"] self.incButton['state'] = DGG.DISABLED @@ -231,7 +232,7 @@ class DirectScrolledList(DirectFrame): ret = 0 else: # deal with an edge condition - make sure any tasks are removed from the disabled arrows. - if (self.incButton['state'] == DGG.DISABLED) or (self.decButton['state'] == DGG.DISABLED): + if self.incButton['state'] == DGG.DISABLED or self.decButton['state'] == DGG.DISABLED: #print "leaving list start/end, ", len(self["items"])," ", self["numItemsVisible"] self.__buttonUp(0) self.incButton['state'] = DGG.NORMAL @@ -300,7 +301,7 @@ class DirectScrolledList(DirectFrame): def __scrollByTask(self, task): assert self.notify.debugStateCall(self) - if ((task.time - task.prevTime) < task.delayTime): + if (task.time - task.prevTime) < task.delayTime: return Task.cont else: ret = self.scrollBy(task.delta) @@ -388,7 +389,7 @@ class DirectScrolledList(DirectFrame): if item in self["items"]: if hasattr(self, "currentSelected") and self.currentSelected is item: del self.currentSelected - if (hasattr(item, 'destroy') and hasattr(item.destroy, '__call__')): + if hasattr(item, 'destroy') and hasattr(item.destroy, '__call__'): item.destroy() self["items"].remove(item) if not isinstance(item, str): @@ -407,7 +408,7 @@ class DirectScrolledList(DirectFrame): retval = 0 #print "remove item called", item #print "items list", self['items'] - while len (self["items"]): + while len(self["items"]) > 0: item = self['items'][0] #print "removing item", item if hasattr(self, "currentSelected") and self.currentSelected is item: @@ -419,7 +420,7 @@ class DirectScrolledList(DirectFrame): item.removeNode() retval = 1 - if (refresh): + if refresh: self.refresh() return retval @@ -431,11 +432,11 @@ class DirectScrolledList(DirectFrame): """ assert self.notify.debugStateCall(self) retval = 0 - while len (self["items"]): + while len(self["items"]) > 0: item = self['items'][0] if hasattr(self, "currentSelected") and self.currentSelected is item: del self.currentSelected - if (hasattr(item, 'destroy') and hasattr(item.destroy, '__call__')): + if hasattr(item, 'destroy') and hasattr(item.destroy, '__call__'): item.destroy() self["items"].remove(item) if not isinstance(item, str): @@ -443,7 +444,7 @@ class DirectScrolledList(DirectFrame): #item.reparentTo(ShowBaseGlobal.hidden) item.removeNode() retval = 1 - if (refresh): + if refresh: self.refresh() return retval @@ -464,9 +465,9 @@ class DirectScrolledList(DirectFrame): def getSelectedText(self): assert self.notify.debugStateCall(self) if isinstance(self['items'][self.index], str): - return self['items'][self.index] + return self['items'][self.index] else: - return self['items'][self.index]['text'] + return self['items'][self.index]['text'] def setIncButtonCallback(self): assert self.notify.debugStateCall(self) @@ -477,54 +478,52 @@ class DirectScrolledList(DirectFrame): self.__decButtonCallback = self["decButtonCallback"] -""" -from DirectGui import * - -def makeButton(itemName, itemNum, *extraArgs): - def buttonCommand(): - print itemName, itemNum - return DirectButton(text = itemName, - relief = DGG.RAISED, - frameSize = (-3.5, 3.5, -0.2, 0.8), - scale = 0.85, - command = buttonCommand) - -s = scrollList = DirectScrolledList( - parent = aspect2d, - relief = None, - # Use the default dialog box image as the background - image = DGG.getDefaultDialogGeom(), - # Scale it to fit around everyting - image_scale = (0.7, 1, .8), - # Give it a label - text = "Scrolled List Example", - text_scale = 0.06, - text_align = TextNode.ACenter, - text_pos = (0, 0.3), - text_fg = (0, 0, 0, 1), - # inc and dec are DirectButtons - # They can contain a combination of text, geometry and images - # Just a simple text one for now - incButton_text = 'Increment', - incButton_relief = DGG.RAISED, - incButton_pos = (0.0, 0.0, -0.36), - incButton_scale = 0.1, - # Same for the decrement button - decButton_text = 'Decrement', - decButton_relief = DGG.RAISED, - decButton_pos = (0.0, 0.0, 0.175), - decButton_scale = 0.1, - # each item is a button with text on it - numItemsVisible = 4, - itemMakeFunction = makeButton, - items = ['Able', 'Baker', 'Charlie', 'Delta', 'Echo', 'Foxtrot', - 'Golf', 'Hotel', 'India', 'Juliet', 'Kilo', 'Lima'], - # itemFrame is a DirectFrame - # Use it to scale up or down the items and to place it relative - # to eveything else - itemFrame_pos = (0, 0, 0.06), - itemFrame_scale = 0.1, - itemFrame_frameSize = (-3.1, 3.1, -3.3, 0.8), - itemFrame_relief = DGG.GROOVE, - ) -""" +#from DirectGui import * +# +#def makeButton(itemName, itemNum, *extraArgs): +# def buttonCommand(): +# print itemName, itemNum +# return DirectButton(text = itemName, +# relief = DGG.RAISED, +# frameSize = (-3.5, 3.5, -0.2, 0.8), +# scale = 0.85, +# command = buttonCommand) +# +#s = scrollList = DirectScrolledList( +# parent = aspect2d, +# relief = None, +# # Use the default dialog box image as the background +# image = DGG.getDefaultDialogGeom(), +# # Scale it to fit around everyting +# image_scale = (0.7, 1, .8), +# # Give it a label +# text = "Scrolled List Example", +# text_scale = 0.06, +# text_align = TextNode.ACenter, +# text_pos = (0, 0.3), +# text_fg = (0, 0, 0, 1), +# # inc and dec are DirectButtons +# # They can contain a combination of text, geometry and images +# # Just a simple text one for now +# incButton_text = 'Increment', +# incButton_relief = DGG.RAISED, +# incButton_pos = (0.0, 0.0, -0.36), +# incButton_scale = 0.1, +# # Same for the decrement button +# decButton_text = 'Decrement', +# decButton_relief = DGG.RAISED, +# decButton_pos = (0.0, 0.0, 0.175), +# decButton_scale = 0.1, +# # each item is a button with text on it +# numItemsVisible = 4, +# itemMakeFunction = makeButton, +# items = ['Able', 'Baker', 'Charlie', 'Delta', 'Echo', 'Foxtrot', +# 'Golf', 'Hotel', 'India', 'Juliet', 'Kilo', 'Lima'], +# # itemFrame is a DirectFrame +# # Use it to scale up or down the items and to place it relative +# # to eveything else +# itemFrame_pos = (0, 0, 0.06), +# itemFrame_scale = 0.1, +# itemFrame_frameSize = (-3.1, 3.1, -3.3, 0.8), +# itemFrame_relief = DGG.GROOVE, +# ) diff --git a/direct/src/gui/DirectSlider.py b/direct/src/gui/DirectSlider.py index e113f34055..435c8f154a 100644 --- a/direct/src/gui/DirectSlider.py +++ b/direct/src/gui/DirectSlider.py @@ -12,11 +12,6 @@ from .DirectFrame import * from .DirectButton import * from math import isnan -""" -import DirectSlider -d = DirectSlider(borderWidth=(0, 0)) - -""" class DirectSlider(DirectFrame): """ @@ -63,7 +58,7 @@ class DirectSlider(DirectFrame): self.thumb = self.createcomponent("thumb", (), None, DirectButton, (self,), borderWidth = self['borderWidth']) - if self.thumb['frameSize'] == None and \ + if self.thumb['frameSize'] is None and \ self.thumb.bounds == [0.0, 0.0, 0.0, 0.0]: # Compute a default frameSize for the thumb. f = self['frameSize'] @@ -148,7 +143,7 @@ class DirectSlider(DirectFrame): self._lastOrientation = self['orientation'] def destroy(self): - if (hasattr(self, 'thumb')): + if hasattr(self, 'thumb'): self.thumb.destroy() # ow! del self.thumb DirectFrame.destroy(self) diff --git a/direct/src/gui/DirectWaitBar.py b/direct/src/gui/DirectWaitBar.py index ae089ecf3e..5afecfe64c 100644 --- a/direct/src/gui/DirectWaitBar.py +++ b/direct/src/gui/DirectWaitBar.py @@ -10,10 +10,6 @@ from panda3d.core import * from . import DirectGuiGlobals as DGG from .DirectFrame import * -""" -import DirectWaitBar -d = DirectWaitBar(borderWidth=(0, 0)) -""" class DirectWaitBar(DirectFrame): """ DirectWaitBar - A DirectWidget that shows progress completed @@ -29,7 +25,7 @@ class DirectWaitBar(DirectFrame): # Define type of DirectGuiWidget ('pgFunc', PGWaitBar, None), ('frameSize', (-1, 1, -0.08, 0.08), None), - ('borderWidth', (0, 0), None), + ('borderWidth', (0, 0), None), ('range', 100, self.setRange), ('value', 0, self.setValue), ('barBorderWidth', (0, 0), self.setBarBorderWidth), @@ -97,7 +93,7 @@ class DirectWaitBar(DirectFrame): # this must be a single texture (or a string). texture = self['barTexture'] if isinstance(texture, str): - texture = loader.loadTexture(texture) + texture = base.loader.loadTexture(texture) if texture: self.barStyle.setTexture(texture) else: @@ -124,4 +120,3 @@ class DirectWaitBar(DirectFrame): if count > self['range']: count = self['range'] self.update(count) - diff --git a/direct/src/gui/OnscreenGeom.py b/direct/src/gui/OnscreenGeom.py index 5c5efbbc32..daa1a8de5d 100644 --- a/direct/src/gui/OnscreenGeom.py +++ b/direct/src/gui/OnscreenGeom.py @@ -80,13 +80,13 @@ class OnscreenGeom(DirectObject, NodePath): # preserve them across this call. if not self.isEmpty(): parent = self.getParent() - if transform == None: + if transform is None: # If we're replacing a previous image, we throw away # the new image's transform in favor of the original # image's transform. transform = self.getTransform() sort = self.getSort() - if color == None and self.hasColor(): + if color is None and self.hasColor(): color = self.getColor() self.removeNode() @@ -95,7 +95,7 @@ class OnscreenGeom(DirectObject, NodePath): if isinstance(geom, NodePath): self.assign(geom.copyTo(parent, sort)) elif isinstance(geom, str): - self.assign(loader.loadModel(geom)) + self.assign(base.loader.loadModel(geom)) self.reparentTo(parent, sort) if not self.isEmpty(): diff --git a/direct/src/gui/OnscreenImage.py b/direct/src/gui/OnscreenImage.py index e6fe258c32..8f85613956 100644 --- a/direct/src/gui/OnscreenImage.py +++ b/direct/src/gui/OnscreenImage.py @@ -89,7 +89,7 @@ class OnscreenImage(DirectObject, NodePath): # preserve them across this call. if not self.isEmpty(): parent = self.getParent() - if transform == None: + if transform is None: # If we're replacing a previous image, we throw away # the new image's transform in favor of the original # image's transform. @@ -107,14 +107,14 @@ class OnscreenImage(DirectObject, NodePath): tex = image else: # It's a Texture file name - tex = loader.loadTexture(image) + tex = base.loader.loadTexture(image) cm = CardMaker('OnscreenImage') cm.setFrame(-1, 1, -1, 1) self.assign(parent.attachNewNode(cm.generate(), sort)) self.setTexture(tex) - elif type(image) == type(()): + elif isinstance(image, tuple): # Assume its a file+node name, extract texture from node - model = loader.loadModel(image[0]) + model = base.loader.loadModel(image[0]) if model: node = model.find(image[1]) if node: @@ -135,11 +135,10 @@ class OnscreenImage(DirectObject, NodePath): # Use option string to access setter function try: setter = getattr(self, 'set' + option[0].upper() + option[1:]) - if (((setter == self.setPos) or - (setter == self.setHpr) or - (setter == self.setScale)) and - (isinstance(value, tuple) or - isinstance(value, list))): + if (setter == self.setPos or + setter == self.setHpr or + setter == self.setScale) and \ + isinstance(value, (tuple, list)): setter(*value) else: setter(value) diff --git a/direct/src/gui/OnscreenText.py b/direct/src/gui/OnscreenText.py index fbc487b3e6..993949f402 100644 --- a/direct/src/gui/OnscreenText.py +++ b/direct/src/gui/OnscreenText.py @@ -122,7 +122,7 @@ class OnscreenText(NodePath): bg = bg or (0, 0, 0, 0) shadow = shadow or (0, 0, 0, 0) frame = frame or (0, 0, 0, 0) - if align == None: + if align is None: align = TextNode.ACenter elif style == ScreenTitle: scale = scale or 0.15 @@ -130,7 +130,7 @@ class OnscreenText(NodePath): bg = bg or (0, 0, 0, 0) shadow = shadow or (0, 0, 0, 1) frame = frame or (0, 0, 0, 0) - if align == None: + if align is None: align = TextNode.ACenter elif style == ScreenPrompt: scale = scale or 0.1 @@ -138,7 +138,7 @@ class OnscreenText(NodePath): bg = bg or (0, 0, 0, 0) shadow = shadow or (0, 0, 0, 1) frame = frame or (0, 0, 0, 0) - if align == None: + if align is None: align = TextNode.ACenter elif style == NameConfirm: scale = scale or 0.1 @@ -146,7 +146,7 @@ class OnscreenText(NodePath): bg = bg or (0, 0, 0, 0) shadow = shadow or (0, 0, 0, 0) frame = frame or (0, 0, 0, 0) - if align == None: + if align is None: align = TextNode.ACenter elif style == BlackOnWhite: scale = scale or 0.1 @@ -154,7 +154,7 @@ class OnscreenText(NodePath): bg = bg or (1, 1, 1, 1) shadow = shadow or (0, 0, 0, 0) frame = frame or (0, 0, 0, 0) - if align == None: + if align is None: align = TextNode.ACenter else: raise ValueError @@ -173,7 +173,7 @@ class OnscreenText(NodePath): if decal: textNode.setCardDecal(1) - if font == None: + if font is None: font = DGG.getDefaultFont() textNode.setFont(font) @@ -217,7 +217,7 @@ class OnscreenText(NodePath): # graph. self.updateTransformMat() - if drawOrder != None: + if drawOrder is not None: textNode.setBin('fixed') textNode.setDrawOrder(drawOrder) @@ -444,7 +444,7 @@ class OnscreenText(NodePath): scale = property(getScale, setScale) def updateTransformMat(self): - assert(isinstance(self.textNode, TextNode)) + assert isinstance(self.textNode, TextNode) mat = ( Mat4.scaleMat(Vec3.rfu(self.__scale[0], 1, self.__scale[1])) * Mat4.rotateMat(self.__roll, Vec3.back()) * @@ -554,4 +554,3 @@ class OnscreenText(NodePath): # Allow index style refererences __getitem__ = cget - diff --git a/direct/src/interval/ActorInterval.py b/direct/src/interval/ActorInterval.py index 8d5044c2b5..76b741820a 100644 --- a/direct/src/interval/ActorInterval.py +++ b/direct/src/interval/ActorInterval.py @@ -60,7 +60,7 @@ class ActorInterval(Interval.Interval): self.playRate = playRate # If no name specified, use id as name - if (name == None): + if name is None: name = id if len(self.controls) == 0: @@ -72,19 +72,19 @@ class ActorInterval(Interval.Interval): self.frameRate = self.controls[0].getFrameRate() * abs(playRate) # Compute start and end frames. - if startFrame != None: + if startFrame is not None: self.startFrame = startFrame - elif startTime != None: + elif startTime is not None: self.startFrame = startTime * self.frameRate else: self.startFrame = 0 - if endFrame != None: + if endFrame is not None: self.endFrame = endFrame - elif endTime != None: + elif endTime is not None: self.endFrame = endTime * self.frameRate - elif duration != None: - if startTime == None: + elif duration is not None: + if startTime is None: startTime = float(self.startFrame) / float(self.frameRate) endTime = startTime + duration self.endFrame = endTime * self.frameRate @@ -115,7 +115,7 @@ class ActorInterval(Interval.Interval): # Compute duration if no duration specified self.implicitDuration = 0 - if duration == None: + if duration is None: self.implicitDuration = 1 duration = float(self.numFrames) / self.frameRate @@ -212,7 +212,7 @@ class LerpAnimInterval(CLerpAnimEffectInterval): blendType = 'noBlend', name = None, partName=None, lodName=None): # Generate unique name if necessary - if (name == None): + if name is None: name = 'LerpAnimInterval-%d' % LerpAnimInterval.lerpAnimNum LerpAnimInterval.lerpAnimNum += 1 @@ -222,7 +222,7 @@ class LerpAnimInterval(CLerpAnimEffectInterval): # Initialize superclass CLerpAnimEffectInterval.__init__(self, name, duration, blendType) - if startAnim != None: + if startAnim is not None: controls = actor.getAnimControls( startAnim, partName = partName, lodName = lodName) #controls = actor.getAnimControls(startAnim) @@ -230,7 +230,7 @@ class LerpAnimInterval(CLerpAnimEffectInterval): self.addControl(control, startAnim, 1.0 - startWeight, 1.0 - endWeight) - if endAnim != None: + if endAnim is not None: controls = actor.getAnimControls( endAnim, partName = partName, lodName = lodName) #controls = actor.getAnimControls(endAnim) diff --git a/direct/src/interval/AnimControlInterval.py b/direct/src/interval/AnimControlInterval.py index 4223e69f08..1c2abf090f 100755 --- a/direct/src/interval/AnimControlInterval.py +++ b/direct/src/interval/AnimControlInterval.py @@ -49,14 +49,14 @@ class AnimControlInterval(Interval.Interval): AnimControlInterval.animNum += 1 # Record class specific variables - if(isinstance(controls, AnimControlCollection)): + if isinstance(controls, AnimControlCollection): self.controls = controls - if(config.GetBool("strict-anim-ival",0)): + if ConfigVariableBool("strict-anim-ival", 0): checkSz = self.controls.getAnim(0).getNumFrames() for i in range(1,self.controls.getNumAnims()): - if(checkSz != self.controls.getAnim(i).getNumFrames()): + if checkSz != self.controls.getAnim(i).getNumFrames(): self.notify.error("anim controls don't have the same number of frames!") - elif(isinstance(controls, AnimControl)): + elif isinstance(controls, AnimControl): self.controls = AnimControlCollection() self.controls.storeAnim(controls,"") else: @@ -67,24 +67,24 @@ class AnimControlInterval(Interval.Interval): self.playRate = playRate # If no name specified, use id as name - if (name == None): + if name is None: name = id self.frameRate = self.controls.getAnim(0).getFrameRate() * abs(playRate) # Compute start and end frames. - if startFrame != None: + if startFrame is not None: self.startFrame = startFrame - elif startTime != None: + elif startTime is not None: self.startFrame = startTime * self.frameRate else: self.startFrame = 0 - if endFrame != None: + if endFrame is not None: self.endFrame = endFrame - elif endTime != None: + elif endTime is not None: self.endFrame = endTime * self.frameRate - elif duration != None: - if startTime == None: + elif duration is not None: + if startTime is None: startTime = float(self.startFrame) / float(self.frameRate) endTime = startTime + duration self.endFrame = duration * self.frameRate @@ -108,7 +108,7 @@ class AnimControlInterval(Interval.Interval): # Compute duration if no duration specified self.implicitDuration = 0 - if duration == None: + if duration is None: self.implicitDuration = 1 duration = float(self.numFrames) / self.frameRate @@ -180,4 +180,3 @@ class AnimControlInterval(Interval.Interval): self.state = CInterval.SFinal self.intervalDone() - diff --git a/direct/src/interval/FunctionInterval.py b/direct/src/interval/FunctionInterval.py index 04f313083c..e7e0c490c9 100644 --- a/direct/src/interval/FunctionInterval.py +++ b/direct/src/interval/FunctionInterval.py @@ -27,13 +27,13 @@ class FunctionInterval(Interval.Interval): FunctionIntervals = weakref.WeakKeyDictionary() @classmethod - def replaceMethod(self, oldFunction, newFunction): + def replaceMethod(cls, oldFunction, newFunction): import types count = 0 - for ival in self.FunctionIntervals: + for ival in cls.FunctionIntervals: # print 'testing: ', ival.function, oldFunction # Note: you can only replace methods currently - if type(ival.function) == types.MethodType: + if isinstance(ival.function, types.MethodType): if ival.function.__func__ == oldFunction: # print 'found: ', ival.function, oldFunction ival.function = types.MethodType(newFunction, @@ -113,7 +113,7 @@ class AcceptInterval(FunctionInterval): def acceptFunc(dirObj = dirObj, event = event, function = function): dirObj.accept(event, function) # Determine name - if (name == None): + if name is None: name = 'Accept-' + event # Create function interval FunctionInterval.__init__(self, acceptFunc, name = name) @@ -127,7 +127,7 @@ class IgnoreInterval(FunctionInterval): def ignoreFunc(dirObj = dirObj, event = event): dirObj.ignore(event) # Determine name - if (name == None): + if name is None: name = 'Ignore-' + event # Create function interval FunctionInterval.__init__(self, ignoreFunc, name = name) @@ -143,7 +143,7 @@ class ParentInterval(FunctionInterval): def reparentFunc(nodePath = nodePath, parent = parent): nodePath.reparentTo(parent) # Determine name - if (name == None): + if name is None: name = 'ParentInterval-%d' % ParentInterval.parentIntervalNum ParentInterval.parentIntervalNum += 1 # Create function interval @@ -160,7 +160,7 @@ class WrtParentInterval(FunctionInterval): def wrtReparentFunc(nodePath = nodePath, parent = parent): nodePath.wrtReparentTo(parent) # Determine name - if (name == None): + if name is None: name = ('WrtParentInterval-%d' % WrtParentInterval.wrtParentIntervalNum) WrtParentInterval.wrtParentIntervalNum += 1 @@ -183,7 +183,7 @@ class PosInterval(FunctionInterval): else: np.setPos(pos) # Determine name - if (name == None): + if name is None: name = 'PosInterval-%d' % PosInterval.posIntervalNum PosInterval.posIntervalNum += 1 # Create function interval @@ -204,7 +204,7 @@ class HprInterval(FunctionInterval): else: np.setHpr(hpr) # Determine name - if (name == None): + if name is None: name = 'HprInterval-%d' % HprInterval.hprIntervalNum HprInterval.hprIntervalNum += 1 # Create function interval @@ -225,7 +225,7 @@ class ScaleInterval(FunctionInterval): else: np.setScale(scale) # Determine name - if (name == None): + if name is None: name = 'ScaleInterval-%d' % ScaleInterval.scaleIntervalNum ScaleInterval.scaleIntervalNum += 1 # Create function interval @@ -246,7 +246,7 @@ class PosHprInterval(FunctionInterval): else: np.setPosHpr(pos, hpr) # Determine name - if (name == None): + if name is None: name = 'PosHprInterval-%d' % PosHprInterval.posHprIntervalNum PosHprInterval.posHprIntervalNum += 1 # Create function interval @@ -268,7 +268,7 @@ class HprScaleInterval(FunctionInterval): else: np.setHprScale(hpr, scale) # Determine name - if (name == None): + if name is None: name = ('HprScale-%d' % HprScaleInterval.hprScaleIntervalNum) HprScaleInterval.hprScaleIntervalNum += 1 @@ -291,7 +291,7 @@ class PosHprScaleInterval(FunctionInterval): else: np.setPosHprScale(pos, hpr, scale) # Determine name - if (name == None): + if name is None: name = ('PosHprScale-%d' % PosHprScaleInterval.posHprScaleIntervalNum) PosHprScaleInterval.posHprScaleIntervalNum += 1 @@ -312,133 +312,3 @@ class Func(FunctionInterval): class Wait(WaitInterval): def __init__(self, duration): WaitInterval.__init__(self, duration) - -""" -SAMPLE CODE - -from IntervalGlobal import * - -i1 = Func(base.transitions.fadeOut) -i2 = Func(base.transitions.fadeIn) - -def caughtIt(): - print 'Caught here-is-an-event' - -class DummyAcceptor(DirectObject): - pass - -da = DummyAcceptor() -i3 = Func(da.accept, 'here-is-an-event', caughtIt) - -i4 = Func(messenger.send, 'here-is-an-event') - -i5 = Func(da.ignore, 'here-is-an-event') - -# Using a function -def printDone(): - print 'done' - -i6 = Func(printDone) - -# Create track -t1 = Sequence([ - # Fade out - (0.0, i1), - # Fade in - (2.0, i2), - # Accept event - (4.0, i3), - # Throw it, - (5.0, i4), - # Ignore event - (6.0, i5), - # Throw event again and see if ignore worked - (7.0, i4), - # Print done - (8.0, i6)], name = 'demo') - -# Play track -t1.play() - -### Specifying interval start times during track construction ### -# Interval start time can be specified relative to three different points: -# PREVIOUS_END -# PREVIOUS_START -# TRACK_START - -startTime = 0.0 -def printStart(): - global startTime - startTime = globalClock.getFrameTime() - print 'Start' - -def printPreviousStart(): - global startTime - currTime = globalClock.getFrameTime() - print 'PREVIOUS_END %0.2f' % (currTime - startTime) - -def printPreviousEnd(): - global startTime - currTime = globalClock.getFrameTime() - print 'PREVIOUS_END %0.2f' % (currTime - startTime) - -def printTrackStart(): - global startTime - currTime = globalClock.getFrameTime() - print 'TRACK_START %0.2f' % (currTime - startTime) - -i1 = Func(printStart) -# Just to take time -i2 = LerpPosInterval(camera, 2.0, Point3(0, 10, 5)) -# This will be relative to end of camera move -i3 = FunctionInterval(printPreviousEnd) -# Just to take time -i4 = LerpPosInterval(camera, 2.0, Point3(0, 0, 5)) -# This will be relative to the start of the camera move -i5 = FunctionInterval(printPreviousStart) -# This will be relative to track start -i6 = FunctionInterval(printTrackStart) -# Create the track, if you don't specify offset type in tuple it defaults to -# relative to TRACK_START (first entry below) -t2 = Track([(0.0, i1), # i1 start at t = 0, duration = 0.0 - (1.0, i2, TRACK_START), # i2 start at t = 1, duration = 2.0 - (2.0, i3, PREVIOUS_END), # i3 start at t = 5, duration = 0.0 - (1.0, i4, PREVIOUS_END), # i4 start at t = 6, duration = 2.0 - (3.0, i5, PREVIOUS_START), # i5 start at t = 9, duration = 0.0 - (10.0, i6, TRACK_START)], # i6 start at t = 10, duration = 0.0 - name = 'startTimeDemo') - -t2.play() - - -smiley = loader.loadModel('models/misc/smiley') - -from direct.actor import Actor -donald = Actor.Actor() -donald.loadModel("phase_6/models/char/donald-wheel-1000") -donald.loadAnims({"steer":"phase_6/models/char/donald-wheel-wheel"}) -donald.reparentTo(render) - - -seq = Sequence(Func(donald.setPos, 0, 0, 0), - donald.actorInterval('steer', duration=1.0), - donald.posInterval(1, Point3(0, 0, 1)), - Parallel(donald.actorInterval('steer', duration=1.0), - donald.posInterval(1, Point3(0, 0, 0)), - ), - Wait(1.0), - Func(base.toggleWireframe), - Wait(1.0), - Parallel(donald.actorInterval('steer', duration=1.0), - donald.posInterval(1, Point3(0, 0, -1)), - Sequence(donald.hprInterval(1, Vec3(180, 0, 0)), - donald.hprInterval(1, Vec3(0, 0, 0)), - ), - ), - Func(base.toggleWireframe), - Func(messenger.send, 'hello'), - ) - - - -""" diff --git a/direct/src/interval/IndirectInterval.py b/direct/src/interval/IndirectInterval.py index a0adf30a82..901940077f 100644 --- a/direct/src/interval/IndirectInterval.py +++ b/direct/src/interval/IndirectInterval.py @@ -33,15 +33,15 @@ class IndirectInterval(Interval.Interval): self.interval = interval self.startAtStart = (startT == 0) - self.endAtEnd = (endT == None or endT == interval.getDuration()) + self.endAtEnd = (endT is None or endT == interval.getDuration()) - if endT == None: + if endT is None: endT = interval.getDuration() - if duration == None: + if duration is None: duration = abs(endT - startT) / playRate - if (name == None): + if name is None: name = ('IndirectInterval-%d' % IndirectInterval.indirectIntervalNum) IndirectInterval.indirectIntervalNum += 1 diff --git a/direct/src/interval/Interval.py b/direct/src/interval/Interval.py index 135cbb9d5d..a88e50d4db 100644 --- a/direct/src/interval/Interval.py +++ b/direct/src/interval/Interval.py @@ -2,16 +2,18 @@ __all__ = ['Interval'] -from direct.directnotify.DirectNotifyGlobal import directNotify -from direct.showbase.DirectObject import DirectObject -from direct.task.Task import Task, TaskManager -from direct.task.TaskManagerGlobal import taskMgr from panda3d.core import * from panda3d.direct import * +from direct.directnotify.DirectNotifyGlobal import directNotify +from direct.showbase.DirectObject import DirectObject +from direct.showbase.MessengerGlobal import messenger +from direct.task.Task import Task, TaskManager +from direct.task.TaskManagerGlobal import taskMgr from direct.extensions_native import CInterval_extensions from direct.extensions_native import NodePath_extensions import math + class Interval(DirectObject): """Interval class: Base class for timeline functionality""" @@ -71,8 +73,8 @@ class Interval(DirectObject): # Returns true if the interval has not been started, has already # played to its completion, or has been explicitly stopped via # finish(). - return (self.getState() == CInterval.SInitial or \ - self.getState() == CInterval.SFinal) + return self.getState() == CInterval.SInitial or \ + self.getState() == CInterval.SFinal def setT(self, t): # There doesn't seem to be any reason to clamp this, and it @@ -132,7 +134,7 @@ class Interval(DirectObject): return self.getT() def resume(self, startT = None): - if startT != None: + if startT is not None: self.setT(startT) self.setupResume() if not self.isPlaying(): @@ -398,7 +400,7 @@ class Interval(DirectObject): space = '' for l in range(indent): space = space + ' ' - return (space + self.name + ' dur: %.2f' % self.duration) + return space + self.name + ' dur: %.2f' % self.duration open_ended = property(getOpenEnded) stopped = property(isStopped) @@ -458,7 +460,7 @@ class Interval(DirectObject): 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) diff --git a/direct/src/interval/IntervalManager.py b/direct/src/interval/IntervalManager.py index a9a44a3bf0..433814fee7 100644 --- a/direct/src/interval/IntervalManager.py +++ b/direct/src/interval/IntervalManager.py @@ -134,7 +134,7 @@ class IntervalManager(CIntervalManager): def __storeInterval(self, interval, index): while index >= len(self.ivals): self.ivals.append(None) - assert self.ivals[index] == None or self.ivals[index] == interval + assert self.ivals[index] is None or self.ivals[index] == interval self.ivals[index] = interval #: The global IntervalManager object. diff --git a/direct/src/interval/IntervalTest.py b/direct/src/interval/IntervalTest.py index fce7e0f755..d6b747df46 100644 --- a/direct/src/interval/IntervalTest.py +++ b/direct/src/interval/IntervalTest.py @@ -4,16 +4,15 @@ __all__ = [] if __name__ == "__main__": - from direct.showbase.ShowBase import ShowBase from panda3d.core import * - from .IntervalGlobal import * + from direct.showbase.ShowBase import ShowBase from direct.actor.Actor import * - from direct.directutil import Mopath + from .IntervalGlobal import * base = ShowBase() - boat = loader.loadModel('models/misc/smiley') + boat = base.loader.loadModel('models/misc/smiley') boat.reparentTo(render) donald = Actor() @@ -21,11 +20,11 @@ if __name__ == "__main__": donald.loadAnims({"steer":"phase_6/models/char/donald-wheel-wheel"}) donald.reparentTo(boat) - dock = loader.loadModel('models/misc/smiley') + dock = base.loader.loadModel('models/misc/smiley') dock.reparentTo(render) - sound = loader.loadSfx('phase_6/audio/sfx/SZ_DD_waterlap.mp3') - foghorn = loader.loadSfx('phase_6/audio/sfx/SZ_DD_foghorn.mp3') + sound = base.loader.loadSfx('phase_6/audio/sfx/SZ_DD_waterlap.mp3') + foghorn = base.loader.loadSfx('phase_6/audio/sfx/SZ_DD_foghorn.mp3') mp = Mopath.Mopath() mp.loadFile(Filename('phase_6/paths/dd-e-w')) @@ -161,11 +160,11 @@ if __name__ == "__main__": i1 = FunctionInterval(printStart) # Just to take time - i2 = LerpPosInterval(camera, 2.0, Point3(0, 10, 5)) + i2 = LerpPosInterval(base.camera, 2.0, Point3(0, 10, 5)) # This will be relative to end of camera move i3 = FunctionInterval(printPreviousEnd) # Just to take time - i4 = LerpPosInterval(camera, 2.0, Point3(0, 0, 5)) + i4 = LerpPosInterval(base.camera, 2.0, Point3(0, 0, 5)) # This will be relative to the start of the camera move i5 = FunctionInterval(printPreviousStart) # This will be relative to track start diff --git a/direct/src/interval/LerpBlendHelpers.py b/direct/src/interval/LerpBlendHelpers.py index fdbcc73cbb..c723b373e8 100644 --- a/direct/src/interval/LerpBlendHelpers.py +++ b/direct/src/interval/LerpBlendHelpers.py @@ -4,7 +4,6 @@ __all__ = ['getBlend'] from panda3d.direct import * -"""global lerp blend types for lerp function""" easeIn = EaseInBlendType() @@ -20,13 +19,13 @@ def getBlend(blendType): Return the C++ blend class corresponding to blendType string """ # Note, this is temporary until blend functions get exposed - if (blendType == "easeIn"): + if blendType == "easeIn": return easeIn - elif (blendType == "easeOut"): + elif blendType == "easeOut": return easeOut - elif (blendType == "easeInOut"): + elif blendType == "easeInOut": return easeInOut - elif (blendType == "noBlend"): + elif blendType == "noBlend": return noBlend else: raise Exception( diff --git a/direct/src/interval/LerpInterval.py b/direct/src/interval/LerpInterval.py index 24435ae084..806299307f 100644 --- a/direct/src/interval/LerpInterval.py +++ b/direct/src/interval/LerpInterval.py @@ -32,7 +32,7 @@ class LerpNodePathInterval(CLerpNodePathInterval): def __init__(self, name, duration, blendType, bakeInStart, fluid, nodePath, other): - if name == None: + if name is None: name = '%s-%d' % (self.__class__.__name__, self.lerpNodePathNum) LerpNodePathInterval.lerpNodePathNum += 1 else: @@ -45,7 +45,7 @@ class LerpNodePathInterval(CLerpNodePathInterval): blendType = self.stringBlendType(blendType) assert blendType != self.BTInvalid - if other == None: + if other is None: other = NodePath() CLerpNodePathInterval.__init__(self, name, duration, blendType, @@ -67,7 +67,7 @@ class LerpNodePathInterval(CLerpNodePathInterval): # function (probably a C++ setter function). If the param is # a callable functor, calls it; otherwise, uses the param # directly. - if param != None: + if param is not None: if callable(param): func(param()) else: @@ -114,7 +114,7 @@ class LerpPosInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndPos(pos) - if startPos != None: + if startPos is not None: self.setStartPos(startPos) def privDoEvent(self, t, event): @@ -143,9 +143,9 @@ class LerpHprInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndHpr(hpr) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) def privDoEvent(self, t, event): @@ -181,9 +181,9 @@ class LerpQuatInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndQuat(quat) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) def privDoEvent(self, t, event): @@ -209,7 +209,7 @@ class LerpScaleInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndScale(scale) - if startScale != None: + if startScale is not None: self.setStartScale(startScale) def privDoEvent(self, t, event): @@ -234,7 +234,7 @@ class LerpShearInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndShear(shear) - if startShear != None: + if startShear is not None: self.setStartShear(startShear) def privDoEvent(self, t, event): @@ -263,12 +263,12 @@ class LerpPosHprInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndPos(pos) - if startPos != None: + if startPos is not None: self.setStartPos(startPos) self.setEndHpr(hpr) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) def privDoEvent(self, t, event): @@ -308,12 +308,12 @@ class LerpPosQuatInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndPos(pos) - if startPos != None: + if startPos is not None: self.setStartPos(startPos) self.setEndQuat(quat) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) def privDoEvent(self, t, event): @@ -346,12 +346,12 @@ class LerpHprScaleInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndHpr(hpr) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) self.setEndScale(scale) - if startScale != None: + if startScale is not None: self.setStartScale(startScale) def privDoEvent(self, t, event): @@ -394,12 +394,12 @@ class LerpQuatScaleInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndQuat(quat) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) self.setEndScale(scale) - if startScale != None: + if startScale is not None: self.setStartScale(startScale) def privDoEvent(self, t, event): @@ -435,15 +435,15 @@ class LerpPosHprScaleInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndPos(pos) - if startPos != None: + if startPos is not None: self.setStartPos(startPos) self.setEndHpr(hpr) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) self.setEndScale(scale) - if startScale != None: + if startScale is not None: self.setStartScale(startScale) def privDoEvent(self, t, event): @@ -491,15 +491,15 @@ class LerpPosQuatScaleInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndPos(pos) - if startPos != None: + if startPos is not None: self.setStartPos(startPos) self.setEndQuat(quat) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) self.setEndScale(scale) - if startScale != None: + if startScale is not None: self.setStartScale(startScale) def privDoEvent(self, t, event): @@ -540,18 +540,18 @@ class LerpPosHprScaleShearInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndPos(pos) - if startPos != None: + if startPos is not None: self.setStartPos(startPos) self.setEndHpr(hpr) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) self.setEndScale(scale) - if startScale != None: + if startScale is not None: self.setStartScale(startScale) self.setEndShear(shear) - if startShear != None: + if startShear is not None: self.setStartShear(startShear) def privDoEvent(self, t, event): @@ -606,18 +606,18 @@ class LerpPosQuatScaleShearInterval(LerpNodePathInterval): self.inPython = 1 else: self.setEndPos(pos) - if startPos != None: + if startPos is not None: self.setStartPos(startPos) self.setEndQuat(quat) - if startHpr != None: + if startHpr is not None: self.setStartHpr(startHpr) - if startQuat != None: + if startQuat is not None: self.setStartQuat(startQuat) self.setEndScale(scale) - if startScale != None: + if startScale is not None: self.setStartScale(startScale) self.setEndShear(shear) - if startShear != None: + if startShear is not None: self.setStartShear(startShear) def privDoEvent(self, t, event): @@ -642,9 +642,9 @@ class LerpColorInterval(LerpNodePathInterval): LerpNodePathInterval.__init__(self, name, duration, blendType, bakeInStart, 0, nodePath, other) self.setEndColor(color) - if startColor != None: + if startColor is not None: self.setStartColor(startColor) - if override != None: + if override is not None: self.setOverride(override) class LerpColorScaleInterval(LerpNodePathInterval): @@ -654,9 +654,9 @@ class LerpColorScaleInterval(LerpNodePathInterval): LerpNodePathInterval.__init__(self, name, duration, blendType, bakeInStart, 0, nodePath, other) self.setEndColorScale(colorScale) - if startColorScale != None: + if startColorScale is not None: self.setStartColorScale(startColorScale) - if override != None: + if override is not None: self.setOverride(override) class LerpTexOffsetInterval(LerpNodePathInterval): @@ -667,11 +667,11 @@ class LerpTexOffsetInterval(LerpNodePathInterval): LerpNodePathInterval.__init__(self, name, duration, blendType, bakeInStart, 0, nodePath, other) self.setEndTexOffset(texOffset) - if startTexOffset != None: + if startTexOffset is not None: self.setStartTexOffset(startTexOffset) - if textureStage != None: + if textureStage is not None: self.setTextureStage(textureStage) - if override != None: + if override is not None: self.setOverride(override) class LerpTexRotateInterval(LerpNodePathInterval): @@ -682,11 +682,11 @@ class LerpTexRotateInterval(LerpNodePathInterval): LerpNodePathInterval.__init__(self, name, duration, blendType, bakeInStart, 0, nodePath, other) self.setEndTexRotate(texRotate) - if startTexRotate != None: + if startTexRotate is not None: self.setStartTexRotate(startTexRotate) - if textureStage != None: + if textureStage is not None: self.setTextureStage(textureStage) - if override != None: + if override is not None: self.setOverride(override) class LerpTexScaleInterval(LerpNodePathInterval): @@ -697,11 +697,11 @@ class LerpTexScaleInterval(LerpNodePathInterval): LerpNodePathInterval.__init__(self, name, duration, blendType, bakeInStart, 0, nodePath, other) self.setEndTexScale(texScale) - if startTexScale != None: + if startTexScale is not None: self.setStartTexScale(startTexScale) - if textureStage != None: + if textureStage is not None: self.setTextureStage(textureStage) - if override != None: + if override is not None: self.setOverride(override) @@ -744,7 +744,7 @@ class LerpFunctionNoStateInterval(Interval.Interval): self.blendType = LerpBlendHelpers.getBlend(blendType) self.extraArgs = extraArgs # Generate unique name if necessary - if (name == None): + if name is None: name = ('LerpFunctionInterval-%d' % LerpFunctionNoStateInterval.lerpFunctionIntervalNum) LerpFunctionNoStateInterval.lerpFunctionIntervalNum += 1 @@ -771,9 +771,9 @@ class LerpFunctionNoStateInterval(Interval.Interval): def privStep(self, t): # Evaluate the function #print "doing priv step",t - if (t >= self.duration): + if t >= self.duration: # Set to end value - if (t > self.duration): + if t > self.duration: print("after end") #apply(self.function, [self.toData] + self.extraArgs) elif self.duration == 0.0: @@ -821,7 +821,7 @@ class LerpFunctionInterval(Interval.Interval): self.blendType = LerpBlendHelpers.getBlend(blendType) self.extraArgs = extraArgs # Generate unique name if necessary - if (name == None): + if name is None: name = ('LerpFunctionInterval-%s-%d' % (function.__name__, LerpFunctionInterval.lerpFunctionIntervalNum)) @@ -839,7 +839,7 @@ class LerpFunctionInterval(Interval.Interval): def privStep(self, t): # Evaluate the function #print "doing priv step",t - if (t >= self.duration): + if t >= self.duration: # Set to end value self.function(*[self.toData] + self.extraArgs) elif self.duration == 0.0: diff --git a/direct/src/interval/MetaInterval.py b/direct/src/interval/MetaInterval.py index 4f31c9839d..2986071ba4 100644 --- a/direct/src/interval/MetaInterval.py +++ b/direct/src/interval/MetaInterval.py @@ -91,7 +91,7 @@ class MetaInterval(CMetaInterval): self.__ivalsDirty = 1 - if name == None: + if name is None: name = self.__class__.__name__ + '-%d' if '%' in name: @@ -155,7 +155,7 @@ class MetaInterval(CMetaInterval): if isinstance(self.ivals, tuple): self.ivals = list(self.ivals) self.__ivalsDirty = 1 - if index == None: + if index is None: return self.ivals.pop() else: return self.ivals.pop(index) @@ -179,7 +179,7 @@ class MetaInterval(CMetaInterval): if isinstance(self.ivals, tuple): self.ivals = list(self.ivals) self.__ivalsDirty = 1 - if cmpfunc == None: + if cmpfunc is None: self.ivals.sort() else: self.ivals.sort(cmpfunc) @@ -371,7 +371,7 @@ class MetaInterval(CMetaInterval): def resume(self, startT = None): self.__updateIvals() - if startT != None: + if startT is not None: self.setT(startT) self.setupResume() self.__manager.addInterval(self) @@ -486,7 +486,7 @@ class MetaInterval(CMetaInterval): ival = None try: - while (self.isEventReady()): + while self.isEventReady(): index = self.getEventIndex() t = self.getEventT() eventType = self.getEventType() @@ -497,7 +497,7 @@ class MetaInterval(CMetaInterval): ival.privPostEvent() ival = None except: - if ival != None: + if ival is not None: print("Exception occurred while processing %s of %s:" % (ival.getName(), self.getName())) else: print("Exception occurred while processing %s:" % (self.getName())) @@ -569,7 +569,7 @@ class MetaInterval(CMetaInterval): # update the interval list first, if necessary. self.__updateIvals() - if out == None: + if out is None: out = ostream CMetaInterval.timeline(self, out) diff --git a/direct/src/interval/MopathInterval.py b/direct/src/interval/MopathInterval.py index 83ea995caa..cc5dafc74d 100644 --- a/direct/src/interval/MopathInterval.py +++ b/direct/src/interval/MopathInterval.py @@ -17,14 +17,14 @@ class MopathInterval(LerpInterval.LerpFunctionInterval): # Class methods def __init__(self, mopath, node, fromT = 0, toT = None, duration = None, blendType = 'noBlend', name = None): - if toT == None: + if toT is None: toT = mopath.getMaxT() - if duration == None: + if duration is None: duration = abs(toT - fromT) # Generate unique name if necessary - if (name == None): + if name is None: name = 'Mopath-%d' % MopathInterval.mopathNum MopathInterval.mopathNum += 1 @@ -45,4 +45,3 @@ class MopathInterval(LerpInterval.LerpFunctionInterval): Go to time t """ self.mopath.goTo(self.node, t) - diff --git a/direct/src/interval/ParticleInterval.py b/direct/src/interval/ParticleInterval.py index de1f533b63..d119853b60 100644 --- a/direct/src/interval/ParticleInterval.py +++ b/direct/src/interval/ParticleInterval.py @@ -55,13 +55,13 @@ class ParticleInterval(Interval): # Generate unique name id = 'Particle-%d' % ParticleInterval.particleNum ParticleInterval.particleNum += 1 - if name == None: + if name is None: name = id # Record instance variables self.particleEffect = particleEffect self.cleanup = cleanup - if parent != None: + if parent is not None: self.particleEffect.reparentTo(parent) if worldRelative: renderParent = render @@ -132,4 +132,3 @@ class ParticleInterval(Interval): if self.cleanup and self.particleEffect: self.particleEffect.cleanup() self.particleEffect = None - diff --git a/direct/src/interval/ProjectileInterval.py b/direct/src/interval/ProjectileInterval.py index a1b5d70014..b6d0d9ea1d 100755 --- a/direct/src/interval/ProjectileInterval.py +++ b/direct/src/interval/ProjectileInterval.py @@ -8,6 +8,7 @@ from direct.directnotify.DirectNotifyGlobal import * from .Interval import Interval from direct.showbase import PythonUtil + class ProjectileInterval(Interval): """ProjectileInterval class: moves a nodepath through the trajectory of a projectile under the influence of gravity""" @@ -67,7 +68,7 @@ class ProjectileInterval(Interval): self.collNode = self.collNode.node() assert self.collNode.getNumSolids() == 0 - if name == None: + if name is None: name = '%s-%s' % (self.__class__.__name__, self.projectileIntervalNum) ProjectileInterval.projectileIntervalNum += 1 @@ -121,7 +122,7 @@ class ProjectileInterval(Interval): def calcStartVel(startPos, endPos, duration, zAccel): # p(t) = p_0 + t*v_0 + .5*a*t^2 # v_0 = [p(t) - p_0 - .5*a*t^2] / t - if (duration == 0): + if duration == 0: return Point3(0, 0, 0) else: return Point3((endPos[0] - startPos[0]) / duration, @@ -138,7 +139,7 @@ class ProjectileInterval(Interval): startVel, accel) if not time: return None - if type(time) == type([]): + if isinstance(time, list): # projectile hits plane once going up, once going down # assume they want the one on the way down assert self.notify.debug('projectile hits plane twice at times: %s' % @@ -152,7 +153,7 @@ class ProjectileInterval(Interval): # now all we need is startVel, duration, and endPos. # which set of input parameters do we have? - if (None not in (endPos, duration)): + if None not in (endPos, duration): assert not startVel assert not endZ assert not wayPoint @@ -161,7 +162,7 @@ class ProjectileInterval(Interval): self.endPos = endPos self.startVel = calcStartVel(self.startPos, self.endPos, self.duration, self.zAcc) - elif (None not in (startVel, duration)): + elif None not in (startVel, duration): assert not endPos assert not endZ assert not wayPoint @@ -169,7 +170,7 @@ class ProjectileInterval(Interval): self.duration = duration self.startVel = startVel self.endPos = None - elif (None not in (startVel, endZ)): + elif None not in (startVel, endZ): assert not endPos assert not duration assert not wayPoint @@ -182,7 +183,7 @@ class ProjectileInterval(Interval): 'projectile never reaches plane Z=%s' % endZ) self.duration = time self.endPos = None - elif (None not in (wayPoint, timeToWayPoint, endZ)): + elif None not in (wayPoint, timeToWayPoint, endZ): assert not endPos assert not duration assert not startVel @@ -253,43 +254,3 @@ class ProjectileInterval(Interval): csolid = self.collNode.modifySolid(0) csolid.setT1(csolid.getT2()) csolid.setT2(t) - -""" - ################################################################## - TODO: support arbitrary sets of inputs - ################################################################## - You must provide a few of the parameters, and the others will be - computed. The input parameters in question are: - duration, endZ, endPos, startVel, gravityMult - - Valid sets of input parameters (AA), - (trivially computed/default parameters) (BB), - non-trivial computed parameters (CC): - AA && BB => CC - - # one parameter - duration && (startVel, gravityMult) => endZ, endPos - endZ && (startVel, gravityMult) => duration, endPos - endPos && (endZ, gravityMult ) => duration, startVel - - # two parameters - duration, endZ && (endPos, gravityMult) => startVel - duration, endPos && (endZ, gravityMult ) => startVel - duration, startVel && (gravityMult ) => endZ, endPos - duration, gravityMult && (startVel ) => endZ, endPos - endZ, startVel && (gravityMult ) => duration, endPos - endZ, gravityMult && (endPos, startVel ) => duration - endPos, gravityMult && (endZ ) => duration, startVel - - # three parameters - duration, endZ, startVel && ( ) => endPos, gravityMult - duration, endZ, gravityMult && (endPos) => startVel - duration, endPos, gravityMult && (endZ ) => startVel - duration, startVel, gravityMult && ( ) => endZ, endPos - endZ, startVel, gravityMult && ( ) => duration, endPos - - # four parameters - duration, endZ, startVel, gravityMult && () => endPos - ################################################################## - ################################################################## -""" diff --git a/direct/src/interval/ProjectileIntervalTest.py b/direct/src/interval/ProjectileIntervalTest.py index bd747be382..fedbfcefac 100755 --- a/direct/src/interval/ProjectileIntervalTest.py +++ b/direct/src/interval/ProjectileIntervalTest.py @@ -6,8 +6,9 @@ from panda3d.core import * from panda3d.direct import * from .IntervalGlobal import * + def doTest(): - smiley = loader.loadModel('models/misc/smiley') + smiley = base.loader.loadModel('models/misc/smiley') smiley.reparentTo(render) pi = ProjectileInterval(smiley, startPos=Point3(0, 0, 0), @@ -15,4 +16,3 @@ def doTest(): timeToWayPoint=3) pi.loop() return pi - diff --git a/direct/src/interval/SoundInterval.py b/direct/src/interval/SoundInterval.py index e5c5a04467..f523fbb9b0 100644 --- a/direct/src/interval/SoundInterval.py +++ b/direct/src/interval/SoundInterval.py @@ -56,14 +56,14 @@ class SoundInterval(Interval.Interval): self._soundPlaying = False self._reverse = False # If no duration given use sound's duration as interval's duration - if float(duration) == 0.0 and self.sound != None: + if float(duration) == 0.0 and self.sound is not None: duration = max(self.soundDuration - self.startTime, 0) - #if (duration == 0): + #if duration == 0: # self.notify.warning('zero length duration!') # Generate unique name if necessary - if (name == None): + if name is None: name = id # Initialize superclass Interval.Interval.__init__(self, name, duration) @@ -73,9 +73,9 @@ class SoundInterval(Interval.Interval): # start at the beginning self._reverse = False t1 = t + self.startTime - if (t1 < 0.1): + if t1 < 0.1: t1 = 0.0 - if (t1 < self.soundDuration) and not (self._seamlessLoop and self._soundPlaying): + if t1 < self.soundDuration and not (self._seamlessLoop and self._soundPlaying): base.sfxPlayer.playSfx( self.sound, self.fLoop, 1, self.volume, t1, self.node, listenerNode = self.listenerNode, cutoff = self.cutOff) @@ -114,12 +114,12 @@ class SoundInterval(Interval.Interval): def privFinalize(self): # if we're just coming to the end of a seamlessloop, leave the sound alone, # let the audio subsystem loop it - if (self._seamlessLoop and self._soundPlaying and self.getLoop() - and not hasattr(self, '_inFinish')): + if self._seamlessLoop and self._soundPlaying and self.getLoop() and \ + not hasattr(self, '_inFinish'): base.sfxPlayer.setFinalVolume(self.sound, self.node, self.volume, self.listenerNode, self.cutOff) return - elif self.sound != None: + elif self.sound is not None: self.sound.stop() self._soundPlaying = False self.currT = self.getDuration() @@ -136,7 +136,7 @@ class SoundInterval(Interval.Interval): self.state = CInterval.SInitial def privInterrupt(self): - if self.sound != None: + if self.sound is not None: self.sound.stop() self._soundPlaying = False self.state = CInterval.SPaused diff --git a/direct/src/interval/TestInterval.py b/direct/src/interval/TestInterval.py index 6a13cce4f2..ab729ff941 100755 --- a/direct/src/interval/TestInterval.py +++ b/direct/src/interval/TestInterval.py @@ -33,7 +33,7 @@ class TestInterval(Interval): # Generate unique name id = 'Particle-%d' % TestInterval.particleNum TestInterval.particleNum += 1 - if name == None: + if name is None: name = id # Record instance variables self.particleEffect = particleEffect @@ -45,34 +45,30 @@ class TestInterval(Interval): def __del__(self): pass - def __step(self,dt): + def __step(self, dt): self.particleEffect.accelerate(dt,1,0.05) - def start(self,*args,**kwargs): + def start(self, *args, **kwargs): self.particleEffect.clearToInitial() self.currT = 0 Interval.start(self,*args,**kwargs) def privInitialize(self, t): - if self.parent != None: + if self.parent is not None: self.particleEffect.reparentTo(self.parent) - if self.renderParent != None: + if self.renderParent is not None: self.setRenderParent(self.renderParent.node()) self.state = CInterval.SStarted #self.particleEffect.enable() - """ - if (self.particleEffect.renderParent != None): - for p in self.particleEffect.particlesDict.values(): - p.setRenderParent(self.particleEffect.renderParent.node()) - """ + #if self.particleEffect.renderParent is not None: + # for p in self.particleEffect.particlesDict.values(): + # p.setRenderParent(self.particleEffect.renderParent.node()) for f in self.particleEffect.forceGroupDict.values(): f.enable() - """ - for p in self.particleEffect.particlesDict.values(): - p.enable() - self.particleEffect.fEnabled = 1 - """ + #for p in self.particleEffect.particlesDict.values(): + # p.enable() + #self.particleEffect.fEnabled = 1 self.__step(t-self.currT) self.currT = t diff --git a/direct/src/leveleditor/ActionMgr.py b/direct/src/leveleditor/ActionMgr.py index 6ccda3e51e..1b7f340fb1 100755 --- a/direct/src/leveleditor/ActionMgr.py +++ b/direct/src/leveleditor/ActionMgr.py @@ -2,6 +2,7 @@ from panda3d.core import * from direct.showbase.PythonUtil import Functor from . import ObjectGlobals as OG + class ActionMgr: def __init__(self): self.undoList = [] @@ -37,6 +38,7 @@ class ActionMgr: self.undoList.append(action) action.redo() + class ActionBase(Functor): """ Base class for user actions """ @@ -73,6 +75,7 @@ class ActionBase(Functor): def undo(self): print("undo method is not defined for this action") + class ActionAddNewObj(ActionBase): """ Action class for adding new object """ @@ -112,6 +115,7 @@ class ActionAddNewObj(ActionBase): else: print("Can't undo this add") + class ActionDeleteObj(ActionBase): """ Action class for deleting object """ @@ -266,20 +270,22 @@ class ActionDeleteObjById(ActionBase): self.hierarchy = {} self.objInfos = {} + class ActionChangeHierarchy(ActionBase): - """ Action class for changing Scene Graph Hierarchy """ + """ Action class for changing Scene Graph Hierarchy """ - def __init__(self, editor, oldGrandParentId, oldParentId, newParentId, childName, *args, **kargs): - self.editor = editor - self.oldGrandParentId = oldGrandParentId - self.oldParentId = oldParentId - self.newParentId = newParentId - self.childName = childName - function = self.editor.ui.sceneGraphUI.parent - ActionBase.__init__(self, function, self.oldParentId, self.newParentId, self.childName, **kargs) + def __init__(self, editor, oldGrandParentId, oldParentId, newParentId, childName, *args, **kargs): + self.editor = editor + self.oldGrandParentId = oldGrandParentId + self.oldParentId = oldParentId + self.newParentId = newParentId + self.childName = childName + function = self.editor.ui.sceneGraphUI.parent + ActionBase.__init__(self, function, self.oldParentId, self.newParentId, self.childName, **kargs) + + def undo(self): + self.editor.ui.sceneGraphUI.parent(self.oldParentId, self.oldGrandParentId, self.childName) - def undo(self): - self.editor.ui.sceneGraphUI.parent(self.oldParentId, self.oldGrandParentId, self.childName) class ActionSelectObj(ActionBase): """ Action class for adding new object """ @@ -307,6 +313,7 @@ class ActionSelectObj(ActionBase): self.editor.select(obj[OG.OBJ_NP], fMultiSelect=1, fUndo=0) self.selectedUIDs = [] + class ActionTransformObj(ActionBase): """ Action class for object transformation """ @@ -343,6 +350,7 @@ class ActionTransformObj(ActionBase): del self.origMat self.origMat = None + class ActionDeselectAll(ActionBase): """ Action class for adding new object """ @@ -369,6 +377,7 @@ class ActionDeselectAll(ActionBase): self.editor.select(obj[OG.OBJ_NP], fMultiSelect=1, fUndo=0) self.selectedUIDs = [] + class ActionUpdateObjectProp(ActionBase): """ Action class for updating object property """ diff --git a/direct/src/leveleditor/AnimControlUI.py b/direct/src/leveleditor/AnimControlUI.py index 2137da5c35..b10bb32647 100755 --- a/direct/src/leveleditor/AnimControlUI.py +++ b/direct/src/leveleditor/AnimControlUI.py @@ -5,7 +5,8 @@ from direct.interval.IntervalGlobal import * from direct.actor.Actor import * from . import ObjectGlobals as OG -import os, wx +import os +import wx from wx.lib.embeddedimage import PyEmbeddedImage #---------------------------------------------------------------------- @@ -431,10 +432,10 @@ class TimeSlider(wx.Window): else: pass - def OnSize(self,evt): + def OnSize(self, evt): self.InitBuffer() - def OnLeftDown(self,evt): + def OnLeftDown(self, evt): point = (evt.GetX(), evt.GetY()) if point[1]>= float(0) and point[1]<= (float(self.h)-2.0): @@ -449,12 +450,12 @@ class TimeSlider(wx.Window): self._mainDialog.OnAnimation(self.curFrame) self.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) - def OnLeftUp(self,evt): + def OnLeftUp(self, evt): if self.GetCapture(): self.ReleaseMouse() self._mouseIn = False - def OnMotion(self,evt): + def OnMotion(self, evt): self._mouseIn = False if evt.Dragging() and evt.LeftIsDown(): point = (evt.GetX(), evt.GetY()) @@ -532,10 +533,10 @@ class TimeRange(wx.Window): dc.DrawRoundedRectangleRect(self.curRect, radius = 2) - def OnSize(self,evt): + def OnSize(self, evt): self.InitBuffer() - def OnLeftDown(self,evt): + def OnLeftDown(self, evt): point = (evt.GetX(), evt.GetY()) self.pos = 0 @@ -547,12 +548,12 @@ class TimeRange(wx.Window): self.CaptureMouse() self.pos = point - def OnLeftUp(self,evt): + def OnLeftUp(self, evt): if self.GetCapture(): self.ReleaseMouse() self._mouseIn = False - def OnMotion(self,evt): + def OnMotion(self, evt): self._mouseIn = False if evt.Dragging() and evt.LeftIsDown(): newPos = (evt.GetX(), evt.GetY()) @@ -626,7 +627,7 @@ class AnimControlUI(wx.Dialog): self.mainPanel1 = wx.Panel(self, -1) self.timeSlider = TimeSlider(self.mainPanel1, wx.Size(560, 35), self.sliderStartFrame, self.sliderEndFrame, self.curFrame) - self.curFrameSpin = wx.SpinCtrl(self.mainPanel1, -1, "",size = (70,25),min=self.startFrame, max=self.endFrame) + self.curFrameSpin = wx.SpinCtrl(self.mainPanel1, -1, "",size = (70,25), min=self.startFrame, max=self.endFrame) bmpFirstFrame = FirstFrame.GetBitmap() bmpPreFrame = PreFrame.GetBitmap() @@ -640,23 +641,23 @@ class AnimControlUI(wx.Dialog): self.bmpStop = Stop.GetBitmap() bmpDeleteKey = DeleteKey.GetBitmap() - self.buttonFirstFrame = wx.BitmapButton(self.mainPanel1, -1, bmpFirstFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonPreFrame = wx.BitmapButton(self.mainPanel1, -1, bmpPreFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonPreKeyFrame = wx.BitmapButton(self.mainPanel1, -1, bmpPreKeyFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPrePlay, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPlay, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonNextKeyFrame = wx.BitmapButton(self.mainPanel1, -1, bmpNextKeyFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonNextFrame = wx.BitmapButton(self.mainPanel1, -1, bmpNextFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonLastFrame = wx.BitmapButton(self.mainPanel1, -1, bmpLastFrame, size = (30,30),style = wx.BU_AUTODRAW) + self.buttonFirstFrame = wx.BitmapButton(self.mainPanel1, -1, bmpFirstFrame, size = (30,30), style = wx.BU_AUTODRAW) + self.buttonPreFrame = wx.BitmapButton(self.mainPanel1, -1, bmpPreFrame, size = (30,30), style = wx.BU_AUTODRAW) + self.buttonPreKeyFrame = wx.BitmapButton(self.mainPanel1, -1, bmpPreKeyFrame, size = (30,30), style = wx.BU_AUTODRAW) + self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPrePlay, size = (30,30), style = wx.BU_AUTODRAW) + self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPlay, size = (30,30), style = wx.BU_AUTODRAW) + self.buttonNextKeyFrame = wx.BitmapButton(self.mainPanel1, -1, bmpNextKeyFrame, size = (30,30), style = wx.BU_AUTODRAW) + self.buttonNextFrame = wx.BitmapButton(self.mainPanel1, -1, bmpNextFrame, size = (30,30), style = wx.BU_AUTODRAW) + self.buttonLastFrame = wx.BitmapButton(self.mainPanel1, -1, bmpLastFrame, size = (30,30), style = wx.BU_AUTODRAW) self.mainPanel2 = wx.Panel(self, -1) - self.timeStartSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=0, max=self.sliderEndFrame) - self.timeSliderStartSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=self.startFrame, max=self.sliderEndFrame) + self.timeStartSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25), min=0, max=self.sliderEndFrame) + self.timeSliderStartSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25), min=self.startFrame, max=self.sliderEndFrame) self.timeRange = TimeRange(self.mainPanel2, wx.Size(450, 25), self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) - self.timeSliderEndSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=self.sliderStartFrame, max=self.endFrame) - self.timeEndSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=self.sliderStartFrame, max=10000) - self.buttonDeleteKey = wx.BitmapButton(self.mainPanel2, -1, bmpDeleteKey, size = (30,30),style = wx.BU_AUTODRAW) + self.timeSliderEndSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25), min=self.sliderStartFrame, max=self.endFrame) + self.timeEndSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25), min=self.sliderStartFrame, max=10000) + self.buttonDeleteKey = wx.BitmapButton(self.mainPanel2, -1, bmpDeleteKey, size = (30,30), style = wx.BU_AUTODRAW) self.SetProperties() self.DoLayout() @@ -742,11 +743,11 @@ class AnimControlUI(wx.Dialog): self.timeSlider.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) self.OnAnimation(self.curFrame) - def OnFirstFrame(self,evt): + def OnFirstFrame(self, evt): self.curFrame = self.sliderStartFrame self.OnControl() - def OnPreFrame(self,evt): + def OnPreFrame(self, evt): if self.curFrame-1 >= self.startFrame: self.curFrame -= 1 self.OnControl() @@ -761,7 +762,7 @@ class AnimControlUI(wx.Dialog): self.keys[i] = self.keys[j] self.keys[j] = temp - def OnPreKeyFrame(self,evt): + def OnPreKeyFrame(self, evt): self.sortKey() if self.curFrame <= self.keys[0] or self.curFrame > self.keys[len(self.keys)-1]: self.curFrame = self.keys[len(self.keys)-1] @@ -772,8 +773,8 @@ class AnimControlUI(wx.Dialog): break self.OnControl() - def OnTimer(self,evt): - if self.prePlay == True and self.stop == False and self.play == False: + def OnTimer(self, evt): + if self.prePlay is True and self.stop is False and self.play is False: if self.curFrame-1>=self.sliderStartFrame: self.curFrame -= 1 self.OnControl() @@ -781,7 +782,7 @@ class AnimControlUI(wx.Dialog): self.curFrame = self.sliderEndFrame self.OnControl() - if self.play == True and self.stop == False and self.prePlay == False: + if self.play is True and self.stop is False and self.prePlay is False: if self.curFrame+1<=self.sliderEndFrame: self.curFrame += 1 self.OnControl() @@ -789,45 +790,45 @@ class AnimControlUI(wx.Dialog): self.curFrame = self.sliderStartFrame self.OnControl() - def OnPrePlay(self,evt): - if self.prePlay == False and self.stop == True and self.play == False: - self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpStop, size = (30,30),style = wx.BU_AUTODRAW) + def OnPrePlay(self, evt): + if self.prePlay is False and self.stop is True and self.play is False: + self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpStop, size = (30,30), style = wx.BU_AUTODRAW) self.DoLayout() self.prePlay = True self.stop = False self.timer.Start(self.timeUnit) evt.Skip() - elif self.prePlay == True and self.stop == False and self.play == False: - self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPrePlay, size = (30,30),style = wx.BU_AUTODRAW) - self.DoLayout() - self.prePlay = False - self.stop = True - self.timer.Stop() - evt.Skip() + elif self.prePlay is True and self.stop is False and self.play is False: + self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPrePlay, size = (30,30), style = wx.BU_AUTODRAW) + self.DoLayout() + self.prePlay = False + self.stop = True + self.timer.Stop() + evt.Skip() else: evt.Skip() - def OnPlay(self,evt): - if self.play == False and self.stop == True and self.prePlay == False: - self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpStop, size = (30,30),style = wx.BU_AUTODRAW) + def OnPlay(self, evt): + if self.play is False and self.stop is True and self.prePlay is False: + self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpStop, size = (30,30), style = wx.BU_AUTODRAW) self.DoLayout() self.play = True self.stop = False self.timer.Start(self.timeUnit) evt.Skip() - elif self.play == True and self.stop == False and self.prePlay == False: - self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPlay, size = (30,30),style = wx.BU_AUTODRAW) - self.DoLayout() - self.play = False - self.stop = True - self.timer.Stop() - evt.Skip() + elif self.play is True and self.stop is False and self.prePlay is False: + self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPlay, size = (30,30), style = wx.BU_AUTODRAW) + self.DoLayout() + self.play = False + self.stop = True + self.timer.Stop() + evt.Skip() else: evt.Skip() - def OnNextKeyFrame(self,evt): + def OnNextKeyFrame(self, evt): self.sortKey() if self.curFrame < self.keys[0] or self.curFrame >= self.keys[len(self.keys)-1]: self.curFrame = self.keys[0] @@ -838,14 +839,14 @@ class AnimControlUI(wx.Dialog): break self.OnControl() - def OnNextFrame(self,evt): + def OnNextFrame(self, evt): if self.curFrame+1 <= self.endFrame: self.curFrame += 1 self.OnControl() else: evt.Skip() - def OnLastFrame(self,evt): + def OnLastFrame(self, evt): self.curFrame = self.sliderEndFrame self.OnControl() @@ -857,7 +858,7 @@ class AnimControlUI(wx.Dialog): self.timeRange.SetTimeRangeData(self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) self.parallel = self.editor.animMgr.createParallel(self.startFrame,self.endFrame) - def OnTimeStartSpin(self,evt): + def OnTimeStartSpin(self, evt): self.startFrame = evt.GetInt() self.timeSliderStartSpin.SetRange(self.startFrame, self.sliderEndFrame) if self.startFrame >= self.sliderStartFrame: @@ -867,17 +868,17 @@ class AnimControlUI(wx.Dialog): else: self.OnTime() - def OnTimeSliderStartSpin(self,evt): + def OnTimeSliderStartSpin(self, evt): self.sliderStartFrame = evt.GetInt() self.timeEndSpin.SetRange(self.sliderStartFrame, 10000) self.OnTime() - def OnTimeSliderEndSpin(self,evt): + def OnTimeSliderEndSpin(self, evt): self.sliderEndFrame = evt.GetInt() self.timeStartSpin.SetRange(0, self.sliderEndFrame) self.OnTime() - def OnTimeEndSpin(self,evt): + def OnTimeEndSpin(self, evt): self.endFrame = evt.GetInt() self.timeSliderEndSpin.SetRange(self.sliderStartFrame, self.endFrame) if self.endFrame <= self.sliderEndFrame: @@ -887,7 +888,7 @@ class AnimControlUI(wx.Dialog): else: self.OnTime() - def OnDeleteKey(self,evt): + def OnDeleteKey(self, evt): for i in range(0,len(self.keys)): if self.curFrame == self.keys[i]: del self.keys[i] @@ -914,10 +915,10 @@ class AnimControlUI(wx.Dialog): def OnAnimation(self, curFrame): time = float(curFrame-1)/float(24) self.parallel.setT(time) - if self.editor.GRAPH_EDITOR == True: + if self.editor.GRAPH_EDITOR is True: self.editor.ui.graphEditorUI.curFrameChange() - def OnExit(self,evt): + def OnExit(self, evt): for actor in self.editor.objectMgr.Actor: actorAnim = os.path.basename(actor[OG.OBJ_ANIM]) actor[OG.OBJ_NP].loop(actorAnim) @@ -925,10 +926,3 @@ class AnimControlUI(wx.Dialog): self.Destroy() self.editor.ui.editAnimMenuItem.Check(False) self.editor.mode = self.editor.BASE_MODE - - - - - - - diff --git a/direct/src/leveleditor/AnimGlobals.py b/direct/src/leveleditor/AnimGlobals.py index 0571cfbabc..cbbc53c063 100755 --- a/direct/src/leveleditor/AnimGlobals.py +++ b/direct/src/leveleditor/AnimGlobals.py @@ -50,4 +50,3 @@ SELECT = 1 X = 0 Y = 1 Z = 2 - diff --git a/direct/src/leveleditor/AnimMgrBase.py b/direct/src/leveleditor/AnimMgrBase.py index 09cf49f73c..56d512c365 100755 --- a/direct/src/leveleditor/AnimMgrBase.py +++ b/direct/src/leveleditor/AnimMgrBase.py @@ -2,13 +2,15 @@ Defines AnimMgrBase """ -import os, math +import os +import math from direct.interval.IntervalGlobal import * from panda3d.core import VBase3 from . import ObjectGlobals as OG from . import AnimGlobals as AG + class AnimMgrBase: """ AnimMgr will create, manage, update animations in the scene """ @@ -20,7 +22,7 @@ class AnimMgrBase: self.curveAnimation = {} #normal properties - self.lerpFuncs={ + self.lerpFuncs = { 'H' : self.lerpFuncH, 'P' : self.lerpFuncP, 'R' : self.lerpFuncR, @@ -31,14 +33,14 @@ class AnimMgrBase: 'CG' : self.lerpFuncCG, 'CB' : self.lerpFuncCB, 'CA' : self.lerpFuncCA - } + } #Properties which has animation curves - self.curveLerpFuncs={ + self.curveLerpFuncs = { 'X' : [ self.lerpFuncX, self.lerpCurveFuncX ], 'Y' : [ self.lerpFuncY, self.lerpCurveFuncY ], 'Z' : [ self.lerpFuncZ, self.lerpCurveFuncZ ] - } + } def reset(self): self.keyFramesInfo = {} @@ -55,7 +57,7 @@ class AnimMgrBase: if frame == keyFrame: exist = True break - if exist == False: + if not exist: self.keyFrames.append(frame) def generateSlope(self, list): @@ -354,7 +356,7 @@ class AnimMgrBase: self.colorUpdate(r,g,b,A,np) def colorUpdate(self, r, g, b, a, np): - if base.direct.selected.last == None: + if base.direct.selected.last is None: self.editor.objectMgr.updateObjectColor(r, g, b, a, np) elif self.editor.objectMgr.findObjectByNodePath(np) == self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last): self.editor.ui.objectPropertyUI.propCR.setValue(r) @@ -364,4 +366,3 @@ class AnimMgrBase: self.editor.objectMgr.updateObjectColor(r, g, b, a, np) else: self.editor.objectMgr.updateObjectColor(r, g, b, a, np) - diff --git a/direct/src/leveleditor/CurveAnimUI.py b/direct/src/leveleditor/CurveAnimUI.py index ca99d1eca4..37a16245fb 100755 --- a/direct/src/leveleditor/CurveAnimUI.py +++ b/direct/src/leveleditor/CurveAnimUI.py @@ -78,7 +78,7 @@ class CurveAnimUI(wx.Dialog): self.Layout() def OnChooseNode(self, evt): - if base.direct.selected.last == None or base.direct.selected.last.hasTag('Controller') or not base.direct.selected.last.hasTag('OBJRoot'): + if base.direct.selected.last is None or base.direct.selected.last.hasTag('Controller') or not base.direct.selected.last.hasTag('OBJRoot'): dlg = wx.MessageDialog(None, 'Please select an object.', 'NOTICE', wx.OK ) dlg.ShowModal() dlg.Destroy() @@ -93,7 +93,7 @@ class CurveAnimUI(wx.Dialog): self.chooseNodeTxt.SetValue(str(self.nodePath[OG.OBJ_UID])) def OnChooseCurve(self, evt): - if base.direct.selected.last == None or base.direct.selected.last.hasTag('Controller') or not base.direct.selected.last.hasTag('OBJRoot'): + if base.direct.selected.last is None or base.direct.selected.last.hasTag('Controller') or not base.direct.selected.last.hasTag('OBJRoot'): dlg = wx.MessageDialog(None, 'Please select a curve.', 'NOTICE', wx.OK ) dlg.ShowModal() dlg.Destroy() @@ -109,7 +109,7 @@ class CurveAnimUI(wx.Dialog): def OnCreateAnim(self, evt): self.time = self.duritionTimeSpin.GetValue() - if self.nodePath == None or self.curve == None: + if self.nodePath is None or self.curve is None: dlg = wx.MessageDialog(None, 'Please select an object and a curve first.', 'NOTICE', wx.OK ) dlg.ShowModal() dlg.Destroy() @@ -143,17 +143,10 @@ class CurveAnimUI(wx.Dialog): hasKey = True return - if hasKey == False and self.editor.animMgr.curveAnimation != {}: + if not hasKey and self.editor.animMgr.curveAnimation != {}: self.editor.animMgr.curveAnimation[(self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID])] = (self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID],self.time) self.editor.updateStatusReadout('Sucessfully saved to global animation list') def OnExit(self,evt): self.Destroy() self.editor.ui.curveAnimMenuItem.Check(False) - - - - - - - diff --git a/direct/src/leveleditor/CurveEditor.py b/direct/src/leveleditor/CurveEditor.py index 57cc119378..8142a69c07 100755 --- a/direct/src/leveleditor/CurveEditor.py +++ b/direct/src/leveleditor/CurveEditor.py @@ -30,9 +30,9 @@ class CurveEditor(DirectObject): x = base.direct.dr.mouseX y = base.direct.dr.mouseY - if self.editor.fMoveCamera == False and self.view != None: + if not self.editor.fMoveCamera and self.view is not None: self.createControler(x,y) - if self.currentRope != None: + if self.currentRope is not None: self.currentRope.detachNode() self.ropeUpdate(self.curve) self.accept("DIRECT-enter", self.onBaseMode) @@ -41,10 +41,10 @@ class CurveEditor(DirectObject): def editCurve(self, task): if self.editor.mode == self.editor.EDIT_CURVE_MODE: - if self.editor.fMoveCamera == False: + if not self.editor.fMoveCamera: self.selected = None self.selected = base.direct.selected.last - if self.selected != None: + if self.selected is not None: for item in self.curveControl: if item[1] == self.selected: self.point = item #temporarily save the controler information for further use @@ -102,9 +102,9 @@ class CurveEditor(DirectObject): base.direct.selected.last = None def createControler(self, x, y): - if self.view != None: - self.controler = render.attachNewNode("controler") - self.controler = loader.loadModel('models/misc/smiley') + if self.view is not None: + self.controler = base.render.attachNewNode("controler") + self.controler = base.loader.loadModel('models/misc/smiley') controlerPathname = 'controler%d' % self.i self.controler.setName(controlerPathname) self.controler.setColor(0, 0, 0, 1) @@ -143,4 +143,3 @@ class CurveEditor(DirectObject): self.curve.append((None, self.controler.getPos())) self.curveControl.append((self.i-1, self.controler)) - diff --git a/direct/src/leveleditor/GraphEditorUI.py b/direct/src/leveleditor/GraphEditorUI.py index 908fde08da..2521c8d8be 100755 --- a/direct/src/leveleditor/GraphEditorUI.py +++ b/direct/src/leveleditor/GraphEditorUI.py @@ -90,7 +90,7 @@ class GraphEditorWindow(wx.Window): self._mainDialog = wx.GetTopLevelParent(self) self.w,self.h = self.GetClientSize() - self.zoom = float(2) + self.zoom = 2.0 self._mouseIn = False self._selectRec = False self._selectHandler = False @@ -100,10 +100,10 @@ class GraphEditorWindow(wx.Window): self.curFrame = curFrame self.property = property - self.zeroPos = (float(0), self.h/float(2)) + self.zeroPos = (0.0, self.h / 2.0) self.zero = 0 - self.unitWidth = self.w/float(xRange) - self.unitHeight = self.h/float(yRange) + self.unitWidth = self.w / float(xRange) + self.unitHeight = self.h / float(yRange) self.generateInfo() self.InitBuffer() @@ -158,31 +158,31 @@ class GraphEditorWindow(wx.Window): t2x = item[AG.OUTSLOPE][0]*self.unitWidth t2y = item[AG.OUTSLOPE][1]*self.unitHeight - tanA = t1y/t1x - temp1 = float(1)/(tanA**2+1) - if t1x <0 : + tanA = t1y / t1x + temp1 = 1.0 / (tanA ** 2 + 1) + if t1x < 0: cosA = -math.sqrt(abs(temp1)) - if t1x >=0: + if t1x >= 0: cosA = math.sqrt(abs(temp1)) - temp2 = (tanA**2)*temp1 - if t1y <0 : + temp2 = (tanA ** 2) * temp1 + if t1y < 0: sinA = -math.sqrt(abs(temp2)) - if t1y >=0: + if t1y >= 0: sinA = math.sqrt(abs(temp2)) x2 = x1-float(self.unitWidth*self.zoom)*cosA y2 = y1+float(self.unitWidth*self.zoom)*sinA - tanA = t2y/t2x - temp1 = float(1)/(tanA**2+1) - if t2x <0 : + tanA = t2y / t2x + temp1 = 1.0 / (tanA ** 2 + 1) + if t2x < 0: cosA = -math.sqrt(abs(temp1)) - if t2x >=0: + if t2x >= 0: cosA = math.sqrt(abs(temp1)) - temp2 = (tanA**2)*temp1 - if t2y <0 : + temp2 = (tanA ** 2) * temp1 + if t2y < 0: sinA = -math.sqrt(abs(temp2)) - if t2y >=0: + if t2y >= 0: sinA = math.sqrt(abs(temp2)) x3 = x1+float(self.unitWidth*self.zoom)*cosA @@ -216,7 +216,7 @@ class GraphEditorWindow(wx.Window): dc.SetBrush(wx.BLACK_BRUSH) dc.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL)) - dc.DrawLine(self.zeroPos[0], float(0), self.zeroPos[0], self.h) + dc.DrawLine(self.zeroPos[0], 0.0, self.zeroPos[0], self.h) st = str(self.zero) self.tw,self.th = dc.GetTextExtent(st) dc.DrawText(st, self.zeroPos[0]+1.0, self.h-self.th-0.5) @@ -228,7 +228,7 @@ class GraphEditorWindow(wx.Window): posPos = self.zeroPos[0]+self.unitWidth posNum = self.zero + 1 while posPos <= self.w: - dc.DrawLine(posPos, float(0), posPos, self.h) + dc.DrawLine(posPos, 0.0, posPos, self.h) st = str(posNum) self.drawXNumber(dc, st, posPos) posPos += self.unitWidth @@ -236,37 +236,37 @@ class GraphEditorWindow(wx.Window): negPos = self.zeroPos[0]-self.unitWidth negNum = self.zero - 1 - while negPos >= float(0): - dc.DrawLine(negPos, float(0), negPos, self.h) + while negPos >= 0.0: + dc.DrawLine(negPos, 0.0, negPos, self.h) st = str(negNum) self.drawXNumber(dc, st, negPos) negPos -= self.unitWidth posNum -= 1 elif self.unitWidth >= 10 and self.unitWidth <= 25: - posPos = self.zeroPos[0]+self.unitWidth*float(2) + posPos = self.zeroPos[0]+self.unitWidth*2.0 posNum = self.zero + 2 while posPos <= self.w: - dc.DrawLine(posPos, float(0), posPos, self.h) + dc.DrawLine(posPos, 0.0, posPos, self.h) st = str(posNum) self.drawXNumber(dc, st, posPos) - posPos += self.unitWidth*float(2) + posPos += self.unitWidth*2.0 posNum += 2 - negPos = self.zeroPos[0]-self.unitWidth*float(2) + negPos = self.zeroPos[0]-self.unitWidth*2.0 negNum = self.zero - 2 - while negPos >= float(0): - dc.DrawLine(negPos, float(0), negPos, self.h) + while negPos >= 0.0: + dc.DrawLine(negPos, 0.0, negPos, self.h) st = str(negNum) self.drawXNumber(dc, st, negPos) - negPos -= self.unitWidth*float(2) + negPos -= self.unitWidth*2.0 posNum -= 2 elif self.unitWidth >= 2 and self.unitWidth <= 10: posPos = self.zeroPos[0]+self.unitWidth*float(5) posNum = self.zero + 5 while posPos <= self.w: - dc.DrawLine(posPos, float(0), posPos, self.h) + dc.DrawLine(posPos, 0.0, posPos, self.h) st = str(posNum) self.drawXNumber(dc, st, posPos) posPos += self.unitWidth*float(5) @@ -274,8 +274,8 @@ class GraphEditorWindow(wx.Window): negPos = self.zeroPos[0]-self.unitWidth*float(5) negNum = self.zero - 5 - while negPos >= float(0): - dc.DrawLine(negPos, float(0), negPos, self.h) + while negPos >= 0.0: + dc.DrawLine(negPos, 0.0, negPos, self.h) st = str(negNum) self.drawXNumber(dc, st, negPos) negPos -= self.unitWidth*float(5) @@ -286,7 +286,7 @@ class GraphEditorWindow(wx.Window): dc.SetBrush(wx.BLACK_BRUSH) dc.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL)) - dc.DrawLine(float(0), self.zeroPos[1], self.w, self.zeroPos[1]) + dc.DrawLine(0.0, self.zeroPos[1], self.w, self.zeroPos[1]) st = str(self.zero) dc.DrawText(st, 5.0, self.zeroPos[1]-1.0) @@ -296,8 +296,8 @@ class GraphEditorWindow(wx.Window): posPos = self.zeroPos[1]-self.unitHeight*float(5) posNum = self.zero + 5 - while posPos >= float(0): - dc.DrawLine(float(0), posPos, self.w, posPos) + while posPos >= 0.0: + dc.DrawLine(0.0, posPos, self.w, posPos) st = str(posNum) self.drawYNumber(dc, st, posPos) posPos -= self.unitHeight*float(5) @@ -306,7 +306,7 @@ class GraphEditorWindow(wx.Window): negPos = self.zeroPos[1]+self.unitHeight*float(5) negNum = self.zero - 5 while negPos <= self.h: - dc.DrawLine(float(0), negPos, self.w, negPos) + dc.DrawLine(0.0, negPos, self.w, negPos) st = str(negNum) self.drawYNumber(dc, st, negPos) negPos += self.unitHeight*float(5) @@ -339,7 +339,7 @@ class GraphEditorWindow(wx.Window): curFramePos = self.zeroPos[0]+self.curFrame*self.unitWidth dc.SetPen(wx.Pen("red")) dc.SetBrush(wx.Brush("red")) - dc.DrawLine(curFramePos, float(0), curFramePos, self.h) + dc.DrawLine(curFramePos, 0.0, curFramePos, self.h) else: pass @@ -403,32 +403,32 @@ class GraphEditorWindow(wx.Window): t2x = list[i+1][AG.IN_SLOPE][0] t2y = list[i+1][AG.IN_SLOPE][1] - x2 = x1 + (x4 - x1) / float(3); - scale1 = (x2 - x1) / t1x; - y2 = y1 - t1y * scale1; + x2 = x1 + (x4 - x1) / 3.0 + scale1 = (x2 - x1) / t1x + y2 = y1 - t1y * scale1 - x3 = x4 - (x4 - x1) / float(3); - scale2 = (x4 - x3) / t2x; - y3 = y4 + t2y * scale2; + x3 = x4 - (x4 - x1) / 3.0 + scale2 = (x4 - x3) / t2x + y3 = y4 + t2y * scale2 - ax = - float(1) * x1 + float(3) * x2 - float(3) * x3 + float(1) * x4; - bx = float(3) * x1 - float(6) * x2 + float(3) * x3 + float(0) * x4; - cx = - float(3) * x1 + float(3) * x2 + float(0) * x3 + float(0) * x4; - dx = float(1) * x1 + float(0) * x2 - float(0) * x3 + float(0) * x4; + ax = - 1.0 * x1 + 3.0 * x2 - 3.0 * x3 + 1.0 * x4 + bx = 3.0 * x1 - 6.0 * x2 + 3.0 * x3 + 0.0 * x4 + cx = - 3.0 * x1 + 3.0 * x2 + 0.0 * x3 + 0.0 * x4 + dx = 1.0 * x1 + 0.0 * x2 - 0.0 * x3 + 0.0 * x4 - ay = - float(1) * y1 + float(3) * y2 - float(3) * y3 + float(1) * y4; - by = float(3) * y1 - float(6) * y2 + float(3) * y3 + float(0) * y4; - cy = - float(3) * y1 + float(3) * y2 + float(0) * y3 + float(0) * y4; - dy = float(1) * y1 + float(0) * y2 - float(0) * y3 + float(0) * y4; + ay = - 1.0 * y1 + 3.0 * y2 - 3.0 * y3 + 1.0 * y4 + by = 3.0 * y1 - 6.0 * y2 + 3.0 * y3 + 0.0 * y4 + cy = - 3.0 * y1 + 3.0 * y2 + 0.0 * y3 + 0.0 * y4 + dy = 1.0 * y1 + 0.0 * y2 - 0.0 * y3 + 0.0 * y4 preX = x1 preY = y1 t = 0.001 - while t<=float(1): - x = ax * t*t*t + bx * t*t + cx * t + dx; - y = ay * t*t*t + by * t*t + cy * t + dy; + while t <= 1.0: + x = ax * t*t*t + bx * t*t + cx * t + dx + y = ay * t*t*t + by * t*t + cy * t + dy curX = x curY = y @@ -537,8 +537,8 @@ class GraphEditorWindow(wx.Window): def OnLeftDown(self,evt): point = (evt.GetX(), evt.GetY()) - if point[1]>= float(0) and point[1]<= float(self.h): - if point[0]>= float(0) and point[0]<= float(self.w): + if point[1]>= 0.0 and point[1]<= float(self.h): + if point[0]>= 0.0 and point[0]<= float(self.w): self._mouseIn = True if self._mouseIn: @@ -556,8 +556,8 @@ class GraphEditorWindow(wx.Window): def OnMiddleDown(self,evt): point = (evt.GetX(), evt.GetY()) - if point[1]>= float(0) and point[1]<= float(self.h): - if point[0]>= float(0) and point[0]<= float(self.w): + if point[1]>= 0.0 and point[1]<= float(self.h): + if point[0]>= 0.0 and point[0]<= float(self.w): self._mouseIn = True if self._mouseIn: @@ -572,8 +572,8 @@ class GraphEditorWindow(wx.Window): self._mouseIn = False if evt.Dragging() and evt.LeftIsDown(): self.newPos = (evt.GetX(), evt.GetY()) - if self.newPos[1]>= float(0) and self.newPos[1]<= float(self.h): - if self.newPos[0]>= float(0) and self.newPos[0]<= float(self.w): + if self.newPos[1]>= 0.0 and self.newPos[1]<= float(self.h): + if self.newPos[0]>= 0.0 and self.newPos[0]<= float(self.w): self._mouseIn = True if self._mouseIn: @@ -586,8 +586,8 @@ class GraphEditorWindow(wx.Window): if evt.Dragging() and evt.MiddleIsDown(): self.newMidPos = (evt.GetX(), evt.GetY()) - if self.newMidPos[1]>= float(0) and self.newMidPos[1]<= float(self.h): - if self.newMidPos[0]>= float(0) and self.newMidPos[0]<= float(self.w): + if self.newMidPos[1]>= 0.0 and self.newMidPos[1]<= float(self.h): + if self.newMidPos[0]>= 0.0 and self.newMidPos[0]<= float(self.w): self._mouseIn = True if self._mouseIn: @@ -907,11 +907,3 @@ class GraphEditorUI(wx.Dialog): self.editor.ui.graphEditorMenuItem.Check(False) self.object = None self.editor.GRAPH_EDITOR = False - - - - - - - - diff --git a/direct/src/leveleditor/LayerEditorUI.py b/direct/src/leveleditor/LayerEditorUI.py index e30dc343b4..2db7929fee 100644 --- a/direct/src/leveleditor/LayerEditorUI.py +++ b/direct/src/leveleditor/LayerEditorUI.py @@ -6,6 +6,7 @@ from panda3d.core import * from . import ObjectGlobals as OG + class LayerEditorUI(wx.Panel): def __init__(self, parent, editor): wx.Panel.__init__(self, parent) @@ -21,11 +22,13 @@ class LayerEditorUI(wx.Panel): sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.llist, 1, wx.EXPAND, 0) - self.SetSizer(sizer); self.Layout() + self.SetSizer(sizer) + self.Layout() parentSizer = wx.BoxSizer(wx.VERTICAL) parentSizer.Add(self, 1, wx.EXPAND, 0) - parent.SetSizer(parentSizer); parent.Layout() + parent.SetSizer(parentSizer) + parent.Layout() self.opAdd = "Add Layer" self.opDelete = "Delete Layer" @@ -77,30 +80,30 @@ class LayerEditorUI(wx.Panel): #import pdb;set_trace() hitItem, flags = self.llist.HitTest(pos) if hitItem == -1: - self.menuAppendGenItems() + self.menuAppendGenItems() else: - self.menuAppendObjItems(hitItem) + self.menuAppendObjItems(hitItem) self.PopupMenu(self.popupmenu, pos) def onPopupItemSelected(self, event): menuItem = self.popupmenu.FindItemById(event.GetId()) text = menuItem.GetText() if text == self.opAddObj: - self.addObj() + self.addObj() elif text == self.opRemoveObj: - self.removeObj() + self.removeObj() elif text == self.opShowObj: - self.HideObj(False) + self.HideObj(False) elif text == self.opHideObj: - self.HideObj(True) + self.HideObj(True) elif text == self.opAdd: - self.addLayer() + self.addLayer() elif text == self.opDelete: - self.deleteLayer() + self.deleteLayer() elif text == self.opRename: - self.renameLayer() + self.renameLayer() else: - wx.MessageBox("You selected item '%s'" % text) + wx.MessageBox("You selected item '%s'" % text) def reset(self): #import pdb;set_trace() @@ -114,7 +117,7 @@ class LayerEditorUI(wx.Panel): for index in range(self.llist.GetItemCount()): itemtext = self.llist.GetItemText(index) if itemtext == text: - return True + return True return found def addLayerData(self, idx, objUID): @@ -128,7 +131,7 @@ class LayerEditorUI(wx.Panel): layersData = list() self.layersDataDict[idx] = layersData if idx > self.layersDataDictNextKey: - self.layersDataDictNextKey = idx + self.layersDataDictNextKey = idx def addLayer(self): #import pdb;set_trace() @@ -137,9 +140,9 @@ class LayerEditorUI(wx.Panel): text = "Layer%s"%(count + i) found = self.findLabel(text) while found: - i = i + 1 - text = "Layer%s"%(count + i) - found = self.findLabel(text) + i = i + 1 + text = "Layer%s"%(count + i) + found = self.findLabel(text) self.layersDataDictNextKey = self.layersDataDictNextKey + 1 self.addLayerEntry(text, self.layersDataDictNextKey) @@ -147,15 +150,15 @@ class LayerEditorUI(wx.Panel): def deleteLayer(self): index = self.llist.GetFirstSelected() if index != -1: - key = self.llist.GetItemData(index) - del(self.layersDataDict[key]) - item = self.llist.DeleteItem(index) + key = self.llist.GetItemData(index) + del self.layersDataDict[key] + item = self.llist.DeleteItem(index) def renameLayer(self): index = self.llist.GetFirstSelected() if index != -1: - self.llist.SetItemState(index, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED) - self.llist.SetItemState(index, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED) + self.llist.SetItemState(index, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED) + self.llist.SetItemState(index, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED) def removeObjData(self, objUID): layersDataDictKeys = list(self.layersDataDict.keys()) @@ -163,41 +166,41 @@ class LayerEditorUI(wx.Panel): layersData = self.layersDataDict[layersDataDictKeys[i]] for j in range(len(layersData)): if layersData[j] == objUID: - del(layersData[j]) + del layersData[j] def removeObj(self): objNodePath = base.direct.selected.last if objNodePath is None: - wx.MessageBox("No object was selected.", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) - return + wx.MessageBox("No object was selected.", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) + return obj = self.editor.objectMgr.findObjectByNodePath(objNodePath) if obj is not None: - self.removeObjData(obj[OG.OBJ_UID]) + self.removeObjData(obj[OG.OBJ_UID]) def addObj(self): index = self.llist.GetFirstSelected() if index == -1: - wx.MessageBox("No layer was selected.", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) - return + wx.MessageBox("No layer was selected.", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) + return objNodePath = base.direct.selected.last if objNodePath is None: - wx.MessageBox("No object was selected.", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) - return + wx.MessageBox("No object was selected.", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) + return # Checking if the object was laready added to the layer obj = self.editor.objectMgr.findObjectByNodePath(objNodePath) if obj is not None: - i = self.llist.GetItemData(index) - layersData = self.layersDataDict[i] - for j in range(len(layersData)): - if layersData[j] == obj[OG.OBJ_UID]: - wx.MessageBox("Selected object already is this layer", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) - return - # Looking for the object in the other layers - # If the object is found - delete it. - self.removeObj() + i = self.llist.GetItemData(index) + layersData = self.layersDataDict[i] + for j in range(len(layersData)): + if layersData[j] == obj[OG.OBJ_UID]: + wx.MessageBox("Selected object already is this layer", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) + return + # Looking for the object in the other layers + # If the object is found - delete it. + self.removeObj() - layersData.append(obj[OG.OBJ_UID]) + layersData.append(obj[OG.OBJ_UID]) def onShowMembers(self, event): item = event.GetItem() @@ -211,33 +214,33 @@ class LayerEditorUI(wx.Panel): layerMembers.append(namestr) dialog = wx.SingleChoiceDialog(None, layerName, self.editorTxt, layerMembers) if dialog.ShowModal() == wx.ID_OK: - #do something here - dialog.GetStringSelection() + #do something here + dialog.GetStringSelection() dialog.Destroy() def HideObj(self, hide): index = self.llist.GetFirstSelected() if index == -1: - wx.MessageBox("No layer was selected.", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) - return + wx.MessageBox("No layer was selected.", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) + return key = self.llist.GetItemData(index) layerData = self.layersDataDict[key] if len(layerData) == 0: - return + return for i in range(len(layerData)): obj = self.editor.objectMgr.findObjectById(layerData[i]) if hide: - obj[OG.OBJ_NP].hide() + obj[OG.OBJ_NP].hide() else: - obj[OG.OBJ_NP].show() + obj[OG.OBJ_NP].show() font = wx.Font font = self.llist.GetItemFont(index) if hide: - font.SetWeight(wx.FONTWEIGHT_BOLD) + font.SetWeight(wx.FONTWEIGHT_BOLD) else: - font.SetWeight(wx.FONTWEIGHT_NORMAL) + font.SetWeight(wx.FONTWEIGHT_NORMAL) self.llist.SetItemFont(index, font) def traverse(self): @@ -255,4 +258,3 @@ class LayerEditorUI(wx.Panel): self.saveData = [] self.traverse() return self.saveData - diff --git a/direct/src/leveleditor/LevelEditorBase.py b/direct/src/leveleditor/LevelEditorBase.py index 16ff696744..6afc4600f0 100755 --- a/direct/src/leveleditor/LevelEditorBase.py +++ b/direct/src/leveleditor/LevelEditorBase.py @@ -14,6 +14,7 @@ from .FileMgr import * from .ActionMgr import * from .MayaConverter import * + class LevelEditorBase(DirectObject): """ Base Class for Panda3D LevelEditor """ def __init__(self): @@ -101,8 +102,8 @@ class LevelEditorBase(DirectObject): def setTitleWithFilename(self, filename=""): title = self.ui.appname if filename != "": - filenameshort = os.path.basename(filename) - title = title + " (%s)"%filenameshort + filenameshort = os.path.basename(filename) + title = title + " (%s)"%filenameshort self.ui.SetLabel(title) def removeNodePathHook(self, nodePath): @@ -114,7 +115,7 @@ class LevelEditorBase(DirectObject): if base.direct.selected.last is not None and nodePath == base.direct.selected.last: # if base.direct.selected.last is refering to this # removed obj, clear the reference - if (hasattr(__builtins__,'last')): + if hasattr(__builtins__, 'last'): __builtins__.last = None else: __builtins__['last'] = None @@ -215,11 +216,11 @@ class LevelEditorBase(DirectObject): return if fMultiSelect == 0 and fLEPane == 0: - oldSelectedNPs = base.direct.selected.getSelectedAsList() - for oldNP in oldSelectedNPs: - obj = self.objectMgr.findObjectByNodePath(oldNP) - if obj: - self.ui.sceneGraphUI.deSelect(obj[OG.OBJ_UID]) + oldSelectedNPs = base.direct.selected.getSelectedAsList() + for oldNP in oldSelectedNPs: + obj = self.objectMgr.findObjectByNodePath(oldNP) + if obj: + self.ui.sceneGraphUI.deSelect(obj[OG.OBJ_UID]) self.objectMgr.selectObject(nodePath, fLEPane) self.ui.buildContextMenu(nodePath) @@ -242,8 +243,7 @@ class LevelEditorBase(DirectObject): reply = wx.MessageBox("Do you want to save current scene?", "Save?", wx.YES_NO | wx.ICON_QUESTION) if reply == wx.YES: - result = self.ui.onSave() - if result == False: + if not self.ui.onSave(): return base.direct.deselectAll() @@ -381,10 +381,10 @@ class LevelEditorBase(DirectObject): # add new status line, first check to see if it already exists alreadyExists = False for currLine in self.statusLines: - if (status == currLine[1]): + if status == currLine[1]: alreadyExists = True break - if (alreadyExists == False): + if not alreadyExists: time = globalClock.getRealTime() + 15 self.statusLines.append([time,status,color]) @@ -396,7 +396,7 @@ class LevelEditorBase(DirectObject): statusText += currLine[1] + '\n' lastColor = currLine[2] self.statusReadout.setText(statusText) - if (lastColor): + if lastColor: self.statusReadout.textNode.setCardColor( lastColor[0], lastColor[1], lastColor[2], lastColor[3]) self.statusReadout.textNode.setCardAsMargin(0.1, 0.1, 0.1, 0.1) @@ -407,7 +407,7 @@ class LevelEditorBase(DirectObject): def updateStatusReadoutTimeouts(self,task=None): removalList = [] for currLine in self.statusLines: - if (globalClock.getRealTime() >= currLine[0]): + if globalClock.getRealTime() >= currLine[0]: removalList.append(currLine) for currRemoval in removalList: self.statusLines.remove(currRemoval) @@ -420,10 +420,10 @@ class LevelEditorBase(DirectObject): def propMeetsReq(self, typeName, parentNP): if self.ui.parentToSelectedMenuItem.IsChecked(): - if base.direct.selected.last: - parent = base.le.objectMgr.findObjectByNodePath(base.direct.selected.last) - if parent: - parentNP[0] = parent[OG.OBJ_NP] + if base.direct.selected.last: + parent = base.le.objectMgr.findObjectByNodePath(base.direct.selected.last) + if parent: + parentNP[0] = parent[OG.OBJ_NP] else: - parentNP[0] = None + parentNP[0] = None return True diff --git a/direct/src/leveleditor/LevelEditorUIBase.py b/direct/src/leveleditor/LevelEditorUIBase.py index 33101dff22..6c9e6469b5 100755 --- a/direct/src/leveleditor/LevelEditorUIBase.py +++ b/direct/src/leveleditor/LevelEditorUIBase.py @@ -243,7 +243,7 @@ class LevelEditorUIBase(WxPandaShell): WxPandaShell.createMenu(self) def onGraphEditor(self,e): - if base.direct.selected.last == None: + if base.direct.selected.last is None: dlg = wx.MessageDialog(None, 'Please select a object first.', 'NOTICE', wx.OK ) dlg.ShowModal() dlg.Destroy() @@ -280,7 +280,7 @@ class LevelEditorUIBase(WxPandaShell): self.onCreateCurve(None) else: self.currentView = self.getCurrentView() - if self.currentView == None: + if self.currentView is None: dlg = wx.MessageDialog(None, 'Please select a viewport first.Do not support curve creation under four viewports.', 'NOTICE', wx.OK ) dlg.ShowModal() dlg.Destroy() @@ -306,12 +306,12 @@ class LevelEditorUIBase(WxPandaShell): self.createCurveMenuItem.Check(False) self.onEditCurve(None) else: - if base.direct.selected.last == None: + if base.direct.selected.last is None: dlg = wx.MessageDialog(None, 'Please select a curve first.', 'NOTICE', wx.OK ) dlg.ShowModal() dlg.Destroy() self.editCurveMenuItem.Check(False) - if base.direct.selected.last != None : + if base.direct.selected.last is not None : base.direct.manipulationControl.enableManipulation() self.createCurveMenuItem.Check(False) self.curveObj = self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last) @@ -388,7 +388,7 @@ class LevelEditorUIBase(WxPandaShell): def onRightDown(self, evt=None): """Invoked when the viewport is right-clicked.""" - if evt == None: + if evt is None: mpos = wx.GetMouseState() mpos = self.ScreenToClient((mpos.x, mpos.y)) else: @@ -643,17 +643,17 @@ class ViewportMenu(wx.Menu): wx.Menu.__init__(self) def addItem(self, name, parent = None, call = None, id = None): - if id == None: id = wx.NewId() - if parent == None: parent = self + if id is None: id = wx.NewId() + if parent is None: parent = self item = wx.MenuItem(parent, id, name) parent.AppendItem(item) - if call != None: + if call is not None: self.Bind(wx.EVT_MENU, call, item) def addMenu(self, name, parent = None, id = None): - if id == None: id = wx.NewId() + if id is None: id = wx.NewId() subMenu = wx.Menu() - if parent == None: parent = self + if parent is None: parent = self parent.AppendMenu(id, name, subMenu) return subMenu @@ -679,11 +679,10 @@ class CurveDegreeUI(wx.Dialog): self.SetSizer(degreeBox) def onApply(self, evt): - if(str(self.degree.GetSelection())=='0'): + if str(self.degree.GetSelection()) == '0': self.parent.editor.curveEditor.degree = 2 - if(str(self.degree.GetSelection())=='1'): + if str(self.degree.GetSelection()) == '1': self.parent.editor.curveEditor.degree = 3 - if(str(self.degree.GetSelection())=='2'): + if str(self.degree.GetSelection()) == '2': self.parent.editor.curveEditor.degree = 4 self.Destroy() - diff --git a/direct/src/leveleditor/LevelLoader.py b/direct/src/leveleditor/LevelLoader.py index 79f4a6644c..02a8eff994 100755 --- a/direct/src/leveleditor/LevelLoader.py +++ b/direct/src/leveleditor/LevelLoader.py @@ -29,4 +29,3 @@ class LevelLoader(LevelLoaderBase): base.protoPalette = ProtoPalette() base.objectHandler = ObjectHandler(None) base.objectMgr = ObjectMgr(None) - diff --git a/direct/src/leveleditor/MayaConverter.py b/direct/src/leveleditor/MayaConverter.py index 6c1feb4db1..712e03b99f 100755 --- a/direct/src/leveleditor/MayaConverter.py +++ b/direct/src/leveleditor/MayaConverter.py @@ -183,4 +183,3 @@ class MayaConverter(wx.Dialog): if self.callBack: self.callBack(result) - diff --git a/direct/src/leveleditor/ObjectHandler.py b/direct/src/leveleditor/ObjectHandler.py index b93fc82ddb..391adb3d57 100755 --- a/direct/src/leveleditor/ObjectHandler.py +++ b/direct/src/leveleditor/ObjectHandler.py @@ -9,6 +9,7 @@ from direct.actor import Actor from . import ObjectGlobals as OG + class ObjectHandler: """ ObjectHandler will create and update objects """ @@ -17,8 +18,8 @@ class ObjectHandler: def createDoubleSmiley(self, horizontal=True): root = render.attachNewNode('doubleSmiley') - a = loader.loadModel('models/smiley.egg') - b = loader.loadModel('models/smiley.egg') + a = base.loader.loadModel('models/smiley.egg') + b = base.loader.loadModel('models/smiley.egg') if horizontal: a.setName('left') b.setName('right') @@ -51,7 +52,7 @@ class ObjectHandler: child.removeNode() for i in range(val): - a = loader.loadModel(obj[OG.OBJ_MODEL]) + a = base.loader.loadModel(obj[OG.OBJ_MODEL]) b = a.find("+GeomNode") b.setPos(0, i*2, 0) b.reparentTo(objNP) @@ -62,15 +63,13 @@ class ObjectHandler: return pandaActor def createGrass(self): - environ = loader.loadModel("models/environment.egg") + environ = base.loader.loadModel("models/environment.egg") environ.setScale(0.25,0.25,0.25) environ.setPos(-8,42,0) return environ + class PandaActor(Actor.Actor): def __init__(self): Actor.Actor.__init__(self, "models/panda-model.egg") self.setScale(0.005) - - - diff --git a/direct/src/leveleditor/ObjectMgrBase.py b/direct/src/leveleditor/ObjectMgrBase.py index 2e9cc2a17c..c769384967 100755 --- a/direct/src/leveleditor/ObjectMgrBase.py +++ b/direct/src/leveleditor/ObjectMgrBase.py @@ -2,14 +2,18 @@ Defines ObjectMgrBase """ -import os, time, copy +import os +import time +import copy -from direct.task import Task -from direct.actor.Actor import Actor from panda3d.core import * +from direct.actor.Actor import Actor +from direct.task import Task +from direct.task.TaskManagerGlobal import taskMgr from .ActionMgr import * from . import ObjectGlobals as OG + # python wrapper around a panda.NodePath object class PythonNodePath(NodePath): def __init__(self,node): @@ -33,9 +37,9 @@ class ObjectMgrBase: self.currLiveNP = None self.Actor = [] - self.findActors(render) + self.findActors(base.render) self.Nodes = [] - self.findNodes(render) + self.findNodes(base.render) def reset(self): base.direct.deselectAllCB() @@ -66,7 +70,7 @@ class ObjectMgrBase: newUid = str(time.time()) + userId # prevent duplicates from being generated in the same frame (this can # happen when creating several new objects at once) - if (self.lastUid == newUid): + if self.lastUid == newUid: # append a value to the end to uniquify the id newUid = newUid + str(self.lastUidMod) self.lastUidMod = self.lastUidMod + 1 @@ -82,14 +86,14 @@ class ObjectMgrBase: #transfer the curve information from simple positions into control nodes for item in curveInfo: - controler = render.attachNewNode("controler") - controler = loader.loadModel('models/misc/smiley') + controler = base.render.attachNewNode("controler") + controler = base.loader.loadModel('models/misc/smiley') controlerPathname = 'controler%d' % item[0] controler.setName(controlerPathname) controler.setPos(item[1]) controler.setColor(0, 0, 0, 1) controler.setScale(0.2) - controler.reparentTo(render) + controler.reparentTo(base.render) controler.setTag('OBJRoot','1') controler.setTag('Controller','1') curve.append((None, item[1])) @@ -170,7 +174,7 @@ class ObjectMgrBase: if objDef is None: objDef = base.protoPalette.findItem(typeName) newobj = None - if objDef and type(objDef) != dict: + if objDef and not isinstance(objDef, dict): if not hasattr(objDef, 'createFunction'): return newobj if nodePath is None: @@ -184,7 +188,7 @@ class ObjectMgrBase: elif pair[1] == OG.ARG_PARENT: funcArgs[pair[0]] = parent - if type(funcName) == str: + if isinstance(funcName, str): if funcName.startswith('.'): # when it's using default objectHandler if self.editor: @@ -214,9 +218,9 @@ class ObjectMgrBase: if model is None: model = objDef.model try: - newobjModel = loader.loadModel(model) + newobjModel = base.loader.loadModel(model) except: - newobjModel = loader.loadModel(Filename.fromOsSpecific(model).getFullpath(), okMissing=True) + newobjModel = base.loader.loadModel(Filename.fromOsSpecific(model).getFullpath(), okMissing=True) if newobjModel: self.flatten(newobjModel, model, objDef, uid) newobj = PythonNodePath(newobjModel) @@ -360,7 +364,7 @@ class ObjectMgrBase: self.updateObjectPropertyUI(obj) #import pdb;pdb.set_trace() if fLEPane == 0: - self.editor.ui.sceneGraphUI.select(obj[OG.OBJ_UID]) + self.editor.ui.sceneGraphUI.select(obj[OG.OBJ_UID]) if not obj[OG.OBJ_DEF].movable: if base.direct.widget.fActive: @@ -509,7 +513,7 @@ class ObjectMgrBase: except: newobj = Actor(Filename.fromOsSpecific(model).getFullpath()) else: - newobjModel = loader.loadModel(model, okMissing=True) + newobjModel = base.loader.loadModel(model, okMissing=True) if newobjModel is None: print("Can't load model %s"%model) return @@ -682,7 +686,7 @@ class ObjectMgrBase: kwargs[key] = funcArgs[key] undoKwargs[key] = funcArgs[key] - if type(funcName) == str: + if isinstance(funcName, str): if funcName.startswith('.'): if self.editor: func = Functor(getattr(self.editor, "objectHandler%s"%funcName), **kwargs) @@ -719,7 +723,7 @@ class ObjectMgrBase: curveNode = obj[OG.OBJ_PROP]['curveInfo'] curveInfor = [] for item in curveNode: - curveInfor.append((None, item[1].getPos())) + curveInfor.append((None, item[1].getPos())) curve.setup(degree, curveInfor) def updateObjectProperties(self, nodePath, propValues): @@ -799,7 +803,7 @@ class ObjectMgrBase: def getSaveData(self): self.saveData = [] self.getPreSaveData() - self.traverse(render) + self.traverse(base.render) self.getPostSaveData() return self.saveData @@ -808,14 +812,12 @@ class ObjectMgrBase: if there are additional data to be saved before main data you can override this function to populate data """ - pass def getPostSaveData(self): """ if there are additional data to be saved after main data you can override this function to populate data """ - pass def duplicateObject(self, nodePath, parent=None): obj = self.findObjectByNodePath(nodePath) diff --git a/direct/src/leveleditor/ObjectPaletteBase.py b/direct/src/leveleditor/ObjectPaletteBase.py index 5bbfe38e50..f91461f843 100755 --- a/direct/src/leveleditor/ObjectPaletteBase.py +++ b/direct/src/leveleditor/ObjectPaletteBase.py @@ -1,10 +1,12 @@ import copy from . import ObjectGlobals as OG + class ObjectGen: """ Base class for obj definitions """ def __init__(self, name=''): - self.name = name + self.name = name + class ObjectBase(ObjectGen): """ Base class for obj definitions """ @@ -27,6 +29,7 @@ class ObjectBase(ObjectGen): # to show/hide properties per editor mode self.propertiesMask = copy.deepcopy(propertiesMask) + class ObjectCurve(ObjectBase): def __init__(self, *args, **kw): ObjectBase.__init__(self, *args, **kw) @@ -59,21 +62,21 @@ class ObjectPaletteBase: 'item' is the object to be inserted, it can be either a group or obj. 'parentName' is the name of parent under where this item will be inserted. """ - if type(self.data) != dict: - return None + if not isinstance(self.data, dict): + return None if parentName is None: - parentName = self.rootName + parentName = self.rootName self.dataStruct[item.name] = parentName self.data[item.name] = item self.dataKeys.append(item.name) def add(self, item, parentName = None): - if type(item) == str: - self.insertItem(ObjectGen(name = item), parentName) + if isinstance(item, str): + self.insertItem(ObjectGen(name = item), parentName) else: - self.insertItem(item, parentName) + self.insertItem(item, parentName) def addHidden(self, item): if hasattr(item, 'name'): @@ -81,27 +84,27 @@ class ObjectPaletteBase: def deleteStruct(self, name, deleteItems): try: - item = self.data.pop(name) - for key in list(self.dataStruct.keys()): - if self.dataStruct[key] == name: - node = self.deleteStruct(key, deleteItems) - if node is not None: - deleteItems[key] = node - return item + item = self.data.pop(name) + for key in list(self.dataStruct.keys()): + if self.dataStruct[key] == name: + node = self.deleteStruct(key, deleteItems) + if node is not None: + deleteItems[key] = node + return item except: - return None + return None return None def delete(self, name): try: - deleteItems = {} - node = self.deleteStruct(name, deleteItems) - if node is not None: - deleteItems[name] = node - for key in list(deleteItems.keys()): - item = self.dataStruct.pop(key) + deleteItems = {} + node = self.deleteStruct(name, deleteItems) + if node is not None: + deleteItems[name] = node + for key in list(deleteItems.keys()): + item = self.dataStruct.pop(key) except: - return + return return def findItem(self, name): @@ -122,13 +125,13 @@ class ObjectPaletteBase: def rename(self, oldName, newName): #import pdb;set_trace() if oldName == newName: - return False + return False if newName == "": - return False + return False try: for key in list(self.dataStruct.keys()): if self.dataStruct[key] == oldName: - self.dataStruct[key] = newName + self.dataStruct[key] = newName self.dataStruct[newName] = self.dataStruct.pop(oldName) item = self.data.pop(oldName) diff --git a/direct/src/leveleditor/ObjectPaletteUI.py b/direct/src/leveleditor/ObjectPaletteUI.py index ffd168a258..050be1838e 100755 --- a/direct/src/leveleditor/ObjectPaletteUI.py +++ b/direct/src/leveleditor/ObjectPaletteUI.py @@ -16,11 +16,13 @@ class ObjectPaletteUI(wx.Panel): sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.tree, 1, wx.EXPAND, 0) - self.SetSizer(sizer); self.Layout() + self.SetSizer(sizer) + self.Layout() parentSizer = wx.BoxSizer(wx.VERTICAL) parentSizer.Add(self, 1, wx.EXPAND, 0) - parent.SetSizer(parentSizer); parent.Layout() + parent.SetSizer(parentSizer) + parent.Layout() self.opSortAlpha = "Sort Alphabetical Order" self.opSortOrig = "Sort Original Order" @@ -53,19 +55,19 @@ class ObjectPaletteUI(wx.Panel): menuItem = self.popupmenu.FindItemById(event.GetId()) text = menuItem.GetText() if text == self.opSortAlpha: - self.opSort = self.opSortAlpha + self.opSort = self.opSortAlpha elif text == self.opSortOrig: - self.opSort = self.opSortOrig + self.opSort = self.opSortOrig self.tree.SortTreeNodes(self.tree.GetRootItem()) def compareItems(self, item1, item2): data1 = self.tree.GetItemText(item1) data2 = self.tree.GetItemText(item2) if self.opSort == self.opSortAlpha: - return cmp(data1, data2) + return cmp(data1, data2) else: - index1 = self.palette.dataKeys.index(data1) - index2 = self.palette.dataKeys.index(data2) + index1 = self.palette.dataKeys.index(data1) + index2 = self.palette.dataKeys.index(data2) return cmp(index1, index2) def getSelected(self): diff --git a/direct/src/leveleditor/ObjectPropertyUI.py b/direct/src/leveleditor/ObjectPropertyUI.py index 4b76cb8879..b1cb5259b0 100755 --- a/direct/src/leveleditor/ObjectPropertyUI.py +++ b/direct/src/leveleditor/ObjectPropertyUI.py @@ -115,13 +115,9 @@ class ObjectPropUI(wx.Panel): exist = True break - if exist == False: + if not exist: self.parent.editor.animMgr.keyFrames.append(frame) - self.parent.editor.ui.animUI.OnPropKey() - - else: - self.parent.editor.ui.animUI.OnPropKey() - + self.parent.editor.ui.animUI.OnPropKey() else: evt.Skip() @@ -320,7 +316,8 @@ class ObjectPropertyUI(ScrolledPanel): parentSizer = wx.BoxSizer(wx.VERTICAL) parentSizer.Add(self, 1, wx.EXPAND, 0) - parent.SetSizer(parentSizer); parent.Layout() + parent.SetSizer(parentSizer) + parent.Layout() self.SetDropTarget(AnimFileDrop(self.editor)) @@ -639,7 +636,7 @@ class ObjectPropertyUI(ScrolledPanel): lambda p0=None, p1=obj, p2=key: self.editor.objectMgr.updateObjectProperty(p0, p1, p2)) - self.propsPane.SetSizer(sizer); + self.propsPane.SetSizer(sizer) self.Layout() self.SetupScrolling(self, scroll_y = True, rate_y = 20) if self.lastPropTab == 'Transform': @@ -648,4 +645,3 @@ class ObjectPropertyUI(ScrolledPanel): self.nb.SetSelection(1) elif self.lastPropTab == 'Properties': self.nb.SetSelection(2) - diff --git a/direct/src/leveleditor/PaletteTreeCtrl.py b/direct/src/leveleditor/PaletteTreeCtrl.py index 75c752f0fc..a618ad5870 100644 --- a/direct/src/leveleditor/PaletteTreeCtrl.py +++ b/direct/src/leveleditor/PaletteTreeCtrl.py @@ -161,4 +161,3 @@ class PaletteTreeCtrl(wx.TreeCtrl): tds = wx.DropSource(self) tds.SetData(tdo) tds.DoDragDrop(True) - diff --git a/direct/src/leveleditor/ProtoObjs.py b/direct/src/leveleditor/ProtoObjs.py index a8e2c7bd34..59d433421e 100755 --- a/direct/src/leveleditor/ProtoObjs.py +++ b/direct/src/leveleditor/ProtoObjs.py @@ -8,8 +8,8 @@ import imp class ProtoObjs: def __init__(self, name): self.dirname = os.path.dirname(__file__) - self.name = name; - self.filename = "/%s.py"%(name) + self.name = name + self.filename = "/%s.py" % (name) self.data = {} def populate(self): @@ -24,7 +24,7 @@ class ProtoObjs: def saveProtoData(self, f): if not f: - return + return for key in self.data.keys(): f.write("\t'%s':'%s',\n"%(key, self.data[key])) diff --git a/direct/src/leveleditor/ProtoObjsUI.py b/direct/src/leveleditor/ProtoObjsUI.py index a4e09af9f3..40a933ce1b 100755 --- a/direct/src/leveleditor/ProtoObjsUI.py +++ b/direct/src/leveleditor/ProtoObjsUI.py @@ -7,38 +7,40 @@ import os from panda3d.core import * from .ProtoObjs import * + class ProtoDropTarget(wx.PyDropTarget): - """Implements drop target functionality to receive files, bitmaps and text""" - def __init__(self, ui): - wx.PyDropTarget.__init__(self) - self.ui = ui - self.do = wx.DataObjectComposite() # the dataobject that gets filled with the appropriate data - self.filedo = wx.FileDataObject() - self.textdo = wx.TextDataObject() - self.bmpdo = wx.BitmapDataObject() - self.do.Add(self.filedo) - self.do.Add(self.bmpdo) - self.do.Add(self.textdo) - self.SetDataObject(self.do) + """Implements drop target functionality to receive files, bitmaps and text""" + def __init__(self, ui): + wx.PyDropTarget.__init__(self) + self.ui = ui + self.do = wx.DataObjectComposite() # the dataobject that gets filled with the appropriate data + self.filedo = wx.FileDataObject() + self.textdo = wx.TextDataObject() + self.bmpdo = wx.BitmapDataObject() + self.do.Add(self.filedo) + self.do.Add(self.bmpdo) + self.do.Add(self.textdo) + self.SetDataObject(self.do) - def OnData(self, x, y, d): - """ - Handles drag/dropping files/text or a bitmap - """ - if self.GetData(): - df = self.do.GetReceivedFormat().GetType() - if df in [wx.DF_UNICODETEXT, wx.DF_TEXT]: - text = self.textdo.GetText() - # self.editor.ui.protoFontsUI.tree.ChangeHierarchy(text, x, y) + def OnData(self, x, y, d): + """ + Handles drag/dropping files/text or a bitmap + """ + if self.GetData(): + df = self.do.GetReceivedFormat().GetType() + if df in [wx.DF_UNICODETEXT, wx.DF_TEXT]: + text = self.textdo.GetText() + #self.editor.ui.protoFontsUI.tree.ChangeHierarchy(text, x, y) - elif df == wx.DF_FILENAME: - for name in self.filedo.GetFilenames(): - self.ui.AquireFile(name) + elif df == wx.DF_FILENAME: + for name in self.filedo.GetFilenames(): + self.ui.AquireFile(name) - elif df == wx.DF_BITMAP: - bmp = self.bmpdo.GetBitmap() + elif df == wx.DF_BITMAP: + bmp = self.bmpdo.GetBitmap() + + return d # you must return this - return d # you must return this class ProtoObjsUI(wx.Panel): def __init__(self, parent, editor, protoObjs, supportedExts): @@ -53,11 +55,13 @@ class ProtoObjsUI(wx.Panel): sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.llist, 1, wx.EXPAND, 0) - self.SetSizer(sizer); self.Layout() + self.SetSizer(sizer) + self.Layout() parentSizer = wx.BoxSizer(wx.VERTICAL) parentSizer.Add(self, 1, wx.EXPAND, 0) - parent.SetSizer(parentSizer); parent.Layout() + parent.SetSizer(parentSizer) + parent.Layout() self.opDelete = "Delete" self.menuItems = list() @@ -83,7 +87,7 @@ class ProtoObjsUI(wx.Panel): menuItem = self.popupmenu.FindItemById(event.GetId()) text = menuItem.GetText() if text == self.opDelete: - self.remove() + self.remove() def onShowPopup(self, event): pos = event.GetPosition() @@ -95,14 +99,14 @@ class ProtoObjsUI(wx.Panel): for index in range(self.llist.GetItemCount()): itemtext = self.llist.GetItemText(index) if itemtext == text: - return True + return True return found def removeItem(self, index): if index != -1: - key = self.llist.GetItemText(index) - del(self.protoObjs.data[key]) - item = self.llist.DeleteItem(index) + key = self.llist.GetItemText(index) + del self.protoObjs.data[key] + item = self.llist.DeleteItem(index) def remove(self): index = self.llist.GetFirstSelected() @@ -112,13 +116,13 @@ class ProtoObjsUI(wx.Panel): name = os.path.basename(filename) for ext in self.supportedExts: if name.upper().endswith(ext.upper()): - try: - index = self.llist.InsertStringItem(self.llist.GetItemCount(), name) - self.protoObjs.data[name]= filename - self.addObj(filename) - except: - pass - break + try: + index = self.llist.InsertStringItem(self.llist.GetItemCount(), name) + self.protoObjs.data[name]= filename + self.addObj(filename) + except: + pass + break def addNewItem(self, result): ProtoObjsUI.AquireFile(self, result[1]) @@ -126,6 +130,6 @@ class ProtoObjsUI(wx.Panel): def AquireFile(self, filename): label = self.findLabel(filename) if label: - self.removeItem(label) + self.removeItem(label) filenameFull = Filename.fromOsSpecific(filename).getFullpath() self.add(filenameFull) diff --git a/direct/src/leveleditor/ProtoPaletteBase.py b/direct/src/leveleditor/ProtoPaletteBase.py index 9d9aa3775f..c9e50821a3 100755 --- a/direct/src/leveleditor/ProtoPaletteBase.py +++ b/direct/src/leveleditor/ProtoPaletteBase.py @@ -42,13 +42,13 @@ class ProtoPaletteBase(ObjectPaletteBase): def saveProtoData(self, f): if not f: - return + return for key in list(self.data.keys()): if isinstance(self.data[key], ObjectBase): - f.write("\t'%s':ObjectBase(name='%s', model='%s', anims=%s, actor=%s),\n"%(key, self.data[key].name, self.data[key].model, self.data[key].anims, self.data[key].actor)) + f.write("\t'%s':ObjectBase(name='%s', model='%s', anims=%s, actor=%s),\n"%(key, self.data[key].name, self.data[key].model, self.data[key].anims, self.data[key].actor)) else: - f.write("\t'%s':ObjectGen(name='%s'),\n"%(key, self.data[key].name)) + f.write("\t'%s':ObjectGen(name='%s'),\n"%(key, self.data[key].name)) def saveToFile(self): try: diff --git a/direct/src/leveleditor/ProtoPaletteUI.py b/direct/src/leveleditor/ProtoPaletteUI.py index 6736311821..d07a6e4204 100755 --- a/direct/src/leveleditor/ProtoPaletteUI.py +++ b/direct/src/leveleditor/ProtoPaletteUI.py @@ -6,38 +6,39 @@ import os from panda3d.core import * from .PaletteTreeCtrl import * + class UniversalDropTarget(wx.DropTarget): - """Implements drop target functionality to receive files, bitmaps and text""" - def __init__(self, editor): - wx.DropTarget.__init__(self) - self.editor = editor - self.do = wx.DataObjectComposite() # the dataobject that gets filled with the appropriate data - self.filedo = wx.FileDataObject() - self.textdo = wx.TextDataObject() - self.bmpdo = wx.BitmapDataObject() - self.do.Add(self.filedo) - self.do.Add(self.bmpdo) - self.do.Add(self.textdo) - self.SetDataObject(self.do) + """Implements drop target functionality to receive files, bitmaps and text""" + def __init__(self, editor): + wx.DropTarget.__init__(self) + self.editor = editor + self.do = wx.DataObjectComposite() # the dataobject that gets filled with the appropriate data + self.filedo = wx.FileDataObject() + self.textdo = wx.TextDataObject() + self.bmpdo = wx.BitmapDataObject() + self.do.Add(self.filedo) + self.do.Add(self.bmpdo) + self.do.Add(self.textdo) + self.SetDataObject(self.do) - def OnData(self, x, y, d): - """ - Handles drag/dropping files/text or a bitmap - """ - if self.GetData(): - df = self.do.GetReceivedFormat().GetType() - if df in [wx.DF_UNICODETEXT, wx.DF_TEXT]: - text = self.textdo.GetText() - self.editor.ui.protoPaletteUI.tree.ChangeHierarchy(text, x, y) + def OnData(self, x, y, d): + """ + Handles drag/dropping files/text or a bitmap + """ + if self.GetData(): + df = self.do.GetReceivedFormat().GetType() + if df in [wx.DF_UNICODETEXT, wx.DF_TEXT]: + text = self.textdo.GetText() + self.editor.ui.protoPaletteUI.tree.ChangeHierarchy(text, x, y) - elif df == wx.DF_FILENAME: - for name in self.filedo.GetFilenames(): - self.editor.ui.protoPaletteUI.AquireFile(name) + elif df == wx.DF_FILENAME: + for name in self.filedo.GetFilenames(): + self.editor.ui.protoPaletteUI.AquireFile(name) - elif df == wx.DF_BITMAP: - bmp = self.bmpdo.GetBitmap() + elif df == wx.DF_BITMAP: + bmp = self.bmpdo.GetBitmap() - return d # you must return this + return d # you must return this class ProtoPaletteUI(wx.Panel): def __init__(self, parent, editor): @@ -76,11 +77,13 @@ class ProtoPaletteUI(wx.Panel): sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.tree, 1, wx.EXPAND, 0) - self.SetSizer(sizer); self.Layout() + self.SetSizer(sizer) + self.Layout() parentSizer = wx.BoxSizer(wx.VERTICAL) parentSizer.Add(self, 1, wx.EXPAND, 0) - parent.SetSizer(parentSizer); parent.Layout() + parent.SetSizer(parentSizer) + parent.Layout() self.tree.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginLabelEdit) self.tree.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnEndLabelEdit) @@ -100,16 +103,16 @@ class ProtoPaletteUI(wx.Panel): if item != self.tree.GetRootItem(): newLabel = event.GetLabel() if self.tree.traverse(self.tree.GetRootItem(), newLabel) is None: - oldLabel = self.tree.GetItemText(item) - if isinstance(self.editor.protoPalette.findItem(oldLabel), ObjectBase): - event.Veto() - wx.MessageBox("Only groups allowed to be renamed", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) - elif not self.editor.protoPalette.rename(oldLabel, newLabel): - event.Veto() - wx.MessageBox("Label '%s' is not allowed" % newLabel, self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) + oldLabel = self.tree.GetItemText(item) + if isinstance(self.editor.protoPalette.findItem(oldLabel), ObjectBase): + event.Veto() + wx.MessageBox("Only groups allowed to be renamed", self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) + elif not self.editor.protoPalette.rename(oldLabel, newLabel): + event.Veto() + wx.MessageBox("Label '%s' is not allowed" % newLabel, self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) else: - event.Veto() - wx.MessageBox("There is already an item labled '%s'" % newLabel, self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) + event.Veto() + wx.MessageBox("There is already an item labled '%s'" % newLabel, self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) else: event.Veto() wx.MessageBox("'%s' renaming is not allowed" % self.tree.rootName, self.editorTxt, wx.OK|wx.ICON_EXCLAMATION) @@ -135,13 +138,13 @@ class ProtoPaletteUI(wx.Panel): hitItem, flags = self.tree.HitTest(pos) if hitItem.IsOk(): - itemText = self.tree.GetItemText(hitItem) - if itemText != self.tree.rootName: - self.menuAppendSelItems() - else: - self.menuAppendGenItems() + itemText = self.tree.GetItemText(hitItem) + if itemText != self.tree.rootName: + self.menuAppendSelItems() + else: + self.menuAppendGenItems() else: - self.menuAppendGenItems() + self.menuAppendGenItems() self.PopupMenu(self.popupmenu, pos) @@ -149,23 +152,23 @@ class ProtoPaletteUI(wx.Panel): menuItem = self.popupmenu.FindItemById(event.GetId()) text = menuItem.GetText() if text == self.opAdd: - self.tree.AddGroup() + self.tree.AddGroup() elif text == self.opDelete: - self.tree.DeleteSelected() + self.tree.DeleteSelected() elif text == self.opSortAlpha: - self.opSort = self.opSortAlpha - self.tree.SortTreeNodes(self.tree.GetRootItem()) + self.opSort = self.opSortAlpha + self.tree.SortTreeNodes(self.tree.GetRootItem()) elif text == self.opSortOrig: - self.opSort = self.opSortOrig - self.tree.SortTreeNodes(self.tree.GetRootItem()) + self.opSort = self.opSortOrig + self.tree.SortTreeNodes(self.tree.GetRootItem()) def AquireFile(self, filename): name = os.path.basename(filename) if self.editor.protoPalette.findItem(name): - item = self.tree.traverse(self.tree.root, name) - if item: - self.tree.DeleteItem(item) + item = self.tree.traverse(self.tree.root, name) + if item: + self.tree.DeleteItem(item) modelname = Filename.fromOsSpecific(filename).getFullpath() if modelname.endswith('.mb') or\ @@ -181,24 +184,24 @@ class ProtoPaletteUI(wx.Panel): self.tree.ScrollTo(newItem) def addNewItem(self, result): - if len(result) == 2: - itemData = ObjectBase(name=result[0], model=result[1], actor=False) - elif len(result) == 3: - itemData = ObjectBase(name=result[0], model=result[1], anims=[result[2]], actor=True) - else: - return - self.palette.add(itemData) - newItem = self.tree.AppendItem(self.tree.root, itemData.name) - self.tree.SetItemPyData(newItem, itemData) - self.tree.ScrollTo(newItem) + if len(result) == 2: + itemData = ObjectBase(name=result[0], model=result[1], actor=False) + elif len(result) == 3: + itemData = ObjectBase(name=result[0], model=result[1], anims=[result[2]], actor=True) + else: + return + self.palette.add(itemData) + newItem = self.tree.AppendItem(self.tree.root, itemData.name) + self.tree.SetItemPyData(newItem, itemData) + self.tree.ScrollTo(newItem) def compareItems(self, item1, item2): data1 = self.tree.GetItemText(item1) data2 = self.tree.GetItemText(item2) if self.opSort == self.opSortAlpha: - return cmp(data1, data2) + return cmp(data1, data2) else: - items = list(self.palette.data.keys()) - index1 = items.index(data1) - index2 = items.index(data2) + items = list(self.palette.data.keys()) + index1 = items.index(data1) + index2 = items.index(data2) return cmp(index1, index2) diff --git a/direct/src/leveleditor/SceneGraphUIBase.py b/direct/src/leveleditor/SceneGraphUIBase.py index 66537fbbdf..0ca7e2f70c 100755 --- a/direct/src/leveleditor/SceneGraphUIBase.py +++ b/direct/src/leveleditor/SceneGraphUIBase.py @@ -32,11 +32,13 @@ class SceneGraphUIBase(wx.Panel): sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.tree, 1, wx.EXPAND, 0) - self.SetSizer(sizer); self.Layout() + self.SetSizer(sizer) + self.Layout() parentSizer = wx.BoxSizer(wx.VERTICAL) parentSizer.Add(self, 1, wx.EXPAND, 0) - parent.SetSizer(parentSizer); parent.Layout() + parent.SetSizer(parentSizer) + parent.Layout() parent.SetDropTarget(SceneGraphUIDropTarget(self.editor)) @@ -54,8 +56,8 @@ class SceneGraphUIBase(wx.Panel): itemList = list() item, cookie = self.tree.GetFirstChild(self.root) while item: - itemList.append(item) - item, cookie = self.tree.GetNextChild(self.root, cookie) + itemList.append(item) + item, cookie = self.tree.GetNextChild(self.root, cookie) for item in itemList: self.tree.Delete(item) @@ -80,47 +82,47 @@ class SceneGraphUIBase(wx.Panel): # first, find Panda Object's NodePath of the item itemId = self.tree.GetItemData(parent) if itemId == "render": - return + return obj = self.editor.objectMgr.findObjectById(itemId) if obj is None: - return + return objNodePath = obj[OG.OBJ_NP] self.traversePandaObjects(parent, objNodePath) item, cookie = self.tree.GetFirstChild(parent) while item: - # recursing... - self.addPandaObjectChildren(item) - item, cookie = self.tree.GetNextChild(parent, cookie) + # recursing... + self.addPandaObjectChildren(item) + item, cookie = self.tree.GetNextChild(parent, cookie) def removePandaObjectChildren(self, parent): # first, find Panda Object's NodePath of the item itemId = self.tree.GetItemData(parent) if itemId == "render": - return + return obj = self.editor.objectMgr.findObjectById(itemId) if obj is None: - self.tree.Delete(parent) - return + self.tree.Delete(parent) + return item, cookie = self.tree.GetFirstChild(parent) while item: - # recurse... - itemToRemove = item - # continue iteration to the next child - item, cookie = self.tree.GetNextChild(parent, cookie) - self.removePandaObjectChildren(itemToRemove) + # recurse... + itemToRemove = item + # continue iteration to the next child + item, cookie = self.tree.GetNextChild(parent, cookie) + self.removePandaObjectChildren(itemToRemove) def add(self, item, parentNP = None): #import pdb;pdb.set_trace() if item is None: - return + return obj = self.editor.objectMgr.findObjectByNodePath(NodePath(item)) if obj is None: - return + return if parentNP is None : - parentNP = obj[OG.OBJ_NP].getParent() + parentNP = obj[OG.OBJ_NP].getParent() parentObj = self.editor.objectMgr.findObjectByNodePath(parentNP) if parentObj is None: @@ -137,55 +139,55 @@ class SceneGraphUIBase(wx.Panel): # adding children of PandaObj if self.shouldShowPandaObjChildren: - self.addPandaObjectChildren(newItem) + self.addPandaObjectChildren(newItem) self.tree.Expand(self.root) def traverse(self, parent, itemId): # prevent from traversing into self if itemId == self.tree.GetItemData(parent): - return None + return None # main loop - serching for an item with an itemId item, cookie = self.tree.GetFirstChild(parent) while item: - # if the item was found - return it - if itemId == self.tree.GetItemData(item): - return item + # if the item was found - return it + if itemId == self.tree.GetItemData(item): + return item - # the tem was not found - checking if it has children - if self.tree.ItemHasChildren(item): - # item has children - delving into it - child = self.traverse(item, itemId) - if child is not None: + # the tem was not found - checking if it has children + if self.tree.ItemHasChildren(item): + # item has children - delving into it + child = self.traverse(item, itemId) + if child is not None: return child - # continue iteration to the next child - item, cookie = self.tree.GetNextChild(parent, cookie) + # continue iteration to the next child + item, cookie = self.tree.GetNextChild(parent, cookie) return None def reParentTree(self, parent, newParent): # main loop - iterating over item's children item, cookie = self.tree.GetFirstChild(parent) while item: - data = self.tree.GetItemText(item) - itemId = self.tree.GetItemData(item) - newItem = self.tree.AppendItem(newParent, data) - self.tree.SetItemPyData(newItem, itemId) + data = self.tree.GetItemText(item) + itemId = self.tree.GetItemData(item) + newItem = self.tree.AppendItem(newParent, data) + self.tree.SetItemPyData(newItem, itemId) - # if an item had children, we need to re-parent them as well - if self.tree.ItemHasChildren(item): - # recursing... - self.reParentTree(item, newItem) + # if an item had children, we need to re-parent them as well + if self.tree.ItemHasChildren(item): + # recursing... + self.reParentTree(item, newItem) - # continue iteration to the next child - item, cookie = self.tree.GetNextChild(parent, cookie) + # continue iteration to the next child + item, cookie = self.tree.GetNextChild(parent, cookie) def reParentData(self, parent, child): child.wrtReparentTo(parent) def reParent(self, oldParent, newParent, child): if newParent is None: - newParent = self.root + newParent = self.root itemId = self.tree.GetItemData(oldParent) newItem = self.tree.AppendItem(newParent, child) self.tree.SetItemPyData(newItem, itemId) @@ -194,17 +196,17 @@ class SceneGraphUIBase(wx.Panel): obj = self.editor.objectMgr.findObjectById(itemId) itemId = self.tree.GetItemData(newParent) if itemId != "render": - newParentObj = self.editor.objectMgr.findObjectById(itemId) - self.reParentData(newParentObj[OG.OBJ_NP], obj[OG.OBJ_NP]) + newParentObj = self.editor.objectMgr.findObjectById(itemId) + self.reParentData(newParentObj[OG.OBJ_NP], obj[OG.OBJ_NP]) else: - self.reParentData(render, obj[OG.OBJ_NP]) + self.reParentData(render, obj[OG.OBJ_NP]) self.tree.Delete(oldParent) if self.shouldShowPandaObjChildren: - self.removePandaObjectChildren(oldParent) - self.addPandaObjectChildren(oldParent) - self.removePandaObjectChildren(newParent) - self.addPandaObjectChildren(newpParent) + self.removePandaObjectChildren(oldParent) + self.addPandaObjectChildren(oldParent) + self.removePandaObjectChildren(newParent) + self.addPandaObjectChildren(newParent) def isChildOrGrandChild(self, parent, child): childId = self.tree.GetItemData(child) @@ -215,20 +217,20 @@ class SceneGraphUIBase(wx.Panel): itemId = itemText[-1] # uid is the last token item = self.traverse(self.tree.GetRootItem(), itemId) if item is None: - return + return dragToItem, flags = self.tree.HitTest(wx.Point(x, y)) if dragToItem.IsOk(): - # prevent draging into itself - if dragToItem == item: - return - if self.isChildOrGrandChild(item, dragToItem): - return + # prevent draging into itself + if dragToItem == item: + return + if self.isChildOrGrandChild(item, dragToItem): + return - # undo function setup... - action = ActionChangeHierarchy(self.editor, self.tree.GetItemData(self.tree.GetItemParent(item)), self.tree.GetItemData(item), self.tree.GetItemData(dragToItem), data) - self.editor.actionMgr.push(action) - action() + # undo function setup... + action = ActionChangeHierarchy(self.editor, self.tree.GetItemData(self.tree.GetItemParent(item)), self.tree.GetItemData(item), self.tree.GetItemData(dragToItem), data) + self.editor.actionMgr.push(action) + action() def parent(self, oldParentId, newParentId, childName): oldParent = self.traverse(self.tree.GetRootItem(), oldParentId) @@ -241,28 +243,28 @@ class SceneGraphUIBase(wx.Panel): item, cookie = self.tree.GetFirstChild(self.root) while item: - itemList.append(item) - item, cookie = self.tree.GetNextChild(self.root, cookie) + itemList.append(item) + item, cookie = self.tree.GetNextChild(self.root, cookie) #import pdb;set_trace() for item in itemList: - if self.shouldShowPandaObjChildren: + if self.shouldShowPandaObjChildren: self.addPandaObjectChildren(item) - else: + else: self.removePandaObjectChildren(item) - # continue iteration to the next child + # continue iteration to the next child def delete(self, itemId): item = self.traverse(self.root, itemId) if item: - self.tree.Delete(item) + self.tree.Delete(item) def select(self, itemId): item = self.traverse(self.root, itemId) if item: - if not self.tree.IsSelected(item): - self.tree.SelectItem(item) - self.tree.EnsureVisible(item) + if not self.tree.IsSelected(item): + self.tree.SelectItem(item) + self.tree.EnsureVisible(item) def changeLabel(self, itemId, newName): item = self.traverse(self.root, itemId) @@ -278,20 +280,20 @@ class SceneGraphUIBase(wx.Panel): def deSelect(self, itemId): item = self.traverse(self.root, itemId) if item is not None: - self.tree.UnselectItem(item) + self.tree.UnselectItem(item) def onSelected(self, event): - item = event.GetItem(); + item = event.GetItem() if item: - itemId = self.tree.GetItemData(item) - if itemId: - obj = self.editor.objectMgr.findObjectById(itemId); - if obj: - selections = self.tree.GetSelections() - if len(selections) > 1: - base.direct.select(obj[OG.OBJ_NP], fMultiSelect = 1, fLEPane = 0) - else: - base.direct.select(obj[OG.OBJ_NP], fMultiSelect = 0, fLEPane = 0) + itemId = self.tree.GetItemData(item) + if itemId: + obj = self.editor.objectMgr.findObjectById(itemId) + if obj: + selections = self.tree.GetSelections() + if len(selections) > 1: + base.direct.select(obj[OG.OBJ_NP], fMultiSelect = 1, fLEPane = 0) + else: + base.direct.select(obj[OG.OBJ_NP], fMultiSelect = 0, fLEPane = 0) def onBeginDrag(self, event): item = event.GetItem() @@ -316,7 +318,7 @@ class SceneGraphUIBase(wx.Panel): itemId = self.tree.GetItemData(item) if not itemId: return - self.currObj = self.editor.objectMgr.findObjectById(itemId); + self.currObj = self.editor.objectMgr.findObjectById(itemId) if self.currObj: self.PopupMenu(self.menu, pos) diff --git a/direct/src/motiontrail/MotionTrail.py b/direct/src/motiontrail/MotionTrail.py index db891548ac..5a874f9217 100644 --- a/direct/src/motiontrail/MotionTrail.py +++ b/direct/src/motiontrail/MotionTrail.py @@ -1,63 +1,62 @@ - - from panda3d.core import * from panda3d.direct import * from direct.task import Task +from direct.task.TaskManagerGlobal import taskMgr from direct.showbase.DirectObject import DirectObject from direct.directnotify.DirectNotifyGlobal import directNotify -def remove_task ( ): - if (MotionTrail.task_added): - total_motion_trails = len (MotionTrail.motion_trail_list) +def remove_task(): + if MotionTrail.task_added: + total_motion_trails = len(MotionTrail.motion_trail_list) if total_motion_trails > 0: - print("warning: %d motion trails still exist when motion trail task is removed" % (total_motion_trails)) + print("warning: %d motion trails still exist when motion trail task is removed" %(total_motion_trails)) - MotionTrail.motion_trail_list = [ ] + MotionTrail.motion_trail_list = [] - taskMgr.remove (MotionTrail.motion_trail_task_name) + taskMgr.remove(MotionTrail.motion_trail_task_name) print("MotionTrail task removed") MotionTrail.task_added = False - return + class MotionTrailVertex: def __init__(self, vertex_id, vertex_function, context): self.vertex_id = vertex_id self.vertex_function = vertex_function self.context = context - self.vertex = Vec4 (0.0, 0.0, 0.0, 1.0) + self.vertex = Vec4(0.0, 0.0, 0.0, 1.0) # default - self.start_color = Vec4 (1.0, 1.0, 1.0, 1.0) - self.end_color = Vec4 (0.0, 0.0, 0.0, 1.0) + self.start_color = Vec4(1.0, 1.0, 1.0, 1.0) + self.end_color = Vec4(0.0, 0.0, 0.0, 1.0) self.v = 0.0 + class MotionTrailFrame: - def __init__ (self, current_time, transform): + def __init__(self, current_time, transform): self.time = current_time self.transform = transform + class MotionTrail(NodePath, DirectObject): - notify = directNotify.newCategory ("MotionTrail") + notify = directNotify.newCategory("MotionTrail") task_added = False - motion_trail_list = [ ] + motion_trail_list = [] motion_trail_task_name = "motion_trail_task" global_enable = True @classmethod - def setGlobalEnable (self, enable): - MotionTrail.global_enable = enable + def setGlobalEnable(cls, enable): + cls.global_enable = enable - def __init__ (self,name,parent_node_path): - - DirectObject.__init__(self) - NodePath.__init__ (self,name) + def __init__(self, name, parent_node_path): + NodePath.__init__(self, name) # required initialization self.active = True @@ -74,15 +73,15 @@ class MotionTrail(NodePath, DirectObject): self.total_vertices = 0 self.last_update_time = 0.0 self.texture = None - self.vertex_list = [ ] - self.frame_list = [ ] + self.vertex_list = [] + self.frame_list = [] self.parent_node_path = parent_node_path self.previous_matrix = None self.calculate_relative_matrix = False - self.playing = False; + self.playing = False # default options self.continuous_motion_trail = True @@ -95,31 +94,31 @@ class MotionTrail(NodePath, DirectObject): self.root_node_path = None # node path states - self.reparentTo (parent_node_path) - self.geom_node = GeomNode ("motion_trail") + self.reparentTo(parent_node_path) + self.geom_node = GeomNode("motion_trail") self.geom_node_path = self.attachNewNode(self.geom_node) node_path = self.geom_node_path ### set render states - node_path.setTwoSided (True) + node_path.setTwoSided(True) # set additive blend effects - node_path.setTransparency (True) - node_path.setDepthWrite (False) - node_path.node ( ).setAttrib (ColorBlendAttrib.make (ColorBlendAttrib.MAdd)) + node_path.setTransparency(True) + node_path.setDepthWrite(False) + node_path.node().setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd)) # do not light - node_path.setLightOff ( ) + node_path.setLightOff() # disable writes to destination alpha, write out rgb colors only - node_path.setAttrib (ColorWriteAttrib.make (ColorWriteAttrib.CRed | ColorWriteAttrib.CGreen | ColorWriteAttrib.CBlue)); + node_path.setAttrib(ColorWriteAttrib.make(ColorWriteAttrib.CRed | ColorWriteAttrib.CGreen | ColorWriteAttrib.CBlue)) - if (MotionTrail.task_added == False): -# taskMgr.add (self.motion_trail_task, "motion_trail_task", priority = 50) - taskMgr.add (self.motion_trail_task, MotionTrail.motion_trail_task_name) + if not MotionTrail.task_added: + #taskMgr.add(self.motion_trail_task, "motion_trail_task", priority = 50) + taskMgr.add(self.motion_trail_task, MotionTrail.motion_trail_task_name) - self.acceptOnce ("clientLogout", remove_task) + self.acceptOnce("clientLogout", remove_task) MotionTrail.task_added = True @@ -129,8 +128,8 @@ class MotionTrail(NodePath, DirectObject): self.use_nurbs = False self.resolution_distance = 0.5 - self.cmotion_trail = CMotionTrail ( ) - self.cmotion_trail.setGeomNode (self.geom_node) + self.cmotion_trail = CMotionTrail() + self.cmotion_trail.setGeomNode(self.geom_node) self.modified_vertices = True if base.config.GetBool('want-python-motion-trails', 0): @@ -143,56 +142,56 @@ class MotionTrail(NodePath, DirectObject): def delete(self): self.reset_motion_trail() self.reset_motion_trail_geometry() - self.cmotion_trail.resetVertexList ( ) + self.cmotion_trail.resetVertexList() self.removeNode() return - def print_matrix (self, matrix): + def print_matrix(self, matrix): separator = ' ' - print(matrix.getCell (0, 0), separator, matrix.getCell (0, 1), separator, matrix.getCell (0, 2), separator, matrix.getCell (0, 3)) - print(matrix.getCell (1, 0), separator, matrix.getCell (1, 1), separator, matrix.getCell (1, 2), separator, matrix.getCell (1, 3)) - print(matrix.getCell (2, 0), separator, matrix.getCell (2, 1), separator, matrix.getCell (2, 2), separator, matrix.getCell (2, 3)) - print(matrix.getCell (3, 0), separator, matrix.getCell (3, 1), separator, matrix.getCell (3, 2), separator, matrix.getCell (3, 3)) + print(matrix.getCell(0, 0), separator, matrix.getCell(0, 1), separator, matrix.getCell(0, 2), separator, matrix.getCell(0, 3)) + print(matrix.getCell(1, 0), separator, matrix.getCell(1, 1), separator, matrix.getCell(1, 2), separator, matrix.getCell(1, 3)) + print(matrix.getCell(2, 0), separator, matrix.getCell(2, 1), separator, matrix.getCell(2, 2), separator, matrix.getCell(2, 3)) + print(matrix.getCell(3, 0), separator, matrix.getCell(3, 1), separator, matrix.getCell(3, 2), separator, matrix.getCell(3, 3)) - def motion_trail_task (self, task): + def motion_trail_task(self, task): current_time = task.time - total_motion_trails = len (MotionTrail.motion_trail_list) + total_motion_trails = len(MotionTrail.motion_trail_list) index = 0 - while (index < total_motion_trails): + while index < total_motion_trails: motion_trail = MotionTrail.motion_trail_list [index] - if (MotionTrail.global_enable): - if (motion_trail.use_python_version): + if MotionTrail.global_enable: + if motion_trail.use_python_version: # Python version - if (motion_trail.active and motion_trail.check_for_update (current_time)): + if motion_trail.active and motion_trail.check_for_update(current_time): transform = None - if (motion_trail.root_node_path != None) and (motion_trail.root_node_path != render): - motion_trail.root_node_path.update ( ) + if motion_trail.root_node_path is not None and motion_trail.root_node_path != render: + motion_trail.root_node_path.update() - if (motion_trail.root_node_path and (motion_trail.relative_to_render == False)): + if motion_trail.root_node_path and not motion_trail.relative_to_render: transform = motion_trail.getMat(motion_trail.root_node_path) else: - transform = Mat4 (motion_trail.getNetTransform ( ).getMat ( )) + transform = Mat4(motion_trail.getNetTransform().getMat()) - if (transform != None): - motion_trail.update_motion_trail (current_time, transform) + if transform is not None: + motion_trail.update_motion_trail(current_time, transform) else: # C++ version - if (motion_trail.active and motion_trail.cmotion_trail.checkForUpdate (current_time)): + if motion_trail.active and motion_trail.cmotion_trail.checkForUpdate(current_time): transform = None - if (motion_trail.root_node_path != None) and (motion_trail.root_node_path != render): - motion_trail.root_node_path.update ( ) + if motion_trail.root_node_path is not None and motion_trail.root_node_path != render: + motion_trail.root_node_path.update() - if (motion_trail.root_node_path and (motion_trail.relative_to_render == False)): + if motion_trail.root_node_path and not motion_trail.relative_to_render: transform = motion_trail.getMat(motion_trail.root_node_path) else: - transform = Mat4 (motion_trail.getNetTransform ( ).getMat ( )) + transform = Mat4(motion_trail.getNetTransform().getMat()) - if (transform != None): - motion_trail.transferVertices ( ) - motion_trail.cmotion_trail.updateMotionTrail (current_time, transform) + if transform is not None: + motion_trail.transferVertices() + motion_trail.cmotion_trail.updateMotionTrail(current_time, transform) else: motion_trail.reset_motion_trail() @@ -202,21 +201,20 @@ class MotionTrail(NodePath, DirectObject): return Task.cont - def add_vertex (self, vertex_id, vertex_function, context): - - motion_trail_vertex = MotionTrailVertex (vertex_id, vertex_function, context) - total_vertices = len (self.vertex_list) + def add_vertex(self, vertex_id, vertex_function, context): + motion_trail_vertex = MotionTrailVertex(vertex_id, vertex_function, context) + total_vertices = len(self.vertex_list) self.vertex_list [total_vertices : total_vertices] = [motion_trail_vertex] - self.total_vertices = len (self.vertex_list) + self.total_vertices = len(self.vertex_list) self.modified_vertices = True return motion_trail_vertex - def set_vertex_color (self, vertex_id, start_color, end_color): - if (vertex_id >= 0 and vertex_id < self.total_vertices): + def set_vertex_color(self, vertex_id, start_color, end_color): + if vertex_id >= 0 and vertex_id < self.total_vertices: motion_trail_vertex = self.vertex_list [vertex_id] motion_trail_vertex.start_color = start_color motion_trail_vertex.end_color = end_color @@ -224,29 +222,27 @@ class MotionTrail(NodePath, DirectObject): self.modified_vertices = True return - def set_texture (self, texture): - + def set_texture(self, texture): self.texture = texture - if (texture): - self.geom_node_path.setTexture (texture) + if texture: + self.geom_node_path.setTexture(texture) # texture.setWrapU(Texture.WMClamp) # texture.setWrapV(Texture.WMClamp) else: - self.geom_node_path.clearTexture ( ) + self.geom_node_path.clearTexture() self.modified_vertices = True return - def update_vertices (self): - - total_vertices = len (self.vertex_list) + def update_vertices(self): + total_vertices = len(self.vertex_list) self.total_vertices = total_vertices - if (total_vertices >= 2): + if total_vertices >= 2: vertex_index = 0 - while (vertex_index < total_vertices): + while vertex_index < total_vertices: motion_trail_vertex = self.vertex_list [vertex_index] - motion_trail_vertex.vertex = motion_trail_vertex.vertex_function (motion_trail_vertex, motion_trail_vertex.vertex_id, motion_trail_vertex.context) + motion_trail_vertex.vertex = motion_trail_vertex.vertex_function(motion_trail_vertex, motion_trail_vertex.vertex_id, motion_trail_vertex.context) vertex_index += 1 # calculate v coordinate @@ -255,7 +251,7 @@ class MotionTrail(NodePath, DirectObject): float_vertex_index = 0.0 float_total_vertices = 0.0 float_total_vertices = total_vertices - 1.0 - while (vertex_index < total_vertices): + while vertex_index < total_vertices: motion_trail_vertex = self.vertex_list [vertex_index] motion_trail_vertex.v = float_vertex_index / float_total_vertices vertex_index += 1 @@ -266,123 +262,121 @@ class MotionTrail(NodePath, DirectObject): self.modified_vertices = True return - def transferVertices (self): + def transferVertices(self): # transfer only on modification - if (self.modified_vertices): - self.cmotion_trail.setParameters (self.sampling_time, self.time_window, self.texture != None, self.calculate_relative_matrix, self.use_nurbs, self.resolution_distance) + if self.modified_vertices: + self.cmotion_trail.setParameters(self.sampling_time, self.time_window, self.texture is not None, self.calculate_relative_matrix, self.use_nurbs, self.resolution_distance) - self.cmotion_trail.resetVertexList ( ) + self.cmotion_trail.resetVertexList() vertex_index = 0 - total_vertices = len (self.vertex_list) - while (vertex_index < total_vertices): + total_vertices = len(self.vertex_list) + while vertex_index < total_vertices: motion_trail_vertex = self.vertex_list [vertex_index] - self.cmotion_trail.addVertex (motion_trail_vertex.vertex, motion_trail_vertex.start_color, motion_trail_vertex.end_color, motion_trail_vertex.v) + self.cmotion_trail.addVertex(motion_trail_vertex.vertex, motion_trail_vertex.start_color, motion_trail_vertex.end_color, motion_trail_vertex.v) vertex_index += 1 self.modified_vertices = False return - def register_motion_trail (self): + def register_motion_trail(self): MotionTrail.motion_trail_list = MotionTrail.motion_trail_list + [self] return - def unregister_motion_trail (self): - if (self in MotionTrail.motion_trail_list): - MotionTrail.motion_trail_list.remove (self) + def unregister_motion_trail(self): + if self in MotionTrail.motion_trail_list: + MotionTrail.motion_trail_list.remove(self) return - def begin_geometry (self): + def begin_geometry(self): + self.vertex_index = 0 - self.vertex_index = 0; - - if (self.texture != None): - self.format = GeomVertexFormat.getV3c4t2 ( ) + if self.texture is not None: + self.format = GeomVertexFormat.getV3c4t2() else: - self.format = GeomVertexFormat.getV3c4 ( ) + self.format = GeomVertexFormat.getV3c4() - self.vertex_data = GeomVertexData ("vertices", self.format, Geom.UHStatic) + self.vertex_data = GeomVertexData("vertices", self.format, Geom.UHStatic) - self.vertex_writer = GeomVertexWriter (self.vertex_data, "vertex") - self.color_writer = GeomVertexWriter (self.vertex_data, "color") - if (self.texture != None): - self.texture_writer = GeomVertexWriter (self.vertex_data, "texcoord") + self.vertex_writer = GeomVertexWriter(self.vertex_data, "vertex") + self.color_writer = GeomVertexWriter(self.vertex_data, "color") + if self.texture is not None: + self.texture_writer = GeomVertexWriter(self.vertex_data, "texcoord") - self.triangles = GeomTriangles (Geom.UHStatic) + self.triangles = GeomTriangles(Geom.UHStatic) - def add_geometry_quad (self, v0, v1, v2, v3, c0, c1, c2, c3, t0, t1, t2, t3): + def add_geometry_quad(self, v0, v1, v2, v3, c0, c1, c2, c3, t0, t1, t2, t3): - self.vertex_writer.addData3f (v0 [0], v0 [1], v0 [2]) - self.vertex_writer.addData3f (v1 [0], v1 [1], v1 [2]) - self.vertex_writer.addData3f (v2 [0], v2 [1], v2 [2]) - self.vertex_writer.addData3f (v3 [0], v3 [1], v3 [2]) + self.vertex_writer.addData3f(v0 [0], v0 [1], v0 [2]) + self.vertex_writer.addData3f(v1 [0], v1 [1], v1 [2]) + self.vertex_writer.addData3f(v2 [0], v2 [1], v2 [2]) + self.vertex_writer.addData3f(v3 [0], v3 [1], v3 [2]) - self.color_writer.addData4f (c0) - self.color_writer.addData4f (c1) - self.color_writer.addData4f (c2) - self.color_writer.addData4f (c3) + self.color_writer.addData4f(c0) + self.color_writer.addData4f(c1) + self.color_writer.addData4f(c2) + self.color_writer.addData4f(c3) - if (self.texture != None): - self.texture_writer.addData2f (t0) - self.texture_writer.addData2f (t1) - self.texture_writer.addData2f (t2) - self.texture_writer.addData2f (t3) + if self.texture is not None: + self.texture_writer.addData2f(t0) + self.texture_writer.addData2f(t1) + self.texture_writer.addData2f(t2) + self.texture_writer.addData2f(t3) - vertex_index = self.vertex_index; + vertex_index = self.vertex_index - self.triangles.addVertex (vertex_index + 0) - self.triangles.addVertex (vertex_index + 1) - self.triangles.addVertex (vertex_index + 2) - self.triangles.closePrimitive ( ) + self.triangles.addVertex(vertex_index + 0) + self.triangles.addVertex(vertex_index + 1) + self.triangles.addVertex(vertex_index + 2) + self.triangles.closePrimitive() - self.triangles.addVertex (vertex_index + 1) - self.triangles.addVertex (vertex_index + 3) - self.triangles.addVertex (vertex_index + 2) - self.triangles.closePrimitive ( ) + self.triangles.addVertex(vertex_index + 1) + self.triangles.addVertex(vertex_index + 3) + self.triangles.addVertex(vertex_index + 2) + self.triangles.closePrimitive() self.vertex_index += 4 - def end_geometry (self): - self.geometry = Geom (self.vertex_data) - self.geometry.addPrimitive (self.triangles) + def end_geometry(self): + self.geometry = Geom(self.vertex_data) + self.geometry.addPrimitive(self.triangles) - self.geom_node.removeAllGeoms ( ) - self.geom_node.addGeom (self.geometry) + self.geom_node.removeAllGeoms() + self.geom_node.addGeom(self.geometry) - def check_for_update (self, current_time): + def check_for_update(self, current_time): state = False - if ((current_time - self.last_update_time) >= self.sampling_time): + if (current_time - self.last_update_time) >= self.sampling_time: state = True - if (self.pause): + if self.pause: state = False update = state and self.enable return state - def update_motion_trail (self, current_time, transform): + def update_motion_trail(self, current_time, transform): - if (len (self.frame_list) >= 1): - if (transform == self.frame_list [0].transform): + if len(self.frame_list) >= 1: + if transform == self.frame_list [0].transform: # ignore duplicate transform updates return - if (self.check_for_update (current_time)): + if self.check_for_update(current_time): + color_scale = self.color_scale - color_scale = self.color_scale; - - if (self.fade): + if self.fade: elapsed_time = current_time - self.fade_start_time - if (elapsed_time < 0.0): - print("elapsed_time < 0: %f" % (elapsed_time)) + if elapsed_time < 0.0: + print("elapsed_time < 0: %f" %(elapsed_time)) elapsed_time = 0.0 - if (elapsed_time < self.fade_time): + if elapsed_time < self.fade_time: color_scale = (1.0 - (elapsed_time / self.fade_time)) * color_scale else: color_scale = 0.0 @@ -395,77 +389,75 @@ class MotionTrail(NodePath, DirectObject): index = 0 - last_frame_index = len (self.frame_list) - 1 + last_frame_index = len(self.frame_list) - 1 - while (index <= last_frame_index): + while index <= last_frame_index: motion_trail_frame = self.frame_list [last_frame_index - index] - if (motion_trail_frame.time >= minimum_time): + if motion_trail_frame.time >= minimum_time: break index += 1 - if (index > 0): - self.frame_list [last_frame_index - index: last_frame_index + 1] = [ ] + if index > 0: + self.frame_list [last_frame_index - index: last_frame_index + 1] = [] # add new frame to beginning of list - motion_trail_frame = MotionTrailFrame (current_time, transform) + motion_trail_frame = MotionTrailFrame(current_time, transform) self.frame_list = [motion_trail_frame] + self.frame_list # convert frames and vertices to geometry - total_frames = len (self.frame_list) + total_frames = len(self.frame_list) - """ - print "total_frames", total_frames + #print("total_frames", total_frames) + # + #index = 0 + #while index < total_frames: + # motion_trail_frame = self.frame_list [index] + # print("frame time", index, motion_trail_frame.time) + # index += 1 - index = 0; - while (index < total_frames): - motion_trail_frame = self.frame_list [index] - print "frame time", index, motion_trail_frame.time - index += 1 - """ + if (total_frames >= 2) and(self.total_vertices >= 2): - if ((total_frames >= 2) and (self.total_vertices >= 2)): - - self.begin_geometry ( ) + self.begin_geometry() total_segments = total_frames - 1 last_motion_trail_frame = self.frame_list [total_segments] minimum_time = last_motion_trail_frame.time delta_time = current_time - minimum_time - if (self.calculate_relative_matrix): - inverse_matrix = Mat4 (transform) - inverse_matrix.invertInPlace ( ) + if self.calculate_relative_matrix: + inverse_matrix = Mat4(transform) + inverse_matrix.invertInPlace() - if (self.use_nurbs and (total_frames >= 5)): + if self.use_nurbs and(total_frames >= 5): total_distance = 0.0 - vector = Vec3 ( ) + vector = Vec3() - nurbs_curve_evaluator_list = [ ] + nurbs_curve_evaluator_list = [] total_vertex_segments = self.total_vertices - 1 - # create a NurbsCurveEvaluator for each vertex (the starting point for the trail) + # create a NurbsCurveEvaluator for each vertex(the starting point for the trail) index = 0 - while (index < self.total_vertices): - nurbs_curve_evaluator = NurbsCurveEvaluator ( ) - nurbs_curve_evaluator.reset (total_segments) + while index < self.total_vertices: + nurbs_curve_evaluator = NurbsCurveEvaluator() + nurbs_curve_evaluator.reset(total_segments) nurbs_curve_evaluator_list = nurbs_curve_evaluator_list + [nurbs_curve_evaluator] index += 1 # add vertices to each NurbsCurveEvaluator segment_index = 0 - while (segment_index < total_segments): + while segment_index < total_segments: motion_trail_frame_start = self.frame_list [segment_index] motion_trail_frame_end = self.frame_list [segment_index + 1] vertex_segement_index = 0 - if (self.calculate_relative_matrix): - start_transform = Mat4 ( ) - end_transform = Mat4 ( ) + if self.calculate_relative_matrix: + start_transform = Mat4() + end_transform = Mat4() - start_transform.multiply (motion_trail_frame_start.transform, inverse_matrix) - end_transform.multiply (motion_trail_frame_end.transform, inverse_matrix) + start_transform.multiply(motion_trail_frame_start.transform, inverse_matrix) + end_transform.multiply(motion_trail_frame_end.transform, inverse_matrix) else: start_transform = motion_trail_frame_start.transform @@ -473,28 +465,28 @@ class MotionTrail(NodePath, DirectObject): motion_trail_vertex_start = self.vertex_list [0] - v0 = start_transform.xform (motion_trail_vertex_start.vertex) - v2 = end_transform.xform (motion_trail_vertex_start.vertex) + v0 = start_transform.xform(motion_trail_vertex_start.vertex) + v2 = end_transform.xform(motion_trail_vertex_start.vertex) nurbs_curve_evaluator = nurbs_curve_evaluator_list [vertex_segement_index] - nurbs_curve_evaluator.setVertex (segment_index, v0) + nurbs_curve_evaluator.setVertex(segment_index, v0) - while (vertex_segement_index < total_vertex_segments): + while vertex_segement_index < total_vertex_segments: motion_trail_vertex_start = self.vertex_list [vertex_segement_index] motion_trail_vertex_end = self.vertex_list [vertex_segement_index + 1] - v1 = start_transform.xform (motion_trail_vertex_end.vertex) - v3 = end_transform.xform (motion_trail_vertex_end.vertex) + v1 = start_transform.xform(motion_trail_vertex_end.vertex) + v3 = end_transform.xform(motion_trail_vertex_end.vertex) nurbs_curve_evaluator = nurbs_curve_evaluator_list [vertex_segement_index + 1] - nurbs_curve_evaluator.setVertex (segment_index, v1) + nurbs_curve_evaluator.setVertex(segment_index, v1) - if (vertex_segement_index == (total_vertex_segments - 1)): + if vertex_segement_index == (total_vertex_segments - 1): v = v1 - v3 - vector.set (v[0], v[1], v[2]) + vector.set(v[0], v[1], v[2]) distance = vector.length() total_distance += distance @@ -504,10 +496,10 @@ class MotionTrail(NodePath, DirectObject): # evaluate NurbsCurveEvaluator for each vertex index = 0 - nurbs_curve_result_list = [ ] - while (index < self.total_vertices): + nurbs_curve_result_list = [] + while index < self.total_vertices: nurbs_curve_evaluator = nurbs_curve_evaluator_list [index] - nurbs_curve_result = nurbs_curve_evaluator.evaluate ( ) + nurbs_curve_result = nurbs_curve_evaluator.evaluate() nurbs_curve_result_list = nurbs_curve_result_list + [nurbs_curve_result] nurbs_start_t = nurbs_curve_result.getStartT() @@ -517,36 +509,34 @@ class MotionTrail(NodePath, DirectObject): # create quads from NurbsCurveResult total_curve_segments = total_distance / self.resolution_distance - if (total_curve_segments < total_segments): - total_curve_segments = total_segments; + if total_curve_segments < total_segments: + total_curve_segments = total_segments - v0 = Vec3 ( ) - v1 = Vec3 ( ) - v2 = Vec3 ( ) - v3 = Vec3 ( ) + v0 = Vec3() + v1 = Vec3() + v2 = Vec3() + v3 = Vec3() - def one_minus_x (x): + def one_minus_x(x): x = 1.0 - x - if (x < 0.0): + if x < 0.0: x = 0.0 return x curve_segment_index = 0.0 - while (curve_segment_index < total_curve_segments): + while curve_segment_index < total_curve_segments: vertex_segement_index = 0 - if (True): - st = curve_segment_index / total_curve_segments - et = (curve_segment_index + 1.0) / total_curve_segments - else: - st = curve_segment_index / total_segments - et = (curve_segment_index + 1.0) / total_segments + st = curve_segment_index / total_curve_segments + et = (curve_segment_index + 1.0) / total_curve_segments + #st = curve_segment_index / total_segments + #et = (curve_segment_index + 1.0) / total_segments start_t = st end_t = et - if (self.square_t): + if self.square_t: start_t *= start_t end_t *= end_t @@ -555,13 +545,13 @@ class MotionTrail(NodePath, DirectObject): vertex_start_color = motion_trail_vertex_start.end_color + (motion_trail_vertex_start.start_color - motion_trail_vertex_start.end_color) color_start_t = color_scale * start_t color_end_t = color_scale * end_t - c0 = vertex_start_color * one_minus_x (color_start_t) - c2 = vertex_start_color * one_minus_x (color_end_t) + c0 = vertex_start_color * one_minus_x(color_start_t) + c2 = vertex_start_color * one_minus_x(color_end_t) - t0 = Vec2 (one_minus_x (st), motion_trail_vertex_start.v) - t2 = Vec2 (one_minus_x (et), motion_trail_vertex_start.v) + t0 = Vec2(one_minus_x(st), motion_trail_vertex_start.v) + t2 = Vec2(one_minus_x(et), motion_trail_vertex_start.v) - while (vertex_segement_index < total_vertex_segments): + while vertex_segement_index < total_vertex_segments: motion_trail_vertex_start = self.vertex_list [vertex_segement_index] motion_trail_vertex_end = self.vertex_list [vertex_segement_index + 1] @@ -577,23 +567,23 @@ class MotionTrail(NodePath, DirectObject): start_delta_t = (start_nurbs_end_t - start_nurbs_start_t) end_delta_t = (end_nurbs_end_t - end_nurbs_start_t) - start_nurbs_curve_result.evalPoint (start_nurbs_start_t + (start_delta_t * st), v0); - end_nurbs_curve_result.evalPoint (end_nurbs_start_t + (end_delta_t * st), v1); + start_nurbs_curve_result.evalPoint(start_nurbs_start_t + (start_delta_t * st), v0) + end_nurbs_curve_result.evalPoint(end_nurbs_start_t + (end_delta_t * st), v1) - start_nurbs_curve_result.evalPoint (start_nurbs_start_t + (start_delta_t * et), v2); - end_nurbs_curve_result.evalPoint (end_nurbs_start_t + (end_delta_t * et), v3); + start_nurbs_curve_result.evalPoint(start_nurbs_start_t + (start_delta_t * et), v2) + end_nurbs_curve_result.evalPoint(end_nurbs_start_t + (end_delta_t * et), v3) # color vertex_end_color = motion_trail_vertex_end.end_color + (motion_trail_vertex_end.start_color - motion_trail_vertex_end.end_color) - c1 = vertex_end_color * one_minus_x (color_start_t) - c3 = vertex_end_color * one_minus_x (color_end_t) + c1 = vertex_end_color * one_minus_x(color_start_t) + c3 = vertex_end_color * one_minus_x(color_end_t) # uv - t1 = Vec2 (one_minus_x (st), motion_trail_vertex_end.v) - t3 = Vec2 (one_minus_x (et), motion_trail_vertex_end.v) + t1 = Vec2(one_minus_x(st), motion_trail_vertex_end.v) + t3 = Vec2(one_minus_x(et), motion_trail_vertex_end.v) - self.add_geometry_quad (v0, v1, v2, v3, c0, c1, c2, c3, t0, t1, t2, t3) + self.add_geometry_quad(v0, v1, v2, v3, c0, c1, c2, c3, t0, t1, t2, t3) # reuse calculations c0 = c1 @@ -610,7 +600,7 @@ class MotionTrail(NodePath, DirectObject): else: segment_index = 0 - while (segment_index < total_segments): + while segment_index < total_segments: motion_trail_frame_start = self.frame_list [segment_index] motion_trail_frame_end = self.frame_list [segment_index + 1] @@ -620,26 +610,26 @@ class MotionTrail(NodePath, DirectObject): st = start_t et = end_t - if (self.square_t): + if self.square_t: start_t *= start_t end_t *= end_t vertex_segement_index = 0 total_vertex_segments = self.total_vertices - 1 - if (self.calculate_relative_matrix): - start_transform = Mat4 ( ) - end_transform = Mat4 ( ) - start_transform.multiply (motion_trail_frame_start.transform, inverse_matrix) - end_transform.multiply (motion_trail_frame_end.transform, inverse_matrix) + if self.calculate_relative_matrix: + start_transform = Mat4() + end_transform = Mat4() + start_transform.multiply(motion_trail_frame_start.transform, inverse_matrix) + end_transform.multiply(motion_trail_frame_end.transform, inverse_matrix) else: start_transform = motion_trail_frame_start.transform end_transform = motion_trail_frame_end.transform motion_trail_vertex_start = self.vertex_list [0] - v0 = start_transform.xform (motion_trail_vertex_start.vertex) - v2 = end_transform.xform (motion_trail_vertex_start.vertex) + v0 = start_transform.xform(motion_trail_vertex_start.vertex) + v2 = end_transform.xform(motion_trail_vertex_start.vertex) vertex_start_color = motion_trail_vertex_start.end_color + (motion_trail_vertex_start.start_color - motion_trail_vertex_start.end_color) color_start_t = color_scale * start_t @@ -647,16 +637,16 @@ class MotionTrail(NodePath, DirectObject): c0 = vertex_start_color * color_start_t c2 = vertex_start_color * color_end_t - t0 = Vec2 (st, motion_trail_vertex_start.v) - t2 = Vec2 (et, motion_trail_vertex_start.v) + t0 = Vec2(st, motion_trail_vertex_start.v) + t2 = Vec2(et, motion_trail_vertex_start.v) - while (vertex_segement_index < total_vertex_segments): + while vertex_segement_index < total_vertex_segments: motion_trail_vertex_start = self.vertex_list [vertex_segement_index] motion_trail_vertex_end = self.vertex_list [vertex_segement_index + 1] - v1 = start_transform.xform (motion_trail_vertex_end.vertex) - v3 = end_transform.xform (motion_trail_vertex_end.vertex) + v1 = start_transform.xform(motion_trail_vertex_end.vertex) + v3 = end_transform.xform(motion_trail_vertex_end.vertex) # color vertex_end_color = motion_trail_vertex_end.end_color + (motion_trail_vertex_end.start_color - motion_trail_vertex_end.end_color) @@ -665,10 +655,10 @@ class MotionTrail(NodePath, DirectObject): c3 = vertex_end_color * color_end_t # uv - t1 = Vec2 (st, motion_trail_vertex_end.v) - t3 = Vec2 (et, motion_trail_vertex_end.v) + t1 = Vec2(st, motion_trail_vertex_end.v) + t3 = Vec2(et, motion_trail_vertex_end.v) - self.add_geometry_quad (v0, v1, v2, v3, c0, c1, c2, c3, t0, t1, t2, t3) + self.add_geometry_quad(v0, v1, v2, v3, c0, c1, c2, c3, t0, t1, t2, t3) # reuse calculations v0 = v1 @@ -684,83 +674,71 @@ class MotionTrail(NodePath, DirectObject): segment_index += 1 - self.end_geometry ( ) - - return + self.end_geometry() def enable_motion_trail(self, enable): self.enable = enable - return def reset_motion_trail(self): - self.frame_list = [ ] - self.cmotion_trail.reset ( ); - return + self.frame_list = [] + self.cmotion_trail.reset() def reset_motion_trail_geometry(self): - if (self.geom_node != None): - self.geom_node.removeAllGeoms ( ) - return + if self.geom_node is not None: + self.geom_node.removeAllGeoms() - def attach_motion_trail (self): - self.reset_motion_trail ( ) - return + def attach_motion_trail(self): + self.reset_motion_trail() - def begin_motion_trail (self): - if (self.continuous_motion_trail == False): - self.reset_motion_trail ( ) - self.active = True; - self.playing = True; - return + def begin_motion_trail(self): + if not self.continuous_motion_trail: + self.reset_motion_trail() + self.active = True + self.playing = True - def end_motion_trail (self): - if (self.continuous_motion_trail == False): + def end_motion_trail(self): + if not self.continuous_motion_trail: self.active = False - self.reset_motion_trail ( ) - self.reset_motion_trail_geometry ( ) - self.playing = False; - return + self.reset_motion_trail() + self.reset_motion_trail_geometry() + self.playing = False # the following functions are not currently supported in the C++ version - def set_fade (self, time, current_time): - if (self.pause == False): + def set_fade(self, time, current_time): + if not self.pause: self.fade_color_scale = 1.0 - if (time == 0.0): + if time == 0.0: self.fade = False else: self.fade_start_time = current_time self.fade_time = time self.fade = True - return def pause_motion_trail(self, current_time): - if (self.pause == False): + if not self.pause: self.pause_time = current_time self.pause = True - return def resume_motion_trail(self, current_time): - if (self.pause): + if self.pause: delta_time = current_time - self.pause_time frame_index = 0 - total_frames = len (self.frame_list) - while (frame_index < total_frames): + total_frames = len(self.frame_list) + while frame_index < total_frames: motion_trail_frame = self.frame_list [frame_index] motion_trail_frame.time += delta_time frame_index += 1 - if (self.fade): + if self.fade: self.fade_start_time += delta_time self.pause = False - return - def toggle_pause_motion_trail (self, current_time): - if (self.pause): - self.resume_motion_trail (current_time) + def toggle_pause_motion_trail(self, current_time): + if self.pause: + self.resume_motion_trail(current_time) else: - self.pause_motion_trail (current_time) - + self.pause_motion_trail(current_time) diff --git a/direct/src/particles/ForceGroup.py b/direct/src/particles/ForceGroup.py index 9cd37953f0..b6d867a406 100644 --- a/direct/src/particles/ForceGroup.py +++ b/direct/src/particles/ForceGroup.py @@ -51,12 +51,12 @@ class ForceGroup(DirectObject): def addForce(self, force): self.node.addForce(force) - if (self.particleEffect): + if self.particleEffect: self.particleEffect.addForce(force) def removeForce(self, force): self.node.removeForce(force) - if (self.particleEffect != None): + if self.particleEffect is not None: self.particleEffect.removeForce(force) # Get/set @@ -73,7 +73,7 @@ class ForceGroup(DirectObject): # Utility functions def __getitem__(self, index): numForces = self.node.getNumForces() - if ((index < 0) or (index >= numForces)): + if index < 0 or index >= numForces: raise IndexError return self.node.getForce(index) @@ -100,11 +100,11 @@ class ForceGroup(DirectObject): radius = f.getRadius() falloffType = f.getFalloffType() ftype = 'FTONEOVERR' - if (falloffType == LinearDistanceForce.FTONEOVERR): + if falloffType == LinearDistanceForce.FTONEOVERR: ftype = 'FTONEOVERR' - elif (falloffType == LinearDistanceForce.FTONEOVERRSQUARED): + elif falloffType == LinearDistanceForce.FTONEOVERRSQUARED: ftype = 'FTONEOVERRSQUARED' - elif (falloffType == LinearDistanceForce.FTONEOVERRCUBED): + elif falloffType == LinearDistanceForce.FTONEOVERRCUBED: ftype = 'FTONEOVERRCUBED' forceCenter = f.getForceCenter() if isinstance(f, LinearSinkForce): diff --git a/direct/src/particles/GlobalForceGroup.py b/direct/src/particles/GlobalForceGroup.py index afeecb4898..037d4bcaa7 100644 --- a/direct/src/particles/GlobalForceGroup.py +++ b/direct/src/particles/GlobalForceGroup.py @@ -1,3 +1,5 @@ +__all__ = ['GlobalForceGroup'] + from . import ForceGroup from direct.showbase.PhysicsManagerGlobal import physicsMgr @@ -9,17 +11,16 @@ class GlobalForceGroup(ForceGroup.ForceGroup): def addForce(self, force): ForceGroup.ForceGroup.addForce(self, force) - if (force.isLinear() == 0): - # Physics manager will need an angular integrator - base.addAngularIntegrator() - if (force.isLinear() == 1): + if force.isLinear(): physicsMgr.addLinearForce(force) else: + # Physics manager will need an angular integrator + base.addAngularIntegrator() physicsMgr.addAngularForce(force) def removeForce(self, force): ForceGroup.ForceGroup.removeForce(self, force) - if (force.isLinear() == 1): + if force.isLinear(): physicsMgr.removeLinearForce(force) else: physicsMgr.removeAngularForce(force) diff --git a/direct/src/particles/ParticleEffect.py b/direct/src/particles/ParticleEffect.py index 9d33fb3150..b6fafde27f 100644 --- a/direct/src/particles/ParticleEffect.py +++ b/direct/src/particles/ParticleEffect.py @@ -2,9 +2,9 @@ from panda3d.core import * # Leave these imports in, they may be used by ptf files. -from panda3d.physics import * -from . import Particles -from . import ForceGroup +from panda3d.physics import * # pylint: disable=unused-import +from . import Particles # pylint: disable=unused-import +from . import ForceGroup # pylint: disable=unused-import from direct.directnotify import DirectNotifyGlobal @@ -99,8 +99,8 @@ class ParticleEffect(NodePath): self.forceGroupDict[forceGroup.getName()] = forceGroup # Associate the force group with all particles - for i in range(len(forceGroup)): - self.addForce(forceGroup[i]) + for force in forceGroup: + self.addForce(force) def addForce(self, force): for p in list(self.particlesDict.values()): @@ -108,8 +108,8 @@ class ParticleEffect(NodePath): def removeForceGroup(self, forceGroup): # Remove forces from all particles - for i in range(len(forceGroup)): - self.removeForce(forceGroup[i]) + for force in forceGroup: + self.removeForce(force) forceGroup.nodePath.removeNode() forceGroup.particleEffect = None @@ -129,12 +129,12 @@ class ParticleEffect(NodePath): # Associate all forces in all force groups with the particles for fg in list(self.forceGroupDict.values()): - for i in range(len(fg)): - particles.addForce(fg[i]) + for force in fg: + particles.addForce(force) def removeParticles(self, particles): if particles is None: - self.notify.warning('removeParticles() - particles == None!') + self.notify.warning('removeParticles() - particles is None!') return particles.nodePath.detachNode() self.particlesDict.pop(particles.getName(), None) @@ -169,40 +169,40 @@ class ParticleEffect(NodePath): def saveConfig(self, filename): filename = Filename(filename) with open(filename.toOsSpecific(), 'w') as f: - # Add a blank line - f.write('\n') + # Add a blank line + f.write('\n') - # Make sure we start with a clean slate - f.write('self.reset()\n') + # Make sure we start with a clean slate + f.write('self.reset()\n') - pos = self.getPos() - hpr = self.getHpr() - scale = self.getScale() - f.write('self.setPos(%0.3f, %0.3f, %0.3f)\n' % - (pos[0], pos[1], pos[2])) - f.write('self.setHpr(%0.3f, %0.3f, %0.3f)\n' % - (hpr[0], hpr[1], hpr[2])) - f.write('self.setScale(%0.3f, %0.3f, %0.3f)\n' % - (scale[0], scale[1], scale[2])) + pos = self.getPos() + hpr = self.getHpr() + scale = self.getScale() + f.write('self.setPos(%0.3f, %0.3f, %0.3f)\n' % + (pos[0], pos[1], pos[2])) + f.write('self.setHpr(%0.3f, %0.3f, %0.3f)\n' % + (hpr[0], hpr[1], hpr[2])) + f.write('self.setScale(%0.3f, %0.3f, %0.3f)\n' % + (scale[0], scale[1], scale[2])) - # Save all the particles to file - num = 0 - for p in list(self.particlesDict.values()): - target = 'p%d' % num - num = num + 1 - f.write(target + ' = Particles.Particles(\'%s\')\n' % p.getName()) - p.printParams(f, target) - f.write('self.addParticles(%s)\n' % target) + # Save all the particles to file + num = 0 + for p in list(self.particlesDict.values()): + target = 'p%d' % num + num = num + 1 + f.write(target + ' = Particles.Particles(\'%s\')\n' % p.getName()) + p.printParams(f, target) + f.write('self.addParticles(%s)\n' % target) - # Save all the forces to file - num = 0 - for fg in list(self.forceGroupDict.values()): - target = 'f%d' % num - num = num + 1 - f.write(target + ' = ForceGroup.ForceGroup(\'%s\')\n' % \ - fg.getName()) - fg.printParams(f, target) - f.write('self.addForceGroup(%s)\n' % target) + # Save all the forces to file + num = 0 + for fg in list(self.forceGroupDict.values()): + target = 'f%d' % num + num = num + 1 + f.write(target + ' = ForceGroup.ForceGroup(\'%s\')\n' % \ + fg.getName()) + fg.printParams(f, target) + f.write('self.addForceGroup(%s)\n' % target) def loadConfig(self, filename): fn = Filename(filename) diff --git a/direct/src/particles/ParticleFloorTest.py b/direct/src/particles/ParticleFloorTest.py index 3ee1bce319..70aeb6a474 100755 --- a/direct/src/particles/ParticleFloorTest.py +++ b/direct/src/particles/ParticleFloorTest.py @@ -5,6 +5,7 @@ from direct.particles import ParticleEffect from direct.particles import Particles from direct.particles import ForceGroup + class ParticleFloorTest(NodePath): def __init__(self): NodePath.__init__(self, "particleFloorTest") @@ -36,21 +37,22 @@ class ParticleFloorTest(NodePath): self.p0.factory.setTerminalVelocityBase(400.0000) self.p0.factory.setTerminalVelocitySpread(0.0000) self.f.addParticles(self.p0) - if 1: - f0 = ForceGroup.ForceGroup('frict') - # Force parameters - force0 = LinearVectorForce(Vec3(0., 0., -1.)) - force0.setActive(1) - f0.addForce(force0) - self.f.addForceGroup(f0) + + f0 = ForceGroup.ForceGroup('frict') + # Force parameters + force0 = LinearVectorForce(Vec3(0., 0., -1.)) + force0.setActive(1) + f0.addForce(force0) + self.f.addForceGroup(f0) def start(self): self.f.enable() + if __name__ == "__main__": from direct.directbase.TestStart import * pt = ParticleFloorTest() - pt.reparentTo(render) + pt.reparentTo(base.render) pt.start() base.camera.setY(-10.0) base.run() diff --git a/direct/src/particles/ParticleTest.py b/direct/src/particles/ParticleTest.py index 780ea4edc5..9236a57834 100644 --- a/direct/src/particles/ParticleTest.py +++ b/direct/src/particles/ParticleTest.py @@ -1,11 +1,12 @@ if __name__ == "__main__": - from direct.directbase.TestStart import * - - from panda3d.physics import LinearVectorForce from panda3d.core import Vec3 - from . import ParticleEffect + from panda3d.physics import LinearVectorForce + + from direct.directbase.TestStart import * from direct.tkpanels import ParticlePanel + + from . import ParticleEffect from . import Particles from . import ForceGroup diff --git a/direct/src/particles/Particles.py b/direct/src/particles/Particles.py index 3dfa5493dd..f284fe86e5 100644 --- a/direct/src/particles/Particles.py +++ b/direct/src/particles/Particles.py @@ -41,7 +41,7 @@ class Particles(ParticleSystem): id = 1 def __init__(self, name=None, poolSize=1024): - if (name == None): + if name is None: self.name = 'particles-%d' % Particles.id Particles.id += 1 else: @@ -86,13 +86,13 @@ class Particles(ParticleSystem): del self.emitter def enable(self): - if (self.fEnabled == 0): + if self.fEnabled == 0: base.physicsMgr.attachPhysical(self) base.particleMgr.attachParticlesystem(self) self.fEnabled = 1 def disable(self): - if (self.fEnabled == 1): + if self.fEnabled == 1: base.physicsMgr.removePhysical(self) base.particleMgr.removeParticlesystem(self) self.fEnabled = 0 @@ -104,17 +104,17 @@ class Particles(ParticleSystem): return self.node def setFactory(self, type): - if (self.factoryType == type): + if self.factoryType == type: return None - if (self.factory): + if self.factory: self.factory = None self.factoryType = type - if (type == "PointParticleFactory"): + if type == "PointParticleFactory": self.factory = PointParticleFactory() - elif (type == "ZSpinParticleFactory"): + elif type == "ZSpinParticleFactory": self.factory = ZSpinParticleFactory() - elif (type == "OrientedParticleFactory"): - self.factory = OrientedParticleFactory() + #elif type == "OrientedParticleFactory": + # self.factory = OrientedParticleFactory() else: print("unknown factory type: %s" % type) return None @@ -122,17 +122,17 @@ class Particles(ParticleSystem): ParticleSystem.setFactory(self, self.factory) def setRenderer(self, type): - if (self.rendererType == type): + if self.rendererType == type: return None - if (self.renderer): + if self.renderer: self.renderer = None self.rendererType = type - if (type == "PointParticleRenderer"): + if type == "PointParticleRenderer": self.renderer = PointParticleRenderer() self.renderer.setPointSize(1.0) - elif (type == "LineParticleRenderer"): + elif type == "LineParticleRenderer": self.renderer = LineParticleRenderer() - elif (type == "GeomParticleRenderer"): + elif type == "GeomParticleRenderer": self.renderer = GeomParticleRenderer() # This was moved here because we do not want to download # the direct tools with toontown. @@ -141,9 +141,9 @@ class Particles(ParticleSystem): npath = NodePath('default-geom') bbox = DirectSelection.DirectBoundingBox(npath) self.renderer.setGeomNode(bbox.lines.node()) - elif (type == "SparkleParticleRenderer"): + elif type == "SparkleParticleRenderer": self.renderer = SparkleParticleRenderer() - elif (type == "SpriteParticleRenderer"): + elif type == "SpriteParticleRenderer": self.renderer = SpriteParticleRendererExt.SpriteParticleRendererExt() # self.renderer.setTextureFromFile() else: @@ -152,31 +152,31 @@ class Particles(ParticleSystem): ParticleSystem.setRenderer(self, self.renderer) def setEmitter(self, type): - if (self.emitterType == type): + if self.emitterType == type: return None - if (self.emitter): + if self.emitter: self.emitter = None self.emitterType = type - if (type == "ArcEmitter"): + if type == "ArcEmitter": self.emitter = ArcEmitter() - elif (type == "BoxEmitter"): + elif type == "BoxEmitter": self.emitter = BoxEmitter() - elif (type == "DiscEmitter"): + elif type == "DiscEmitter": self.emitter = DiscEmitter() - elif (type == "LineEmitter"): + elif type == "LineEmitter": self.emitter = LineEmitter() - elif (type == "PointEmitter"): + elif type == "PointEmitter": self.emitter = PointEmitter() - elif (type == "RectangleEmitter"): + elif type == "RectangleEmitter": self.emitter = RectangleEmitter() - elif (type == "RingEmitter"): + elif type == "RingEmitter": self.emitter = RingEmitter() - elif (type == "SphereSurfaceEmitter"): + elif type == "SphereSurfaceEmitter": self.emitter = SphereSurfaceEmitter() - elif (type == "SphereVolumeEmitter"): + elif type == "SphereVolumeEmitter": self.emitter = SphereVolumeEmitter() self.emitter.setRadius(1.0) - elif (type == "TangentRingEmitter"): + elif type == "TangentRingEmitter": self.emitter = TangentRingEmitter() else: print("unknown emitter type: %s" % type) @@ -184,16 +184,16 @@ class Particles(ParticleSystem): ParticleSystem.setEmitter(self, self.emitter) def addForce(self, force): - if (force.isLinear()): + if force.isLinear(): self.addLinearForce(force) else: self.addAngularForce(force) def removeForce(self, force): - if (force == None): - self.notify.warning('removeForce() - force == None!') + if force is None: + self.notify.warning('removeForce() - force is None!') return - if (force.isLinear()): + if force.isLinear(): self.removeLinearForce(force) else: self.removeAngularForce(force) @@ -248,9 +248,9 @@ class Particles(ParticleSystem): self.factory.getTerminalVelocityBase()) file.write(targ + '.factory.setTerminalVelocitySpread(%.4f)\n' % \ self.factory.getTerminalVelocitySpread()) - if (self.factoryType == "PointParticleFactory"): + if self.factoryType == "PointParticleFactory": file.write('# Point factory parameters\n') - elif (self.factoryType == "ZSpinParticleFactory"): + elif self.factoryType == "ZSpinParticleFactory": file.write('# Z Spin factory parameters\n') file.write(targ + '.factory.setInitialAngle(%.4f)\n' % \ self.factory.getInitialAngle()) @@ -258,7 +258,7 @@ class Particles(ParticleSystem): self.factory.getInitialAngleSpread()) file.write(targ + '.factory.enableAngularVelocity(%d)\n' % \ self.factory.getAngularVelocityEnabled()) - if(self.factory.getAngularVelocityEnabled()): + if self.factory.getAngularVelocityEnabled(): file.write(targ + '.factory.setAngularVelocity(%.4f)\n' % \ self.factory.getAngularVelocity()) file.write(targ + '.factory.setAngularVelocitySpread(%.4f)\n' % \ @@ -269,7 +269,7 @@ class Particles(ParticleSystem): file.write(targ + '.factory.setFinalAngleSpread(%.4f)\n' % \ self.factory.getFinalAngleSpread()) - elif (self.factoryType == "OrientedParticleFactory"): + elif self.factoryType == "OrientedParticleFactory": file.write('# Oriented factory parameters\n') file.write(targ + '.factory.setInitialOrientation(%.4f)\n' % \ self.factory.getInitialOrientation()) @@ -279,20 +279,20 @@ class Particles(ParticleSystem): file.write('# Renderer parameters\n') alphaMode = self.renderer.getAlphaMode() aMode = "PRALPHANONE" - if (alphaMode == BaseParticleRenderer.PRALPHANONE): + if alphaMode == BaseParticleRenderer.PRALPHANONE: aMode = "PRALPHANONE" - elif (alphaMode == BaseParticleRenderer.PRALPHAOUT): + elif alphaMode == BaseParticleRenderer.PRALPHAOUT: aMode = "PRALPHAOUT" - elif (alphaMode == BaseParticleRenderer.PRALPHAIN): + elif alphaMode == BaseParticleRenderer.PRALPHAIN: aMode = "PRALPHAIN" - elif (alphaMode == BaseParticleRenderer.PRALPHAINOUT): + elif alphaMode == BaseParticleRenderer.PRALPHAINOUT: aMode = "PRALPHAINOUT" - elif (alphaMode == BaseParticleRenderer.PRALPHAUSER): + elif alphaMode == BaseParticleRenderer.PRALPHAUSER: aMode = "PRALPHAUSER" file.write(targ + '.renderer.setAlphaMode(BaseParticleRenderer.' + aMode + ')\n') file.write(targ + '.renderer.setUserAlpha(%.2f)\n' % \ self.renderer.getUserAlpha()) - if (self.rendererType == "PointParticleRenderer"): + if self.rendererType == "PointParticleRenderer": file.write('# Point parameters\n') file.write(targ + '.renderer.setPointSize(%.2f)\n' % \ self.renderer.getPointSize()) @@ -302,23 +302,23 @@ class Particles(ParticleSystem): file.write((targ + '.renderer.setEndColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3]))) blendType = self.renderer.getBlendType() bType = "PPONECOLOR" - if (blendType == PointParticleRenderer.PPONECOLOR): + if blendType == PointParticleRenderer.PPONECOLOR: bType = "PPONECOLOR" - elif (blendType == PointParticleRenderer.PPBLENDLIFE): + elif blendType == PointParticleRenderer.PPBLENDLIFE: bType = "PPBLENDLIFE" - elif (blendType == PointParticleRenderer.PPBLENDVEL): + elif blendType == PointParticleRenderer.PPBLENDVEL: bType = "PPBLENDVEL" file.write(targ + '.renderer.setBlendType(PointParticleRenderer.' + bType + ')\n') blendMethod = self.renderer.getBlendMethod() bMethod = "PPNOBLEND" - if (blendMethod == BaseParticleRenderer.PPNOBLEND): + if blendMethod == BaseParticleRenderer.PPNOBLEND: bMethod = "PPNOBLEND" - elif (blendMethod == BaseParticleRenderer.PPBLENDLINEAR): + elif blendMethod == BaseParticleRenderer.PPBLENDLINEAR: bMethod = "PPBLENDLINEAR" - elif (blendMethod == BaseParticleRenderer.PPBLENDCUBIC): + elif blendMethod == BaseParticleRenderer.PPBLENDCUBIC: bMethod = "PPBLENDCUBIC" file.write(targ + '.renderer.setBlendMethod(BaseParticleRenderer.' + bMethod + ')\n') - elif (self.rendererType == "LineParticleRenderer"): + elif self.rendererType == "LineParticleRenderer": file.write('# Line parameters\n') sColor = self.renderer.getHeadColor() file.write((targ + '.renderer.setHeadColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3]))) @@ -326,12 +326,12 @@ class Particles(ParticleSystem): file.write((targ + '.renderer.setTailColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3]))) sf = self.renderer.getLineScaleFactor() file.write((targ + '.renderer.setLineScaleFactor(%.2f)\n' % (sf))) - elif (self.rendererType == "GeomParticleRenderer"): + elif self.rendererType == "GeomParticleRenderer": file.write('# Geom parameters\n') node = self.renderer.getGeomNode() file.write('geomRef = loader.loadModel("' + self.geomReference + '")\n') file.write(targ + '.renderer.setGeomNode(geomRef.node())\n') - file.write(targ + '.geomReference = "' + self.geomReference + '"\n'); + file.write(targ + '.geomReference = "' + self.geomReference + '"\n') cbmLut = ('MNone','MAdd','MSubtract','MInvSubtract','MMin','MMax') cboLut = ('OZero','OOne','OIncomingColor','OOneMinusIncomingColor','OFbufferColor', 'OOneMinusFbufferColor','OIncomingAlpha','OOneMinusIncomingAlpha', @@ -349,10 +349,10 @@ class Particles(ParticleSystem): file.write(targ + '.renderer.setFinalZScale(%.4f)\n' % self.renderer.getFinalZScale()) cbAttrib = self.renderer.getRenderNode().getAttrib(ColorBlendAttrib.getClassType()) - if(cbAttrib): + if cbAttrib: cbMode = cbAttrib.getMode() - if(cbMode > 0): - if(cbMode in (ColorBlendAttrib.MAdd, ColorBlendAttrib.MSubtract, ColorBlendAttrib.MInvSubtract)): + if cbMode > 0: + if cbMode in (ColorBlendAttrib.MAdd, ColorBlendAttrib.MSubtract, ColorBlendAttrib.MInvSubtract): cboa = cbAttrib.getOperandA() cbob = cbAttrib.getOperandB() file.write(targ+'.renderer.setColorBlendMode(ColorBlendAttrib.%s, ColorBlendAttrib.%s, ColorBlendAttrib.%s)\n' % @@ -397,7 +397,7 @@ class Particles(ParticleSystem): 'Vec4('+repr(c_b[0])+','+repr(c_b[1])+','+repr(c_b[2])+','+repr(c_b[3])+'),' + \ repr(per)+','+repr(mod)+')\n') - elif (self.rendererType == "SparkleParticleRenderer"): + elif self.rendererType == "SparkleParticleRenderer": file.write('# Sparkle parameters\n') sColor = self.renderer.getCenterColor() file.write((targ + '.renderer.setCenterColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3]))) @@ -407,20 +407,20 @@ class Particles(ParticleSystem): file.write(targ + '.renderer.setDeathRadius(%.4f)\n' % self.renderer.getDeathRadius()) lifeScale = self.renderer.getLifeScale() lScale = "SPNOSCALE" - if (lifeScale == SparkleParticleRenderer.SPSCALE): + if lifeScale == SparkleParticleRenderer.SPSCALE: lScale = "SPSCALE" file.write(targ + '.renderer.setLifeScale(SparkleParticleRenderer.' + lScale + ')\n') - elif (self.rendererType == "SpriteParticleRenderer"): + elif self.rendererType == "SpriteParticleRenderer": file.write('# Sprite parameters\n') - if (self.renderer.getAnimateFramesEnable()): + if self.renderer.getAnimateFramesEnable(): file.write(targ + '.renderer.setAnimateFramesEnable(True)\n') rate = self.renderer.getAnimateFramesRate() - if(rate): + if rate: file.write(targ + '.renderer.setAnimateFramesRate(%.3f)\n'%rate) animCount = self.renderer.getNumAnims() for x in range(animCount): anim = self.renderer.getAnim(x) - if(anim.getSourceType() == SpriteAnim.STTexture): + if anim.getSourceType() == SpriteAnim.STTexture: file.write(targ + '.renderer.addTextureFromFile(\'%s\')\n' % (anim.getTexSource(),)) else: file.write(targ + '.renderer.addTextureFromNode(\'%s\',\'%s\')\n' % (anim.getModelSource(), anim.getNodeSource())) @@ -436,11 +436,11 @@ class Particles(ParticleSystem): file.write(targ + '.renderer.setNonanimatedTheta(%.4f)\n' % self.renderer.getNonanimatedTheta()) blendMethod = self.renderer.getAlphaBlendMethod() bMethod = "PPNOBLEND" - if (blendMethod == BaseParticleRenderer.PPNOBLEND): + if blendMethod == BaseParticleRenderer.PPNOBLEND: bMethod = "PPNOBLEND" - elif (blendMethod == BaseParticleRenderer.PPBLENDLINEAR): + elif blendMethod == BaseParticleRenderer.PPBLENDLINEAR: bMethod = "PPBLENDLINEAR" - elif (blendMethod == BaseParticleRenderer.PPBLENDCUBIC): + elif blendMethod == BaseParticleRenderer.PPBLENDCUBIC: bMethod = "PPBLENDCUBIC" file.write(targ + '.renderer.setAlphaBlendMethod(BaseParticleRenderer.' + bMethod + ')\n') file.write(targ + '.renderer.setAlphaDisable(%d)\n' % self.renderer.getAlphaDisable()) @@ -452,10 +452,10 @@ class Particles(ParticleSystem): 'OOneMinusConstantColor','OConstantAlpha','OOneMinusConstantAlpha', 'OIncomingColorSaturate') cbAttrib = self.renderer.getRenderNode().getAttrib(ColorBlendAttrib.getClassType()) - if(cbAttrib): + if cbAttrib: cbMode = cbAttrib.getMode() - if(cbMode > 0): - if(cbMode in (ColorBlendAttrib.MAdd, ColorBlendAttrib.MSubtract, ColorBlendAttrib.MInvSubtract)): + if cbMode > 0: + if cbMode in (ColorBlendAttrib.MAdd, ColorBlendAttrib.MSubtract, ColorBlendAttrib.MInvSubtract): cboa = cbAttrib.getOperandA() cbob = cbAttrib.getOperandB() file.write(targ+'.renderer.setColorBlendMode(ColorBlendAttrib.%s, ColorBlendAttrib.%s, ColorBlendAttrib.%s)\n' % @@ -503,11 +503,11 @@ class Particles(ParticleSystem): file.write('# Emitter parameters\n') emissionType = self.emitter.getEmissionType() eType = "ETEXPLICIT" - if (emissionType == BaseParticleEmitter.ETEXPLICIT): + if emissionType == BaseParticleEmitter.ETEXPLICIT: eType = "ETEXPLICIT" - elif (emissionType == BaseParticleEmitter.ETRADIATE): + elif emissionType == BaseParticleEmitter.ETRADIATE: eType = "ETRADIATE" - elif (emissionType == BaseParticleEmitter.ETCUSTOM): + elif emissionType == BaseParticleEmitter.ETCUSTOM: eType = "ETCUSTOM" file.write(targ + '.emitter.setEmissionType(BaseParticleEmitter.' + eType + ')\n') file.write(targ + '.emitter.setAmplitude(%.4f)\n' % self.emitter.getAmplitude()) @@ -518,51 +518,51 @@ class Particles(ParticleSystem): file.write((targ + '.emitter.setExplicitLaunchVector(Vec3(%.4f, %.4f, %.4f))\n' % (oForce[0], oForce[1], oForce[2]))) orig = self.emitter.getRadiateOrigin() file.write((targ + '.emitter.setRadiateOrigin(Point3(%.4f, %.4f, %.4f))\n' % (orig[0], orig[1], orig[2]))) - if (self.emitterType == "BoxEmitter"): + if self.emitterType == "BoxEmitter": file.write('# Box parameters\n') bound = self.emitter.getMinBound() file.write((targ + '.emitter.setMinBound(Point3(%.4f, %.4f, %.4f))\n' % (bound[0], bound[1], bound[2]))) bound = self.emitter.getMaxBound() file.write((targ + '.emitter.setMaxBound(Point3(%.4f, %.4f, %.4f))\n' % (bound[0], bound[1], bound[2]))) - elif (self.emitterType == "DiscEmitter"): + elif self.emitterType == "DiscEmitter": file.write('# Disc parameters\n') file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius()) - if (eType == "ETCUSTOM"): + if eType == "ETCUSTOM": file.write(targ + '.emitter.setOuterAngle(%.4f)\n' % self.emitter.getOuterAngle()) file.write(targ + '.emitter.setInnerAngle(%.4f)\n' % self.emitter.getInnerAngle()) file.write(targ + '.emitter.setOuterMagnitude(%.4f)\n' % self.emitter.getOuterMagnitude()) file.write(targ + '.emitter.setInnerMagnitude(%.4f)\n' % self.emitter.getInnerMagnitude()) file.write(targ + '.emitter.setCubicLerping(%d)\n' % self.emitter.getCubicLerping()) - elif (self.emitterType == "LineEmitter"): + elif self.emitterType == "LineEmitter": file.write('# Line parameters\n') point = self.emitter.getEndpoint1() file.write((targ + '.emitter.setEndpoint1(Point3(%.4f, %.4f, %.4f))\n' % (point[0], point[1], point[2]))) point = self.emitter.getEndpoint2() file.write((targ + '.emitter.setEndpoint2(Point3(%.4f, %.4f, %.4f))\n' % (point[0], point[1], point[2]))) - elif (self.emitterType == "PointEmitter"): + elif self.emitterType == "PointEmitter": file.write('# Point parameters\n') point = self.emitter.getLocation() file.write((targ + '.emitter.setLocation(Point3(%.4f, %.4f, %.4f))\n' % (point[0], point[1], point[2]))) - elif (self.emitterType == "RectangleEmitter"): + elif self.emitterType == "RectangleEmitter": file.write('# Rectangle parameters\n') point = self.emitter.getMinBound() file.write((targ + '.emitter.setMinBound(Point2(%.4f, %.4f))\n' % (point[0], point[1]))) point = self.emitter.getMaxBound() file.write((targ + '.emitter.setMaxBound(Point2(%.4f, %.4f))\n' % (point[0], point[1]))) - elif (self.emitterType == "RingEmitter"): + elif self.emitterType == "RingEmitter": file.write('# Ring parameters\n') file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius()) file.write(targ + '.emitter.setRadiusSpread(%.4f)\n' % self.emitter.getRadiusSpread()) - if (eType == "ETCUSTOM"): + if eType == "ETCUSTOM": file.write(targ + '.emitter.setAngle(%.4f)\n' % self.emitter.getAngle()) - elif (self.emitterType == "SphereSurfaceEmitter"): + elif self.emitterType == "SphereSurfaceEmitter": file.write('# Sphere Surface parameters\n') file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius()) - elif (self.emitterType == "SphereVolumeEmitter"): + elif self.emitterType == "SphereVolumeEmitter": file.write('# Sphere Volume parameters\n') file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius()) - elif (self.emitterType == "TangentRingEmitter"): + elif self.emitterType == "TangentRingEmitter": file.write('# Tangent Ring parameters\n') file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius()) file.write(targ + '.emitter.setRadiusSpread(%.4f)\n' % self.emitter.getRadiusSpread()) @@ -595,7 +595,7 @@ class Particles(ParticleSystem): base.particleMgr.doParticles(stepTime,self,False) base.physicsMgr.doPhysics(stepTime,self) - if(remainder): + if remainder: base.particleMgr.doParticles(remainder,self,False) base.physicsMgr.doPhysics(remainder,self) diff --git a/direct/src/particles/SpriteParticleRendererExt.py b/direct/src/particles/SpriteParticleRendererExt.py index f73b61e350..3bae273843 100644 --- a/direct/src/particles/SpriteParticleRendererExt.py +++ b/direct/src/particles/SpriteParticleRendererExt.py @@ -17,7 +17,7 @@ class SpriteParticleRendererExt(SpriteParticleRenderer): sourceNodeName = None def getSourceTextureName(self): - if self.sourceTextureName == None: + if self.sourceTextureName is None: SpriteParticleRendererExt.sourceTextureName = base.config.GetString( 'particle-sprite-texture', 'maps/lightbulb.rgb') # Return instance copy of class variable @@ -28,11 +28,11 @@ class SpriteParticleRendererExt(SpriteParticleRenderer): self.sourceTextureName = name def setTextureFromFile(self, fileName = None): - if fileName == None: + if fileName is None: fileName = self.getSourceTextureName() - t = loader.loadTexture(fileName) - if (t != None): + t = base.loader.loadTexture(fileName) + if t is not None: self.setTexture(t, t.getYSize()) self.setSourceTextureName(fileName) return True @@ -41,14 +41,14 @@ class SpriteParticleRendererExt(SpriteParticleRenderer): return False def addTextureFromFile(self, fileName = None): - if(self.getNumAnims() == 0): + if self.getNumAnims() == 0: return self.setTextureFromFile(fileName) - if fileName == None: + if fileName is None: fileName = self.getSourceTextureName() - t = loader.loadTexture(fileName) - if (t != None): + t = base.loader.loadTexture(fileName) + if t is not None: self.addTexture(t, t.getYSize()) return True else: @@ -56,7 +56,7 @@ class SpriteParticleRendererExt(SpriteParticleRenderer): return False def getSourceFileName(self): - if self.sourceFileName == None: + if self.sourceFileName is None: SpriteParticleRendererExt.sourceFileName = base.config.GetString( 'particle-sprite-model', 'models/misc/smiley') # Return instance copy of class variable @@ -67,7 +67,7 @@ class SpriteParticleRendererExt(SpriteParticleRenderer): self.sourceFileName = name def getSourceNodeName(self): - if self.sourceNodeName == None: + if self.sourceNodeName is None: SpriteParticleRendererExt.sourceNodeName = base.config.GetString( 'particle-sprite-node', '**/*') # Return instance copy of class variable @@ -78,14 +78,14 @@ class SpriteParticleRendererExt(SpriteParticleRenderer): self.sourceNodeName = name def setTextureFromNode(self, modelName = None, nodeName = None, sizeFromTexels = False): - if modelName == None: + if modelName is None: modelName = self.getSourceFileName() - if nodeName == None: + if nodeName is None: nodeName = self.getSourceNodeName() # Load model and get texture - m = loader.loadModel(modelName) - if (m == None): + m = base.loader.loadModel(modelName) + if m is None: print("SpriteParticleRendererExt: Couldn't find model: %s!" % modelName) return False @@ -102,17 +102,17 @@ class SpriteParticleRendererExt(SpriteParticleRenderer): return True def addTextureFromNode(self, modelName = None, nodeName = None, sizeFromTexels = False): - if(self.getNumAnims() == 0): + if self.getNumAnims() == 0: return self.setTextureFromNode(modelName, nodeName, sizeFromTexels) - if modelName == None: + if modelName is None: modelName = self.getSourceFileName() - if nodeName == None: + if nodeName is None: nodeName = self.getSourceNodeName() # Load model and get texture - m = loader.loadModel(modelName) - if (m == None): + m = base.loader.loadModel(modelName) + if m is None: print("SpriteParticleRendererExt: Couldn't find model: %s!" % modelName) return False diff --git a/direct/src/physics/FallTest.py b/direct/src/physics/FallTest.py index 833269c984..f1e431aabe 100644 --- a/direct/src/physics/FallTest.py +++ b/direct/src/physics/FallTest.py @@ -1,38 +1,39 @@ from panda3d.core import NodePath from panda3d.physics import * + class FallTest(NodePath): def __init__(self): NodePath.__init__(self, "FallTest") def setup(self): # Connect to Physics Manager: - self.actorNode=ActorNode("FallTestActorNode") + self.actorNode = ActorNode("FallTestActorNode") #self.actorNode.getPhysicsObject().setOriented(1) #self.actorNode.getPhysical(0).setViscosity(0.1) - actorNodePath=self.attachNewNode(self.actorNode) + actorNodePath = self.attachNewNode(self.actorNode) #self.setPos(avatarNodePath, Vec3(0)) #self.setHpr(avatarNodePath, Vec3(0)) - avatarNodePath=loader.loadModel("models/misc/smiley") + avatarNodePath = base.loader.loadModel("models/misc/smiley") assert not avatarNodePath.isEmpty() - camLL=render.find("**/camLL") + camLL = base.render.find("**/camLL") camLL.reparentTo(avatarNodePath) camLL.setPosHpr(0, -10, 0, 0, 0, 0) avatarNodePath.reparentTo(actorNodePath) #avatarNodePath.setPos(Vec3(0)) #avatarNodePath.setHpr(Vec3(0)) #avatarNodePath.assign(physicsActor) - #self.phys=PhysicsManager() - self.phys=base.physicsMgr + #self.phys = PhysicsManager() + self.phys = base.physicsMgr if 1: fn=ForceNode("FallTest gravity") fnp=NodePath(fn) fnp.reparentTo(self) - fnp.reparentTo(render) + fnp.reparentTo(base.render) gravity=LinearVectorForce(0.0, 0.0, -.5) fn.addForce(gravity) self.phys.addLinearForce(gravity) @@ -42,7 +43,7 @@ class FallTest(NodePath): fn=ForceNode("FallTest viscosity") fnp=NodePath(fn) fnp.reparentTo(self) - fnp.reparentTo(render) + fnp.reparentTo(base.render) self.avatarViscosity=LinearFrictionForce(0.0, 1.0, 0) #self.avatarViscosity.setCoef(0.9) fn.addForce(self.avatarViscosity) @@ -59,7 +60,7 @@ class FallTest(NodePath): self.momentumForce=LinearVectorForce(0.0, 0.0, 0.0) fn=ForceNode("FallTest momentum") fnp=NodePath(fn) - fnp.reparentTo(render) + fnp.reparentTo(base.render) fn.addForce(self.momentumForce) self.phys.addLinearForce(self.momentumForce) @@ -67,13 +68,13 @@ class FallTest(NodePath): self.acForce=LinearVectorForce(0.0, 0.0, 0.0) fn=ForceNode("FallTest avatarControls") fnp=NodePath(fn) - fnp.reparentTo(render) + fnp.reparentTo(base.render) fn.addForce(self.acForce) self.phys.addLinearForce(self.acForce) #self.phys.removeLinearForce(self.acForce) #fnp.remove() - #avatarNodePath.reparentTo(render) + #avatarNodePath.reparentTo(base.render) self.avatarNodePath = avatarNodePath #self.actorNode.getPhysicsObject().resetPosition(self.avatarNodePath.getPos()) #self.actorNode.updateTransform() diff --git a/direct/src/physics/RotationTest.py b/direct/src/physics/RotationTest.py index b32a1195f5..aee5fe18cc 100644 --- a/direct/src/physics/RotationTest.py +++ b/direct/src/physics/RotationTest.py @@ -1,58 +1,59 @@ from panda3d.core import NodePath from panda3d.physics import * + class RotationTest(NodePath): def __init__(self): NodePath.__init__(self, "RotationTest") def setup(self): # Connect to Physics Manager: - self.actorNode=ActorNode("RotationTestActorNode") + self.actorNode = ActorNode("RotationTestActorNode") #self.actorNode.getPhysicsObject().setOriented(1) #self.actorNode.getPhysical(0).setViscosity(0.1) - actorNodePath=self.attachNewNode(self.actorNode) + actorNodePath = self.attachNewNode(self.actorNode) #self.setPos(avatarNodePath, Vec3(0)) #self.setHpr(avatarNodePath, Vec3(0)) - avatarNodePath=loader.loadModel("models/misc/smiley") + avatarNodePath = base.loader.loadModel("models/misc/smiley") assert not avatarNodePath.isEmpty() - camLL=render.find("**/camLL") + camLL = base.render.find("**/camLL") camLL.reparentTo(avatarNodePath) camLL.setPosHpr(0, -10, 0, 0, 0, 0) avatarNodePath.reparentTo(actorNodePath) #avatarNodePath.setPos(Vec3(0)) #avatarNodePath.setHpr(Vec3(0)) #avatarNodePath.assign(physicsActor) - #self.phys=PhysicsManager() - self.phys=base.physicsMgr + #self.phys = PhysicsManager() + self.phys = base.physicsMgr if 0: - fn=ForceNode("RotationTest gravity") - fnp=NodePath(fn) + fn = ForceNode("RotationTest gravity") + fnp = NodePath(fn) fnp.reparentTo(self) - fnp.reparentTo(render) - gravity=LinearVectorForce(0.0, 0.0, -.5) + fnp.reparentTo(base.render) + gravity=LinearVectorForce(0.0, 0.0, -0.5) fn.addForce(gravity) self.phys.addLinearForce(gravity) self.gravity = gravity if 1: - fn=ForceNode("RotationTest spin") - fnp=NodePath(fn) + fn = ForceNode("RotationTest spin") + fnp = NodePath(fn) fnp.reparentTo(self) - fnp.reparentTo(render) - spin=AngularVectorForce(0.0, 0.0, 0.5) + fnp.reparentTo(base.render) + spin = AngularVectorForce(0.0, 0.0, 0.5) fn.addForce(spin) self.phys.addAngularForce(spin) self.spin = spin if 0: - fn=ForceNode("RotationTest viscosity") - fnp=NodePath(fn) + fn = ForceNode("RotationTest viscosity") + fnp = NodePath(fn) fnp.reparentTo(self) - fnp.reparentTo(render) + fnp.reparentTo(base.render) self.avatarViscosity=LinearFrictionForce(0.0, 1.0, 0) #self.avatarViscosity.setCoef(0.9) fn.addForce(self.avatarViscosity) @@ -66,24 +67,24 @@ class RotationTest(NodePath): self.phys.attachPhysicalNode(self.actorNode) if 0: - self.momentumForce=LinearVectorForce(0.0, 0.0, 0.0) - fn=ForceNode("RotationTest momentum") - fnp=NodePath(fn) - fnp.reparentTo(render) + self.momentumForce = LinearVectorForce(0.0, 0.0, 0.0) + fn = ForceNode("RotationTest momentum") + fnp = NodePath(fn) + fnp.reparentTo(base.render) fn.addForce(self.momentumForce) self.phys.addLinearForce(self.momentumForce) if 0: - self.acForce=LinearVectorForce(0.0, 0.0, 0.0) - fn=ForceNode("RotationTest avatarControls") - fnp=NodePath(fn) - fnp.reparentTo(render) + self.acForce = LinearVectorForce(0.0, 0.0, 0.0) + fn = ForceNode("RotationTest avatarControls") + fnp = NodePath(fn) + fnp.reparentTo(base.render) fn.addForce(self.acForce) self.phys.addLinearForce(self.acForce) #self.phys.removeLinearForce(self.acForce) #fnp.remove() - #avatarNodePath.reparentTo(render) + #avatarNodePath.reparentTo(base.render) self.avatarNodePath = avatarNodePath #self.actorNode.getPhysicsObject().resetPosition(self.avatarNodePath.getPos()) #self.actorNode.updateTransform() diff --git a/direct/src/showbase/Audio3DManager.py b/direct/src/showbase/Audio3DManager.py index 78389c63ba..65804de7a0 100644 --- a/direct/src/showbase/Audio3DManager.py +++ b/direct/src/showbase/Audio3DManager.py @@ -4,7 +4,8 @@ __all__ = ['Audio3DManager'] from panda3d.core import Vec3, VBase3, WeakNodePath, ClockObject from direct.task.TaskManagerGlobal import Task, taskMgr -# + + class Audio3DManager: def __init__(self, audio_manager, listener_target = None, root = None, @@ -12,8 +13,8 @@ class Audio3DManager: self.audio_manager = audio_manager self.listener_target = listener_target - if (root==None): - self.root = render + if root is None: + self.root = base.render else: self.root = root @@ -28,8 +29,8 @@ class Audio3DManager: Use Audio3DManager.loadSfx to load a sound with 3D positioning enabled """ sound = None - if (name): - sound=self.audio_manager.getSound(name, 1) + if name: + sound = self.audio_manager.getSound(name, 1) return sound def setDistanceFactor(self, factor): @@ -330,4 +331,3 @@ class Audio3DManager: detach_listener = detachListener set_drop_off_factor = setDropOffFactor detach_sound = detachSound - diff --git a/direct/src/showbase/BufferViewer.py b/direct/src/showbase/BufferViewer.py index 0c43063bc8..4213881fcf 100644 --- a/direct/src/showbase/BufferViewer.py +++ b/direct/src/showbase/BufferViewer.py @@ -47,7 +47,7 @@ class BufferViewer(DirectObject): self.task = 0 self.dirty = 1 self.accept("render-texture-targets-changed", self.refreshReadout) - if (ConfigVariableBool("show-buffers", 0).getValue()): + if ConfigVariableBool("show-buffers", 0): self.enable(1) def refreshReadout(self): @@ -65,9 +65,9 @@ class BufferViewer(DirectObject): def isValidTextureSet(self, x): """Access: private. Returns true if the parameter is a list of GraphicsOutput and Texture, or the keyword 'all'.""" - if (isinstance(x, list)): + if isinstance(x, list): for elt in x: - if (self.isValidTextureSet(elt)==0): + if not self.isValidTextureSet(elt): return 0 else: return (x=="all") or (isinstance(x, Texture)) or (isinstance(x, GraphicsOutput)) @@ -79,7 +79,7 @@ class BufferViewer(DirectObject): def enable(self, x): """Turn the buffer viewer on or off. The initial state of the buffer viewer depends on the Config variable 'show-buffers'.""" - if (x != 0) and (x != 1): + if x != 0 and x != 1: BufferViewer.notify.error('invalid parameter to BufferViewer.enable') return self.enabled = x @@ -102,7 +102,7 @@ class BufferViewer(DirectObject): If both dimensions are zero, the viewer uses a heuristic to choose a reasonable size for the card. The initial value is (0, 0).""" - if (x < 0) or (y < 0): + if x < 0 or y < 0: BufferViewer.notify.error('invalid parameter to BufferViewer.setCardSize') return self.sizex = x @@ -119,12 +119,12 @@ class BufferViewer(DirectObject): - *window* - put them in a separate window The initial value is 'lrcorner'.""" - valid=["llcorner","lrcorner","ulcorner","urcorner","window"] - if (valid.count(pos)==0): + valid = ["llcorner", "lrcorner", "ulcorner", "urcorner", "window"] + if valid.count(pos) == 0: BufferViewer.notify.error('invalid parameter to BufferViewer.setPosition') BufferViewer.notify.error('valid parameters are: llcorner, lrcorner, ulcorner, urcorner, window') return - if (pos == "window"): + if pos == "window": BufferViewer.notify.error('BufferViewer.setPosition - "window" mode not implemented yet.') return self.position = pos @@ -140,8 +140,8 @@ class BufferViewer(DirectObject): - *cycle* - display one card at a time, using selectCard/advanceCard The default value is 'hline'.""" - valid=["vline","hline","vgrid","hgrid","cycle"] - if (valid.count(lay)==0): + valid=["vline", "hline", "vgrid", "hgrid", "cycle"] + if valid.count(lay) == 0: BufferViewer.notify.error('invalid parameter to BufferViewer.setLayout') BufferViewer.notify.error('valid parameters are: vline, hline, vgrid, hgrid, cycle') return @@ -168,7 +168,7 @@ class BufferViewer(DirectObject): Valid inputs are the string 'all' (display every render-to-texture target), or a list of GraphicsOutputs or Textures. The initial value is 'all'.""" - if (self.isValidTextureSet(x)==0): + if not self.isValidTextureSet(x): BufferViewer.notify.error('setInclude: must be list of textures and buffers, or "all"') return self.include = x @@ -180,7 +180,7 @@ class BufferViewer(DirectObject): The exclude-set is subtracted from the include-set (so the excludes effectively override the includes.) The initial value is the empty list.""" - if (self.isValidTextureSet(x)==0): + if not self.isValidTextureSet(x): BufferViewer.notify.error('setExclude: must be list of textures and buffers') return self.exclude = x @@ -203,20 +203,20 @@ class BufferViewer(DirectObject): """Access: private. Converts a list of GraphicsObject, GraphicsEngine, and Texture into a table of Textures.""" - if (isinstance(x, list)): + if isinstance(x, list): for elt in x: self.analyzeTextureSet(elt, set) - elif (isinstance(x, Texture)): + elif isinstance(x, Texture): set[x] = 1 - elif (isinstance(x, GraphicsOutput)): + elif isinstance(x, GraphicsOutput): for itex in range(x.countTextures()): tex = x.getTexture(itex) set[tex] = 1 - elif (isinstance(x, GraphicsEngine)): + elif isinstance(x, GraphicsEngine): for iwin in range(x.getNumWindows()): win = x.getWindow(iwin) self.analyzeTextureSet(win, set) - elif (x=="all"): + elif x == "all": self.analyzeTextureSet(self.engine, set) else: return @@ -228,11 +228,11 @@ class BufferViewer(DirectObject): be precise so that the frame exactly aligns to pixel boundaries, and so that it doesn't overlap the card at all.""" - format=GeomVertexFormat.getV3cp() - vdata=GeomVertexData('card-frame', format, Geom.UHDynamic) + format = GeomVertexFormat.getV3cp() + vdata = GeomVertexData('card-frame', format, Geom.UHDynamic) - vwriter=GeomVertexWriter(vdata, 'vertex') - cwriter=GeomVertexWriter(vdata, 'color') + vwriter = GeomVertexWriter(vdata, 'vertex') + cwriter = GeomVertexWriter(vdata, 'color') ringoffset = [0, 1, 1, 2] ringbright = [0, 0, 1, 1] @@ -249,7 +249,7 @@ class BufferViewer(DirectObject): cwriter.addData3f(bright, bright, bright) cwriter.addData3f(bright, bright, bright) - triangles=GeomTriangles(Geom.UHStatic) + triangles = GeomTriangles(Geom.UHStatic) for i in range(2): delta = i*8 triangles.addVertices(0+delta, 4+delta, 1+delta) @@ -262,7 +262,7 @@ class BufferViewer(DirectObject): triangles.addVertices(0+delta, 7+delta, 4+delta) triangles.closePrimitive() - geom=Geom(vdata) + geom = Geom(vdata) geom.addPrimitive(triangles) geomnode=GeomNode("card-frame") geomnode.addGeom(geom) @@ -275,7 +275,7 @@ class BufferViewer(DirectObject): parameters have changed.""" # If nothing has changed, don't update. - if (self.dirty==0): + if not self.dirty: return Task.cont self.dirty = 0 @@ -285,7 +285,7 @@ class BufferViewer(DirectObject): self.cards = [] # If not enabled, return. - if (self.enabled == 0): + if not self.enabled: self.task = 0 return Task.done @@ -312,13 +312,13 @@ class BufferViewer(DirectObject): for itex in range(win.countTextures()): tex = win.getTexture(itex) if (tex in include) and (tex not in exclude): - if (tex.getTextureType() == Texture.TTCubeMap): + if tex.getTextureType() == Texture.TTCubeMap: for face in range(6): self.cardmaker.setUvRangeCube(face) card = NodePath(self.cardmaker.generate()) card.setTexture(tex, sampler) cards.append(card) - elif (tex.getTextureType() == Texture.TT2dTextureArray): + elif tex.getTextureType() == Texture.TT2dTextureArray: for layer in range(tex.getZSize()): self.cardmaker.setUvRange((0, 1, 1, 0), (0, 0, 1, 1),\ (layer, layer, layer, layer)) @@ -336,29 +336,33 @@ class BufferViewer(DirectObject): wins.append(win) exclude[tex] = 1 self.cards = cards - if (len(cards)==0): + if len(cards) == 0: self.task = 0 return Task.done ncards = len(cards) # Decide how many rows and columns to use for the layout. - if (self.layout == "hline"): + if self.layout == "hline": rows = 1 cols = ncards - elif (self.layout == "vline"): + elif self.layout == "vline": rows = ncards cols = 1 - elif (self.layout == "hgrid"): + elif self.layout == "hgrid": rows = int(math.sqrt(ncards)) cols = rows - if (rows * cols < ncards): cols += 1 - if (rows * cols < ncards): rows += 1 - elif (self.layout == "vgrid"): + if rows * cols < ncards: + cols += 1 + if rows * cols < ncards: + rows += 1 + elif self.layout == "vgrid": rows = int(math.sqrt(ncards)) cols = rows - if (rows * cols < ncards): rows += 1 - if (rows * cols < ncards): cols += 1 - elif (self.layout == "cycle"): + if rows * cols < ncards: + rows += 1 + if rows * cols < ncards: + cols += 1 + elif self.layout == "cycle": rows = 1 cols = 1 else: @@ -372,7 +376,7 @@ class BufferViewer(DirectObject): aspectx = wins[0].getXSize() aspecty = wins[0].getYSize() for win in wins: - if (win.getXSize()*aspecty) != (win.getYSize()*aspectx): + if win.getXSize() * aspecty != win.getYSize() * aspectx: aspectx = 1 aspecty = 1 @@ -398,7 +402,7 @@ class BufferViewer(DirectObject): h_sizex = float (self.win.getXSize() - adjustment) / float (cols) h_sizex -= bordersize - if (h_sizex < 1.0): + if h_sizex < 1.0: h_sizex = 1.0 h_sizey = (h_sizex * aspecty) // aspectx @@ -408,8 +412,10 @@ class BufferViewer(DirectObject): else: sizex = int(self.sizex * 0.5 * self.win.getXSize()) sizey = int(self.sizey * 0.5 * self.win.getYSize()) - if (sizex == 0): sizex = (sizey*aspectx) // aspecty - if (sizey == 0): sizey = (sizex*aspecty) // aspectx + if sizex == 0: + sizex = (sizey * aspectx) // aspecty + if sizey == 0: + sizey = (sizex * aspecty) // aspectx # Convert from pixels to render2d-units. fsizex = (2.0 * sizex) / float(self.win.getXSize()) @@ -418,16 +424,16 @@ class BufferViewer(DirectObject): fpixely = 2.0 / float(self.win.getYSize()) # Choose directional offsets - if (self.position == "llcorner"): + if self.position == "llcorner": dirx = -1.0 diry = -1.0 - elif (self.position == "lrcorner"): + elif self.position == "lrcorner": dirx = 1.0 diry = -1.0 - elif (self.position == "ulcorner"): + elif self.position == "ulcorner": dirx = -1.0 diry = 1.0 - elif (self.position == "urcorner"): + elif self.position == "urcorner": dirx = 1.0 diry = 1.0 else: @@ -442,7 +448,7 @@ class BufferViewer(DirectObject): for r in range(rows): for c in range(cols): index = c + r*cols - if (index < ncards): + if index < ncards: index = (index + self.cardindex) % len(cards) posx = dirx * (1.0 - ((c + 0.5) * (fsizex + fpixelx * bordersize))) - (fpixelx * dirx) diff --git a/direct/src/showbase/BulletinBoard.py b/direct/src/showbase/BulletinBoard.py index 5b1cdd71a0..9478b68bfa 100755 --- a/direct/src/showbase/BulletinBoard.py +++ b/direct/src/showbase/BulletinBoard.py @@ -3,6 +3,8 @@ __all__ = ['BulletinBoard'] from direct.directnotify import DirectNotifyGlobal +from direct.showbase.MessengerGlobal import messenger + class BulletinBoard: """This class implements a global location for key/value pairs to be diff --git a/direct/src/showbase/BulletinBoardWatcher.py b/direct/src/showbase/BulletinBoardWatcher.py index efc75b43ac..407b0425b8 100755 --- a/direct/src/showbase/BulletinBoardWatcher.py +++ b/direct/src/showbase/BulletinBoardWatcher.py @@ -5,6 +5,8 @@ __all__ = ['BulletinBoardWatcher'] from direct.directnotify import DirectNotifyGlobal from direct.showbase.PythonUtil import Functor, makeList from direct.showbase import DirectObject +from direct.showbase.BulletinBoardGlobal import bulletinBoard as bboard + class BulletinBoardWatcher(DirectObject.DirectObject): """ This class allows you to wait for a set of posts to be made to (or diff --git a/direct/src/showbase/ContainerLeakDetector.py b/direct/src/showbase/ContainerLeakDetector.py index 48c3e810a1..ed60e75097 100755 --- a/direct/src/showbase/ContainerLeakDetector.py +++ b/direct/src/showbase/ContainerLeakDetector.py @@ -1,8 +1,14 @@ from direct.directnotify.DirectNotifyGlobal import directNotify +import direct.showbase.DConfig as config from direct.showbase.PythonUtil import makeFlywheelGen from direct.showbase.PythonUtil import itype, serialNum, safeRepr, fastRepr from direct.showbase.Job import Job -import types, weakref, random, sys +from direct.showbase.JobManagerGlobal import jobMgr +from direct.showbase.MessengerGlobal import messenger +from direct.task.TaskManagerGlobal import taskMgr +import types +import weakref +import random import builtins deadEndTypes = (bool, types.BuiltinFunctionType, @@ -445,13 +451,11 @@ class FindContainers(Job): if objId in self._id2discoveredStartRef: existingRef = self._id2discoveredStartRef[objId] if type(existingRef) is not int: - if (existingRef.getNumIndirections() >= - ref.getNumIndirections()): + if existingRef.getNumIndirections() >= ref.getNumIndirections(): # the ref that we already have is more concise than the new ref return if objId in self._id2ref: - if (self._id2ref[objId].getNumIndirections() >= - ref.getNumIndirections()): + if self._id2ref[objId].getNumIndirections() >= ref.getNumIndirections(): # the ref that we already have is more concise than the new ref return storedItem = ref @@ -851,7 +855,7 @@ class FPTObjsOfType(Job): cName = container.__class__.__name__ else: cName = container.__name__ - if (self._otn.lower() in cName.lower()): + if self._otn.lower() in cName.lower(): try: for ptc in self._leakDetector.getContainerNameByIdGen( id, getInstance=getInstance): diff --git a/direct/src/showbase/ContainerReport.py b/direct/src/showbase/ContainerReport.py index 753e72e84c..3a2cd768b2 100755 --- a/direct/src/showbase/ContainerReport.py +++ b/direct/src/showbase/ContainerReport.py @@ -2,8 +2,10 @@ from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import Queue, invertDictLossless from direct.showbase.PythonUtil import safeRepr from direct.showbase.Job import Job +from direct.showbase.JobManagerGlobal import jobMgr import types + class ContainerReport(Job): notify = directNotify.newCategory("ContainerReport") # set of containers that should not be included in the report @@ -22,7 +24,7 @@ class ContainerReport(Job): # for breadth-first searching self._queue = Queue() jobMgr.add(self) - if threaded == False: + if not threaded: jobMgr.finish(self) def destroy(self): @@ -84,18 +86,18 @@ class ContainerReport(Job): except: pass - if type(parentObj) in (types.StringType, types.UnicodeType): + if isinstance(parentObj, (str, bytes)): continue if type(parentObj) in (types.ModuleType, types.InstanceType): child = parentObj.__dict__ if self._examine(child): - assert (self._queue.back() is child) + assert self._queue.back() is child self._instanceDictIds.add(id(child)) self._id2pathStr[id(child)] = str(self._id2pathStr[id(parentObj)]) continue - if type(parentObj) is dict: + if isinstance(parentObj, dict): key = None attr = None keys = list(parentObj.keys()) @@ -112,7 +114,7 @@ class ContainerReport(Job): if id(attr) not in self._visitedIds: self._visitedIds.add(id(attr)) if self._examine(attr): - assert (self._queue.back() is attr) + assert self._queue.back() is attr if parentObj is __builtins__: self._id2pathStr[id(attr)] = key else: @@ -142,7 +144,7 @@ class ContainerReport(Job): if id(attr) not in self._visitedIds: self._visitedIds.add(id(attr)) if self._examine(attr): - assert (self._queue.back() is attr) + assert self._queue.back() is attr self._id2pathStr[id(attr)] = self._id2pathStr[id(parentObj)] + '[%s]' % index index += 1 del attr @@ -163,7 +165,7 @@ class ContainerReport(Job): if id(child) not in self._visitedIds: self._visitedIds.add(id(child)) if self._examine(child): - assert (self._queue.back() is child) + assert self._queue.back() is child self._id2pathStr[id(child)] = self._id2pathStr[id(parentObj)] + '.%s' % childName del childName del child @@ -196,11 +198,9 @@ class ContainerReport(Job): self._type2id2len[type(obj)][objId] = length def _examine(self, obj): # return False if it's an object that can't contain or lead to other objects - if type(obj) in (types.BooleanType, types.BuiltinFunctionType, - types.BuiltinMethodType, types.ComplexType, - types.FloatType, types.IntType, types.LongType, - types.NoneType, types.NotImplementedType, - types.TypeType, types.CodeType, types.FunctionType): + if type(obj) in (bool, types.BuiltinFunctionType, types.BuiltinMethodType, + complex, float, int, type(None), type(NotImplemented), + type, types.CodeType, types.FunctionType): return False # if it's an internal object, ignore it if id(obj) in ContainerReport.PrivateIds: diff --git a/direct/src/showbase/CountedResource.py b/direct/src/showbase/CountedResource.py index 62a25d28b2..a1463470e8 100755 --- a/direct/src/showbase/CountedResource.py +++ b/direct/src/showbase/CountedResource.py @@ -225,6 +225,3 @@ if __debug__ and __name__ == '__main__': print('Cursor will be freed on function exit') demoFunc() - - - diff --git a/direct/src/showbase/DirectObject.py b/direct/src/showbase/DirectObject.py index 0833b1890a..f511e8f49d 100644 --- a/direct/src/showbase/DirectObject.py +++ b/direct/src/showbase/DirectObject.py @@ -3,17 +3,15 @@ object needs to be able to respond to events.""" __all__ = ['DirectObject'] - from direct.directnotify.DirectNotifyGlobal import directNotify +from direct.task.TaskManagerGlobal import taskMgr from .MessengerGlobal import messenger + class DirectObject: """ This is the class that all Direct/SAL classes should inherit from """ - def __init__(self): - pass - #def __del__(self): # This next line is useful for debugging leaks #print "Destructing: ", self.__class__.__name__ @@ -44,21 +42,21 @@ class DirectObject: #This function must be used if you want a managed task def addTask(self, *args, **kwargs): - if(not hasattr(self,"_taskList")): + if not hasattr(self, "_taskList"): self._taskList = {} kwargs['owner']=self task = taskMgr.add(*args, **kwargs) return task def doMethodLater(self, *args, **kwargs): - if(not hasattr(self,"_taskList")): - self._taskList ={} + if not hasattr(self, "_taskList"): + self._taskList = {} kwargs['owner']=self task = taskMgr.doMethodLater(*args, **kwargs) return task def removeTask(self, taskOrName): - if type(taskOrName) == type(''): + if isinstance(taskOrName, str): # we must use a copy, since task.remove will modify self._taskList if hasattr(self, '_taskList'): taskListValues = list(self._taskList.values()) @@ -69,7 +67,7 @@ class DirectObject: taskOrName.remove() def removeAllTasks(self): - if hasattr(self,'_taskList'): + if hasattr(self, '_taskList'): for task in list(self._taskList.values()): task.remove() @@ -93,10 +91,10 @@ class DirectObject: tasks = [] if hasattr(self, '_taskList'): tasks = [task.name for task in self._taskList.values()] - if len(events) or len(tasks): - estr = ('listening to events: %s' % events if len(events) else '') - andStr = (' and ' if len(events) and len(tasks) else '') - tstr = ('%srunning tasks: %s' % (andStr, tasks) if len(tasks) else '') + if len(events) != 0 or len(tasks) != 0: + estr = ('listening to events: %s' % events if len(events) != 0 else '') + andStr = (' and ' if len(events) != 0 and len(tasks) != 0 else '') + tstr = ('%srunning tasks: %s' % (andStr, tasks) if len(tasks) != 0 else '') notify = directNotify.newCategory('LeakDetect') crash = getattr(getRepository(), '_crashOnProactiveLeakDetect', False) func = (self.notify.error if crash else self.notify.warning) diff --git a/direct/src/showbase/EventGroup.py b/direct/src/showbase/EventGroup.py index 6385761ca4..2c9bf0af5a 100755 --- a/direct/src/showbase/EventGroup.py +++ b/direct/src/showbase/EventGroup.py @@ -4,6 +4,8 @@ __all__ = ['EventGroup'] from direct.showbase import DirectObject from direct.showbase.PythonUtil import SerialNumGen, Functor +from direct.showbase.MessengerGlobal import messenger + class EventGroup(DirectObject.DirectObject): """This class allows you to group together multiple events and treat diff --git a/direct/src/showbase/EventManager.py b/direct/src/showbase/EventManager.py index 319503b414..c7c6e00e50 100644 --- a/direct/src/showbase/EventManager.py +++ b/direct/src/showbase/EventManager.py @@ -10,6 +10,7 @@ from direct.task.TaskManagerGlobal import taskMgr from panda3d.core import PStatCollector, EventQueue, EventHandler from panda3d.core import ConfigVariableBool + class EventManager: notify = None @@ -54,17 +55,17 @@ class EventManager: """ Extract the actual data from the eventParameter """ - if (eventParameter.isInt()): + if eventParameter.isInt(): return eventParameter.getIntValue() - elif (eventParameter.isDouble()): + elif eventParameter.isDouble(): return eventParameter.getDoubleValue() - elif (eventParameter.isString()): + elif eventParameter.isString(): return eventParameter.getStringValue() - elif (eventParameter.isWstring()): + elif eventParameter.isWstring(): return eventParameter.getWstringValue() - elif (eventParameter.isTypedRefCount()): + elif eventParameter.isTypedRefCount(): return eventParameter.getTypedRefCountValue() - elif (eventParameter.isEmpty()): + elif eventParameter.isEmpty(): return None else: # Must be some user defined type, return the ptr @@ -88,7 +89,7 @@ class EventManager: paramList.append(eventParameterData) # Do not print the new frame debug, it is too noisy! - if (EventManager.notify.getDebug() and eventName != 'NewFrame'): + if EventManager.notify.getDebug() and eventName != 'NewFrame': EventManager.notify.debug('received C++ event named: ' + eventName + ' parameters: ' + repr(paramList)) # ************************************************************** @@ -124,7 +125,7 @@ class EventManager: paramList.append(eventParameterData) # Do not print the new frame debug, it is too noisy! - if (EventManager.notify.getDebug() and eventName != 'NewFrame'): + if EventManager.notify.getDebug() and eventName != 'NewFrame': EventManager.notify.debug('received C++ event named: ' + eventName + ' parameters: ' + repr(paramList)) # Send the event, we used to send it with the event diff --git a/direct/src/showbase/ExceptionVarDump.py b/direct/src/showbase/ExceptionVarDump.py index 90fa052a0c..151ba35bcd 100755 --- a/direct/src/showbase/ExceptionVarDump.py +++ b/direct/src/showbase/ExceptionVarDump.py @@ -2,7 +2,7 @@ __all__ = ["install"] from panda3d.core import * from direct.directnotify.DirectNotifyGlobal import directNotify -from direct.showbase.PythonUtil import fastRepr +from direct.showbase.PythonUtil import fastRepr, Stack import sys import traceback @@ -125,7 +125,7 @@ def _excepthookDumpVars(eType, eValue, tb): name, obj, traversedIds = stateStack.pop() #notify.info('%s, %s, %s' % (name, fastRepr(obj), traversedIds)) r = fastRepr(obj, maxLen=10) - if type(r) is str: + if isinstance(r, str): r = r.replace('\n', '\\n') s += '\n %s = %s' % (name, r) # if we've already traversed through this object, don't traverse through it again @@ -133,7 +133,7 @@ def _excepthookDumpVars(eType, eValue, tb): attrName2obj = {} for attrName in codeNames: attr = getattr(obj, attrName, _AttrNotFound) - if (attr is not _AttrNotFound): + if attr is not _AttrNotFound: # prevent infinite recursion on method wrappers (__init__.__init__.__init__...) try: className = attr.__class__.__name__ @@ -143,7 +143,7 @@ def _excepthookDumpVars(eType, eValue, tb): if className == 'method-wrapper': continue attrName2obj[attrName] = attr - if len(attrName2obj): + if len(attrName2obj) > 0: # show them in alphabetical order attrNames = list(attrName2obj.keys()) attrNames.sort() diff --git a/direct/src/showbase/Factory.py b/direct/src/showbase/Factory.py index 0abd217c07..75edd2483f 100755 --- a/direct/src/showbase/Factory.py +++ b/direct/src/showbase/Factory.py @@ -4,6 +4,7 @@ __all__ = ['Factory'] from direct.directnotify.DirectNotifyGlobal import directNotify + class Factory: """This class manages a list of object types and their corresponding constructors. Objects may be created on-demand from their type. Object types may be any hashable @@ -30,4 +31,3 @@ class Factory: def nullCtor(self, *args, **kwArgs): return None - diff --git a/direct/src/showbase/Finder.py b/direct/src/showbase/Finder.py index 129bcb4dc6..02accf4a12 100644 --- a/direct/src/showbase/Finder.py +++ b/direct/src/showbase/Finder.py @@ -6,6 +6,10 @@ import types import os import sys +from direct.showbase.MessengerGlobal import messenger +from direct.task.TaskManagerGlobal import taskMgr + + def findClass(className): """ Look in sys.modules dictionary for a module that defines a class @@ -21,18 +25,17 @@ def findClass(className): # is the same as the module we are looking in, then we found # the matching class and a good module namespace to redefine # our class in. - if (classObj and - ((type(classObj) == types.ClassType) or - (type(classObj) == types.TypeType)) and - (classObj.__module__ == moduleName)): + if classObj and isinstance(classObj, type) and \ + classObj.__module__ == moduleName: return [classObj, module.__dict__] return None + def rebindClass(filename): file = open(filename, 'r') lines = file.readlines() for line in lines: - if (line[0:6] == 'class '): + if line[0:6] == 'class ': # Chop off the "class " syntax and strip extra whitespace classHeader = line[6:].strip() # Look for a open paren if it does inherit @@ -94,35 +97,32 @@ def copyFuncs(fromClass, toClass): # Copy the functions from fromClass into toClass dictionary for funcName, newFunc in fromClass.__dict__.items(): # Filter out for functions - if (type(newFunc) == types.FunctionType): + if isinstance(newFunc, types.FunctionType): # See if we already have a function with this name oldFunc = toClass.__dict__.get(funcName) if oldFunc: - - """ # This code is nifty, but with nested functions, give an error: # SystemError: cellobject.c:22: bad argument to internal function # Give the new function code the same filename as the old function # Perhaps there is a cleaner way to do this? This was my best idea. - newCode = types.CodeType(newFunc.func_code.co_argcount, - newFunc.func_code.co_nlocals, - newFunc.func_code.co_stacksize, - newFunc.func_code.co_flags, - newFunc.func_code.co_code, - newFunc.func_code.co_consts, - newFunc.func_code.co_names, - newFunc.func_code.co_varnames, - # Use the oldFunc's filename here. Tricky! - oldFunc.func_code.co_filename, - newFunc.func_code.co_name, - newFunc.func_code.co_firstlineno, - newFunc.func_code.co_lnotab) - newFunc = types.FunctionType(newCode, - newFunc.func_globals, - newFunc.func_name, - newFunc.func_defaults, - newFunc.func_closure) - """ + #newCode = types.CodeType(newFunc.func_code.co_argcount, + # newFunc.func_code.co_nlocals, + # newFunc.func_code.co_stacksize, + # newFunc.func_code.co_flags, + # newFunc.func_code.co_code, + # newFunc.func_code.co_consts, + # newFunc.func_code.co_names, + # newFunc.func_code.co_varnames, + # # Use the oldFunc's filename here. Tricky! + # oldFunc.func_code.co_filename, + # newFunc.func_code.co_name, + # newFunc.func_code.co_firstlineno, + # newFunc.func_code.co_lnotab) + #newFunc = types.FunctionType(newCode, + # newFunc.func_globals, + # newFunc.func_name, + # newFunc.func_defaults, + # newFunc.func_closure) replaceFuncList.append((oldFunc, funcName, newFunc)) else: # TODO: give these new functions a proper code filename diff --git a/direct/src/showbase/GarbageReport.py b/direct/src/showbase/GarbageReport.py index 73e1210a99..f47b97df86 100755 --- a/direct/src/showbase/GarbageReport.py +++ b/direct/src/showbase/GarbageReport.py @@ -3,9 +3,12 @@ __all__ = ['FakeObject', '_createGarbage', 'GarbageReport', 'GarbageLogger'] from direct.directnotify.DirectNotifyGlobal import directNotify -from direct.showbase.PythonUtil import fastRepr -from direct.showbase.PythonUtil import AlphabetCounter +from direct.showbase.PythonUtil import ScratchPad, Stack, AlphabetCounter +from direct.showbase.PythonUtil import itype, deeptype, fastRepr from direct.showbase.Job import Job +from direct.showbase.JobManagerGlobal import jobMgr +from direct.showbase.MessengerGlobal import messenger +import direct.showbase.DConfig as config import gc import types @@ -83,7 +86,7 @@ class GarbageReport(Job): self.garbageInstanceIds = set() for i in range(len(garbageInstances)): self.garbageInstanceIds.add(id(garbageInstances[i])) - if not (i % 20): + if i % 20 == 0: yield None # then release the list of instances so that it doesn't interfere with the gc.collect() below del garbageInstances @@ -115,14 +118,12 @@ class GarbageReport(Job): if self._args.verbose: self.notify.info('found %s garbage items' % self.numGarbage) - """ spammy # print the types of the garbage first, in case the repr of an object # causes a crash - if self.numGarbage > 0: - self.notify.info('TYPES ONLY (this is only needed if a crash occurs before GarbageReport finishes):') - for result in printNumberedTypesGen(self.garbage): - yield None - """ + #if self.numGarbage > 0: + # self.notify.info('TYPES ONLY (this is only needed if a crash occurs before GarbageReport finishes):') + # for result in printNumberedTypesGen(self.garbage): + # yield None # Py obj id -> garbage list index self._id2index = {} @@ -143,7 +144,7 @@ class GarbageReport(Job): # make the id->index table to speed up the next steps for i in range(self.numGarbage): self._id2index[id(self.garbage[i])] = i - if not (i % 20): + if i % 20 == 0: yield None # grab the referrers (pointing to garbage) @@ -179,7 +180,7 @@ class GarbageReport(Job): self._id2garbageInfo[id(self.garbage[i])] = info yield None else: - if not (i % 20): + if i % 20 == 0: yield None # find the cycles @@ -350,7 +351,7 @@ class GarbageReport(Job): yield None s.append('%s:%s' % (ac.next(), self.cyclesBySyntax[i])) - if len(self._id2garbageInfo): + if len(self._id2garbageInfo) > 0: s.append('===== Garbage Custom Info =====') ac = AlphabetCounter() for i in range(len(self.cyclesBySyntax)): @@ -448,7 +449,7 @@ class GarbageReport(Job): # look to see if each referrer is another garbage item byNum = [] for i in range(len(byRef)): - if not (i % 20): + if i % 20 == 0: yield None referrer = byRef[i] num = self._id2index.get(id(referrer), None) @@ -465,7 +466,7 @@ class GarbageReport(Job): # look to see if each referent is another garbage item byNum = [] for i in range(len(byRef)): - if not (i % 20): + if i % 20 == 0: yield None referent = byRef[i] num = self._id2index.get(id(referent), None) @@ -561,8 +562,8 @@ class _CFGLGlobals: def checkForGarbageLeaks(): gc.collect() numGarbage = len(gc.garbage) - if (numGarbage > 0 and config.GetBool('auto-garbage-logging', 0)): - if (numGarbage != _CFGLGlobals.LastNumGarbage): + if numGarbage > 0 and config.GetBool('auto-garbage-logging', 0): + if numGarbage != _CFGLGlobals.LastNumGarbage: print("") gr = GarbageReport('found garbage', threaded=False, collect=False) print("") diff --git a/direct/src/showbase/Job.py b/direct/src/showbase/Job.py index 01b7a0c8b7..76a6f1ee97 100755 --- a/direct/src/showbase/Job.py +++ b/direct/src/showbase/Job.py @@ -1,4 +1,5 @@ from direct.showbase.DirectObject import DirectObject +from direct.showbase.PythonUtil import ScratchPad, SerialNumGen if __debug__: from panda3d.core import PStatCollector @@ -107,7 +108,6 @@ class Job(DirectObject): self._generator = None if __debug__: # __dev__ not yet available at this point - from direct.showbase.Job import Job class TestJob(Job): def __init__(self): Job.__init__(self, 'TestJob') @@ -134,4 +134,5 @@ if __debug__: # __dev__ not yet available at this point yield None def addTestJob(): + from direct.showbase.JobManagerGlobal import jobMgr jobMgr.add(TestJob()) diff --git a/direct/src/showbase/JobManager.py b/direct/src/showbase/JobManager.py index 0c2ab09bbf..01567c7462 100755 --- a/direct/src/showbase/JobManager.py +++ b/direct/src/showbase/JobManager.py @@ -1,7 +1,10 @@ +from panda3d.core import ConfigVariableBool, ConfigVariableDouble from direct.directnotify.DirectNotifyGlobal import directNotify from direct.task.TaskManagerGlobal import taskMgr from direct.showbase.Job import Job -from direct.showbase.PythonUtil import getBase +from direct.showbase.PythonUtil import flywheel +from direct.showbase.MessengerGlobal import messenger + class JobManager: """ @@ -127,7 +130,8 @@ class JobManager: def getDefaultTimeslice(): # run for 1/2 millisecond per frame by default # config is in milliseconds, this func returns value in seconds - return getBase().config.GetFloat('job-manager-timeslice-ms', .5) / 1000. + return ConfigVariableDouble('job-manager-timeslice-ms', .5).value / 1000. + def getTimeslice(self): if self._timeslice: return self._timeslice @@ -143,8 +147,9 @@ class JobManager: def _process(self, task=None): if self._useOverflowTime is None: - self._useOverflowTime = config.GetBool('job-use-overflow-time', 1) - if len(self._pri2jobId2job): + self._useOverflowTime = ConfigVariableBool('job-use-overflow-time', 1).value + + if len(self._pri2jobId2job) > 0: #assert self.notify.debugCall() # figure out how long we can run endT = globalClock.getRealTime() + (self.getTimeslice() * .9) diff --git a/direct/src/showbase/LeakDetectors.py b/direct/src/showbase/LeakDetectors.py index 1cec5bf74d..ba93262158 100755 --- a/direct/src/showbase/LeakDetectors.py +++ b/direct/src/showbase/LeakDetectors.py @@ -4,7 +4,11 @@ ContainerLeakDetector. from panda3d.core import * from direct.showbase.DirectObject import DirectObject +from direct.showbase.PythonUtil import safeTypeName, typeName, uniqueName, serialNum from direct.showbase.Job import Job +from direct.showbase.JobManagerGlobal import jobMgr +from direct.showbase.MessengerGlobal import messenger +from direct.task.TaskManagerGlobal import taskMgr import gc import builtins @@ -19,6 +23,7 @@ class LeakDetector: if __dev__: assert self._leakDetectorsKey not in leakDetectors leakDetectors[self._leakDetectorsKey] = self + def destroy(self): del leakDetectors[self._leakDetectorsKey] @@ -27,6 +32,7 @@ class LeakDetector: # point to what is leaking return '%s-%s' % (self.__class__.__name__, id(self)) + class ObjectTypeLeakDetector(LeakDetector): def __init__(self, otld, objType, generation): self._otld = otld @@ -46,6 +52,7 @@ class ObjectTypeLeakDetector(LeakDetector): self._generation = self._otld._getGeneration() return num + class ObjectTypesLeakDetector(LeakDetector): # are we accumulating any particular Python object type? def __init__(self): @@ -85,6 +92,7 @@ class ObjectTypesLeakDetector(LeakDetector): self._thisLdGen = self._generation return len(self._type2count) + class GarbageLeakDetector(LeakDetector): # are we accumulating Python garbage? def __len__(self): @@ -97,31 +105,37 @@ class GarbageLeakDetector(LeakDetector): gc.set_debug(oldFlags) return numGarbage + class SceneGraphLeakDetector(LeakDetector): # is a scene graph leaking nodes? def __init__(self, render): LeakDetector.__init__(self) self._render = render - if config.GetBool('leak-scene-graph', 0): + if ConfigVariableBool('leak-scene-graph', False): self._leakTaskName = 'leakNodes-%s' % serialNum() self._leakNode() + def destroy(self): if hasattr(self, '_leakTaskName'): taskMgr.remove(self._leakTaskName) del self._render LeakDetector.destroy(self) + def __len__(self): try: # this will be available when the build server finishes return self._render.countNumDescendants() except: return self._render.getNumDescendants() + def __repr__(self): return 'SceneGraphLeakDetector(%s)' % self._render + def _leakNode(self, task=None): self._render.attachNewNode('leakNode-%s' % serialNum()) taskMgr.doMethodLater(10, self._leakNode, self._leakTaskName) + class CppMemoryUsage(LeakDetector): def __len__(self): haveMemoryUsage = True @@ -134,6 +148,7 @@ class CppMemoryUsage(LeakDetector): else: return 0 + class TaskLeakDetectorBase: def _getTaskNamePattern(self, taskName): # get a generic string pattern from a task name by removing numeric characters @@ -141,6 +156,7 @@ class TaskLeakDetectorBase: taskName = taskName.replace('%s' % i, '') return taskName + class _TaskNamePatternLeakDetector(LeakDetector, TaskLeakDetectorBase): # tracks the number of each individual task type # e.g. are we leaking 'examine-' tasks @@ -162,6 +178,7 @@ class _TaskNamePatternLeakDetector(LeakDetector, TaskLeakDetectorBase): def getLeakDetectorKey(self): return '%s-%s' % (self._taskNamePattern, self.__class__.__name__) + class TaskLeakDetector(LeakDetector, TaskLeakDetectorBase): # tracks the number task 'types' and creates leak detectors for each task type def __init__(self): @@ -190,6 +207,7 @@ class TaskLeakDetector(LeakDetector, TaskLeakDetectorBase): # are we leaking task types? return len(self._taskName2collector) + class MessageLeakDetectorBase: def _getMessageNamePattern(self, msgName): # get a generic string pattern from a message name by removing numeric characters @@ -197,6 +215,7 @@ class MessageLeakDetectorBase: msgName = msgName.replace('%s' % i, '') return msgName + class _MessageTypeLeakDetector(LeakDetector, MessageLeakDetectorBase): # tracks the number of objects that are listening to each message def __init__(self, msgNamePattern): @@ -225,6 +244,7 @@ class _MessageTypeLeakDetector(LeakDetector, MessageLeakDetectorBase): def getLeakDetectorKey(self): return '%s-%s' % (self._msgNamePattern, self.__class__.__name__) + class _MessageTypeLeakDetectorCreator(Job): def __init__(self, creator): Job.__init__(self, uniqueName(typeName(self))) @@ -246,12 +266,13 @@ class _MessageTypeLeakDetectorCreator(Job): self._creator._msgName2detector[namePattern].addMsgName(msgName) yield Job.Done + class MessageTypesLeakDetector(LeakDetector, MessageLeakDetectorBase): def __init__(self): LeakDetector.__init__(self) self._msgName2detector = {} self._createJob = None - if config.GetBool('leak-message-types', 0): + if ConfigVariableBool('leak-message-types', False): self._leakers = [] self._leakTaskName = uniqueName('leak-message-types') taskMgr.add(self._leak, self._leakTaskName) @@ -285,6 +306,7 @@ class MessageTypesLeakDetector(LeakDetector, MessageLeakDetectorBase): # are we leaking message types? return len(self._msgName2detector) + class _MessageListenerTypeLeakDetector(LeakDetector): # tracks the number of each object type that is listening for events def __init__(self, typeName): @@ -301,6 +323,7 @@ class _MessageListenerTypeLeakDetector(LeakDetector): def getLeakDetectorKey(self): return '%s-%s' % (self._typeName, self.__class__.__name__) + class _MessageListenerTypeLeakDetectorCreator(Job): def __init__(self, creator): Job.__init__(self, uniqueName(typeName(self))) @@ -322,12 +345,13 @@ class _MessageListenerTypeLeakDetectorCreator(Job): _MessageListenerTypeLeakDetector(tName)) yield Job.Done + class MessageListenerTypesLeakDetector(LeakDetector): def __init__(self): LeakDetector.__init__(self) self._typeName2detector = {} self._createJob = None - if config.GetBool('leak-message-listeners', 0): + if ConfigVariableBool('leak-message-listeners', False): self._leakers = [] self._leakTaskName = uniqueName('leak-message-listeners') taskMgr.add(self._leak, self._leakTaskName) diff --git a/direct/src/showbase/Loader.py b/direct/src/showbase/Loader.py index 711a40f30e..cc34ed8f4f 100644 --- a/direct/src/showbase/Loader.py +++ b/direct/src/showbase/Loader.py @@ -444,7 +444,7 @@ class Loader(DirectObject): nodeList = node gotList = True - assert(len(modelList) == len(nodeList)) + assert len(modelList) == len(nodeList) # Make sure we have PandaNodes, not NodePaths. for i in range(len(nodeList)): @@ -627,7 +627,7 @@ class Loader(DirectObject): assert Loader.notify.debug("Loading font: %s" % (modelPath)) if phaseChecker: loaderOptions = LoaderOptions() - if(okMissing): + if okMissing: loaderOptions.setFlags(loaderOptions.getFlags() & ~LoaderOptions.LFReportErrors) phaseChecker(modelPath, loaderOptions) @@ -958,7 +958,7 @@ class Loader(DirectObject): independently of the other group.""" # showbase-created sfxManager should always be at front of list - if(self.base.sfxManagerList): + if self.base.sfxManagerList: return self.loadSound(self.base.sfxManagerList[0], *args, **kw) return None @@ -970,7 +970,7 @@ class Loader(DirectObject): to load the sound file, but this distinction allows the sound effects and/or the music files to be adjusted as a group, independently of the other group.""" - if(self.base.musicManager): + if self.base.musicManager: return self.loadSound(self.base.musicManager, *args, **kw) else: return None @@ -1025,8 +1025,8 @@ class Loader(DirectObject): return cb def unloadSfx(self, sfx): - if (sfx): - if(self.base.sfxManagerList): + if sfx: + if self.base.sfxManagerList: self.base.sfxManagerList[0].uncacheSound (sfx.getName()) ## def makeNodeNamesUnique(self, nodePath, nodeCount): @@ -1096,7 +1096,7 @@ class Loader(DirectObject): """ The asynchronous flatten operation has completed; quietly drop in the new models. """ self.notify.debug("asyncFlattenDone: %s" % (models,)) - assert(len(models) == len(origModelList)) + assert len(models) == len(origModelList) for i in range(len(models)): origModelList[i].getChildren().detach() orig = origModelList[i].node() diff --git a/direct/src/showbase/Messenger.py b/direct/src/showbase/Messenger.py index d99c71b3d1..359c09d82c 100644 --- a/direct/src/showbase/Messenger.py +++ b/direct/src/showbase/Messenger.py @@ -4,12 +4,10 @@ __all__ = ['Messenger'] - -from .PythonUtil import * -from direct.directnotify import DirectNotifyGlobal -import types - from direct.stdpy.threading import Lock +from direct.directnotify import DirectNotifyGlobal +from .PythonUtil import * +import types class Messenger: @@ -116,6 +114,7 @@ class Messenger: """ Returns a future that is triggered by the given event name. This will function only once. """ + from .EventManagerGlobal import eventMgr return eventMgr.eventHandler.get_future(event) def accept(self, event, object, method, extraArgs=[], persistent=1): @@ -195,14 +194,14 @@ class Messenger: del acceptorDict[id] # If this dictionary is now empty, remove the event # entry from the Messenger alltogether - if (len(acceptorDict) == 0): + if len(acceptorDict) == 0: del self.__callbacks[event] # This object is no longer listening for this event eventDict = self.__objectEvents.get(id) if eventDict and event in eventDict: del eventDict[event] - if (len(eventDict) == 0): + if len(eventDict) == 0: del self.__objectEvents[id] self._releaseObject(object) @@ -232,7 +231,7 @@ class Messenger: del acceptorDict[id] # If this dictionary is now empty, remove the event # entry from the Messenger alltogether - if (len(acceptorDict) == 0): + if len(acceptorDict) == 0: del self.__callbacks[event] self._releaseObject(object) del self.__objectEvents[id] @@ -282,7 +281,7 @@ class Messenger: """ isIgnorning(self, string, DirectObject) Is this object ignoring this event? """ - return (not self.isAccepting(event, object)) + return not self.isAccepting(event, object) def send(self, event, sentArgs=[], taskChain=None): """ @@ -306,12 +305,12 @@ class Messenger: self.lock.acquire() try: - foundWatch=0 + foundWatch = 0 if __debug__: if self.__isWatching: - for i in self.__watching.keys(): + for i in self.__watching: if str(event).find(i) >= 0: - foundWatch=1 + foundWatch = 1 break acceptorDict = self.__callbacks.get(event) if not acceptorDict: @@ -386,15 +385,15 @@ class Messenger: eventDict = self.__objectEvents.get(id) if eventDict and event in eventDict: del eventDict[event] - if (len(eventDict) == 0): + if len(eventDict) == 0: del self.__objectEvents[id] self._releaseObject(self._getObject(id)) del acceptorDict[id] # If the dictionary at this event is now empty, remove # the event entry from the Messenger altogether - if (event in self.__callbacks \ - and (len(self.__callbacks[event]) == 0)): + if event in self.__callbacks \ + and (len(self.__callbacks[event]) == 0): del self.__callbacks[event] if __debug__: @@ -424,6 +423,7 @@ class Messenger: if hasattr(result, 'cr_await'): # It's a coroutine, so schedule it with the task manager. + from direct.task.TaskManagerGlobal import taskMgr taskMgr.add(result) def clear(self): @@ -439,7 +439,7 @@ class Messenger: self.lock.release() def isEmpty(self): - return (len(self.__callbacks) == 0) + return len(self.__callbacks) == 0 def getEvents(self): return list(self.__callbacks.keys()) @@ -455,7 +455,7 @@ class Messenger: for objectEntry in list(objectDict.items()): object, params = objectEntry method = params[0] - if (type(method) == types.MethodType): + if isinstance(method, types.MethodType): function = method.__func__ else: function = method @@ -463,7 +463,7 @@ class Messenger: # 'method: ' + repr(method) + '\n' + # 'oldMethod: ' + repr(oldMethod) + '\n' + # 'newFunction: ' + repr(newFunction) + '\n') - if (function == oldMethod): + if function == oldMethod: newMethod = types.MethodType(newFunction, method.__self__) params[0] = newMethod # Found it retrun true @@ -570,7 +570,7 @@ class Messenger: """ return string version of class.method or method. """ - if (type(method) == types.MethodType): + if isinstance(method, types.MethodType): functionName = method.__self__.__class__.__name__ + '.' + \ method.__func__.__name__ else: @@ -615,7 +615,6 @@ class Messenger: """ Print out the table in a detailed readable format """ - import types str = 'Messenger\n' str = str + '='*50 + '\n' keys = list(self.__callbacks.keys()) @@ -638,7 +637,7 @@ class Messenger: 'Extra Args: ' + repr(extraArgs) + '\n\t' + 'Persistent: ' + repr(persistent) + '\n') # If this is a class method, get its actual function - if (type(function) == types.MethodType): + if isinstance(function, types.MethodType): str = (str + '\t' + 'Method: ' + repr(function) + '\n\t' + 'Function: ' + repr(function.__func__) + '\n') diff --git a/direct/src/showbase/MessengerLeakDetector.py b/direct/src/showbase/MessengerLeakDetector.py index 187c0d51ac..73ab6376f4 100755 --- a/direct/src/showbase/MessengerLeakDetector.py +++ b/direct/src/showbase/MessengerLeakDetector.py @@ -1,6 +1,9 @@ from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.DirectObject import DirectObject +from direct.showbase.PythonUtil import itype, fastRepr from direct.showbase.Job import Job +from direct.showbase.JobManagerGlobal import jobMgr +from direct.showbase.MessengerGlobal import messenger import gc import builtins @@ -76,7 +79,7 @@ class MessengerLeakDetector(Job): foundBuiltin = False # breadth-first search, go until you run out of new objects or you find __builtin__ - while len(nextObjList): + while len(nextObjList) > 0: if foundBuiltin: break # swap the lists, prepare for the next pass diff --git a/direct/src/showbase/MirrorDemo.py b/direct/src/showbase/MirrorDemo.py index 1e43f7621b..732768c817 100755 --- a/direct/src/showbase/MirrorDemo.py +++ b/direct/src/showbase/MirrorDemo.py @@ -23,6 +23,8 @@ __all__ = ['setupMirror', 'showFrustum'] from panda3d.core import * from direct.task import Task +from direct.task.TaskManagerGlobal import taskMgr + def setupMirror(name, width, height, rootCamera = None, bufferSize = 256, clearColor = None): @@ -77,7 +79,7 @@ def setupMirror(name, width, height, rootCamera = None, camera.setInitialState(dummy.getState()) # Create a visible representation of the camera so we can see it. - #cameraVis = loader.loadModel('camera.egg') + #cameraVis = base.loader.loadModel('camera.egg') #if not cameraVis.isEmpty(): # cameraVis.reparentTo(cameraNP) @@ -127,6 +129,7 @@ def setupMirror(name, width, height, rootCamera = None, return root + def showFrustum(np): # Utility function to reveal the frustum for a particular camera. cameraNP = np.find('**/+Camera') @@ -136,15 +139,16 @@ def showFrustum(np): geomNode.addGeom(lens.makeGeometry()) cameraNP.attachNewNode(geomNode) + if __name__ == "__main__": from direct.showbase.ShowBase import ShowBase base = ShowBase() - panda = loader.loadModel("panda") + panda = base.loader.loadModel("panda") panda.setH(180) panda.setPos(0, 10, -2.5) panda.setScale(0.5) - panda.reparentTo(render) + panda.reparentTo(base.render) myMirror = setupMirror("mirror", 10, 10, bufferSize=1024, clearColor=(0, 0, 1, 1)) myMirror.setPos(0, 15, 2.5) diff --git a/direct/src/showbase/ObjectPool.py b/direct/src/showbase/ObjectPool.py index e82e6cdaae..5531dd1946 100755 --- a/direct/src/showbase/ObjectPool.py +++ b/direct/src/showbase/ObjectPool.py @@ -3,14 +3,16 @@ __all__ = ['Diff', 'ObjectPool'] from direct.directnotify.DirectNotifyGlobal import directNotify -from direct.showbase.PythonUtil import invertDictLossless, makeList, safeRepr +from direct.showbase.PythonUtil import invertDictLossless, makeList, safeRepr, itype from direct.showbase.PythonUtil import getNumberedTypedString, getNumberedTypedSortedString import gc + class Diff: def __init__(self, lost, gained): - self.lost=lost - self.gained=gained + self.lost = lost + self.gained = gained + def printOut(self, full=False): print('lost %s objects, gained %s objects' % (len(self.lost), len(self.gained))) print('\n\nself.lost\n') @@ -22,6 +24,7 @@ class Diff: print('\n\nGAINED-OBJECT REFERRERS\n') self.gained.printReferrers(1) + class ObjectPool: """manipulate a pool of Python objects""" notify = directNotify.newCategory('ObjectPool') @@ -124,7 +127,7 @@ class ObjectPool: print('\nOBJ: %s\n' % safeRepr(obj)) referrers = gc.get_referrers(obj) print('%s REFERRERS:\n' % len(referrers)) - if len(referrers): + if len(referrers) > 0: print(getNumberedTypedString(referrers, maxLen=80, numPrefix='REF')) else: diff --git a/direct/src/showbase/ObjectReport.py b/direct/src/showbase/ObjectReport.py index 4ee511a597..5362716e25 100755 --- a/direct/src/showbase/ObjectReport.py +++ b/direct/src/showbase/ObjectReport.py @@ -1,3 +1,5 @@ +# pylint: skip-file + """ >>> from direct.showbase import ObjectReport @@ -12,14 +14,16 @@ __all__ = ['ExclusiveObjectPool', 'ObjectReport'] from direct.directnotify.DirectNotifyGlobal import directNotify -from direct.showbase import DirectObject, ObjectPool, GarbageReport -from direct.showbase.PythonUtil import makeList, Sync +from direct.showbase.DirectObject import DirectObject +from direct.showbase.ObjectPool import ObjectPool +from direct.showbase.GarbageReport import GarbageReport +from direct.showbase.PythonUtil import makeList, Sync, SerialNumGen import gc import sys import builtins -class ExclusiveObjectPool(DirectObject.DirectObject): +class ExclusiveObjectPool(DirectObject): # ObjectPool specialization that excludes particular objects # IDs of objects to globally exclude from reporting _ExclObjs = [] @@ -35,6 +39,7 @@ class ExclusiveObjectPool(DirectObject.DirectObject): cls._ExclObjIds.setdefault(id(obj), 0) cls._ExclObjIds[id(obj)] += 1 cls._SyncMaster.change() + @classmethod def removeExclObjs(cls, *objs): for obj in makeList(objs): @@ -82,29 +87,34 @@ class ExclusiveObjectPool(DirectObject.DirectObject): def getObjsOfType(self, type): self._resync() return self._filteredPool.getObjsOfType(type) + def printObjsOfType(self, type): self._resync() return self._filteredPool.printObjsOfType(type) + def diff(self, other): self._resync() return self._filteredPool.diff(other._filteredPool) + def typeFreqStr(self): self._resync() return self._filteredPool.typeFreqStr() + def __len__(self): self._resync() return len(self._filteredPool) + class ObjectReport: """report on every Python object in the current process""" notify = directNotify.newCategory('ObjectReport') def __init__(self, name, log=True): - gr = GarbageReport.GarbageReport('ObjectReport\'s GarbageReport: %s' % name, log=log) + gr = GarbageReport('ObjectReport\'s GarbageReport: %s' % name, log=log) gr.destroy() del gr self._name = name - self._pool = ObjectPool.ObjectPool(self._getObjectList()) + self._pool = ObjectPool(self._getObjectList()) #ExclusiveObjectPool.addExclObjs(self, self._pool, self._name) if log: self.notify.info('===== ObjectReport: \'%s\' =====\n%s' % (self._name, self.typeFreqStr())) @@ -142,7 +152,7 @@ class ObjectReport: for obj in objects: found.add(id(obj)) # repeatedly call get_referents until we can't find any more objects - while len(nextObjList): + while len(nextObjList) > 0: curObjList = nextObjList nextObjList = [] for obj in curObjList: @@ -153,39 +163,3 @@ class ObjectReport: objects.append(ref) nextObjList.append(ref) return objects - """ - if hasattr(sys, 'getobjects'): - return sys.getobjects(0) - else: - objs = [] - stateStack = Stack() - root = builtins - objIds = set([id(root)]) - stateStack.push((root, None, 0)) - while True: - if len(stateStack) == 0: - break - obj, adjacents, resumeIndex = stateStack.pop() - objs.append(obj) - print id(obj) - if adjacents is None: - adjacents = gc.get_referents(obj) - adjacents.extend(gc.get_referrers(obj)) - # pare the list down to the ones that have not already been visited - # to minimize calls to get_referents/get_referrers - newObjs = [] - for adj in adjacents: - adjId = id(adj) - if adjId not in objIds: - objIds.add(adjId) - newObjs.append(adj) - adjacents = newObjs - if len(adjacents) == 0: - print 'DEAD END' - for i in range(resumeIndex, len(adjacents)): - adj = adjacents[i] - stateStack.push((obj, adjacents, i+1)) - stateStack.push((adj, None, 0)) - continue - """ - diff --git a/direct/src/showbase/OnScreenDebug.py b/direct/src/showbase/OnScreenDebug.py index da38db5301..e5a1c7aedb 100755 --- a/direct/src/showbase/OnScreenDebug.py +++ b/direct/src/showbase/OnScreenDebug.py @@ -7,6 +7,7 @@ from panda3d.core import * from direct.gui import OnscreenText from direct.directtools import DirectUtil + class OnScreenDebug: enabled = ConfigVariableBool("on-screen-debug-enabled", False) @@ -33,7 +34,7 @@ class OnScreenDebug: fgColor.setW(ConfigVariableDouble("on-screen-debug-fg-alpha", 0.85).value) bgColor.setW(ConfigVariableDouble("on-screen-debug-bg-alpha", 0.85).value) - font = loader.loadFont(fontPath) + font = base.loader.loadFont(fontPath) if not font.isValid(): print("failed to load OnScreenDebug font %s" % fontPath) font = TextNode.getDefaultFont() @@ -63,7 +64,7 @@ class OnScreenDebug: #isNew = "was" isNew = "~" value = v[1] - if type(value) == float: + if isinstance(value, float): value = "% 10.4f"%(value,) # else: other types will be converted to str by the "%s" self.onScreenText.appendText("%20s %s %-44s\n"%(k, isNew, value)) diff --git a/direct/src/showbase/PhasedObject.py b/direct/src/showbase/PhasedObject.py index 4a6dad1481..bd3a2aad7d 100755 --- a/direct/src/showbase/PhasedObject.py +++ b/direct/src/showbase/PhasedObject.py @@ -1,5 +1,6 @@ from direct.directnotify.DirectNotifyGlobal import * + class PhasedObject: """ This class is governs the loading and unloading of successive @@ -190,4 +191,3 @@ if __debug__: def unloadPhaseAt(self): print('unloading At') - diff --git a/direct/src/showbase/Pool.py b/direct/src/showbase/Pool.py index 9c11979c6a..1da67cee5b 100755 --- a/direct/src/showbase/Pool.py +++ b/direct/src/showbase/Pool.py @@ -82,19 +82,19 @@ class Pool: """ Returns true if there is at least one free item. """ - return (len(self.__free) != 0) + return len(self.__free) != 0 def isFree(self, item): """ Returns true if this item is free for check out. """ - return (item in self.__free) + return item in self.__free def isUsed(self, item): """ Returns true if this item has already been checked out. """ - return (item in self.__used) + return item in self.__used def getNumItems(self): """ diff --git a/direct/src/showbase/ProfileSession.py b/direct/src/showbase/ProfileSession.py index a1b56b92e1..dd5ef6e828 100755 --- a/direct/src/showbase/ProfileSession.py +++ b/direct/src/showbase/ProfileSession.py @@ -2,7 +2,7 @@ from panda3d.core import TrueClock from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import ( StdoutCapture, _installProfileCustomFuncs,_removeProfileCustomFuncs, - _getProfileResultFileInfo, _setProfileResultsFileInfo) + _getProfileResultFileInfo, _setProfileResultsFileInfo, Default) import profile import pstats import builtins @@ -24,7 +24,8 @@ class PercentStats(pstats.Stats): def print_stats(self, *amount): for filename in self.files: print(filename) - if self.files: print() + if self.files: + print() indent = ' ' * 8 for func in self.top_level: print(indent, func_get_function_name(func)) @@ -367,4 +368,3 @@ class ProfileSession: self._resultCache[k] = output return output - diff --git a/direct/src/showbase/PythonUtil.py b/direct/src/showbase/PythonUtil.py index 7a5efc9dac..21dd0049c1 100644 --- a/direct/src/showbase/PythonUtil.py +++ b/direct/src/showbase/PythonUtil.py @@ -46,16 +46,13 @@ __report_indent = 3 from panda3d.core import ConfigVariableBool -""" -# with one integer positional arg, this uses about 4/5 of the memory of the Functor class below -def Functor(function, *args, **kArgs): - argsCopy = args[:] - def functor(*cArgs, **ckArgs): - kArgs.update(ckArgs) - return function(*(argsCopy + cArgs), **kArgs) - return functor -""" - +## with one integer positional arg, this uses about 4/5 of the memory of the Functor class below +#def Functor(function, *args, **kArgs): +# argsCopy = args[:] +# def functor(*cArgs, **ckArgs): +# kArgs.update(ckArgs) +# return function(*(argsCopy + cArgs), **kArgs) +# return functor class Functor: def __init__(self, function, *args, **kargs): @@ -178,7 +175,7 @@ if __debug__: comma = ',' for filename, lineNum, funcName, text in self.trace: r += '%s.%s:%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma) - if len(r): + if len(r) > 0: r = r[:-len(comma)] return r @@ -187,7 +184,7 @@ if __debug__: comma = ',' for filename, lineNum, funcName, text in self.trace: r = '%s.%s:%s%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma, r) - if len(r): + if len(r) > 0: r = r[:-len(comma)] return r @@ -221,16 +218,18 @@ if __debug__: co = f.f_code dict = f.f_locals n = co.co_argcount - if co.co_flags & 4: n = n+1 - if co.co_flags & 8: n = n+1 - r='' + if co.co_flags & 4: + n = n + 1 + if co.co_flags & 8: + n = n + 1 + r = '' if 'self' in dict: - r = '%s.'%(dict['self'].__class__.__name__,) - r+="%s("%(f.f_code.co_name,) + r = '%s.' % (dict['self'].__class__.__name__,) + r += "%s(" % (f.f_code.co_name,) comma=0 # formatting, whether we should type a comma. for i in range(n): name = co.co_varnames[i] - if name=='self': + if name == 'self': continue if comma: r+=', ' @@ -323,8 +322,8 @@ def intersection(a, b): """ intersection(list, list): """ - if not a: return [] - if not b: return [] + if not a or not b: + return [] d = [] for i in a: if (i in b) and (i not in d): @@ -341,7 +340,7 @@ def union(a, b): # Copy a c = a[:] for i in b: - if (i not in c): + if i not in c: c.append(i) return c @@ -358,18 +357,18 @@ def sameElements(a, b): def makeList(x): """returns x, converted to a list""" - if type(x) is list: + if isinstance(x, list): return x - elif type(x) is tuple: + elif isinstance(x, tuple): return list(x) else: return [x,] def makeTuple(x): """returns x, converted to a tuple""" - if type(x) is list: + if isinstance(x, list): return tuple(x) - elif type(x) is tuple: + elif isinstance(x, tuple): return x else: return (x,) @@ -443,7 +442,7 @@ def contains(whole, sub): """ Return 1 if whole contains sub, 0 otherwise """ - if (whole == sub): + if whole == sub: return 1 for elem in sub: # The first item you find not in whole, return 0 @@ -483,7 +482,7 @@ def reduceAngle(deg): """ Reduces an angle (in degrees) to a value in [-180..180) """ - return (((deg + 180.) % 360.) - 180.) + return ((deg + 180.) % 360.) - 180. def fitSrcAngle2Dest(src, dest): """ @@ -626,19 +625,17 @@ if __debug__: assert type(category) in (str, type(None)), "must provide a category name for @profiled" # allow profiling in published versions - """ - try: - null = not __dev__ - except: - null = not __debug__ - if null: - # if we're not in __dev__, just return the function itself. This - # results in zero runtime overhead, since decorators are evaluated - # at module-load. - def nullDecorator(f): - return f - return nullDecorator - """ + #try: + # null = not __dev__ + #except: + # null = not __debug__ + #if null: + # # if we're not in __dev__, just return the function itself. This + # # results in zero runtime overhead, since decorators are evaluated + # # at module-load. + # def nullDecorator(f): + # return f + # return nullDecorator def profileDecorator(f): def _profiled(*args, **kArgs): @@ -759,7 +756,6 @@ if __debug__: Profile = profile.Profile statement = cmd sort = -1 - retVal = None #### COPIED FROM profile.run #### prof = Profile() try: @@ -770,11 +766,10 @@ if __debug__: prof.dump_stats(filename) else: #return prof.print_stats(sort) #DCR - retVal = prof.print_stats(sort) #DCR + prof.print_stats(sort) #DCR ################################# # eliminate the garbage leak del prof.dispatcher - return retVal def startProfile(filename=PyUtilProfileDefaultFilename, lines=PyUtilProfileDefaultLines, @@ -1524,9 +1519,8 @@ def convertTree(objTree, idList): def r_convertTree(oldTree, newTree, idList): for key in list(oldTree.keys()): - obj = idList.get(key) - if(not obj): + if not obj: continue obj = str(obj)[:100] @@ -1541,10 +1535,10 @@ def pretty_print(tree): def r_pretty_print(tree, num): - num+=1 + num += 1 for name in tree.keys(): - print(" "*num,name) - r_pretty_print(tree[name],num) + print(" " * num, name) + r_pretty_print(tree[name], num) def isDefaultValue(x): @@ -1682,7 +1676,6 @@ def getNumberedTypedString(items, maxLen=5000, numPrefix=''): while n > 0: digits += 1 n //= 10 - digits = digits format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s' first = True s = '' @@ -1706,7 +1699,6 @@ def getNumberedTypedSortedString(items, maxLen=5000, numPrefix=''): while n > 0: digits += 1 n //= 10 - digits = digits format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s' snip = '' strs = [] @@ -1734,7 +1726,6 @@ def printNumberedTyped(items, maxLen=5000): while n > 0: digits += 1 n //= 10 - digits = digits format = '%0' + '%s' % digits + 'i:%s \t%s' for i in range(len(items)): objStr = fastRepr(items[i]) @@ -1749,7 +1740,6 @@ def printNumberedTypesGen(items, maxLen=5000): while n > 0: digits += 1 n //= 10 - digits = digits format = '%0' + '%s' % digits + 'i:%s' for i in range(len(items)): print(format % (i, itype(items[i]))) @@ -1869,7 +1859,7 @@ class SubframeCall: self._taskName = None return task.done def cleanup(self): - if (self._taskName): + if self._taskName: taskMgr.remove(self._taskName) self._taskName = None @@ -1903,7 +1893,6 @@ class PStatScope: def start(self, push = None): if push: self.push(push) - pass self.getCollector().start() def stop(self, pop = False): @@ -1916,7 +1905,6 @@ class PStatScope: if label not in self.collectors: from panda3d.core import PStatCollector self.collectors[label] = PStatCollector(label) - pass # print ' ',self.collectors[label] return self.collectors[label] @@ -1925,7 +1913,6 @@ def pstatcollect(scope, level = None): return f try: - if not (__dev__ or ConfigVariableBool('force-pstatcollect', False)) or \ not scope: return decorator @@ -1937,8 +1924,6 @@ def pstatcollect(scope, level = None): scope.stop(pop = True) return val return wrap - - pass except: pass @@ -2015,7 +2000,6 @@ def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigPara if not dConfigParam: doPrint = True else: - if not isinstance(dConfigParam, (list,tuple)): dConfigParams = (dConfigParam,) else: @@ -2025,7 +2009,6 @@ def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigPara if config.GetBool('want-%s-report' % (param,), 0)] doPrint = bool(dConfigParamList) - pass if not doPrint: return decorator @@ -2035,14 +2018,11 @@ def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigPara prefixes = set([prefix]) else: prefixes = set() - pass for param in dConfigParamList: prefix = config.GetString('prefix-%s-report' % (param,), '') if prefix: prefixes.add(prefix) - pass - pass except NameError as e: return decorator @@ -2119,8 +2099,6 @@ def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigPara __report_indent -= 1 if rVal is not None: print(indent(' -> '+repr(rVal))) - pass - pass return rVal wrap.__name__ = f.__name__ @@ -2180,7 +2158,7 @@ if __debug__: s += '%s, ' % arg for key, value in list(kArgs.items()): s += '%s=%s, ' % (key, value) - if len(args) or len(kArgs): + if len(args) > 0 or len(kArgs) > 0: s = s[:-2] s += ')' if append: @@ -2230,7 +2208,7 @@ def makeFlywheelGen(objects, countList=None, countFunc=None, scale=None): # if scale is provided, all counts are scaled by the scale value and then int()'ed. def flywheel(index2objectAndCount): # generator to produce a sequence whose elements appear a specific number of times - while len(index2objectAndCount): + while len(index2objectAndCount) > 0: keyList = list(index2objectAndCount.keys()) for key in keyList: if index2objectAndCount[key][1] > 0: @@ -2278,12 +2256,12 @@ if __debug__: def quickProfile(name="unnamed"): import pstats def profileDecorator(f): - if(not config.GetBool("use-profiler",0)): + if not config.GetBool("use-profiler", False): return f def _profiled(*args, **kArgs): # must do this in here because we don't have base/simbase # at the time that PythonUtil is loaded - if(not config.GetBool("profile-debug",0)): + if not config.GetBool("profile-debug", False): #dumb timings st=globalClock.getRealTime() f(*args,**kArgs) @@ -2293,10 +2271,10 @@ if __debug__: import profile as prof, pstats #detailed profile, stored in base.stats under ( - if(not hasattr(base,"stats")): - base.stats={} - if(not base.stats.get(name)): - base.stats[name]=[] + if not hasattr(base, "stats"): + base.stats = {} + if not base.stats.get(name): + base.stats[name] = [] prof.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None,"t.prof") s=pstats.Stats("t.prof") @@ -2322,10 +2300,10 @@ def getAnnounceGenerateTime(stat): val=0 stats=stat.stats for i in list(stats.keys()): - if(i[2]=="announceGenerate"): - newVal=stats[i][3] - if(newVal>val): - val=newVal + if i[2] == "announceGenerate": + newVal = stats[i][3] + if newVal > val: + val = newVal return val @@ -2526,10 +2504,10 @@ superLogFile = None def startSuperLog(customFunction = None): global superLogFile - if(not superLogFile): + if not superLogFile: superLogFile = open("c:\\temp\\superLog.txt", "w") def trace_dispatch(a,b,c): - if(b=='call' and a.f_code.co_name != '?' and a.f_code.co_name.find("safeRepr")<0): + if b == 'call' and a.f_code.co_name != '?' and a.f_code.co_name.find("safeRepr") < 0: vars = dict(a.f_locals) if 'self' in vars: del vars['self'] @@ -2553,7 +2531,7 @@ def startSuperLog(customFunction = None): def endSuperLog(): global superLogFile - if(superLogFile): + if superLogFile: sys.settrace(None) superLogFile.close() superLogFile = None diff --git a/direct/src/showbase/RandomNumGen.py b/direct/src/showbase/RandomNumGen.py index df37f1cd17..7fcd732049 100644 --- a/direct/src/showbase/RandomNumGen.py +++ b/direct/src/showbase/RandomNumGen.py @@ -32,11 +32,10 @@ class RandomNumGen: def __rand(self, N): """returns integer in [0..N)""" - """ - # using modulus biases the numbers a little bit - # the bias is worse for larger values of N - return self.__rng.getUint31() % N - """ + + ## using modulus biases the numbers a little bit + ## the bias is worse for larger values of N + #return self.__rng.getUint31() % N # this technique produces an even distribution. # random.py would solve this problem like so: diff --git a/direct/src/showbase/ReferrerSearch.py b/direct/src/showbase/ReferrerSearch.py index 1015c1973b..2b27fdc04d 100755 --- a/direct/src/showbase/ReferrerSearch.py +++ b/direct/src/showbase/ReferrerSearch.py @@ -1,8 +1,11 @@ import inspect import sys import gc -from direct.showbase.PythonUtil import _getSafeReprNotify +from direct.showbase.PythonUtil import _getSafeReprNotify, fastRepr from direct.showbase.Job import Job +from direct.showbase.MessengerGlobal import messenger +from direct.task.TaskManagerGlobal import taskMgr + class ReferrerSearch(Job): def __init__(self, obj, maxRefs = 100): @@ -24,10 +27,8 @@ class ReferrerSearch(Job): self.step(0, [self.obj]) finally: self.obj = None - pass safeReprNotify.setInfo(info) - pass def run(self): safeReprNotify = _getSafeReprNotify() @@ -39,10 +40,8 @@ class ReferrerSearch(Job): self.visited = set() for x in self.stepGenerator(0, [self.obj]): yield None - pass yield Job.Done - pass def finished(self): print('RefPath(%s): Finished ReferrerSearch for %s' %(self._id, fastRepr(self.obj))) @@ -50,7 +49,6 @@ class ReferrerSearch(Job): safeReprNotify = _getSafeReprNotify() safeReprNotify.setInfo(self.info) - pass def __del__(self): print('ReferrerSearch garbage collected') @@ -63,28 +61,27 @@ class ReferrerSearch(Job): def printStatsWhenAble(self): self.shouldPrintStats = True - pass def myrepr(self, referrer, refersTo): pre = '' - if (isinstance(referrer, dict)): + if isinstance(referrer, dict): for k,v in referrer.items(): if v is refersTo: pre = self.truncateAtNewLine(fastRepr(k)) + ']-> ' break - elif (isinstance(referrer, (list, tuple))): + elif isinstance(referrer, (list, tuple)): for x, ref in enumerate(referrer): if ref is refersTo: pre = '%s]-> ' % (x) break - if (isinstance(refersTo, dict)): + if isinstance(refersTo, dict): post = 'dict[' - elif (isinstance(refersTo, list)): + elif isinstance(refersTo, list): post = 'list[' - elif (isinstance(refersTo, tuple)): + elif isinstance(refersTo, tuple): post = 'tuple[' - elif (isinstance(refersTo, set)): + elif isinstance(refersTo, set): post = 'set->' else: post = self.truncateAtNewLine(fastRepr(refersTo)) + "-> " @@ -99,11 +96,11 @@ class ReferrerSearch(Job): at = path[-1] if id(at) in self.visited: - # don't continue down this path - return + # don't continue down this path + return # check for success - if (self.isAtRoot(at, path)): + if self.isAtRoot(at, path): self.found += 1 return @@ -123,17 +120,15 @@ class ReferrerSearch(Job): # sort of global, singleton, or manager object # and as such no further knowledge would be gained from # traversing further up the ref tree. - if (self.isManyRef(at, path, referrers)): + if self.isManyRef(at, path, referrers): return - while(referrers): + while referrers: ref = referrers.pop() - self.depth+=1 + self.depth += 1 for x in self.stepGenerator(depth + 1, path + [ref]): pass - self.depth-=1 - pass - pass + self.depth -= 1 def stepGenerator(self, depth, path): if self.shouldPrintStats: @@ -144,7 +139,7 @@ class ReferrerSearch(Job): at = path[-1] # check for success - if (self.isAtRoot(at, path)): + if self.isAtRoot(at, path): self.found += 1 raise StopIteration @@ -174,27 +169,23 @@ class ReferrerSearch(Job): # sort of global, singleton, or manager object # and as such no further knowledge would be gained from # traversing further up the ref tree. - if (self.isManyRef(at, path, referrers)): + if self.isManyRef(at, path, referrers): raise StopIteration - while(referrers): + while referrers: ref = referrers.pop() - self.depth+=1 + self.depth += 1 for x in self.stepGenerator(depth + 1, path + [ref]): yield None - pass - self.depth-=1 - pass + self.depth -= 1 yield None - pass def printStats(self, path): path = list(reversed(path)) path.insert(0,0) print('RefPath(%s) - Stats - visited(%s) | found(%s) | depth(%s) | CurrentPath(%s)' % \ (self._id, len(self.visited), self.found, self.depth, ''.join(self.myrepr(path[x], path[x+1]) for x in range(len(path) - 1)))) - pass def isAtRoot(self, at, path): # Now we define our 'roots', or places where we will @@ -207,12 +198,9 @@ class ReferrerSearch(Job): path.insert(0,0) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True - - # __builtins__ if at is __builtins__: sys.stdout.write("RefPath(%s): __builtins__-> " % self._id) @@ -220,7 +208,6 @@ class ReferrerSearch(Job): path.insert(0,0) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True @@ -230,7 +217,6 @@ class ReferrerSearch(Job): path = list(reversed(path)) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True @@ -240,7 +226,6 @@ class ReferrerSearch(Job): path = list(reversed(path)) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True @@ -250,7 +235,6 @@ class ReferrerSearch(Job): path = list(reversed(path)) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True @@ -260,7 +244,6 @@ class ReferrerSearch(Job): path = list(reversed(path)) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True @@ -270,7 +253,6 @@ class ReferrerSearch(Job): path = list(reversed(path)) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True @@ -280,7 +262,6 @@ class ReferrerSearch(Job): path = list(reversed(path)) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True @@ -290,10 +271,8 @@ class ReferrerSearch(Job): path = list(reversed(path)) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True - pass return False @@ -306,24 +285,17 @@ class ReferrerSearch(Job): path.insert(0,0) for x in range(len(path) - 1): sys.stdout.write(self.myrepr(path[x], path[x+1])) - pass print("") return True else: sys.stdout.write("RefPath(%s): ManyRefsAllowed(%s)[%s]-> " % (self._id, len(referrers), fastRepr(at, maxLen = 1, strFactor = 30))) print("") - pass - pass return False - pass - -""" -from direct.showbase.ReferrerSearch import ReferrerSearch -door = simbase.air.doFind("DistributedBuildingDoorAI") -class A: pass -door = A() -ReferrerSearch()(door) -reload(ReferrerSearch); from direct.showbase.PythonUtil import ReferrerSearch -""" +#from direct.showbase.ReferrerSearch import ReferrerSearch +#door = simbase.air.doFind("DistributedBuildingDoorAI") +#class A: pass +#door = A() +#ReferrerSearch()(door) +#reload(ReferrerSearch); from direct.showbase.PythonUtil import ReferrerSearch diff --git a/direct/src/showbase/SfxPlayer.py b/direct/src/showbase/SfxPlayer.py index c50c498236..c543b5734b 100644 --- a/direct/src/showbase/SfxPlayer.py +++ b/direct/src/showbase/SfxPlayer.py @@ -6,6 +6,7 @@ __all__ = ['SfxPlayer'] import math from panda3d.core import * + class SfxPlayer: """ Play sound effects, potentially localized. @@ -55,7 +56,7 @@ class SfxPlayer: d = node.getDistance(base.cam) if not cutoff: cutoff = self.cutoffDistance - if d == None or d > cutoff: + if d is None or d > cutoff: volume = 0 else: if SfxPlayer.UseInverseSquare: diff --git a/direct/src/showbase/ShadowDemo.py b/direct/src/showbase/ShadowDemo.py index efcc491e71..0fbe6a3c3c 100755 --- a/direct/src/showbase/ShadowDemo.py +++ b/direct/src/showbase/ShadowDemo.py @@ -13,6 +13,7 @@ __all__ = ['ShadowCaster', 'avatarShadow', 'piratesAvatarShadow', 'arbitraryShad from panda3d.core import * from direct.task import Task +from direct.task.TaskManagerGlobal import taskMgr sc = None @@ -132,7 +133,7 @@ def avatarShadow(): taskMgr.add(shadowCameraRotate, 'shadowCamera') global sc - if sc != None: + if sc is not None: sc.clear() sc = ShadowCaster(lightPath, objectPath, 4, 6) @@ -178,7 +179,7 @@ def arbitraryShadow(node): taskMgr.add(shadowCameraRotate, 'shadowCamera') global sc - if sc != None: + if sc is not None: sc.clear() sc = ShadowCaster(lightPath, objectPath, 100, 100) @@ -216,6 +217,3 @@ def arbitraryShadow(node): ## LerpPosInterval(bs.lightPath, 10.0, Vec3(200, 0, 50)), ##) ##ival.loop() - - - diff --git a/direct/src/showbase/ShowBase.py b/direct/src/showbase/ShowBase.py index c82876d05b..91cf6d111f 100644 --- a/direct/src/showbase/ShowBase.py +++ b/direct/src/showbase/ShowBase.py @@ -43,7 +43,7 @@ from panda3d.direct import storeAccessibilityShortcutKeys, allowAccessibilitySho from . import DConfig # Register the extension methods for NodePath. -from direct.extensions_native import NodePath_extensions +from direct.extensions_native import NodePath_extensions # pylint: disable=unused-import # This needs to be available early for DirectGUI imports import sys @@ -56,6 +56,7 @@ from .BulletinBoardGlobal import bulletinBoard from direct.task.TaskManagerGlobal import taskMgr from .JobManagerGlobal import jobMgr from .EventManagerGlobal import eventMgr +from .PythonUtil import Stack #from PythonUtil import * from direct.interval import IntervalManager from direct.showbase.BufferViewer import BufferViewer @@ -329,7 +330,7 @@ class ShowBase(DirectObject.DirectObject): # Open the default rendering window. if self.windowType != 'none': props = WindowProperties.getDefault() - if (self.config.GetBool('read-raw-mice', 0)): + if self.config.GetBool('read-raw-mice', 0): props.setRawMice(1) self.openDefaultWindow(startDirect = False, props=props) @@ -454,7 +455,6 @@ class ShowBase(DirectObject.DirectObject): builtins.pixel2dp = self.pixel2dp # Now add this instance to the ShowBaseGlobal module scope. - from . import ShowBaseGlobal builtins.run = ShowBaseGlobal.run ShowBaseGlobal.base = self ShowBaseGlobal.__dev__ = self.__dev__ @@ -558,12 +558,12 @@ class ShowBase(DirectObject.DirectObject): add stuff to this. """ if self.config.GetBool('want-env-debug-info', 0): - print("\n\nEnvironment Debug Info {") - print("* model path:") - print(getModelPath()) - #print "* dna path:" - #print getDnaPath() - print("}") + print("\n\nEnvironment Debug Info {") + print("* model path:") + print(getModelPath()) + #print "* dna path:" + #print getDnaPath() + print("}") def destroy(self): """ Call this function to destroy the ShowBase and stop all @@ -1092,10 +1092,10 @@ class ShowBase(DirectObject.DirectObject): Sets up a task that calls python 'sleep' every frame. This is a simple way to reduce the CPU usage (and frame rate) of a panda program. """ - if (self.clientSleep == amount): + if self.clientSleep == amount: return self.clientSleep = amount - if (amount == 0.0): + if amount == 0.0: self.taskMgr.remove('clientSleep') else: # Spawn it after igloop (at the end of each frame) @@ -1427,7 +1427,7 @@ class ShowBase(DirectObject.DirectObject): # Use the existing camera node. cam = useCamera camNode = useCamera.node() - assert(isinstance(camNode, Camera)) + assert isinstance(camNode, Camera) lens = camNode.getLens() cam.reparentTo(self.camera) @@ -1450,7 +1450,7 @@ class ShowBase(DirectObject.DirectObject): camNode.setScene(scene) if mask is not None: - if (isinstance(mask, int)): + if isinstance(mask, int): mask = BitMask32(mask) camNode.setCameraMask(mask) @@ -1508,7 +1508,7 @@ class ShowBase(DirectObject.DirectObject): left, right, bottom, top = coords # Now make a new Camera node. - if (cameraName): + if cameraName: cam2dNode = Camera('cam2d_' + cameraName) else: cam2dNode = Camera('cam2d') @@ -1554,7 +1554,7 @@ class ShowBase(DirectObject.DirectObject): left, right, bottom, top = coords # Now make a new Camera node. - if (cameraName): + if cameraName: cam2dNode = Camera('cam2dp_' + cameraName) else: cam2dNode = Camera('cam2dp') @@ -1706,7 +1706,7 @@ class ShowBase(DirectObject.DirectObject): mb.addButton(KeyboardButton.meta()) mw.node().setModifierButtons(mb) bt = mw.attachNewNode(ButtonThrower("buttons%s" % (i))) - if (i != 0): + if i != 0: bt.node().setPrefix('mousedev%s-' % (i)) mods = ModifierButtons() mods.addButton(KeyboardButton.shift()) @@ -1715,7 +1715,7 @@ class ShowBase(DirectObject.DirectObject): mods.addButton(KeyboardButton.meta()) bt.node().setModifierButtons(mods) buttonThrowers.append(bt) - if (win.hasPointer(i)): + if win.hasPointer(i): pointerWatcherNodes.append(mw.node()) return buttonThrowers, pointerWatcherNodes @@ -1726,8 +1726,8 @@ class ShowBase(DirectObject.DirectObject): the currently-known mouse position. Useful if the mouse pointer is invisible for some reason. """ - mouseViz = render2d.attachNewNode('mouseViz') - lilsmiley = loader.loadModel('lilsmiley') + mouseViz = self.render2d.attachNewNode('mouseViz') + lilsmiley = self.loader.loadModel('lilsmiley') lilsmiley.reparentTo(mouseViz) aspectRatio = self.getAspectRatio() @@ -1903,9 +1903,9 @@ class ShowBase(DirectObject.DirectObject): def updateManagers(self, state): dt = globalClock.getDt() - if (self.particleMgrEnabled == 1): + if self.particleMgrEnabled: self.particleMgr.doParticles(dt) - if (self.physicsMgrEnabled == 1): + if self.physicsMgrEnabled: self.physicsMgr.doPhysics(dt) return Task.cont @@ -1938,7 +1938,7 @@ class ShowBase(DirectObject.DirectObject): # keep a list of sfx manager objects to apply settings to, # since there may be others in addition to the one we create here self.sfxManagerList.append(extraSfxManager) - newSfxManagerIsValid = (extraSfxManager!=None) and extraSfxManager.isValid() + newSfxManagerIsValid = extraSfxManager is not None and extraSfxManager.isValid() self.sfxManagerIsValidList.append(newSfxManagerIsValid) if newSfxManagerIsValid: extraSfxManager.setActive(self.sfxActive) @@ -1982,7 +1982,7 @@ class ShowBase(DirectObject.DirectObject): def SetAllSfxEnables(self, bEnabled): """Calls ``setActive(bEnabled)`` on all valid SFX managers.""" for i in range(len(self.sfxManagerList)): - if (self.sfxManagerIsValidList[i]): + if self.sfxManagerIsValidList[i]: self.sfxManagerList[i].setActive(bEnabled) def enableSoundEffects(self, bEnableSoundEffects): @@ -1990,9 +1990,9 @@ class ShowBase(DirectObject.DirectObject): Enables or disables SFX managers. """ # don't setActive(1) if no audiofocus - if self.AppHasAudioFocus or (bEnableSoundEffects==0): + if self.AppHasAudioFocus or not bEnableSoundEffects: self.SetAllSfxEnables(bEnableSoundEffects) - self.sfxActive=bEnableSoundEffects + self.sfxActive = bEnableSoundEffects if bEnableSoundEffects: self.notify.debug("Enabling sound effects") else: @@ -2101,7 +2101,7 @@ class ShowBase(DirectObject.DirectObject): # run the collision traversal if we have a # CollisionTraverser set. if self.shadowTrav: - self.shadowTrav.traverse(self.render) + self.shadowTrav.traverse(self.render) return Task.cont def __collisionLoop(self, state): @@ -2112,7 +2112,7 @@ class ShowBase(DirectObject.DirectObject): if self.appTrav: self.appTrav.traverse(self.render) if self.shadowTrav: - self.shadowTrav.traverse(self.render) + self.shadowTrav.traverse(self.render) messenger.send("collisionLoopFinished") return Task.cont @@ -2560,11 +2560,11 @@ class ShowBase(DirectObject.DirectObject): self.oobe2cam = self.oobeTrackball.attachNewNode(Transform2SG('oobe2cam')) self.oobe2cam.node().setNode(self.oobeCameraTrackball.node()) - self.oobeVis = loader.loadModel('models/misc/camera', okMissing = True) + self.oobeVis = base.loader.loadModel('models/misc/camera', okMissing = True) if not self.oobeVis: # Sometimes we have default-model-extension set to # egg, but the file might be a bam file. - self.oobeVis = loader.loadModel('models/misc/camera.bam', okMissing = True) + self.oobeVis = base.loader.loadModel('models/misc/camera.bam', okMissing = True) if not self.oobeVis: self.oobeVis = NodePath('oobeVis') self.oobeVis.node().setFinal(1) @@ -2600,9 +2600,9 @@ class ShowBase(DirectObject.DirectObject): # self.camNode.setLens(self.camLens) self.oobeCamera.reparentTo(self.hidden) self.oobeMode = 0 - bboard.post('oobeEnabled', False) + self.bboard.post('oobeEnabled', False) else: - bboard.post('oobeEnabled', True) + self.bboard.post('oobeEnabled', True) try: cameraParent = localAvatar except: @@ -3290,7 +3290,7 @@ class ShowBase(DirectObject.DirectObject): :rtype: panda3d.core.NodePath """ - return loader.loadModel("models/misc/xyzAxis.bam") + return self.loader.loadModel("models/misc/xyzAxis.bam") def __doStartDirect(self): if self.__directStarted: @@ -3306,7 +3306,7 @@ class ShowBase(DirectObject.DirectObject): # Set fWantTk to 0 to avoid starting Tk with this call self.startDirect(fWantDirect = fDirect, fWantTk = fTk, fWantWx = fWx) - def run(self): + def run(self): # pylint: disable=method-hidden """This method runs the :class:`~direct.task.Task.TaskManager` when ``self.appRunner is None``, which is to say, when we are not running from within a p3d file. When we *are* within a p3d diff --git a/direct/src/showbase/ShowBaseGlobal.py b/direct/src/showbase/ShowBaseGlobal.py index d4a1a09138..a6bf22c113 100644 --- a/direct/src/showbase/ShowBaseGlobal.py +++ b/direct/src/showbase/ShowBaseGlobal.py @@ -13,8 +13,8 @@ adds itself to this module's scope when instantiated.""" __all__ = [] -from .ShowBase import ShowBase, WindowControls -from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify +from .ShowBase import ShowBase, WindowControls # pylint: disable=unused-import +from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify # pylint: disable=unused-import from panda3d.core import VirtualFileSystem, Notify, ClockObject, PandaSystem from panda3d.core import ConfigPageManager, ConfigVariableManager from panda3d.core import NodePath, PGTop diff --git a/direct/src/showbase/TaskThreaded.py b/direct/src/showbase/TaskThreaded.py index a6634cd751..75a52b7ad5 100755 --- a/direct/src/showbase/TaskThreaded.py +++ b/direct/src/showbase/TaskThreaded.py @@ -4,8 +4,9 @@ __all__ = ['TaskThreaded', 'TaskThread'] from direct.directnotify.DirectNotifyGlobal import directNotify from direct.task import Task +from direct.task.TaskManagerGlobal import taskMgr -from .PythonUtil import SerialNumGen +from .PythonUtil import SerialNumGen, Functor class TaskThreaded: @@ -19,7 +20,7 @@ class TaskThreaded: def __init__(self, name, threaded=True, timeslice=None, callback=None): # timeslice is how long this thread should take every frame. self.__name = name - self.__threaded=threaded + self.__threaded = threaded if timeslice is None: timeslice = .01 self.__timeslice = timeslice diff --git a/direct/src/showbase/ThreeUpShow.py b/direct/src/showbase/ThreeUpShow.py index 7e042c7f39..4e3a1fb3ee 100644 --- a/direct/src/showbase/ThreeUpShow.py +++ b/direct/src/showbase/ThreeUpShow.py @@ -3,23 +3,22 @@ different parts of the window.""" __all__ = ['ThreeUpShow'] +from .ShowBase import ShowBase -from . import ShowBase -class ThreeUpShow(ShowBase.ShowBase): +class ThreeUpShow(ShowBase): def __init__(self): - ShowBase.ShowBase.__init__(self) + ShowBase.__init__(self) def makeCamera(self, win, sort = 0, scene = None, displayRegion = (0, 1, 0, 1), stereo = None, aspectRatio = None, clearDepth = 0, clearColor = None, lens = None, camName = 'cam', mask = None, useCamera = None): - self.camRS=ShowBase.ShowBase.makeCamera( + self.camRS = ShowBase.makeCamera( self, win, displayRegion = (.5, 1, 0, 1), aspectRatio=.67, camName='camRS') - self.camLL=ShowBase.ShowBase.makeCamera( + self.camLL = ShowBase.makeCamera( self, win, displayRegion = (0, .5, 0, .5), camName='camLL') - self.camUR=ShowBase.ShowBase.makeCamera( + self.camUR = ShowBase.makeCamera( self, win, displayRegion = (0, .5, .5, 1), camName='camUR') return self.camUR - diff --git a/direct/src/showbase/TkGlobal.py b/direct/src/showbase/TkGlobal.py index 8d4f4e3ae1..072a9b65ab 100644 --- a/direct/src/showbase/TkGlobal.py +++ b/direct/src/showbase/TkGlobal.py @@ -1,6 +1,7 @@ """ This module is now vestigial. """ -import sys, Pmw +import sys +import Pmw from tkinter import * @@ -20,7 +21,7 @@ def bordercolors(root, colorName): value40pc = (14 * value) // 10 if value40pc > int(Pmw.Color._MAX_RGB): value40pc = int(Pmw.Color._MAX_RGB) - valueHalfWhite = (int(Pmw.Color._MAX_RGB) + value) // 2; + valueHalfWhite = (int(Pmw.Color._MAX_RGB) + value) // 2 lightRGB.append(max(value40pc, valueHalfWhite)) darkValue = (60 * value) // 100 diff --git a/direct/src/showbase/Transitions.py b/direct/src/showbase/Transitions.py index e67ad68292..8eb2bd7012 100644 --- a/direct/src/showbase/Transitions.py +++ b/direct/src/showbase/Transitions.py @@ -6,14 +6,15 @@ __all__ = ['Transitions'] from panda3d.core import * from direct.showbase import ShowBaseGlobal +from direct.showbase.MessengerGlobal import messenger from direct.gui.DirectGui import DirectFrame from direct.gui import DirectGuiGlobals as DGG from direct.interval.LerpInterval import LerpColorScaleInterval, LerpColorInterval, LerpScaleInterval, LerpPosInterval from direct.interval.MetaInterval import Sequence, Parallel from direct.interval.FunctionInterval import Func -class Transitions: +class Transitions: # These may be reassigned before the fade or iris transitions are # actually invoked to change the models that will be used. IrisModelName = "models/misc/iris" @@ -100,7 +101,7 @@ class Transitions: #self.noTransitions() masad: this creates a one frame pop, is it necessary? self.loadFade() - transitionIval = Sequence(Func(self.fade.reparentTo, aspect2d, DGG.FADE_SORT_INDEX), + transitionIval = Sequence(Func(self.fade.reparentTo, ShowBaseGlobal.aspect2d, DGG.FADE_SORT_INDEX), Func(self.fade.showThrough), # in case aspect2d is hidden for some reason self.lerpFunc(self.fade, t, self.alphaOff, @@ -122,7 +123,7 @@ class Transitions: self.noTransitions() self.loadFade() - transitionIval = Sequence(Func(self.fade.reparentTo, aspect2d, DGG.FADE_SORT_INDEX), + transitionIval = Sequence(Func(self.fade.reparentTo, ShowBaseGlobal.aspect2d, DGG.FADE_SORT_INDEX), Func(self.fade.showThrough), # in case aspect2d is hidden for some reason self.lerpFunc(self.fade, t, self.alphaOn, @@ -147,10 +148,10 @@ class Transitions: # If we're about to fade in from black, go ahead and # preload all the textures etc. base.graphicsEngine.renderFrame() - render.prepareScene(gsg) - render2d.prepareScene(gsg) + base.render.prepareScene(gsg) + base.render2d.prepareScene(gsg) - if (t == 0): + if t == 0: # Fade in immediately with no lerp #print "transitiosn: fadeIn 0.0" self.noTransitions() @@ -177,12 +178,12 @@ class Transitions: fadeIn or call noFade. lerp """ - if (t == 0): + if t == 0: # Fade out immediately with no lerp self.noTransitions() self.loadFade() - self.fade.reparentTo(aspect2d, DGG.FADE_SORT_INDEX) + self.fade.reparentTo(ShowBaseGlobal.aspect2d, DGG.FADE_SORT_INDEX) self.fade.setColor(self.alphaOn) elif ConfigVariableBool('no-loading-screen', False): if finishIval: @@ -215,7 +216,7 @@ class Transitions: self.noTransitions() self.loadFade() - self.fade.reparentTo(aspect2d, DGG.FADE_SORT_INDEX) + self.fade.reparentTo(ShowBaseGlobal.aspect2d, DGG.FADE_SORT_INDEX) self.fade.setColor(self.alphaOn[0], self.alphaOn[1], self.alphaOn[2], @@ -231,7 +232,7 @@ class Transitions: self.noTransitions() self.loadFade() - self.fade.reparentTo(aspect2d, DGG.FADE_SORT_INDEX) + self.fade.reparentTo(ShowBaseGlobal.aspect2d, DGG.FADE_SORT_INDEX) self.fade.setColor(color) def noFade(self): @@ -260,8 +261,8 @@ class Transitions: ################################################## def loadIris(self): - if self.iris == None: - self.iris = loader.loadModel(self.IrisModelName) + if self.iris is None: + self.iris = base.loader.loadModel(self.IrisModelName) self.iris.setPos(0, 0, 0) def irisIn(self, t=0.5, finishIval=None, blendType = 'noBlend'): @@ -273,13 +274,13 @@ class Transitions: """ self.noTransitions() self.loadIris() - if (t == 0): + if t == 0: self.iris.detachNode() fut = AsyncFuture() fut.setResult(None) return fut else: - self.iris.reparentTo(aspect2d, DGG.FADE_SORT_INDEX) + self.iris.reparentTo(ShowBaseGlobal.aspect2d, DGG.FADE_SORT_INDEX) scale = 0.18 * max(base.a2dRight, base.a2dTop) self.transitionIval = Sequence(LerpScaleInterval(self.iris, t, @@ -307,14 +308,14 @@ class Transitions: self.noTransitions() self.loadIris() self.loadFade() # we need this to cover up the hole. - if (t == 0): + if t == 0: self.iris.detachNode() self.fadeOut(0) fut = AsyncFuture() fut.setResult(None) return fut else: - self.iris.reparentTo(aspect2d, DGG.FADE_SORT_INDEX) + self.iris.reparentTo(ShowBaseGlobal.aspect2d, DGG.FADE_SORT_INDEX) scale = 0.18 * max(base.a2dRight, base.a2dTop) self.transitionIval = Sequence(LerpScaleInterval(self.iris, t, @@ -340,7 +341,7 @@ class Transitions: if self.transitionIval: self.transitionIval.pause() self.transitionIval = None - if self.iris != None: + if self.iris is not None: self.iris.detachNode() # Actually we need to remove the fade too, # because the iris effect uses it. @@ -381,8 +382,8 @@ class Transitions: # TODO: This model isn't available everywhere. We should # pass it in as a parameter. - button = loader.loadModel('models/gui/toplevel_gui', - okMissing = True) + button = base.loader.loadModel('models/gui/toplevel_gui', + okMissing = True) barImage = None if button: @@ -422,7 +423,7 @@ class Transitions: # masad: always place these at the bottom of render self.letterboxTop.setBin('sorted',0) self.letterboxBottom.setBin('sorted',0) - self.letterbox.reparentTo(render2d, -1) + self.letterbox.reparentTo(ShowBaseGlobal.render2d, -1) self.letterboxOff(0) def noLetterbox(self): @@ -450,7 +451,7 @@ class Transitions: self.noLetterbox() self.loadLetterbox() self.letterbox.unstash() - if (t == 0): + if t == 0: self.letterboxBottom.setPos(0, 0, -1) self.letterboxTop.setPos(0, 0, 0.8) fut = AsyncFuture() @@ -487,7 +488,7 @@ class Transitions: self.noLetterbox() self.loadLetterbox() self.letterbox.unstash() - if (t == 0): + if t == 0: self.letterbox.stash() fut = AsyncFuture() fut.setResult(None) @@ -508,11 +509,11 @@ class Transitions: blendType=blendType ), ), - Func(self.letterbox.stash), - Func(self.__finishLetterbox), - Func(messenger.send,'letterboxOff'), - name = self.letterboxTaskName, - ) + Func(self.letterbox.stash), + Func(self.__finishLetterbox), + Func(messenger.send, 'letterboxOff'), + name = self.letterboxTaskName, + ) if finishIval: self.letterboxIval.append(finishIval) self.letterboxIval.start() diff --git a/direct/src/showutil/BuildGeometry.py b/direct/src/showutil/BuildGeometry.py index c01c33c42b..fad774a3bc 100644 --- a/direct/src/showutil/BuildGeometry.py +++ b/direct/src/showutil/BuildGeometry.py @@ -1,16 +1,20 @@ from panda3d.core import * from math import * + GEO_ID = 0 + def circleX(angle, radius, centerX, centerY): x = radius * cos(angle) + centerX return x + def circleY(angle, radius, centerX, centerY): y = radius * sin(angle) + centerY return y + def getCirclePoints(segCount, centerX, centerY, radius, wideX= 1.0, wideY = 1.0): returnShape = [] for seg in range(0, segCount): @@ -18,15 +22,15 @@ def getCirclePoints(segCount, centerX, centerY, radius, wideX= 1.0, wideY = 1.0) coordY = wideY * (circleY(((pi * 2.0) * float(float(seg) / float(segCount))), radius, centerX, centerY)) returnShape.append((coordX, coordY, 1)) - coordX = wideX * (circleX(((pi * 2.0) * float(0 / segCount)), radius, centerX, centerY)) - coordY = wideY * (circleY(((pi * 2.0) * float(0 / segCount)), radius, centerX, centerY)) + coordX = wideX * (circleX(((pi * 2.0) * float(0 / segCount)), radius, centerX, centerY)) + coordY = wideY * (circleY(((pi * 2.0) * float(0 / segCount)), radius, centerX, centerY)) returnShape.append((coordX, coordY, 1)) return returnShape def addCircle(attachNode, vertexCount, radius, color = Vec4(1.0, 1.0, 1.0, 1.0), centerColor = None, layer = 0): - targetGN=GeomNode("target Circle") - if centerColor == None: + targetGN = GeomNode("target Circle") + if centerColor is None: centerColor = color zFloat = 0.025 targetCircleShape = getCirclePoints(5 + (vertexCount), 0.0, 0.0, radius) @@ -42,7 +46,7 @@ def addCircle(attachNode, vertexCount, radius, color = Vec4(1.0, 1.0, 1.0, 1.0), targetCircleColorWriter.addData4f(color[0], color[1], color[2], color[3]) #targetCircleColorWriter.addData4f(1.0, 1.0, 1.0, 1.0) - targetTris=GeomTrifans(Geom.UHStatic) # triangle object + targetTris = GeomTrifans(Geom.UHStatic) # triangle object sizeTarget = len(targetCircleShape) targetTris.addVertex(0) @@ -51,21 +55,23 @@ def addCircle(attachNode, vertexCount, radius, color = Vec4(1.0, 1.0, 1.0, 1.0), targetTris.addVertex(1) targetTris.closePrimitive() - targetGeom=Geom(targetCircleVertexData) + targetGeom = Geom(targetCircleVertexData) targetGeom.addPrimitive(targetTris) attachNode.addGeom(targetGeom) return targetGeom + def addCircleGeom(rootNode, vertexCount, radius, color = Vec4(1.0, 1.0, 1.0, 1.0), centerColor = None, layer = 0): - global GEO_ID - GN=GeomNode("Circle %s" % (GEO_ID)) - GEO_ID += 1 - NodePathGeom = rootNode.attachNewNode(GN) - geo = addCircle(GN, vertexCount, radius, color, centerColor,layer) - return NodePathGeom, GN, geo + global GEO_ID + GN=GeomNode("Circle %s" % (GEO_ID)) + GEO_ID += 1 + NodePathGeom = rootNode.attachNewNode(GN) + geo = addCircle(GN, vertexCount, radius, color, centerColor,layer) + return NodePathGeom, GN, geo + def addSquare(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = 0): - targetGN=GeomNode("Square Geom") + targetGN = GeomNode("Square Geom") sX = sizeX / 2.0 sY = sizeY / 2.0 @@ -102,7 +108,7 @@ def addSquare(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) boxTextureWriter.addData2f(1.0, 1.0) - boxTris=GeomTristrips(Geom.UHStatic) # trianglestrip obejcet + boxTris = GeomTristrips(Geom.UHStatic) # trianglestrip obejcet boxTris.addVertex(1) boxTris.addVertex(2) @@ -110,23 +116,25 @@ def addSquare(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer boxTris.addVertex(3) boxTris.closePrimitive() - boxGeom=Geom(boxVertexData) + boxGeom = Geom(boxVertexData) boxGeom.addPrimitive(boxTris) attachNode.addGeom(boxGeom) return boxGeom + def addSquareGeom(rootNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = 0): - global GEO_ID - GN=GeomNode("Square %s" % (GEO_ID)) - GEO_ID += 1 - NodePathGeom = rootNode.attachNewNode(GN) - geo = addSquare(GN, sizeX, sizeY, color, layer) - return NodePathGeom, GN, geo + global GEO_ID + GN = GeomNode("Square %s" % (GEO_ID)) + GEO_ID += 1 + NodePathGeom = rootNode.attachNewNode(GN) + geo = addSquare(GN, sizeX, sizeY, color, layer) + return NodePathGeom, GN, geo + def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), darken = 0): - targetGN=GeomNode("Box Geom") + targetGN = GeomNode("Box Geom") sX = sizeX / 2.0 sY = sizeY / 2.0 sZ = sizeZ / 2.0 @@ -257,7 +265,7 @@ def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), da boxColorWriter.addData4f(color2[0], color2[1], color2[2], color2[3]) - boxTris=GeomTristrips(Geom.UHStatic) # trianglestrip obejcet + boxTris = GeomTristrips(Geom.UHStatic) # trianglestrip obejcet boxTris.addVertex(0)#(1) boxTris.addVertex(1)#(2) boxTris.addVertex(3)#(0) @@ -294,24 +302,25 @@ def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), da boxTris.addVertex(23) boxTris.closePrimitive() - boxGeom=Geom(boxVertexData) + boxGeom = Geom(boxVertexData) boxGeom.addPrimitive(boxTris) attachNode.addGeom(boxGeom) return boxGeom + def addBoxGeom(rootNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), darken = 0): - global GEO_ID - GN=GeomNode("Box %s" % (GEO_ID)) - GEO_ID += 1 - nodePathGeom = rootNode.attachNewNode(GN) - geo = addBox(GN, sizeX, sizeY, sizeZ, color, darken) - return nodePathGeom, GN, geo + global GEO_ID + GN = GeomNode("Box %s" % (GEO_ID)) + GEO_ID += 1 + nodePathGeom = rootNode.attachNewNode(GN) + geo = addBox(GN, sizeX, sizeY, sizeZ, color, darken) + return nodePathGeom, GN, geo def addArrow(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = 0): - targetGN=GeomNode("Arrow Geom") + targetGN = GeomNode("Arrow Geom") sX = sizeX / 2.0 sY = sizeY / 2.0 @@ -343,7 +352,7 @@ def addArrow(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) - boxTris=GeomTristrips(Geom.UHStatic) # trianglestrip obejcet + boxTris = GeomTristrips(Geom.UHStatic) # trianglestrip obejcet boxTris.addVertex(1) boxTris.addVertex(2) @@ -369,17 +378,18 @@ def addArrow(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = boxTris.closePrimitive() - boxGeom=Geom(boxVertexData) + boxGeom = Geom(boxVertexData) boxGeom.addPrimitive(boxTris) attachNode.addGeom(boxGeom) return boxGeom + def addArrowGeom(rootNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = 0): - global GEO_ID - GN=GeomNode("Arrow %s" % (GEO_ID)) - GEO_ID += 1 - NodePathGeom = rootNode.attachNewNode(GN) - geo = addArrow(GN, sizeX, sizeY, color, layer) - return NodePathGeom, GN, geo + global GEO_ID + GN = GeomNode("Arrow %s" % (GEO_ID)) + GEO_ID += 1 + NodePathGeom = rootNode.attachNewNode(GN) + geo = addArrow(GN, sizeX, sizeY, color, layer) + return NodePathGeom, GN, geo diff --git a/direct/src/showutil/Effects.py b/direct/src/showutil/Effects.py index d98223711b..137832ebb5 100644 --- a/direct/src/showutil/Effects.py +++ b/direct/src/showutil/Effects.py @@ -130,5 +130,3 @@ def createBounce(nodeObj, numBounces, startValues, totalTime, amplitude, currTime = bounceTime return result - - diff --git a/direct/src/showutil/Rope.py b/direct/src/showutil/Rope.py index 1c3af011d6..85541a0eef 100644 --- a/direct/src/showutil/Rope.py +++ b/direct/src/showutil/Rope.py @@ -107,7 +107,7 @@ class Rope(NodePath): thickness = v.get('thickness', defaultThickness) if isinstance(point, tuple): - if (len(point) >= 4): + if len(point) >= 4: self.curve.setVertex(i, VBase4(point[0], point[1], point[2], point[3])) else: self.curve.setVertex(i, VBase3(point[0], point[1], point[2])) @@ -123,7 +123,7 @@ class Rope(NodePath): if useVertexThickness: self.curve.setExtendedVertex(i, vtd, thickness) - if self.knots != None: + if self.knots is not None: for i in range(len(self.knots)): self.curve.setKnot(i, self.knots[i]) diff --git a/direct/src/showutil/TexMemWatcher.py b/direct/src/showutil/TexMemWatcher.py index 99d99f07ee..638101ead2 100644 --- a/direct/src/showutil/TexMemWatcher.py +++ b/direct/src/showutil/TexMemWatcher.py @@ -1,8 +1,10 @@ from panda3d.core import * from direct.showbase.DirectObject import DirectObject +from direct.task.TaskManagerGlobal import taskMgr import math import copy + class TexMemWatcher(DirectObject): """ This class creates a separate graphics window that displays an @@ -479,7 +481,7 @@ class TexMemWatcher(DirectObject): tnp = self.isolate.attachNewNode(tn) scale = 30.0 / wy tnp.setScale(scale * wy / wx, scale, scale) - tnp.setPos(render2d, 0, 0, -1 - tn.getBottom() * scale) + tnp.setPos(base.render2d, 0, 0, -1 - tn.getBottom() * scale) labelTop = tn.getHeight() * scale diff --git a/direct/src/showutil/TexViewer.py b/direct/src/showutil/TexViewer.py index 46d8c1bb43..c8bbd76b18 100644 --- a/direct/src/showutil/TexViewer.py +++ b/direct/src/showutil/TexViewer.py @@ -1,5 +1,7 @@ from panda3d.core import * from direct.showbase.DirectObject import DirectObject +from direct.showbase import ShowBaseGlobal + class TexViewer(DirectObject): """ A simple class to pop up a card onscreen to see the contents @@ -9,7 +11,7 @@ class TexViewer(DirectObject): self.tex = tex self.cleanedUp = False - self.root = aspect2d.attachNewNode('texViewer') + self.root = ShowBaseGlobal.aspect2d.attachNewNode('texViewer') self.root.setBin('gui-popup', 10000) cards = self.root.attachNewNode('cards') diff --git a/direct/src/task/FrameProfiler.py b/direct/src/task/FrameProfiler.py index 4207937d1c..6520db26bf 100755 --- a/direct/src/task/FrameProfiler.py +++ b/direct/src/task/FrameProfiler.py @@ -1,7 +1,11 @@ +from panda3d.core import ConfigVariableBool from direct.directnotify.DirectNotifyGlobal import directNotify from direct.fsm.StatePush import FunctionCall -from direct.showbase.PythonUtil import formatTimeExact, normalDistrib -from direct.task import Task +from direct.showbase.PythonUtil import formatTimeExact, normalDistrib, serialNum +from direct.showbase.PythonUtil import Functor +from .Task import Task +from .TaskManagerGlobal import taskMgr + class FrameProfiler: notify = directNotify.newCategory('FrameProfiler') @@ -15,8 +19,9 @@ class FrameProfiler: def __init__(self): Hour = FrameProfiler.Hour # how long to wait between frame profiles + frequent_profiles = ConfigVariableBool('frequent-frame-profiles', False) self._period = 2 * FrameProfiler.Minute - if config.GetBool('frequent-frame-profiles', 0): + if frequent_profiles: self._period = 1 * FrameProfiler.Minute # used to prevent profile from being taken exactly every 'period' seconds self._jitterMagnitude = self._period * .75 @@ -28,7 +33,7 @@ class FrameProfiler: 12 * FrameProfiler.Hour, 1 * FrameProfiler.Day, ] # day schedule proceeds as 1, 2, 4, 8 days, etc. - if config.GetBool('frequent-frame-profiles', 0): + if frequent_profiles: self._logSchedule = [ 1 * FrameProfiler.Minute, 4 * FrameProfiler.Minute, 12 * FrameProfiler.Minute, @@ -79,7 +84,7 @@ class FrameProfiler: def _scheduleNextProfileDoLater(self, task): self._scheduleNextProfile() - return task.done + return Task.done def _scheduleNextProfile(self): self._profileCounter += 1 diff --git a/direct/src/task/MiniTask.py b/direct/src/task/MiniTask.py index ee2f04a1ca..ffd62a9f7a 100755 --- a/direct/src/task/MiniTask.py +++ b/direct/src/task/MiniTask.py @@ -7,6 +7,7 @@ Panda has been fully downloaded. """ __all__ = ['MiniTask', 'MiniTaskManager'] + class MiniTask: done = 0 cont = 1 @@ -14,6 +15,7 @@ class MiniTask: def __init__(self, callback): self.__call__ = callback + class MiniTaskManager: def __init__(self): @@ -36,12 +38,12 @@ class MiniTaskManager: def step(self): i = 0 - while (i < len(self.taskList)): + while i < len(self.taskList): task = self.taskList[i] ret = task(task) # See if the task is done - if (ret == task.cont): + if ret == task.cont: # Leave it for next frame, its not done yet pass @@ -65,4 +67,3 @@ class MiniTaskManager: def stop(self): # Set a flag so we will stop before beginning next frame self.running = 0 - diff --git a/direct/src/task/Task.py b/direct/src/task/Task.py index 8f6bbd4766..951bb13173 100644 --- a/direct/src/task/Task.py +++ b/direct/src/task/Task.py @@ -11,7 +11,6 @@ __all__ = ['Task', 'TaskManager', 'sequence', 'loop', 'pause'] from direct.directnotify.DirectNotifyGlobal import * -from direct.showbase import ExceptionVarDump from direct.showbase.PythonUtil import * from direct.showbase.MessengerGlobal import messenger import types @@ -197,7 +196,7 @@ class TaskManager: so in most cases there is no need to check this method first. """ - return (self.mgr.findTaskChain(chainName) != None) + return self.mgr.findTaskChain(chainName) is not None def setupTaskChain(self, chainName, numThreads = None, tickClock = None, threadPriority = None, frameBudget = None, @@ -396,8 +395,8 @@ class TaskManager: if isinstance(funcOrTask, AsyncTask): task = funcOrTask elif hasattr(funcOrTask, '__call__') or \ - hasattr(funcOrTask, 'cr_await') or \ - type(funcOrTask) == types.GeneratorType: + hasattr(funcOrTask, 'cr_await') or \ + isinstance(funcOrTask, types.GeneratorType): # It's a function, coroutine, or something emulating a coroutine. task = PythonTask(funcOrTask) if name is None: @@ -512,7 +511,7 @@ class TaskManager: self.globalClock.setRealTime(t) messenger.send("resetClock", [timeDelta]) - if self.resumeFunc != None: + if self.resumeFunc is not None: self.resumeFunc() if self.stepping: @@ -521,7 +520,7 @@ class TaskManager: self.running = True while self.running: try: - if len(self._frameProfileQueue): + if len(self._frameProfileQueue) > 0: numFrames, session, callback = self._frameProfileQueue.pop(0) def _profileFunc(numFrames=numFrames): self._doProfiledFrames(numFrames) @@ -555,8 +554,9 @@ class TaskManager: self.stop() print_exc_plus() else: - if (ExceptionVarDump.wantStackDumpLog and - ExceptionVarDump.dumpOnExceptionInit): + from direct.showbase import ExceptionVarDump + if ExceptionVarDump.wantStackDumpLog and \ + ExceptionVarDump.dumpOnExceptionInit: ExceptionVarDump._varDump__print(e) raise except: @@ -588,11 +588,11 @@ class TaskManager: return 0 method = task.getFunction() - if (type(method) == types.MethodType): + if isinstance(method, types.MethodType): function = method.__func__ else: function = method - if (function == oldMethod): + if function == oldMethod: newMethod = types.MethodType(newFunction, method.__self__) task.setFunction(newMethod) # Found a match @@ -632,8 +632,7 @@ class TaskManager: def _doProfiledFrames(self, numFrames): for i in range(numFrames): - result = self.step() - return result + self.step() def getProfileFrames(self): return self._profileFrames.get() @@ -753,18 +752,16 @@ class TaskManager: def doYield(self, frameStartTime, nextScheduledTaskTime): pass - """ - def doYieldExample(self, frameStartTime, nextScheduledTaskTime): - minFinTime = frameStartTime + self.MaxEpochSpeed - if nextScheduledTaskTime > 0 and nextScheduledTaskTime < minFinTime: - print ' Adjusting Time' - minFinTime = nextScheduledTaskTime - delta = minFinTime - self.globalClock.getRealTime() - while(delta > 0.002): - print ' sleep %s'% (delta) - time.sleep(delta) - delta = minFinTime - self.globalClock.getRealTime() - """ + #def doYieldExample(self, frameStartTime, nextScheduledTaskTime): + # minFinTime = frameStartTime + self.MaxEpochSpeed + # if nextScheduledTaskTime > 0 and nextScheduledTaskTime < minFinTime: + # print(' Adjusting Time') + # minFinTime = nextScheduledTaskTime + # delta = minFinTime - self.globalClock.getRealTime() + # while delta > 0.002: + # print ' sleep %s'% (delta) + # time.sleep(delta) + # delta = minFinTime - self.globalClock.getRealTime() if __debug__: # to catch memory leaks during the tests at the bottom of the file @@ -1228,50 +1225,50 @@ class TaskManager: _testTaskObjRemove = None tm._checkMemLeaks() - """ # this test fails, and it's not clear what the correct behavior should be. # sort passed to Task.__init__ is always overridden by taskMgr.add() # even if no sort is specified, and calling Task.setSort() has no # effect on the taskMgr's behavior. # set/get Task sort - l = [] - def _testTaskObjSort(arg, task, l=l): - l.append(arg) - return task.cont - t1 = Task(_testTaskObjSort, sort=1) - t2 = Task(_testTaskObjSort, sort=2) - tm.add(t1, 'testTaskObjSort1', extraArgs=['a',], appendTask=True) - tm.add(t2, 'testTaskObjSort2', extraArgs=['b',], appendTask=True) - tm.step() - assert len(l) == 2 - assert l == ['a', 'b'] - assert t1.getSort() == 1 - assert t2.getSort() == 2 - t1.setSort(3) - assert t1.getSort() == 3 - tm.step() - assert len(l) == 4 - assert l == ['a', 'b', 'b', 'a',] - t1.remove() - t2.remove() - tm.step() - assert len(l) == 4 - del t1 - del t2 - _testTaskObjSort = None - tm._checkMemLeaks() - """ + #l = [] + #def _testTaskObjSort(arg, task, l=l): + # l.append(arg) + # return task.cont + #t1 = Task(_testTaskObjSort, sort=1) + #t2 = Task(_testTaskObjSort, sort=2) + #tm.add(t1, 'testTaskObjSort1', extraArgs=['a',], appendTask=True) + #tm.add(t2, 'testTaskObjSort2', extraArgs=['b',], appendTask=True) + #tm.step() + #assert len(l) == 2 + #assert l == ['a', 'b'] + #assert t1.getSort() == 1 + #assert t2.getSort() == 2 + #t1.setSort(3) + #assert t1.getSort() == 3 + #tm.step() + #assert len(l) == 4 + #assert l == ['a', 'b', 'b', 'a',] + #t1.remove() + #t2.remove() + #tm.step() + #assert len(l) == 4 + #del t1 + #del t2 + #_testTaskObjSort = None + #tm._checkMemLeaks() del l tm.destroy() del tm + if __debug__: def checkLeak(): import sys import gc gc.enable() from direct.showbase.DirectObject import DirectObject + from direct.task.TaskManagerGlobal import taskMgr class TestClass(DirectObject): def doTask(self, task): return task.done diff --git a/direct/src/task/TaskProfiler.py b/direct/src/task/TaskProfiler.py index e099f82905..4417e3b287 100755 --- a/direct/src/task/TaskProfiler.py +++ b/direct/src/task/TaskProfiler.py @@ -1,32 +1,40 @@ +from panda3d.core import ConfigVariableInt, ConfigVariableDouble from direct.directnotify.DirectNotifyGlobal import directNotify from direct.fsm.StatePush import FunctionCall from direct.showbase.PythonUtil import Averager +from .TaskManagerGlobal import taskMgr + class TaskTracker: # call it TaskProfiler to avoid confusion for the user notify = directNotify.newCategory("TaskProfiler") MinSamples = None SpikeThreshold = None + def __init__(self, namePrefix): self._namePrefix = namePrefix self._durationAverager = Averager('%s-durationAverager' % namePrefix) self._avgSession = None if TaskTracker.MinSamples is None: # number of samples required before spikes start getting identified - TaskTracker.MinSamples = config.GetInt('profile-task-spike-min-samples', 30) + TaskTracker.MinSamples = ConfigVariableInt('profile-task-spike-min-samples', 30).value # defines spike as longer than this multiple of avg task duration TaskTracker.SpikeThreshold = TaskProfiler.GetDefaultSpikeThreshold() + def destroy(self): self.flush() del self._namePrefix del self._durationAverager + def flush(self): self._durationAverager.reset() if self._avgSession: self._avgSession.release() self._avgSession = None + def getNamePrefix(self, namePrefix): return self._namePrefix + def _checkSpike(self, session): duration = session.getDuration() isSpike = False @@ -45,6 +53,7 @@ class TaskTracker: session.getResults(sorts=sorts))) self.notify.info(s) return isSpike + def addProfileSession(self, session): duration = session.getDuration() if duration == 0.: @@ -69,11 +78,14 @@ class TaskTracker: def getAvgDuration(self): return self._durationAverager.getAverage() + def getNumDurationSamples(self): return self._durationAverager.getCount() + def getAvgSession(self): # returns profile session for closest-to-average sample return self._avgSession + def log(self): if self._avgSession: s = 'task CPU profile (%s):\n' % self._namePrefix @@ -84,6 +96,7 @@ class TaskTracker: else: self.notify.info('task CPU profile (%s): no data collected' % self._namePrefix) + class TaskProfiler: # this does intermittent profiling of tasks running on the system # if a task has a spike in execution time, the profile of the spike is logged @@ -107,7 +120,7 @@ class TaskProfiler: @staticmethod def GetDefaultSpikeThreshold(): - return config.GetFloat('profile-task-spike-threshold', 5.) + return ConfigVariableDouble('profile-task-spike-threshold', 5.).value @staticmethod def SetSpikeThreshold(spikeThreshold): @@ -120,7 +133,7 @@ class TaskProfiler: if name: name = name.lower() for namePrefix, tracker in self._namePrefix2tracker.items(): - if (name and (name not in namePrefix.lower())): + if name and name not in namePrefix.lower(): continue tracker.log() @@ -129,7 +142,7 @@ class TaskProfiler: name = name.lower() # flush stored task profiles for namePrefix, tracker in self._namePrefix2tracker.items(): - if (name and (name not in namePrefix.lower())): + if name and name not in namePrefix.lower(): continue tracker.flush() @@ -146,7 +159,7 @@ class TaskProfiler: def _doProfileTasks(self, task=None): # gather data from the previous frame # set up for the next frame - if (self._task is not None) and taskMgr._hasProfiledDesignatedTask(): + if self._task is not None and taskMgr._hasProfiledDesignatedTask(): session = taskMgr._getLastTaskProfileSession() # if we couldn't profile, throw this result out if session.profileSucceeded(): diff --git a/direct/src/task/Timer.py b/direct/src/task/Timer.py index 47d5041de9..0746aff26f 100644 --- a/direct/src/task/Timer.py +++ b/direct/src/task/Timer.py @@ -3,6 +3,8 @@ __all__ = ['Timer'] from . import Task +from .TaskManagerGlobal import taskMgr + class Timer: id = 0 @@ -10,7 +12,7 @@ class Timer: def __init__(self, name=None): self.finalT = 0.0 self.currT = 0.0 - if (name == None): + if name is None: name = 'default-timer-%d' % Timer.id Timer.id += 1 self.name = name @@ -18,7 +20,7 @@ class Timer: self.callback = None def start(self, t, name): - if (self.started): + if self.started: self.stop() self.callback = None self.finalT = t @@ -29,7 +31,7 @@ class Timer: self.started = 1 def startCallback(self, t, callback): - if (self.started): + if self.started: self.stop() self.callback = callback self.finalT = t @@ -39,7 +41,7 @@ class Timer: self.started = 1 def stop(self): - if (not self.started): + if not self.started: return 0.0 taskMgr.remove(self.name + '-run') self.started = 0 @@ -51,7 +53,7 @@ class Timer: self.start(self.finalT - self.currT, self.name) def restart(self): - if (self.callback != None): + if self.callback is not None: self.startCallback(self.finalT, self.callback) else: self.start(self.finalT, self.name) @@ -66,16 +68,17 @@ class Timer: self.finalT = t def getT(self): - return (self.finalT - self.currT) + return self.finalT - self.currT def __timerTask(self, task): t = globalClock.getFrameTime() te = t - self.startT self.currT = te - if (te >= self.finalT): - if (self.callback != None): + if te >= self.finalT: + if self.callback is not None: self.callback() else: + from direct.showbase.MessengerGlobal import messenger messenger.send(self.name) return Task.done return Task.cont diff --git a/direct/src/tkpanels/AnimPanel.py b/direct/src/tkpanels/AnimPanel.py index 27b7f23cfe..16d7a3283f 100644 --- a/direct/src/tkpanels/AnimPanel.py +++ b/direct/src/tkpanels/AnimPanel.py @@ -2,18 +2,18 @@ __all__ = ['AnimPanel', 'ActorControl'] - - ### SEE END OF FILE FOR EXAMPLE USEAGE ### # Import Tkinter, Pmw, and the floater code from this directory tree. +from panda3d.core import Filename, getModelPath from direct.tkwidgets.AppShell import * from direct.showbase.TkGlobal import * -import Pmw, os from direct.task import Task -from panda3d.core import Filename, getModelPath +from direct.task.TaskManagerGlobal import taskMgr from tkinter.simpledialog import askfloat from tkinter.filedialog import askopenfilename +import Pmw +import os FRAMES = 0 @@ -183,7 +183,7 @@ class AnimPanel(AppShell): # add actors and animations, only allowed if a direct # session has been specified since these currently require # interaction with selected objects - if (self.session): + if self.session: menuBar.addmenuitem('File', 'command', 'Set currently selected group of objects as actors to animate.', label = 'Set Actors', @@ -206,27 +206,27 @@ class AnimPanel(AppShell): topAnims = [] if 'neutral' in anims: i = anims.index('neutral') - del(anims[i]) + del anims[i] topAnims.append('neutral') if 'walk' in anims: i = anims.index('walk') - del(anims[i]) + del anims[i] topAnims.append('walk') if 'run' in anims: i = anims.index('run') - del(anims[i]) + del anims[i] topAnims.append('run') anims.sort() anims = topAnims + anims - if (len(anims)== 0): + if len(anims) == 0: # no animations set for this actor, don't # display the control panel continue # currComponents = self.components() -# if ('actorControl%d' % index in currComponents): +# if 'actorControl%d' % index in currComponents: # self.destroycomponent('actorControl%d' % index) # ac = self.component('actorControl%d' % index) -# if (ac == None): +# if ac is None: ac = self.createcomponent( 'actorControl%d' % self.actorControlIndex, (), 'Actor', ActorControl, (self.actorFrame,), @@ -242,7 +242,7 @@ class AnimPanel(AppShell): self.actorFrame.pack(expand = 1, fill = BOTH) def clearActorControls(self): - if (self.actorFrame): + if self.actorFrame: self.actorFrame.forget() self.actorFrame.destroy() self.actorFrame = None @@ -517,7 +517,7 @@ class ActorControl(Pmw.MegaWidget): actor = self['actor'] active = self['active'] self.fps = actor.getFrameRate(active) - if (self.fps == None): + if self.fps is None: # there was probably a problem loading the # active animation, set default anim properties print("unable to get animation fps, zeroing out animation info") @@ -576,7 +576,7 @@ class ActorControl(Pmw.MegaWidget): newOffset = askfloat(parent = self.interior(), title = self['text'], prompt = 'Start offset (seconds):') - if newOffset != None: + if newOffset is not None: self.offset = newOffset self.updateDisplay() @@ -603,7 +603,7 @@ class ActorControl(Pmw.MegaWidget): loopT = self.currT % self.duration self.goToT(loopT) else: - if (self.currT > self.maxSeconds): + if self.currT > self.maxSeconds: # Clear this actor control from play list self['animPanel'].playList.remove(self) else: @@ -616,7 +616,7 @@ class ActorControl(Pmw.MegaWidget): if self.unitsVar.get() == FRAMES: self.frameControl.set(f) else: - self.frameControl.set(f/self.fps) + self.frameControl.set(f / self.fps) def goToT(self, t): if self.unitsVar.get() == FRAMES: diff --git a/direct/src/tkpanels/DirectSessionPanel.py b/direct/src/tkpanels/DirectSessionPanel.py index b40583cda3..4f2865d441 100644 --- a/direct/src/tkpanels/DirectSessionPanel.py +++ b/direct/src/tkpanels/DirectSessionPanel.py @@ -3,24 +3,18 @@ __all__ = ['DirectSessionPanel'] # Import Tkinter, Pmw, and the dial code +from panda3d.core import * from direct.showbase.TkGlobal import * from direct.tkwidgets.AppShell import * -from panda3d.core import * -import Pmw from direct.tkwidgets import Dial from direct.tkwidgets import Floater from direct.tkwidgets import Slider from direct.tkwidgets import VectorWidgets from direct.tkwidgets import SceneGraphExplorer -from .TaskManagerPanel import TaskManagerWidget from direct.tkwidgets import MemoryExplorer +from .TaskManagerPanel import TaskManagerWidget +import Pmw -""" -Possible to add: -messenger.clear? -popup panels -taskMgr page -""" class DirectSessionPanel(AppShell): # Override class variables here @@ -532,7 +526,7 @@ class DirectSessionPanel(AppShell): Label(devicePage, text = 'DEVICES', font=('MSSansSerif', 14, 'bold')).pack(expand = 0) - if base.direct.joybox != None: + if base.direct.joybox is not None: joyboxFrame = Frame(devicePage, borderwidth = 2, relief = 'sunken') Label(joyboxFrame, text = 'Joybox', font=('MSSansSerif', 14, 'bold')).pack(expand = 0) @@ -637,7 +631,7 @@ class DirectSessionPanel(AppShell): # See if node path has already been selected nodePath = self.nodePathDict.get(name, None) # If not, see if listbox evals into a node path - if (nodePath == None): + if nodePath is None: # See if this evaluates into a node path try: nodePath = eval(name) @@ -653,7 +647,7 @@ class DirectSessionPanel(AppShell): listbox = self.nodePathMenu.component('scrolledlist') listbox.setlist(self.nodePathNames) # Did we finally get something? - if (nodePath != None): + if nodePath is not None: # Yes, select it! base.direct.select(nodePath) @@ -687,7 +681,7 @@ class DirectSessionPanel(AppShell): else: # See if node path has already been selected nodePath = self.jbNodePathDict.get(name, None) - if (nodePath == None): + if nodePath is None: # If not, see if listbox evals into a node path try: nodePath = eval(name) @@ -703,9 +697,9 @@ class DirectSessionPanel(AppShell): listbox = self.jbNodePathMenu.component('scrolledlist') listbox.setlist(self.jbNodePathNames) # Did we finally get something? - if (nodePath != None): + if nodePath is not None: # Yes, select it! - if (nodePath == 'No Node Path'): + if nodePath == 'No Node Path': base.direct.joybox.setNodePath(None) else: base.direct.joybox.setNodePath(nodePath) @@ -801,7 +795,7 @@ class DirectSessionPanel(AppShell): # See if light exists self.activeLight = base.direct.lights[name] # If not...create new one - if self.activeLight == None: + if self.activeLight is None: self.activeLight = base.direct.lights.create(name) # Do we have a valid light at this point? if self.activeLight: diff --git a/direct/src/tkpanels/FSMInspector.py b/direct/src/tkpanels/FSMInspector.py index 418bcfb0f6..95bd86333c 100644 --- a/direct/src/tkpanels/FSMInspector.py +++ b/direct/src/tkpanels/FSMInspector.py @@ -106,8 +106,10 @@ __all__ = ['FSMInspector', 'StateInspector'] from direct.tkwidgets.AppShell import * from direct.showbase.TkGlobal import * -import Pmw, math, operator from tkinter.simpledialog import askstring +import Pmw +import math +import operator DELTA = (5.0 / 360.) * 2.0 * math.pi diff --git a/direct/src/tkpanels/Inspector.py b/direct/src/tkpanels/Inspector.py index ddbbe30dc1..0a0dfcde64 100644 --- a/direct/src/tkpanels/Inspector.py +++ b/direct/src/tkpanels/Inspector.py @@ -124,7 +124,7 @@ class Inspector: except: pass if doc: - return (str(object) + '\n' + str(doc)) + return str(object) + '\n' + str(doc) else: return str(object) @@ -319,7 +319,7 @@ class InspectorWindow: # Event Handling def listSelectionChanged(self, event): partNumber = self.selectedIndex() - if partNumber == None: + if partNumber is None: partNumber = 0 string = self.topInspector().stringForPartNumber(partNumber) self.textWidget.component('text').configure(state = 'normal') @@ -355,7 +355,7 @@ class InspectorWindow: # Menu Events def inspect(self): inspector = self.inspectorForSelectedPart() - if inspector == None: + if inspector is None: return InspectorWindow(inspector).open() @@ -366,7 +366,7 @@ class InspectorWindow: def dive(self): inspector = self.inspectorForSelectedPart() - if inspector == None: + if inspector is None: return self.inspectors.append(inspector) self.update() @@ -388,7 +388,7 @@ class InspectorWindow: self.listWidget.component('listbox').focus_set() def showHelp(self): - help = Toplevel(tkroot) + help = Toplevel(base.tkRoot) help.title("Inspector Help") frame = Frame(help) frame.pack() @@ -408,7 +408,7 @@ class InspectorWindow: def inspectorForSelectedPart(self): partNumber = self.selectedIndex() - if partNumber == None: + if partNumber is None: return None part = self.topInspector().partNumber(partNumber) return self.topInspector().inspectorFor(part) @@ -417,7 +417,7 @@ class InspectorWindow: print(event) partNumber = self.selectedIndex() print(partNumber) - if partNumber == None: + if partNumber is None: return part = self.topInspector().partNumber(partNumber) print(part) diff --git a/direct/src/tkpanels/MopathRecorder.py b/direct/src/tkpanels/MopathRecorder.py index 2690556f3b..a3b57052ff 100644 --- a/direct/src/tkpanels/MopathRecorder.py +++ b/direct/src/tkpanels/MopathRecorder.py @@ -12,13 +12,14 @@ from direct.directtools.DirectGlobals import * from direct.directtools.DirectUtil import * from direct.directtools.DirectGeometry import * from direct.directtools.DirectSelection import * -import Pmw, os from direct.tkwidgets import Dial from direct.tkwidgets import Floater from direct.tkwidgets import Slider from direct.tkwidgets import EntryScale from direct.tkwidgets import VectorWidgets from tkinter.filedialog import * +import Pmw +import os PRF_UTILITIES = [ @@ -72,7 +73,7 @@ class MopathRecorder(AppShell, DirectObject): self.tempCS = self.recorderNodePath.attachNewNode( 'mopathRecorderTempCS') # Marker for use in playback - self.playbackMarker = loader.loadModel('models/misc/smiley') + self.playbackMarker = base.loader.loadModel('models/misc/smiley') self.playbackMarker.setName('Playback Marker') self.playbackMarker.reparentTo(self.recorderNodePath) self.playbackMarkerIds = self.getChildIds( @@ -81,7 +82,7 @@ class MopathRecorder(AppShell, DirectObject): # Tangent marker self.tangentGroup = self.playbackMarker.attachNewNode('Tangent Group') self.tangentGroup.hide() - self.tangentMarker = loader.loadModel('models/misc/sphere') + self.tangentMarker = base.loader.loadModel('models/misc/sphere') self.tangentMarker.reparentTo(self.tangentGroup) self.tangentMarker.setScale(0.5) self.tangentMarker.setColor(1, 0, 1, 1) @@ -690,12 +691,12 @@ class MopathRecorder(AppShell, DirectObject): Hook called upon deselection of a node path used to select playback marker if subnode selected """ - if ((nodePath.id() == self.playbackMarker.id()) or - (nodePath.id() == self.tangentMarker.id())): + if nodePath.id() == self.playbackMarker.id() or \ + nodePath.id() == self.tangentMarker.id(): self.tangentGroup.hide() def curveEditTask(self, state): - if self.curveCollection != None: + if self.curveCollection is not None: # Update curve position if self.manipulandumId == self.playbackMarker.id(): # Show playback marker @@ -952,7 +953,7 @@ class MopathRecorder(AppShell, DirectObject): # Clear out old trace, get ready to draw new self.initTrace() # Keyframe mode? - if (self.samplingMode == 'Keyframe'): + if self.samplingMode == 'Keyframe': # Record first point self.lastPos.assign(Point3( self.nodePath.getPos(self.nodePathParent))) @@ -962,8 +963,8 @@ class MopathRecorder(AppShell, DirectObject): self.recordPoint(self.recordStart) # Everything else else: - if ((self.recordingType.get() == 'Refine') or - (self.recordingType.get() == 'Extend')): + if self.recordingType.get() == 'Refine' or \ + self.recordingType.get() == 'Extend': # Turn off looping playback self.loopPlayback = 0 # Update widget to reflect new value @@ -987,8 +988,8 @@ class MopathRecorder(AppShell, DirectObject): if self.samplingMode == 'Continuous': # Kill old task taskMgr.remove(self.name + '-recordTask') - if ((self.recordingType.get() == 'Refine') or - (self.recordingType.get() == 'Extend')): + if self.recordingType.get() == 'Refine' or \ + self.recordingType.get() == 'Extend': # Reparent node path back to parent self.nodePath.wrtReparentTo(self.nodePathParent) # Restore playback Node Path @@ -1000,8 +1001,8 @@ class MopathRecorder(AppShell, DirectObject): self.setSamplingMode('Continuous') self.enableKeyframeButton() # Clean up after refine or extend - if ((self.recordingType.get() == 'Refine') or - (self.recordingType.get() == 'Extend')): + if self.recordingType.get() == 'Refine' or \ + self.recordingType.get() == 'Extend': # Merge prePoints, pointSet, postPoints self.mergePoints() # Clear out pre and post list @@ -1021,8 +1022,7 @@ class MopathRecorder(AppShell, DirectObject): def addKeyframe(self, fToggleRecord = 1): # Make sure we're in a recording mode! - if (fToggleRecord and - (not self.getVariable('Recording', 'Record').get())): + if fToggleRecord and not self.getVariable('Recording', 'Record').get(): # Set sampling mode self.setSamplingMode('Keyframe') # This will automatically add the first point @@ -1055,8 +1055,8 @@ class MopathRecorder(AppShell, DirectObject): def recordPoint(self, time): # Call user define callback before recording point - if (self.getVariable('Recording', 'PRF Active').get() and - (self.preRecordFunc != None)): + if self.getVariable('Recording', 'PRF Active').get() and \ + self.preRecordFunc is not None: self.preRecordFunc() # Get point pos = self.nodePath.getPos(self.nodePathParent) @@ -1064,10 +1064,10 @@ class MopathRecorder(AppShell, DirectObject): qNP = Quat() qNP.setHpr(hpr) # Blend between recordNodePath and self.nodePath - if ((self.recordingType.get() == 'Refine') or - (self.recordingType.get() == 'Extend')): - if ((time < self.controlStart) and - ((self.controlStart - self.recordStart) != 0.0)): + if self.recordingType.get() == 'Refine' or \ + self.recordingType.get() == 'Extend': + if time < self.controlStart and \ + self.controlStart - self.recordStart != 0.0: rPos = self.playbackNodePath.getPos(self.nodePathParent) rHpr = self.playbackNodePath.getHpr(self.nodePathParent) qR = Quat() @@ -1078,9 +1078,9 @@ class MopathRecorder(AppShell, DirectObject): pos = (rPos * (1 - t)) + (pos * t) q = qSlerp(qR, qNP, t) hpr.assign(q.getHpr()) - elif ((self.recordingType.get() == 'Refine') and - (time > self.controlStop) and - ((self.recordStop - self.controlStop) != 0.0)): + elif self.recordingType.get() == 'Refine' and \ + time > self.controlStop and \ + self.recordStop - self.controlStop != 0.0: rPos = self.playbackNodePath.getPos(self.nodePathParent) rHpr = self.playbackNodePath.getHpr(self.nodePathParent) qR = Quat() @@ -1096,7 +1096,7 @@ class MopathRecorder(AppShell, DirectObject): # Add it to the curve fitters self.curveFitter.addXyzHpr(time, pos, hpr) # Update trace now if recording keyframes - if (self.samplingMode == 'Keyframe'): + if self.samplingMode == 'Keyframe': self.trace.reset() for t, p, h in self.pointSet: self.trace.drawTo(p[0], p[1], p[2]) @@ -1104,7 +1104,7 @@ class MopathRecorder(AppShell, DirectObject): def computeCurves(self): # Check to make sure curve fitters have points - if (self.curveFitter.getNumSamples() == 0): + if self.curveFitter.getNumSamples() == 0: print('MopathRecorder.computeCurves: Must define curve first') return # Create curves @@ -1185,7 +1185,7 @@ class MopathRecorder(AppShell, DirectObject): self.addNodePath(nodePath) else: nodePath = self.nodePathDict.get(name, None) - if (nodePath == None): + if nodePath is None: # See if this evaluates into a node path try: nodePath = eval(name) @@ -1208,7 +1208,7 @@ class MopathRecorder(AppShell, DirectObject): self.playbackMarker.show() # Initialize tangent marker position tan = Point3(0) - if self.curveCollection != None: + if self.curveCollection is not None: self.curveCollection.getXyzCurve().getTangent( self.playbackTime, tan) self.tangentMarker.setPos(tan) @@ -1261,17 +1261,17 @@ class MopathRecorder(AppShell, DirectObject): self.loopPlayback = self.getVariable('Playback', 'Loop').get() def playbackGoTo(self, time): - if self.curveCollection == None: + if self.curveCollection is None: return self.playbackTime = CLAMP(time, 0.0, self.maxT) - if self.curveCollection != None: + if self.curveCollection is not None: pos = Point3(0) hpr = Point3(0) self.curveCollection.evaluate(self.playbackTime, pos, hpr) self.playbackNodePath.setPosHpr(self.nodePathParent, pos, hpr) def startPlayback(self): - if self.curveCollection == None: + if self.curveCollection is None: return # Kill any existing tasks self.stopPlayback() @@ -1300,8 +1300,7 @@ class MopathRecorder(AppShell, DirectObject): cTime = state.currentTime + dTime # Stop task if not looping and at end of curve # Or if refining curve and past recordStop - if ((self.recordingType.get() == 'Refine') and - (cTime > self.recordStop)): + if self.recordingType.get() == 'Refine' and cTime > self.recordStop: # Go to recordStop self.getWidget('Playback', 'Time').set(self.recordStop) # Then stop playback @@ -1309,14 +1308,13 @@ class MopathRecorder(AppShell, DirectObject): # Also kill record task self.toggleRecordVar() return Task.done - elif ((self.loopPlayback == 0) and (cTime > self.maxT)): + elif self.loopPlayback == 0 and cTime > self.maxT: # Go to maxT self.getWidget('Playback', 'Time').set(self.maxT) # Then stop playback self.stopPlayback() return Task.done - elif ((self.recordingType.get() == 'Extend') and - (cTime > self.controlStart)): + elif self.recordingType.get() == 'Extend' and cTime > self.controlStart: # Go to final point self.getWidget('Playback', 'Time').set(self.controlStart) # Stop playback @@ -1337,7 +1335,7 @@ class MopathRecorder(AppShell, DirectObject): def jumpToEndOfPlayback(self): self.stopPlayback() - if self.curveCollection != None: + if self.curveCollection is not None: self.getWidget('Playback', 'Time').set(self.maxT) def startStopPlayback(self): @@ -1350,7 +1348,7 @@ class MopathRecorder(AppShell, DirectObject): self.desampleFrequency = frequency def desampleCurve(self): - if (self.curveFitter.getNumSamples() == 0): + if self.curveFitter.getNumSamples() == 0: print('MopathRecorder.desampleCurve: Must define curve first') return # NOTE: This is destructive, points will be deleted from curve fitter @@ -1364,7 +1362,7 @@ class MopathRecorder(AppShell, DirectObject): self.numSamples = int(numSamples) def sampleCurve(self, fCompute = 1): - if self.curveCollection == None: + if self.curveCollection is None: print('MopathRecorder.sampleCurve: Must define curve first') return # Reset curve fitters @@ -1579,7 +1577,7 @@ class MopathRecorder(AppShell, DirectObject): self.fAdjustingValues = 0 def cropCurve(self): - if self.pointSet == None: + if self.pointSet is None: print('Empty Point Set') return # Keep handle on old points @@ -1597,8 +1595,7 @@ class MopathRecorder(AppShell, DirectObject): # Get points within bounds for time, pos, hpr in oldPoints: # Is it within the time? - if ((time > self.cropFrom) and - (time < self.cropTo)): + if time > self.cropFrom and time < self.cropTo: # Add it to the curve fitters t = time - self.cropFrom self.curveFitter.addXyzHpr(t, pos, hpr) @@ -1636,7 +1633,7 @@ class MopathRecorder(AppShell, DirectObject): parent = self.parent) if mopathFilename and mopathFilename != 'None': self.reset() - nodePath = loader.loadModel( + nodePath = base.loader.loadModel( Filename.fromOsSpecific(mopathFilename)) self.curveCollection = ParametricCurveCollection() # MRM: Add error check diff --git a/direct/src/tkpanels/NotifyPanel.py b/direct/src/tkpanels/NotifyPanel.py index f13e7d92c6..459378e13e 100644 --- a/direct/src/tkpanels/NotifyPanel.py +++ b/direct/src/tkpanels/NotifyPanel.py @@ -18,7 +18,7 @@ class NotifyPanel: # To get severity levels from panda3d.core import NSFatal, NSError, NSWarning, NSInfo, NSDebug, NSSpam - if tl == None: + if tl is None: tl = Toplevel() tl.title('Notify Controls') tl.geometry('300x400') @@ -115,7 +115,6 @@ class NotifyPanel: self.categoryList.select_set(0) self.setActivePandaCategory() - def _getPandaCategories(self, category): categories = [category] for i in range(category.getNumChildren()): @@ -129,9 +128,8 @@ class NotifyPanel: return self._getPandaCategories(topCategory) def _getPandaCategoriesAsList(self, pc, list): - import types for item in pc: - if type(item) == list: + if isinstance(item, list): self._getPandaCategoriesAsList(item, list) else: list.append(item) @@ -151,4 +149,3 @@ class NotifyPanel: def setActiveSeverity(self): if self.activeCategory: self.activeCategory.setSeverity(self.severity.get()) - diff --git a/direct/src/tkpanels/ParticlePanel.py b/direct/src/tkpanels/ParticlePanel.py index bd8e35abed..9e084145d6 100644 --- a/direct/src/tkpanels/ParticlePanel.py +++ b/direct/src/tkpanels/ParticlePanel.py @@ -3,6 +3,9 @@ __all__ = ['ParticlePanel'] # Import Tkinter, Pmw, and the floater code from this directory tree. +from panda3d.core import * +from panda3d.physics import * +from panda3d.direct import getParticlePath from direct.tkwidgets.AppShell import * from direct.showbase.TkGlobal import * from direct.tkwidgets import Dial @@ -13,12 +16,10 @@ from direct.tkpanels import Placer from direct.particles import ForceGroup from direct.particles import Particles from direct.particles import ParticleEffect -import Pmw, os from tkinter.filedialog import * from tkinter.simpledialog import askstring -from panda3d.core import * -from panda3d.physics import * -from panda3d.direct import getParticlePath +import Pmw +import os class ParticlePanel(AppShell): @@ -38,7 +39,7 @@ class ParticlePanel(AppShell): self.defineoptions(kw, optiondefs) # Record particle effect - if particleEffect != None: + if particleEffect is not None: self.particleEffect = particleEffect else: # Make sure particles are enabled @@ -297,7 +298,7 @@ class ParticlePanel(AppShell): zSpinPage, 'Z Spin Factory', 'Enable Angular Velocity', ("On: angular velocity is used; " + "Off: final angle is used"), - self.toggleAngularVelocity, 0, side = TOP), + self.toggleAngularVelocity, 0, side = TOP) self.createFloater( zSpinPage, 'Z Spin Factory', 'Angular Velocity', @@ -1103,7 +1104,7 @@ class ParticlePanel(AppShell): def updateLabels(self): self.effectsLabel['text'] = self.particleEffect.getName() self.particlesLabel['text'] = self.particles.getName() - if self.forceGroup != None: + if self.forceGroup is not None: self.forceGroupLabel['text'] = self.forceGroup.getName() else: self.forceGroupLabel['text'] = 'Force Group' @@ -1188,7 +1189,7 @@ class ParticlePanel(AppShell): def selectEffectNamed(self, name): effect = self.effectsDict.get(name, None) - if effect != None: + if effect is not None: self.particleEffect = effect # Default to first particle in particlesDict self.particles = self.particleEffect.getParticlesList()[0] @@ -1211,7 +1212,7 @@ class ParticlePanel(AppShell): def selectParticlesNamed(self, name): particles = self.particleEffect.getParticlesNamed(name) - if particles != None: + if particles is not None: self.particles = particles self.updateInfo() @@ -1223,7 +1224,7 @@ class ParticlePanel(AppShell): def selectForceGroupNamed(self, name): forceGroup = self.particleEffect.getForceGroupNamed(name) - if forceGroup != None: + if forceGroup is not None: self.forceGroup = forceGroup self.updateInfo('Force') @@ -1681,7 +1682,7 @@ class ParticlePanel(AppShell): finalZScale = renderer.getFinalZScale() self.getWidget('Geom Renderer', 'Final Z Scale').set( finalZScale) - if(self.getVariable('Geom Renderer','Color Blend').get() in ['MAdd','MSubtract','MInvSubtract']): + if self.getVariable('Geom Renderer','Color Blend').get() in ['MAdd','MSubtract','MInvSubtract']: self.getWidget('Geom Renderer','Incoming Op.').pack(fill = X) self.getWidget('Geom Renderer','Fbuffer Op.').pack(fill = X) else: @@ -1704,20 +1705,20 @@ class ParticlePanel(AppShell): self.getWidget('Point Renderer', 'End Color').set( [endColor[0], endColor[1], endColor[2], endColor[3]]) blendType = renderer.getBlendType() - if (blendType == PointParticleRenderer.PPONECOLOR): + if blendType == PointParticleRenderer.PPONECOLOR: bType = "PP_ONE_COLOR" - elif (blendType == PointParticleRenderer.PPBLENDLIFE): + elif blendType == PointParticleRenderer.PPBLENDLIFE: bType = "PP_BLEND_LIFE" - elif (blendType == PointParticleRenderer.PPBLENDVEL): + elif blendType == PointParticleRenderer.PPBLENDVEL: bType = "PP_BLEND_VEL" self.getVariable('Point Renderer', 'Blend Type').set(bType) blendMethod = renderer.getBlendMethod() bMethod = "PP_NO_BLEND" - if (blendMethod == BaseParticleRenderer.PPNOBLEND): + if blendMethod == BaseParticleRenderer.PPNOBLEND: bMethod = "PP_NO_BLEND" - elif (blendMethod == BaseParticleRenderer.PPBLENDLINEAR): + elif blendMethod == BaseParticleRenderer.PPBLENDLINEAR: bMethod = "PP_BLEND_LINEAR" - elif (blendMethod == BaseParticleRenderer.PPBLENDCUBIC): + elif blendMethod == BaseParticleRenderer.PPBLENDCUBIC: bMethod = "PP_BLEND_CUBIC" self.getVariable('Point Renderer', 'Blend Method').set(bMethod) @@ -1735,7 +1736,7 @@ class ParticlePanel(AppShell): self.getWidget('Sparkle Renderer', 'Death Radius').set(deathRadius) lifeScale = renderer.getLifeScale() lScale = "SP_NO_SCALE" - if (lifeScale == SparkleParticleRenderer.SPSCALE): + if lifeScale == SparkleParticleRenderer.SPSCALE: lScale = "SP_SCALE" self.getVariable('Sparkle Renderer', 'Life Scale').set(lScale) @@ -1767,15 +1768,15 @@ class ParticlePanel(AppShell): nonanimatedTheta) blendMethod = renderer.getAlphaBlendMethod() bMethod = "PP_NO_BLEND" - if (blendMethod == BaseParticleRenderer.PPNOBLEND): + if blendMethod == BaseParticleRenderer.PPNOBLEND: bMethod = "PP_NO_BLEND" - elif (blendMethod == BaseParticleRenderer.PPBLENDLINEAR): + elif blendMethod == BaseParticleRenderer.PPBLENDLINEAR: bMethod = "PP_BLEND_LINEAR" - elif (blendMethod == BaseParticleRenderer.PPBLENDCUBIC): + elif blendMethod == BaseParticleRenderer.PPBLENDCUBIC: bMethod = "PP_BLEND_CUBIC" self.getVariable('Sprite Renderer', 'Alpha Disable').set( renderer.getAlphaDisable()) - if(self.getVariable('Sprite Renderer','Color Blend').get() in ['MAdd','MSubtract','MInvSubtract']): + if self.getVariable('Sprite Renderer','Color Blend').get() in ['MAdd','MSubtract','MInvSubtract']: self.getWidget('Sprite Renderer','Incoming Op.').pack(fill = X) self.getWidget('Sprite Renderer','Fbuffer Op.').pack(fill = X) else: @@ -1790,8 +1791,8 @@ class ParticlePanel(AppShell): def selectRendererPage(self): type = self.particles.renderer.__class__.__name__ - if(type == 'SpriteParticleRendererExt'): - type = 'SpriteParticleRenderer' + if type == 'SpriteParticleRendererExt': + type = 'SpriteParticleRenderer' self.rendererNotebook.selectpage(type) self.getVariable('Renderer', 'Renderer Type').set(type) @@ -1826,10 +1827,10 @@ class ParticlePanel(AppShell): # Geom # def setRendererGeomNode(self, event): node = None - nodePath = loader.loadModel(self.rendererGeomNode.get()) - if nodePath != None: + nodePath = base.loader.loadModel(self.rendererGeomNode.get()) + if nodePath is not None: node = nodePath.node() - if (node != None): + if node is not None: self.particles.geomReference = self.rendererGeomNode.get() self.particles.renderer.setGeomNode(node) # Point # @@ -1984,7 +1985,7 @@ class ParticlePanel(AppShell): getattr(ColorBlendAttrib, incomingOperandStr), getattr(ColorBlendAttrib, fbufferOperandStr)) - if(blendMethodStr in ['MAdd','MSubtract','MInvSubtract']): + if blendMethodStr in ['MAdd','MSubtract','MInvSubtract']: self.getWidget(rendererName,'Incoming Op.').pack(fill = X) self.getWidget(rendererName,'Fbuffer Op.').pack(fill = X) else: @@ -2064,12 +2065,12 @@ class ParticlePanel(AppShell): else: seg = cim.getSegment(id) - if(ren.__class__.__name__ == 'SpriteParticleRendererExt'): + if ren.__class__.__name__ == 'SpriteParticleRendererExt': parent = self.rendererSpriteSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Constant' self.rendererSegmentWidgetList.append( self.createConstantInterpolationSegmentWidget(parent, segName, seg)) - elif(ren.__class__.__name__ == 'GeomParticleRenderer'): + elif ren.__class__.__name__ == 'GeomParticleRenderer': parent = self.rendererGeomSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Constant' self.rendererSegmentWidgetList.append( @@ -2084,12 +2085,12 @@ class ParticlePanel(AppShell): else: seg = cim.getSegment(id) - if(ren.__class__.__name__ == 'SpriteParticleRendererExt'): + if ren.__class__.__name__ == 'SpriteParticleRendererExt': parent = self.rendererSpriteSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Linear' self.rendererSegmentWidgetList.append( self.createLinearInterpolationSegmentWidget(parent, segName, seg)) - elif(ren.__class__.__name__ == 'GeomParticleRenderer'): + elif ren.__class__.__name__ == 'GeomParticleRenderer': parent = self.rendererGeomSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Linear' self.rendererSegmentWidgetList.append( @@ -2104,12 +2105,12 @@ class ParticlePanel(AppShell): else: seg = cim.getSegment(id) - if(ren.__class__.__name__ == 'SpriteParticleRendererExt'): + if ren.__class__.__name__ == 'SpriteParticleRendererExt': parent = self.rendererSpriteSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Stepwave' self.rendererSegmentWidgetList.append( self.createStepwaveInterpolationSegmentWidget(parent, segName, seg)) - elif(ren.__class__.__name__ == 'GeomParticleRenderer'): + elif ren.__class__.__name__ == 'GeomParticleRenderer': parent = self.rendererGeomSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Stepwave' self.rendererSegmentWidgetList.append( @@ -2124,12 +2125,12 @@ class ParticlePanel(AppShell): else: seg = cim.getSegment(id) - if(ren.__class__.__name__ == 'SpriteParticleRendererExt'): + if ren.__class__.__name__ == 'SpriteParticleRendererExt': parent = self.rendererSpriteSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Sinusoid' self.rendererSegmentWidgetList.append( self.createSinusoidInterpolationSegmentWidget(parent, segName, seg)) - elif(ren.__class__.__name__ == 'GeomParticleRenderer'): + elif ren.__class__.__name__ == 'GeomParticleRenderer': parent = self.rendererGeomSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Sinusoid' self.rendererSegmentWidgetList.append( @@ -2349,18 +2350,17 @@ class ParticlePanel(AppShell): Button(lFrame, text = 'X', foreground = 'Red', font = ('MSSansSerif', 8, 'bold'), command = delete).pack(side = RIGHT, expand = 0) - if(anim == SpriteAnim.STTexture or - anim == SpriteAnim.STFromNode): + if anim == SpriteAnim.STTexture or anim == SpriteAnim.STFromNode: frame.valid = False frame.animSourceType = anim - if(anim == SpriteAnim.STTexture): + if anim == SpriteAnim.STTexture: type = 'Texture' else: type = 'From Node' else: frame.valid = True - if(anim.getSourceType()==SpriteAnim.STTexture): + if anim.getSourceType() == SpriteAnim.STTexture: frame.animSourceType = SpriteAnim.STTexture type = 'Texture' else: @@ -2389,7 +2389,7 @@ class ParticlePanel(AppShell): strVar.set('Base model path: ' + repr(getModelPath().getValue())) def checkForTexture(strVar = strVar): - tex = loader.loadTexture(strVar.get()) + tex = base.loader.loadTexture(strVar.get()) if tex: frame.valid = True else: @@ -2439,7 +2439,7 @@ class ParticlePanel(AppShell): self.widgetDict['Sprite Renderer-'+animName+' Anim Node'] = entry def checkForNode(modelStrVar=mStrVar, nodeStrVar=nStrVar): - mod = loader.loadModel(modelStrVar.get()) + mod = base.loader.loadModel(modelStrVar.get()) if mod: node = mod.find(nodeStrVar.get()) if node: @@ -2463,14 +2463,14 @@ class ParticlePanel(AppShell): ren = self.particles.getRenderer() for widget in self.rendererSpriteAnimationWidgetList: - if(widget): + if widget: widget.pack_forget() widget.destroy() self.rendererSpriteAnimationWidgetList = [] for anim in [ren.getAnim(x) for x in range(ren.getNumAnims())]: - if(anim.getSourceType() == SpriteAnim.STTexture): + if anim.getSourceType() == SpriteAnim.STTexture: w = self.createSpriteAnimationTextureWidget(self.rendererSpriteAnimationFrame, anim, repr(len(self.rendererSpriteAnimationWidgetList))) else: w = self.createSpriteAnimationNodeWidget(self.rendererSpriteAnimationFrame, anim, repr(len(self.rendererSpriteAnimationWidgetList))) @@ -2485,8 +2485,8 @@ class ParticlePanel(AppShell): for x in range(len(self.rendererSpriteAnimationWidgetList)): widget = self.rendererSpriteAnimationWidgetList[x] - if(widget and widget.valid): - if(widget.animSourceType == SpriteAnim.STTexture): + if widget and widget.valid: + if widget.animSourceType == SpriteAnim.STTexture: texSource = self.getVariable('Sprite Renderer', repr(x) + ' Anim Texture').get() ren.addTextureFromFile(texSource) else: @@ -2497,14 +2497,14 @@ class ParticlePanel(AppShell): ## FORCEGROUP COMMANDS ## def updateForceWidgets(self): # Select appropriate notebook page - if self.forceGroup != None: + if self.forceGroup is not None: self.forceGroupNotebook.pack(fill = X) self.forcePageName = (self.particleEffect.getName() + '-' + self.forceGroup.getName()) self.forcePage = self.forcePagesDict.get( self.forcePageName, None) # Page doesn't exist, add it - if self.forcePage == None: + if self.forcePage is None: self.addForceGroupNotebookPage( self.particleEffect, self.forceGroup) self.forceGroupNotebook.selectpage(self.forcePageName) @@ -2529,7 +2529,7 @@ class ParticlePanel(AppShell): self.addForce(LinearUserDefinedForce()) def addForce(self, f): - if self.forceGroup == None: + if self.forceGroup is None: self.createNewForceGroup() self.forceGroup.addForce(f) self.addForceWidget(self.forceGroup, f) diff --git a/direct/src/tkpanels/Placer.py b/direct/src/tkpanels/Placer.py index 8cda08310b..b9bc8add04 100644 --- a/direct/src/tkpanels/Placer.py +++ b/direct/src/tkpanels/Placer.py @@ -362,16 +362,16 @@ class Placer(AppShell): # Set prefix namePrefix = '' self.movementMode = movementMode - if (movementMode == 'Relative To:'): + if movementMode == 'Relative To:': namePrefix = 'Relative ' - elif (movementMode == 'Orbit:'): + elif movementMode == 'Orbit:': namePrefix = 'Orbit ' # Update pos widgets self.posX['text'] = namePrefix + 'X' self.posY['text'] = namePrefix + 'Y' self.posZ['text'] = namePrefix + 'Z' # Update hpr widgets - if (movementMode == 'Orbit:'): + if movementMode == 'Orbit:': namePrefix = 'Orbit delta ' self.hprH['text'] = namePrefix + 'H' self.hprP['text'] = namePrefix + 'P' @@ -382,9 +382,9 @@ class Placer(AppShell): def setScalingMode(self): if self['nodePath']: scale = self['nodePath'].getScale() - if ((scale[0] != scale[1]) or - (scale[0] != scale[2]) or - (scale[1] != scale[2])): + if scale[0] != scale[1] or \ + scale[0] != scale[2] or \ + scale[1] != scale[2]: self.scalingMode.set('Scale Free') def selectNodePathNamed(self, name): @@ -399,7 +399,7 @@ class Placer(AppShell): self.addNodePath(nodePath) else: nodePath = self.nodePathDict.get(name, None) - if (nodePath == None): + if nodePath is None: # See if this evaluates into a node path try: nodePath = eval(name) @@ -427,8 +427,7 @@ class Placer(AppShell): self.nodePathMenuEntry.configure( background = self.nodePathMenuBG) # Check to see if node path and ref node path are the same - if ((self.refCS != None) and - (self.refCS == self['nodePath'])): + if self.refCS is not None and self.refCS == self['nodePath']: # Yes they are, use temp CS as ref # This calls updatePlacer self.setReferenceNodePath(self.tempCS) @@ -457,7 +456,7 @@ class Placer(AppShell): nodePath = self['nodePath'].getParent() else: nodePath = self.refNodePathDict.get(name, None) - if (nodePath == None): + if nodePath is None: # See if this evaluates into a node path try: nodePath = eval(name) @@ -473,7 +472,7 @@ class Placer(AppShell): listbox = self.refNodePathMenu.component('scrolledlist') listbox.setlist(self.refNodePathNames) # Check to see if node path and ref node path are the same - if (nodePath != None) and (nodePath == self['nodePath']): + if nodePath is not None and nodePath == self['nodePath']: # Yes they are, use temp CS and update listbox accordingly nodePath = self.tempCS self.refNodePathMenu.selectitem('parent') @@ -523,7 +522,7 @@ class Placer(AppShell): hpr = Vec3(0) scale = Vec3(1) np = self['nodePath'] - if (np != None) and isinstance(np, NodePath): + if np is not None and isinstance(np, NodePath): # Update temp CS self.updateAuxiliaryCoordinateSystems() # Update widgets @@ -595,7 +594,7 @@ class Placer(AppShell): def xformRelative(self, value, axis): nodePath = self['nodePath'] - if (nodePath != None) and (self.refCS != None): + if nodePath is not None and self.refCS is not None: if axis == 'x': nodePath.setX(self.refCS, value) elif axis == 'y': @@ -614,8 +613,8 @@ class Placer(AppShell): def xformOrbit(self, value, axis): nodePath = self['nodePath'] - if ((nodePath != None) and (self.refCS != None) and - (self.orbitFromCS != None) and (self.orbitToCS != None)): + if nodePath is not None and self.refCS is not None and \ + self.orbitFromCS is not None and self.orbitToCS is not None: if axis == 'x': self.posOffset.setX(value) elif axis == 'y': @@ -645,11 +644,11 @@ class Placer(AppShell): scale.set(value, value, value) elif mode == 'Scale Proportional': if axis == 'sx': - sf = value/scale[0] + sf = value / scale[0] elif axis == 'sy': - sf = value/scale[1] + sf = value / scale[1] elif axis == 'sz': - sf = value/scale[2] + sf = value / scale[2] scale = scale * sf self['nodePath'].setScale(scale) diff --git a/direct/src/tkpanels/TaskManagerPanel.py b/direct/src/tkpanels/TaskManagerPanel.py index c333f5a6d4..d83c825f59 100644 --- a/direct/src/tkpanels/TaskManagerPanel.py +++ b/direct/src/tkpanels/TaskManagerPanel.py @@ -217,5 +217,3 @@ class TaskManagerWidget(DirectObject): def onDestroy(self): self.ignore('TaskManager-spawnTask') self.ignore('TaskManager-removeTask') - - diff --git a/direct/src/tkwidgets/AppShell.py b/direct/src/tkwidgets/AppShell.py index 34e933b859..4307c344a1 100644 --- a/direct/src/tkwidgets/AppShell.py +++ b/direct/src/tkwidgets/AppShell.py @@ -9,7 +9,6 @@ __all__ = ['AppShell'] from direct.showbase.DirectObject import DirectObject from direct.showbase.TkGlobal import * -import Pmw, sys from . import Dial from . import Floater from . import Slider @@ -17,13 +16,9 @@ from . import EntryScale from . import VectorWidgets from . import ProgressBar from tkinter.filedialog import * +import Pmw -""" -TO FIX: -Radiobutton ordering change -""" - # Create toplevel widget dictionary try: __builtins__["widgetDict"] @@ -72,7 +67,7 @@ class AppShell(Pmw.MegaWidget, DirectObject): ) self.defineoptions(kw, optiondefs) # If no toplevel passed in, create one - if parent == None: + if parent is None: self.parent = Toplevel() else: self.parent = parent @@ -285,7 +280,7 @@ class AppShell(Pmw.MegaWidget, DirectObject): newBtn = self.__buttonBox.add(buttonName) newBtn.configure(kw) if helpMessage: - self.bind(newBtn, helpMessage, statusMessage) + self.bind(newBtn, helpMessage, statusMessage) return newBtn def alignbuttons(self): @@ -557,4 +552,3 @@ class TestAppShell(AppShell): if __name__ == '__main__': test = TestAppShell(balloon_state='none') - diff --git a/direct/src/tkwidgets/Dial.py b/direct/src/tkwidgets/Dial.py index 5b10cdb95a..457563b6b9 100644 --- a/direct/src/tkwidgets/Dial.py +++ b/direct/src/tkwidgets/Dial.py @@ -8,7 +8,9 @@ __all__ = ['Dial', 'AngleDial', 'DialWidget'] from direct.showbase.TkGlobal import * from .Valuator import Valuator, VALUATOR_MINI, VALUATOR_FULL from direct.task import Task -import math, operator, Pmw +import math +import operator +import Pmw TWO_PI = 2.0 * math.pi ONEPOINTFIVE_PI = 1.5 * math.pi @@ -256,7 +258,7 @@ class DialWidget(Pmw.MegaWidget): self.rollCount = 0 value = self['base'] + ((value - self['base']) % self['delta']) # Send command if any - if fCommand and (self['command'] != None): + if fCommand and (self['command'] is not None): self['command'](*[value] + self['commandData']) # Record value self.value = value diff --git a/direct/src/tkwidgets/EntryScale.py b/direct/src/tkwidgets/EntryScale.py index a1b050aefa..ced74f8eeb 100644 --- a/direct/src/tkwidgets/EntryScale.py +++ b/direct/src/tkwidgets/EntryScale.py @@ -10,9 +10,6 @@ import Pmw from tkinter.simpledialog import * from tkinter.colorchooser import askcolor -""" -Change Min/Max buttons to labels, add highlight binding -""" class EntryScale(Pmw.MegaWidget): "Scale with linked and validated entry" @@ -257,11 +254,9 @@ class EntryScale(Pmw.MegaWidget): def onReturn(self, *args): """ User redefinable callback executed on in entry """ - pass def onReturnRelease(self, *args): """ User redefinable callback executed on release in entry """ - pass def __onPress(self, event): # First execute onpress callback @@ -272,7 +267,6 @@ class EntryScale(Pmw.MegaWidget): def onPress(self, *args): """ User redefinable callback executed on button press """ - pass def __onRelease(self, event): # Now disable slider command @@ -283,7 +277,6 @@ class EntryScale(Pmw.MegaWidget): def onRelease(self, *args): """ User redefinable callback executed on button release """ - pass class EntryScaleGroup(Pmw.MegaToplevel): def __init__(self, parent = None, **kw): @@ -429,7 +422,6 @@ class EntryScaleGroup(Pmw.MegaToplevel): def onReturnRelease(self, *args): """ User redefinable callback executed on button press """ - pass def __onPress(self, esg): # Execute onPress callback @@ -438,7 +430,6 @@ class EntryScaleGroup(Pmw.MegaToplevel): def onPress(self, *args): """ User redefinable callback executed on button press """ - pass def __onRelease(self, esg): # Execute onRelease callback @@ -447,7 +438,7 @@ class EntryScaleGroup(Pmw.MegaToplevel): def onRelease(self, *args): """ User redefinable callback executed on button release """ - pass + def rgbPanel(nodePath, callback = None): def setNodePathColor(color, np = nodePath, cb = callback): @@ -533,6 +524,7 @@ def rgbPanel(nodePath, callback = None): esg['postCallback'] = onRelease return esg + ## SAMPLE CODE if __name__ == '__main__': # Initialise Tkinter and Pmw. @@ -547,22 +539,20 @@ if __name__ == '__main__': mega1 = EntryScale(root, command = printVal) mega1.pack(side = 'left', expand = 1, fill = 'x') - """ # These are things you can set/configure # Starting value for entryScale - mega1['value'] = 123.456 - mega1['text'] = 'Drive delta X' - mega1['min'] = 0.0 - mega1['max'] = 1000.0 - mega1['resolution'] = 1.0 + #mega1['value'] = 123.456 + #mega1['text'] = 'Drive delta X' + #mega1['min'] = 0.0 + #mega1['max'] = 1000.0 + #mega1['resolution'] = 1.0 # To change the color of the label: - mega1.label['foreground'] = 'Red' + #mega1.label['foreground'] = 'Red' # Max change/update, default is 100 # To have really fine control, for example # mega1['maxVelocity'] = 0.1 # Number of digits to the right of the decimal point, default = 2 # mega1['numDigits'] = 5 - """ # To create a entryScale group to set an RGBA value: group1 = EntryScaleGroup(root, dim = 4, diff --git a/direct/src/tkwidgets/Floater.py b/direct/src/tkwidgets/Floater.py index d8a1b83534..73bde3271e 100644 --- a/direct/src/tkwidgets/Floater.py +++ b/direct/src/tkwidgets/Floater.py @@ -8,7 +8,8 @@ __all__ = ['Floater', 'FloaterWidget', 'FloaterGroup'] from direct.showbase.TkGlobal import * from .Valuator import Valuator, VALUATOR_MINI, VALUATOR_FULL from direct.task import Task -import math, Pmw +import math +import Pmw FLOATER_WIDTH = 22 FLOATER_HEIGHT = 18 @@ -121,7 +122,7 @@ class FloaterWidget(Pmw.MegaWidget): Set floater to new value, execute command if fCommand == 1 """ # Send command if any - if fCommand and (self['command'] != None): + if fCommand and (self['command'] is not None): self['command'](*[value] + self['commandData']) # Record value self.value = value diff --git a/direct/src/tkwidgets/MemoryExplorer.py b/direct/src/tkwidgets/MemoryExplorer.py index 04e81875a0..c2a29eed56 100755 --- a/direct/src/tkwidgets/MemoryExplorer.py +++ b/direct/src/tkwidgets/MemoryExplorer.py @@ -68,7 +68,7 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): # Item Ctrls #-------------------------------------------------------------------------- def createDefaultCtrls(self): - if self.renderItem == None or self.render2dItem == None: + if self.renderItem is None or self.render2dItem is None: return totalBytes = self.renderItem.getVertexBytes()+self.render2dItem.getVertexBytes() @@ -189,7 +189,7 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): btIndex += 1 def updateDefaultBTWidth(self): - if self.renderItem == None or self.render2dItem == None: + if self.renderItem is None or self.render2dItem is None: return totalBytes = self.renderItem.getVertexBytes() + self.render2dItem.getVertexBytes() self.buttons[0]['width'] = self.getBTWidth(self.renderItem.getVertexBytes(), totalBytes) @@ -219,7 +219,7 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): def addItemCtrls(self, item): self.rootItem = item - if item == None: + if item is None: self.createDefaultCtrls() else: self.addSelfCtrl(item, item.getVertexBytes()) diff --git a/direct/src/tkwidgets/Slider.py b/direct/src/tkwidgets/Slider.py index ceb36287d3..c397612f5b 100644 --- a/direct/src/tkwidgets/Slider.py +++ b/direct/src/tkwidgets/Slider.py @@ -265,7 +265,7 @@ class SliderWidget(Pmw.MegaWidget): self.updateIndicator(self['value']) def destroy(self): - if (self['style'] == VALUATOR_MINI) and self._isPosted: + if self['style'] == VALUATOR_MINI and self._isPosted: Pmw.popgrab(self._popup) Pmw.MegaWidget.destroy(self) @@ -279,7 +279,7 @@ class SliderWidget(Pmw.MegaWidget): Set slider to new value, execute command if fCommand == 1 """ # Send command if any - if fCommand and (self['command'] != None): + if fCommand and (self['command'] is not None): self['command'](*[value] + self['commandData']) # Record value self.value = value @@ -407,8 +407,7 @@ class SliderWidget(Pmw.MegaWidget): # Do post callback if any if self._fUpdate and self['postCallback']: self['postCallback'](*self['callbackData']) - if (self._fUnpost or - (not (self._firstPress or self._fPressInside))): + if self._fUnpost or not (self._firstPress or self._fPressInside): self._unpostSlider() # Otherwise, continue self._fUpdate = 0 @@ -500,4 +499,3 @@ class SliderWidget(Pmw.MegaWidget): def restoreWidget(self, event): self._arrowBtn.itemconfigure('arrow', fill = 'grey50') - diff --git a/direct/src/tkwidgets/Tree.py b/direct/src/tkwidgets/Tree.py index 9de192ca0c..f5f6a98ef9 100644 --- a/direct/src/tkwidgets/Tree.py +++ b/direct/src/tkwidgets/Tree.py @@ -142,9 +142,9 @@ class TreeNode: def popupMenuCommand(self): command = self.menuList[self.menuVar.get()] - if (command == 'Expand All'): + if command == 'Expand All': self.updateAll(1) - elif (command == 'Collapse All'): + elif command == 'Collapse All': self.updateAll(0) else: skipUpdate = self.item.MenuCommand(command) @@ -230,7 +230,7 @@ class TreeNode: # Remove unused children for key in list(self.children.keys()): if key not in self.kidKeys: - del(self.children[key]) + del self.children[key] for key in self.kidKeys: child = self.children[key] @@ -274,9 +274,9 @@ class TreeNode: def compareText(x, y): textX = x.GetText() textY = y.GetText() - if (textX > textY): + if textX > textY: return 1 - elif (textX == textY): + elif textX == textY: return 0 else: # textX < textY return -1 @@ -308,7 +308,7 @@ class TreeNode: # Remove unused children for key in list(self.children.keys()): if key not in self.kidKeys: - del(self.children[key]) + del self.children[key] cx = x+20 cy = y+17 cylast = 0 diff --git a/direct/src/tkwidgets/Valuator.py b/direct/src/tkwidgets/Valuator.py index 6115a4e198..7030704740 100644 --- a/direct/src/tkwidgets/Valuator.py +++ b/direct/src/tkwidgets/Valuator.py @@ -2,13 +2,13 @@ __all__ = ['Valuator', 'ValuatorGroup', 'ValuatorGroupPanel'] +from panda3d.core import Vec4 from direct.showbase.DirectObject import * from direct.showbase.TkGlobal import * -from . import WidgetPropertiesDialog -import Pmw from direct.directtools.DirectUtil import getTkColorString -from panda3d.core import Vec4 +from . import WidgetPropertiesDialog from tkinter.colorchooser import askcolor +import Pmw VALUATOR_MINI = 'mini' VALUATOR_FULL = 'full' @@ -324,19 +324,15 @@ class Valuator(Pmw.MegaWidget): # Virtual functions to be redefined by subclass def createValuator(self): """ Function used by subclass to create valuator geometry """ - pass def packValuator(self): """ Function used by subclass to pack widget """ - pass def addValuatorMenuEntries(self): """ Function used by subclass to add menu entries to popup menu """ - pass def addValuatorPropertiesToDialog(self): """ Function used by subclass to add properties to property dialog """ - pass FLOATER = 'floater' @@ -754,4 +750,3 @@ def lightRGBPanel(light, style = 'mini'): pButton['bg'] = getTkColorString(color) vgp['command'] = setLightColor return vgp - diff --git a/direct/src/tkwidgets/VectorWidgets.py b/direct/src/tkwidgets/VectorWidgets.py index ef3963aa1a..fe963c7332 100644 --- a/direct/src/tkwidgets/VectorWidgets.py +++ b/direct/src/tkwidgets/VectorWidgets.py @@ -219,7 +219,7 @@ class VectorEntry(Pmw.MegaWidget): def action(self, fCommand = 1): self._refreshFloaters() - if fCommand and (self['command'] != None): + if fCommand and (self['command'] is not None): self['command'](self._value) def reset(self): diff --git a/direct/src/tkwidgets/WidgetPropertiesDialog.py b/direct/src/tkwidgets/WidgetPropertiesDialog.py index 97d186b51f..528967eca0 100644 --- a/direct/src/tkwidgets/WidgetPropertiesDialog.py +++ b/direct/src/tkwidgets/WidgetPropertiesDialog.py @@ -5,13 +5,6 @@ __all__ = ['WidgetPropertiesDialog'] from direct.showbase.TkGlobal import * import Pmw -""" -TODO: - Checkboxes for None? - Floaters to adjust float values - OK and Cancel to allow changes to be delayed - Something other than Return to accept a new value -""" class WidgetPropertiesDialog(Toplevel): """Class to open dialogs to adjust widget properties.""" @@ -227,5 +220,3 @@ class WidgetPropertiesDialog(Toplevel): This method is called automatically to process the data, *after* the dialog is destroyed. By default, it does nothing. """ - pass # override - diff --git a/direct/src/wxwidgets/ViewPort.py b/direct/src/wxwidgets/ViewPort.py index 57d7d4fc13..6974b1f687 100755 --- a/direct/src/wxwidgets/ViewPort.py +++ b/direct/src/wxwidgets/ViewPort.py @@ -8,14 +8,15 @@ Modified by Summer 2010 Carnegie Mellon University ETC PandaLE team: fixed a bug __all__ = ["Viewport", "ViewportManager"] +from panda3d.core import OrthographicLens, Point3, Plane, CollisionPlane, CollisionNode, NodePath from direct.showbase.DirectObject import DirectObject from direct.directtools.DirectGrid import DirectGrid from direct.showbase.ShowBase import WindowControls from direct.directtools.DirectGlobals import * from .WxPandaWindow import WxPandaWindow -from panda3d.core import OrthographicLens, Point3, Plane, CollisionPlane, CollisionNode, NodePath import wx + HORIZONTAL = wx.SPLIT_HORIZONTAL VERTICAL = wx.SPLIT_VERTICAL CREATENEW = 99 @@ -24,96 +25,101 @@ VPFRONT = 11 VPTOP = 12 VPPERSPECTIVE = 13 + class ViewportManager: - """Manages the global viewport stuff.""" - viewports = [] - gsg = None + """Manages the global viewport stuff.""" + viewports = [] + gsg = None - @staticmethod - def initializeAll(*args, **kwargs): - """Calls initialize() on all the viewports.""" - for v in ViewportManager.viewports: - v.initialize(*args, **kwargs) + @staticmethod + def initializeAll(*args, **kwargs): + """Calls initialize() on all the viewports.""" + for v in ViewportManager.viewports: + v.initialize(*args, **kwargs) - @staticmethod - def updateAll(*args, **kwargs): - """Calls Update() on all the viewports.""" - for v in ViewportManager.viewports: - v.Update(*args, **kwargs) + @staticmethod + def updateAll(*args, **kwargs): + """Calls Update() on all the viewports.""" + for v in ViewportManager.viewports: + v.Update(*args, **kwargs) + + @staticmethod + def layoutAll(*args, **kwargs): + """Calls Layout() on all the viewports.""" + for v in ViewportManager.viewports: + v.Layout(*args, **kwargs) - @staticmethod - def layoutAll(*args, **kwargs): - """Calls Layout() on all the viewports.""" - for v in ViewportManager.viewports: - v.Layout(*args, **kwargs) class Viewport(WxPandaWindow, DirectObject): - """Class representing a 3D Viewport.""" - CREATENEW = CREATENEW - VPLEFT = VPLEFT - VPFRONT = VPFRONT - VPTOP = VPTOP - VPPERSPECTIVE = VPPERSPECTIVE - def __init__(self, name, *args, **kwargs): - self.name = name - DirectObject.__init__(self) + """Class representing a 3D Viewport.""" + CREATENEW = CREATENEW + VPLEFT = VPLEFT + VPFRONT = VPFRONT + VPTOP = VPTOP + VPPERSPECTIVE = VPPERSPECTIVE + def __init__(self, name, *args, **kwargs): + self.name = name + DirectObject.__init__(self) - kwargs['gsg'] = ViewportManager.gsg - WxPandaWindow.__init__(self, *args, **kwargs) + kwargs['gsg'] = ViewportManager.gsg + WxPandaWindow.__init__(self, *args, **kwargs) - ViewportManager.viewports.append(self) - if ViewportManager.gsg == None: - ViewportManager.gsg = self.win.getGsg() + ViewportManager.viewports.append(self) + if ViewportManager.gsg is None: + ViewportManager.gsg = self.win.getGsg() - self.camera = None - self.lens = None - self.camPos = None - self.camLookAt = None - self.initialized = False - self.grid = None - self.collPlane = None + self.camera = None + self.lens = None + self.camPos = None + self.camLookAt = None + self.initialized = False + self.grid = None + self.collPlane = None - def initialize(self): - self.Update() - if self.win: - self.cam2d = base.makeCamera2d(self.win) - self.cam2d.node().setCameraMask(LE_CAM_MASKS[self.name]) + def initialize(self): + self.Update() + if self.win: + self.cam2d = base.makeCamera2d(self.win) + self.cam2d.node().setCameraMask(LE_CAM_MASKS[self.name]) - self.cam = base.camList[-1] - self.camera = render.attachNewNode(self.name) - #self.camera.setName(self.name) - #self.camera.reparentTo(render) - self.cam.reparentTo(self.camera) - self.camNode = self.cam.node() + self.cam = base.camList[-1] + self.camera = render.attachNewNode(self.name) + #self.camera.setName(self.name) + #self.camera.reparentTo(render) + self.cam.reparentTo(self.camera) + self.camNode = self.cam.node() - self.camNode.setCameraMask(LE_CAM_MASKS[self.name]) + self.camNode.setCameraMask(LE_CAM_MASKS[self.name]) - self.bt = base.setupMouse(self.win, True) - self.bt.node().setPrefix('_le_%s_'%self.name[:3]) - mw = self.bt.getParent() - mk = mw.getParent() - winCtrl = WindowControls( - self.win, mouseWatcher=mw, - cam=self.camera, - camNode = self.camNode, - cam2d=None, - mouseKeyboard =mk, - grid = self.grid) - base.setupWindowControls(winCtrl) + self.bt = base.setupMouse(self.win, True) + self.bt.node().setPrefix('_le_%s_'%self.name[:3]) + mw = self.bt.getParent() + mk = mw.getParent() + winCtrl = WindowControls( + self.win, mouseWatcher=mw, + cam=self.camera, + camNode = self.camNode, + cam2d=None, + mouseKeyboard =mk, + grid = self.grid) + base.setupWindowControls(winCtrl) - self.initialized = True - if self.lens != None: self.cam.node().setLens(self.lens) - if self.camPos != None: self.camera.setPos(self.camPos) - if self.camLookAt != None: self.camera.lookAt(self.camLookAt) + self.initialized = True + if self.lens is not None: + self.cam.node().setLens(self.lens) + if self.camPos is not None: + self.camera.setPos(self.camPos) + if self.camLookAt is not None: + self.camera.lookAt(self.camLookAt) - self.camLens = self.camNode.getLens() + self.camLens = self.camNode.getLens() - if self.name in ['top', 'front', 'left']: - x = self.ClientSize.GetWidth() * 0.1 - y = self.ClientSize.GetHeight() * 0.1 - self.camLens.setFilmSize(x, y) + if self.name in ['top', 'front', 'left']: + x = self.ClientSize.GetWidth() * 0.1 + y = self.ClientSize.GetHeight() * 0.1 + self.camLens.setFilmSize(x, y) - self.Bind(wx.EVT_SIZE, self.onSize) + self.Bind(wx.EVT_SIZE, self.onSize) ## self.accept("wheel_down", self.zoomOut) ## self.accept("wheel_up", self.zoomIn) @@ -121,125 +127,128 @@ class Viewport(WxPandaWindow, DirectObject): ## self.accept("page_down-repeat", self.zoomOut) ## self.accept("page_up", self.zoomIn) ## self.accept("page_up-repeat", self.zoomIn) - #self.accept("mouse3", self.onRightDown) + #self.accept("mouse3", self.onRightDown) - def Close(self): - """Closes the viewport.""" - if self.initialized: - wx.Window.Close(self) - #base.closeWindow(self.win) - ViewportManager.viewports.remove(self) + def Close(self): + """Closes the viewport.""" + if self.initialized: + wx.Window.Close(self) + #base.closeWindow(self.win) + ViewportManager.viewports.remove(self) - def onSize(self, evt): - """Invoked when the viewport is resized.""" - WxPandaWindow.onSize(self, evt) + def onSize(self, evt): + """Invoked when the viewport is resized.""" + WxPandaWindow.onSize(self, evt) - if self.win != None: - newWidth = self.ClientSize.GetWidth() - newHeight = self.ClientSize.GetHeight() + if self.win is not None: + newWidth = self.ClientSize.GetWidth() + newHeight = self.ClientSize.GetHeight() - if hasattr(base, "direct") and base.direct: - for dr in base.direct.drList: - if dr.camNode == self.camNode: - dr.updateFilmSize(newWidth, newHeight) - break + if hasattr(base, "direct") and base.direct: + for dr in base.direct.drList: + if dr.camNode == self.camNode: + dr.updateFilmSize(newWidth, newHeight) + break - def onRightDown(self, evt = None): - """Invoked when the viewport is right-clicked.""" - if evt == None: - mpos = wx.GetMouseState() - mpos = self.ScreenToClient((mpos.x, mpos.y)) - else: - mpos = evt.GetPosition() - self.Update() - #self.PopupMenu(self.menu, mpos) - #self.menu.Destroy() + def onRightDown(self, evt = None): + """Invoked when the viewport is right-clicked.""" + if evt is None: + mpos = wx.GetMouseState() + mpos = self.ScreenToClient((mpos.x, mpos.y)) + else: + mpos = evt.GetPosition() + self.Update() + #self.PopupMenu(self.menu, mpos) + #self.menu.Destroy() - def zoomOut(self): - self.camera.setY(self.camera, -MOUSE_ZOO_SPEED) + @staticmethod + def make(parent, vpType = None): + """Safe constructor that also takes CREATENEW, VPLEFT, VPTOP, etc.""" + if vpType is None or vpType == CREATENEW: + return Viewport(parent) + if isinstance(vpType, Viewport): + return vpType + if vpType == VPLEFT: + return Viewport.makeLeft(parent) + if vpType == VPFRONT: + return Viewport.makeFront(parent) + if vpType == VPTOP: + return Viewport.makeTop(parent) + if vpType == VPPERSPECTIVE: + return Viewport.makePerspective(parent) + raise TypeError("Unknown viewport type: %s" % vpType) - def zoomIn(self): - self.camera.setY(self.camera, MOUSE_ZOOM_SPEED) + @staticmethod + def makeOrthographic(parent, name, campos): + v = Viewport(name, parent) + v.lens = OrthographicLens() + v.lens.setFilmSize(30) + v.camPos = campos + v.camLookAt = Point3(0, 0, 0) + v.grid = DirectGrid(parent=render) + if name == 'left': + v.grid.setHpr(0, 0, 90) + collPlane = CollisionNode('LeftGridCol') + collPlane.addSolid(CollisionPlane(Plane(1, 0, 0, 0))) + collPlane.setIntoCollideMask(BitMask32.bit(21)) + v.collPlane = NodePath(collPlane) + v.collPlane.wrtReparentTo(v.grid) + #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_leftViewGridBack") + LE_showInOneCam(v.grid, name) + elif name == 'front': + v.grid.setHpr(90, 0, 90) + collPlane = CollisionNode('FrontGridCol') + collPlane.addSolid(CollisionPlane(Plane(0, -1, 0, 0))) + collPlane.setIntoCollideMask(BitMask32.bit(21)) + v.collPlane = NodePath(collPlane) + v.collPlane.wrtReparentTo(v.grid) + #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_frontViewGridBack") + LE_showInOneCam(v.grid, name) + else: + collPlane = CollisionNode('TopGridCol') + collPlane.addSolid(CollisionPlane(Plane(0, 0, 1, 0))) + collPlane.setIntoCollideMask(BitMask32.bit(21)) + v.collPlane = NodePath(collPlane) + v.collPlane.reparentTo(v.grid) + #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_topViewGridBack") + LE_showInOneCam(v.grid, name) + return v - @staticmethod - def make(parent, vpType = None): - """Safe constructor that also takes CREATENEW, VPLEFT, VPTOP, etc.""" - if vpType == None or vpType == CREATENEW: - return Viewport(parent) - if isinstance(vpType, Viewport): return vpType - if vpType == VPLEFT: return Viewport.makeLeft(parent) - if vpType == VPFRONT: return Viewport.makeFront(parent) - if vpType == VPTOP: return Viewport.makeTop(parent) - if vpType == VPPERSPECTIVE: return Viewport.makePerspective(parent) - raise TypeError("Unknown viewport type: %s" % vpType) + @staticmethod + def makePerspective(parent): + v = Viewport('persp', parent) + v.camPos = Point3(-19, -19, 19) + v.camLookAt = Point3(0, 0, 0) - @staticmethod - def makeOrthographic(parent, name, campos): - v = Viewport(name, parent) - v.lens = OrthographicLens() - v.lens.setFilmSize(30) - v.camPos = campos - v.camLookAt = Point3(0, 0, 0) - v.grid = DirectGrid(parent=render) - if name == 'left': - v.grid.setHpr(0, 0, 90) - collPlane = CollisionNode('LeftGridCol') - collPlane.addSolid(CollisionPlane(Plane(1, 0, 0, 0))) - collPlane.setIntoCollideMask(BitMask32.bit(21)) - v.collPlane = NodePath(collPlane) - v.collPlane.wrtReparentTo(v.grid) - #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_leftViewGridBack") - LE_showInOneCam(v.grid, name) - elif name == 'front': - v.grid.setHpr(90, 0, 90) - collPlane = CollisionNode('FrontGridCol') - collPlane.addSolid(CollisionPlane(Plane(0, -1, 0, 0))) - collPlane.setIntoCollideMask(BitMask32.bit(21)) - v.collPlane = NodePath(collPlane) - v.collPlane.wrtReparentTo(v.grid) - #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_frontViewGridBack") - LE_showInOneCam(v.grid, name) - else: - collPlane = CollisionNode('TopGridCol') - collPlane.addSolid(CollisionPlane(Plane(0, 0, 1, 0))) - collPlane.setIntoCollideMask(BitMask32.bit(21)) - v.collPlane = NodePath(collPlane) - v.collPlane.reparentTo(v.grid) - #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_topViewGridBack") - LE_showInOneCam(v.grid, name) - return v + v.grid = DirectGrid(parent=render) + collPlane = CollisionNode('PerspGridCol') + collPlane.addSolid(CollisionPlane(Plane(0, 0, 1, 0))) + #oldBitmask = collPlane.getIntoCollideMask() + #collPlane.setIntoCollideMask(BitMask32.bit(21)|oldBitmask) + collPlane.setIntoCollideMask(BitMask32.bit(21)) + v.collPlane = NodePath(collPlane) + v.collPlane.reparentTo(v.grid) - @staticmethod - def makePerspective(parent): - v = Viewport('persp', parent) - v.camPos = Point3(-19, -19, 19) - v.camLookAt = Point3(0, 0, 0) + collPlane2 = CollisionNode('PerspGridCol2') + collPlane2.addSolid(CollisionPlane(Plane(0, 0, -1, 0))) + #oldBitmask = collPlane2.getIntoCollideMask() + #collPlane2.setIntoCollideMask(BitMask32.bit(21)|oldBitmask) + collPlane2.setIntoCollideMask(BitMask32.bit(21)) + v.collPlane2 = NodePath(collPlane2) + v.collPlane2.reparentTo(v.grid) - v.grid = DirectGrid(parent=render) - collPlane = CollisionNode('PerspGridCol') - collPlane.addSolid(CollisionPlane(Plane(0, 0, 1, 0))) - #oldBitmask = collPlane.getIntoCollideMask() - #collPlane.setIntoCollideMask(BitMask32.bit(21)|oldBitmask) - collPlane.setIntoCollideMask(BitMask32.bit(21)) - v.collPlane = NodePath(collPlane) - v.collPlane.reparentTo(v.grid) + #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_perspViewGridBack") + LE_showInOneCam(v.grid, 'persp') + return v - collPlane2 = CollisionNode('PerspGridCol2') - collPlane2.addSolid(CollisionPlane(Plane(0, 0, -1, 0))) - #oldBitmask = collPlane2.getIntoCollideMask() - #collPlane2.setIntoCollideMask(BitMask32.bit(21)|oldBitmask) - collPlane2.setIntoCollideMask(BitMask32.bit(21)) - v.collPlane2 = NodePath(collPlane2) - v.collPlane2.reparentTo(v.grid) + @staticmethod + def makeLeft(parent): + return Viewport.makeOrthographic(parent, 'left', Point3(600, 0, 0)) - #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_perspViewGridBack") - LE_showInOneCam(v.grid, 'persp') - return v - - @staticmethod - def makeLeft(parent): return Viewport.makeOrthographic(parent, 'left', Point3(600, 0, 0)) - @staticmethod - def makeFront(parent): return Viewport.makeOrthographic(parent, 'front', Point3(0, -600, 0)) - @staticmethod - def makeTop(parent): return Viewport.makeOrthographic(parent, 'top', Point3(0, 0, 600)) + @staticmethod + def makeFront(parent): + return Viewport.makeOrthographic(parent, 'front', Point3(0, -600, 0)) + @staticmethod + def makeTop(parent): + return Viewport.makeOrthographic(parent, 'top', Point3(0, 0, 600)) diff --git a/direct/src/wxwidgets/WxAppShell.py b/direct/src/wxwidgets/WxAppShell.py index 1159ff8e32..39da7eb224 100755 --- a/direct/src/wxwidgets/WxAppShell.py +++ b/direct/src/wxwidgets/WxAppShell.py @@ -2,7 +2,9 @@ WxAppShell provides a GUI application framework using wxPython. This is an wxPython version of AppShell.py """ -import wx, sys +import wx +import sys + class WxAppShell(wx.Frame): appversion = '1.0' diff --git a/direct/src/wxwidgets/WxPandaShell.py b/direct/src/wxwidgets/WxPandaShell.py index 4835f28e2b..1d40f7a45a 100755 --- a/direct/src/wxwidgets/WxPandaShell.py +++ b/direct/src/wxwidgets/WxPandaShell.py @@ -104,7 +104,8 @@ class WxPandaShell(WxAppShell): sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.mainFrame, 1, wx.EXPAND, 0) - self.SetSizer(sizer); self.Layout() + self.SetSizer(sizer) + self.Layout() def initialize(self): """Initializes the viewports and editor.""" @@ -113,9 +114,9 @@ class WxPandaShell(WxAppShell): self.wxStep() ViewportManager.initializeAll() # Position the camera - if base.trackball != None: - base.trackball.node().setPos(0, 30, 0) - base.trackball.node().setHpr(0, 15, 0) + if base.trackball is not None: + base.trackball.node().setPos(0, 30, 0) + base.trackball.node().setHpr(0, 15, 0) # to make persp view as default self.perspViewMenuItem.Toggle() @@ -202,9 +203,10 @@ class WxPandaShell(WxAppShell): def wxStep(self, task = None): """A step in the WX event loop. You can either call this yourself or use as task.""" while self.evtLoop.Pending(): - self.evtLoop.Dispatch() + self.evtLoop.Dispatch() self.evtLoop.ProcessIdle() - if task != None: return task.cont + if task is not None: + return task.cont def appInit(self): """Overridden from WxAppShell.py.""" diff --git a/direct/src/wxwidgets/WxPandaStart.py b/direct/src/wxwidgets/WxPandaStart.py index 80cd385bf1..4c285fa2be 100755 --- a/direct/src/wxwidgets/WxPandaStart.py +++ b/direct/src/wxwidgets/WxPandaStart.py @@ -1,3 +1,2 @@ from .WxPandaShell import * base.app = WxPandaShell() - diff --git a/direct/src/wxwidgets/WxPandaWindow.py b/direct/src/wxwidgets/WxPandaWindow.py index 79a4ebc68d..de17f49502 100644 --- a/direct/src/wxwidgets/WxPandaWindow.py +++ b/direct/src/wxwidgets/WxPandaWindow.py @@ -124,7 +124,7 @@ else: del kw['gsg'] fbprops = kw.get('fbprops', None) - if fbprops == None: + if fbprops is None: fbprops = FrameBufferProperties.getDefault() attribList = kw.get('attribList', None) diff --git a/direct/src/wxwidgets/WxSlider.py b/direct/src/wxwidgets/WxSlider.py index f42026ee25..48ed06b041 100755 --- a/direct/src/wxwidgets/WxSlider.py +++ b/direct/src/wxwidgets/WxSlider.py @@ -7,6 +7,7 @@ __all__ = ['WxSlider'] import wx + class WxSlider(wx.Slider): def __init__(self, parent, id, value, minValue, maxValue,\ pos=wx.DefaultPosition, size=wx.DefaultSize,\ @@ -90,4 +91,3 @@ class WxSlider(wx.Slider): if not self.textValue is None: self.textValue.Enable() self.textValue.Bind(wx.EVT_TEXT_ENTER, self.onEnter) -