add usd-21-05-win64_py37

This commit is contained in:
Sébastien Albert committed 2021-12-07 17:16:25 +01:00
1 parent 41d23e71ba
commit 66bc054336
15675 files changed
+3061008

No files matched your search

+341
View File
@@ -0,0 +1,341 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import sys, argparse, os
from .qt import QtWidgets, QtCore
from .common import Timer
from .appController import AppController
from pxr import UsdAppUtils, Tf
class InvalidUsdviewOption(Exception):
"""Raised when an invalid Usdview option is found in
Launcher.ValidateOptions or any methods which override it.
"""
pass
class Launcher(object):
'''
Base class for argument parsing, validation, and initialization for UsdView
Subclasses can choose to override
-- GetHelpDescription()
-- RegisterOptions()
-- ParseOptions()
-- ValidateOptions()
-- GetResolverContext()
'''
def __init__(self):
pass
def Run(self):
'''
The main entry point to launch a process using UsdView.
'''
parser = argparse.ArgumentParser(prog=sys.argv[0],
description=self.GetHelpDescription())
traceCollector = None
with Timer() as totalTimer:
self.RegisterPositionals(parser)
self.RegisterOptions(parser)
arg_parse_result = self.ParseOptions(parser)
self.ValidateOptions(arg_parse_result)
if arg_parse_result.traceToFile:
from pxr import Trace
traceCollector = Trace.Collector()
if arg_parse_result.tracePython:
traceCollector.pythonTracingEnabled = True
traceCollector.enabled = True
self.__LaunchProcess(arg_parse_result)
if traceCollector:
traceCollector.enabled = False
if arg_parse_result.timing and arg_parse_result.quitAfterStartup:
totalTimer.PrintTime('open and close usdview')
if traceCollector:
if arg_parse_result.traceFormat == 'trace':
Trace.Reporter.globalReporter.Report(
arg_parse_result.traceToFile)
elif arg_parse_result.traceFormat == 'chrome':
Trace.Reporter.globalReporter.ReportChromeTracingToFile(
arg_parse_result.traceToFile)
else:
Tf.RaiseCodingError("Invalid trace format option provided: %s -"
"trace/chrome are the valid options" %
arg_parse_result.traceFormat)
def GetHelpDescription(self):
'''return the help description'''
return 'View a usd file'
def RegisterPositionals(self, parser):
'''
register positional arguments on the ArgParser
'''
parser.add_argument('usdFile', action='store',
type=str,
help='The file to view')
def RegisterOptions(self, parser):
'''
register optional arguments on the ArgParser
'''
from pxr import UsdUtils
parser.add_argument('--renderer', action='store',
type=str, dest='renderer',
choices=AppController.GetRendererOptionChoices(),
help="Which render backend to use (named as it "
"appears in the menu). Use '%s' to "
"turn off Hydra renderers." %
AppController.HYDRA_DISABLED_OPTION_STRING,
default='')
parser.add_argument('--select', action='store', default='/',
dest='primPath', type=str,
help='A prim path to initially select and frame')
UsdAppUtils.cameraArgs.AddCmdlineArgs(parser,
altHelpText=(
"Which camera to set the view to on open - may be given as "
"either just the camera's prim name (ie, just the last "
"element in the prim path), or as a full prim path. Note "
"that if only the prim name is used, and more than one camera "
"exists with the name, which is used will be effectively "
"random (default=%(default)s)"))
parser.add_argument('--mask', action='store',
dest='populationMask',
metavar='PRIMPATH[,PRIMPATH...]',
help='Limit stage population to these prims, '
'their descendants and ancestors. To specify '
'multiple paths, either use commas with no spaces '
'or quote the argument and separate paths by '
'commas and/or spaces.')
parser.add_argument('--clearsettings', action='store_true',
dest='clearSettings',
help='Restores usdview settings to default')
parser.add_argument('--defaultsettings', action='store_true',
dest='defaultSettings',
help='Launch usdview with default settings')
parser.add_argument('--norender', action='store_true',
dest='noRender',
help='Display only hierarchy browser')
parser.add_argument('--noplugins', action='store_true',
dest='noPlugins',
help='Do not load plugins')
parser.add_argument('--unloaded', action='store_true',
dest='unloaded',
help='Do not load payloads')
parser.add_argument('--timing', action='store_true',
dest='timing',
help='Echo timing stats to console. NOTE: timings will be unreliable when the --mallocTagStats option is also in use')
parser.add_argument('--traceToFile', action='store',
type=str,
dest='traceToFile',
default=None,
help='Start tracing at application startup and '
'write --traceFormat specified format output to the '
'specified trace file when the application quits')
parser.add_argument('--traceFormat', action='store',
type=str,
dest='traceFormat',
default='chrome',
choices=['chrome', 'trace'],
help='Output format for trace file specified by '
'--traceToFile. \'chrome\' files can be read in '
'chrome, \'trace\' files are simple text reports. '
'(default=%(default)s)')
parser.add_argument('--tracePython', action='store_true',
dest='tracePython',
help='Enable python trace collection, '
'requires --traceToFile to be set.')
parser.add_argument('--memstats', action='store', default='none',
dest='mallocTagStats', type=str,
choices=['none', 'stage', 'stageAndImaging'],
help='Use the Pxr MallocTags memory accounting system to profile USD, saving results to a tmp file, with a summary to the console. Will have no effect if MallocTags are not supported in the USD installation.')
parser.add_argument('--numThreads', action='store',
type=int, default=0,
help='Number of threads used for processing'
'(0 is max, negative numbers imply max - N)')
parser.add_argument('--ff', action='store',
dest='firstframe', type=int,
help='Set the first frame of the viewer')
parser.add_argument('--lf', action='store',
dest='lastframe', type=int,
help='Set the last frame of the viewer')
parser.add_argument('--cf', action='store',
dest='currentframe', type=int,
help='Set the current frame of the viewer')
UsdAppUtils.complexityArgs.AddCmdlineArgs(parser,
altHelpText=(
'Set the initial mesh refinement complexity (%(default)s).'))
parser.add_argument('--quitAfterStartup', action='store_true',
dest='quitAfterStartup',
help='quit immediately after start up')
parser.add_argument('--sessionLayer', default=None, type=str,
help= "If specified, the stage will be opened "
"with the 'sessionLayer' in place of the default "
"anonymous layer. As this changes the session "
"layer from anonymous to persistent, be "
"aware that layers saved from Export Overrides "
"will include the opinions in the persistent "
"session layer.")
def ParseOptions(self, parser):
'''
runs the parser on the arguments
'''
return parser.parse_args()
def ValidateOptions(self, arg_parse_result):
'''
Called by Run(), after ParseOptions() is called. Validates and
potentially modifies the parsed arguments. Raises InvalidUsdviewOption
if an invalid option is found. If a derived class has overridden
ParseOptions(), ValidateOptions() is an opportunity to process the
options and transmute other "core" options in response. If
overridden, derived classes should likely first call the base method.
'''
# split arg_parse_result.populationMask into paths.
if arg_parse_result.populationMask:
arg_parse_result.populationMask = (
arg_parse_result.populationMask.replace(',', ' ').split())
# Verify that the camera path is either an absolute path, or is just
# the name of a camera.
if arg_parse_result.camera:
camPath = arg_parse_result.camera
if camPath.isEmpty:
raise InvalidUsdviewOption(
"invalid camera path - %r" % camPath)
if not camPath.IsPrimPath():
raise InvalidUsdviewOption(
"invalid camera path - must be a raw prim path with no "
"variant selections or properties - got: %r" % camPath)
# If it's a multi-element path, make sure it is absolute.
if camPath.pathElementCount > 1:
if not camPath.IsAbsolutePath():
# perhaps we should error here? For now just pre-pending
# root, and printing warning...
from pxr import Sdf
print("WARNING: camera path %r was not absolute, prepending "
"%r to make it absolute" % (str(camPath),
str(Sdf.Path.absoluteRootPath)), file=sys.stderr)
arg_parse_result.camera = camPath.MakeAbsolutePath(
Sdf.Path.absoluteRootPath)
if arg_parse_result.clearSettings and arg_parse_result.defaultSettings:
raise InvalidUsdviewOption(
"cannot supply both --clearsettings and --defaultsettings.")
def GetResolverContext(self, usdFile):
"""
Create and return the ArResolverContext that will be used to Open
the Stage for the given usdFile. Base implementation
creates a default asset context for the usdFile asset, but derived
classes can do more sophisticated resolver and context configuration.
Will be called each time a new stage is opened.
It is not necessary to create an ArResolverContext for every UsdStage
one opens, as the Stage will use reasonable fallback behavior if no
context is provided. For usdview, configuring an asset context by
default is reasonable, and allows clients that embed usdview to
achieve different behavior when needed.
"""
from pxr import Ar
r = Ar.GetResolver()
r.ConfigureResolverForAsset(usdFile)
return r.CreateDefaultContextForAsset(usdFile)
def LaunchPreamble(self, arg_parse_result):
# Initialize concurrency limit as early as possible so that it is
# respected by subsequent imports.
from pxr import Work
Work.SetConcurrencyLimitArgument(arg_parse_result.numThreads)
if arg_parse_result.clearSettings:
AppController.clearSettings()
# Create the Qt application
app = QtWidgets.QApplication(sys.argv)
contextCreator = lambda usdFile: self.GetResolverContext(usdFile)
appController = AppController(arg_parse_result, contextCreator)
return (app, appController)
def __LaunchProcess(self, arg_parse_result):
'''
after the arguments have been parsed, launch the UI in a forked process
'''
# Initialize concurrency limit as early as possible so that it is
# respected by subsequent imports.
(app, appController) = self.LaunchPreamble(arg_parse_result)
if arg_parse_result.quitAfterStartup:
# Enqueue event to shutdown application. We don't use quit() because
# it doesn't trigger the closeEvent() on the main window which is
# used to orchestrate the shutdown.
QtCore.QTimer.singleShot(0, app.instance().closeAllWindows)
app.exec_()
Binary file not shown.
Binary file not shown.
+160
View File
@@ -0,0 +1,160 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .adjustClippingUI import Ui_AdjustClipping
from .common import FixableDoubleValidator
class AdjustClipping(QtWidgets.QDialog):
"""The dataModel provided to this VC must conform to the following
interface:
Editable properties:
overrideNear (float or None, which indicates the override is disabled)
overrideFar (float or None, which indicates the override is disabled)
Readable properties:
cameraFrustum (Gf.Frustum, or struct that has a Gf.Range1d 'nearFar' member)
Signals:
signalFrustumChanged() - whenever the near/far clipping values
may have changed.
"""
def __init__(self, parent, dataModel):
QtWidgets.QDialog.__init__(self,parent)
self._ui = Ui_AdjustClipping()
self._ui.setupUi(self)
self._dataModel = dataModel
clipRange = self._dataModel.cameraFrustum.nearFar
self._nearCache = self._dataModel.overrideNear or clipRange.min
self._farCache = self._dataModel.overrideFar or clipRange.max
self._dataModel.signalFrustumChanged.connect(self.update)
# When the checkboxes change, we want to update instantly
self._ui.overrideNear.stateChanged.connect(self._overrideNearToggled)
self._ui.overrideFar.stateChanged.connect(self._overrideFarToggled)
# we also want to update the clipping planes as the user is typing
self._ui.nearEdit.textChanged.connect(self._nearChanged)
self._ui.farEdit.textChanged.connect(self._farChanged)
def AddValidation(lineEdit):
dv = FixableDoubleValidator(lineEdit)
dv.setDecimals(3)
dv.setBottom(0)
lineEdit.setValidator(dv)
# Make sure only human-readable doubles can be typed in the text boxes
AddValidation(self._ui.nearEdit)
AddValidation(self._ui.farEdit)
# Set the checkboxes to their initial state
self._ui.overrideNear.setChecked(self._dataModel.overrideNear \
is not None)
self._ui.overrideFar.setChecked(self._dataModel.overrideFar \
is not None)
# load the initial values for the text boxes, but first deactivate them
# if their corresponding checkbox is off.
self._ui.nearEdit.setEnabled(self._ui.overrideNear.isChecked())
self._ui.nearEdit.validator().fixup(str(self._nearCache))
self._ui.farEdit.setEnabled(self._ui.overrideFar.isChecked())
self._ui.farEdit.validator().fixup(str(self._farCache))
def _updateEditorsFromDataModel(self):
"""Read the dataModel-computed clipping planes and put them
in the text boxes when they are deactivated."""
clipRange = self._dataModel.cameraFrustum.nearFar
if (not self._ui.overrideNear.isChecked()) and \
self._nearCache != clipRange.min :
self._nearCache = clipRange.min
nearStr = str(self._nearCache)
self._ui.nearEdit.validator().fixup(nearStr)
if (not self._ui.overrideFar.isChecked()) and \
self._farCache != clipRange.max :
self._farCache = clipRange.max
farStr = str(self._farCache)
self._ui.farEdit.validator().fixup(farStr)
def paintEvent(self, paintEvent):
"""Overridden from base class so we can perform JIT updating
of editors to limit the number of redraws we perform"""
self._updateEditorsFromDataModel()
super(AdjustClipping, self).paintEvent(paintEvent)
def _overrideNearToggled(self, state):
"""Called when the "Override Near" checkbox is toggled"""
self._ui.nearEdit.setEnabled(state)
if state:
self._dataModel.overrideNear = self._nearCache
else:
self._dataModel.overrideNear = None
def _overrideFarToggled(self, state):
"""Called when the "Override Far" checkbox is toggled"""
self._ui.farEdit.setEnabled(state)
if state:
self._dataModel.overrideFar = self._farCache
else:
self._dataModel.overrideFar = None
def _nearChanged(self, text):
"""Called when the Near text box changed. This can happen when we
are updating the value but the widget is actually inactive - don't
do anything in that case."""
if len(text) == 0 or not self._ui.nearEdit.isEnabled():
return
try:
self._dataModel.overrideNear = float(text)
except ValueError:
pass
def _farChanged(self, text):
"""Called when the Far text box changed. This can happen when we
are updating the value but the widget is actually inactive - don't
do anything in that case."""
if len(text) == 0 or not self._ui.farEdit.isEnabled():
return
try:
self._dataModel.overrideFar = float(text)
except ValueError:
pass
def closeEvent(self, event):
# Ensure that even if the dialog doesn't get destroyed right away,
# we'll stop doing work.
self._dataModel.signalFrustumChanged.disconnect(self.update)
event.accept()
# Since the dialog is the immediate-edit kind, we consider
# window-close to be an accept, so our clients can know the dialog is
# done by listening for the finished(int) signal
self.accept()
Binary file not shown.
+102
View File
@@ -0,0 +1,102 @@
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'adjustClippingUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_AdjustClipping(object):
def setupUi(self, AdjustClipping):
if not AdjustClipping.objectName():
AdjustClipping.setObjectName(u"AdjustClipping")
AdjustClipping.resize(331, 86)
self.verticalLayout = QVBoxLayout(AdjustClipping)
self.verticalLayout.setObjectName(u"verticalLayout")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.verticalLayout_2 = QVBoxLayout()
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
self.overrideNear = QCheckBox(AdjustClipping)
self.overrideNear.setObjectName(u"overrideNear")
self.overrideNear.setFocusPolicy(Qt.NoFocus)
self.verticalLayout_2.addWidget(self.overrideNear)
self.overrideFar = QCheckBox(AdjustClipping)
self.overrideFar.setObjectName(u"overrideFar")
self.overrideFar.setFocusPolicy(Qt.NoFocus)
self.verticalLayout_2.addWidget(self.overrideFar)
self.horizontalLayout.addLayout(self.verticalLayout_2)
self.verticalLayout_3 = QVBoxLayout()
self.verticalLayout_3.setObjectName(u"verticalLayout_3")
self.nearEdit = QLineEdit(AdjustClipping)
self.nearEdit.setObjectName(u"nearEdit")
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.nearEdit.sizePolicy().hasHeightForWidth())
self.nearEdit.setSizePolicy(sizePolicy)
self.verticalLayout_3.addWidget(self.nearEdit)
self.farEdit = QLineEdit(AdjustClipping)
self.farEdit.setObjectName(u"farEdit")
sizePolicy.setHeightForWidth(self.farEdit.sizePolicy().hasHeightForWidth())
self.farEdit.setSizePolicy(sizePolicy)
self.verticalLayout_3.addWidget(self.farEdit)
self.horizontalLayout.addLayout(self.verticalLayout_3)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(AdjustClipping)
QMetaObject.connectSlotsByName(AdjustClipping)
# setupUi
def retranslateUi(self, AdjustClipping):
AdjustClipping.setProperty("comment", QCoreApplication.translate("AdjustClipping", u"\n"
" Copyright 2016 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
AdjustClipping.setWindowTitle(QCoreApplication.translate("AdjustClipping", u"Adjust Clipping Planes", None))
self.overrideNear.setText(QCoreApplication.translate("AdjustClipping", u"Override Near", None))
self.overrideFar.setText(QCoreApplication.translate("AdjustClipping", u"Override Far", None))
# retranslateUi
@@ -0,0 +1,86 @@
#
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets
from .adjustDefaultMaterialUI import Ui_AdjustDefaultMaterial
class AdjustDefaultMaterial(QtWidgets.QDialog):
"""Popup widget to adjust the default material used for rendering.
`datamodel` should be a ViewSettingsDataModel.
"""
def __init__(self, parent, dataModel):
QtWidgets.QDialog.__init__(self,parent)
self._ui = Ui_AdjustDefaultMaterial()
self._ui.setupUi(self)
self._dataModel = dataModel
self._ambientCache = None
self._specularCache = None
self._ui.ambientIntSpinBox.valueChanged['double'].connect(self._ambientChanged)
self._ui.specularIntSpinBox.valueChanged['double'].connect(self._specularChanged)
dataModel.signalDefaultMaterialChanged.connect(self._updateFromData)
self._ui.resetButton.clicked[bool].connect(self._reset)
self._ui.doneButton.clicked[bool].connect(self._done)
self._updateFromData()
def _updateFromData(self):
if self._dataModel.defaultMaterialAmbient != self._ambientCache:
self._ambientCache = self._dataModel.defaultMaterialAmbient
self._ui.ambientIntSpinBox.setValue(self._ambientCache)
if self._dataModel.defaultMaterialSpecular != self._specularCache:
self._specularCache = self._dataModel.defaultMaterialSpecular
self._ui.specularIntSpinBox.setValue(self._specularCache)
def _ambientChanged(self, val):
if val != self._ambientCache:
# Must do update cache first to prevent update cycle
self._ambientCache = val
self._dataModel.defaultMaterialAmbient = val
def _specularChanged(self, val):
if val != self._specularCache:
# Must do update cache first to prevent update cycle
self._specularCache = val
self._dataModel.defaultMaterialSpecular = val
def _reset(self, unused):
self._dataModel.resetDefaultMaterial()
def _done(self, unused):
self.close()
def closeEvent(self, event):
event.accept()
# Since the dialog is the immediate-edit kind, we consider
# window-close to be an accept, so our clients can know the dialog is
# done
self.accept()
Binary file not shown.
@@ -0,0 +1,144 @@
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'adjustDefaultMaterialUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_AdjustDefaultMaterial(object):
def setupUi(self, AdjustDefaultMaterial):
if not AdjustDefaultMaterial.objectName():
AdjustDefaultMaterial.setObjectName(u"AdjustDefaultMaterial")
AdjustDefaultMaterial.resize(238, 123)
sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(AdjustDefaultMaterial.sizePolicy().hasHeightForWidth())
AdjustDefaultMaterial.setSizePolicy(sizePolicy)
self.verticalLayout = QVBoxLayout(AdjustDefaultMaterial)
self.verticalLayout.setObjectName(u"verticalLayout")
self.verticalLayout_4 = QVBoxLayout()
self.verticalLayout_4.setObjectName(u"verticalLayout_4")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.horizontalSpacer_4 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(self.horizontalSpacer_4)
self.ambientInt = QLabel(AdjustDefaultMaterial)
self.ambientInt.setObjectName(u"ambientInt")
self.ambientInt.setFocusPolicy(Qt.NoFocus)
self.horizontalLayout.addWidget(self.ambientInt)
self.ambientIntSpinBox = QDoubleSpinBox(AdjustDefaultMaterial)
self.ambientIntSpinBox.setObjectName(u"ambientIntSpinBox")
self.ambientIntSpinBox.setDecimals(1)
self.ambientIntSpinBox.setMaximum(1.000000000000000)
self.ambientIntSpinBox.setSingleStep(0.100000000000000)
self.horizontalLayout.addWidget(self.ambientIntSpinBox)
self.horizontalSpacer_5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(self.horizontalSpacer_5)
self.verticalLayout_4.addLayout(self.horizontalLayout)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.horizontalSpacer_6 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer_6)
self.specularInt = QLabel(AdjustDefaultMaterial)
self.specularInt.setObjectName(u"specularInt")
self.specularInt.setFocusPolicy(Qt.NoFocus)
self.horizontalLayout_2.addWidget(self.specularInt)
self.specularIntSpinBox = QDoubleSpinBox(AdjustDefaultMaterial)
self.specularIntSpinBox.setObjectName(u"specularIntSpinBox")
self.specularIntSpinBox.setDecimals(1)
self.specularIntSpinBox.setMaximum(1.000000000000000)
self.specularIntSpinBox.setSingleStep(0.100000000000000)
self.horizontalLayout_2.addWidget(self.specularIntSpinBox)
self.horizontalSpacer_7 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer_7)
self.verticalLayout_4.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.resetButton = QPushButton(AdjustDefaultMaterial)
self.resetButton.setObjectName(u"resetButton")
self.resetButton.setAutoDefault(False)
self.horizontalLayout_3.addWidget(self.resetButton)
self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(self.horizontalSpacer_2)
self.doneButton = QPushButton(AdjustDefaultMaterial)
self.doneButton.setObjectName(u"doneButton")
self.horizontalLayout_3.addWidget(self.doneButton)
self.verticalLayout_4.addLayout(self.horizontalLayout_3)
self.verticalLayout.addLayout(self.verticalLayout_4)
self.retranslateUi(AdjustDefaultMaterial)
QMetaObject.connectSlotsByName(AdjustDefaultMaterial)
# setupUi
def retranslateUi(self, AdjustDefaultMaterial):
AdjustDefaultMaterial.setProperty("comment", QCoreApplication.translate("AdjustDefaultMaterial", u"\n"
" Copyright 2017 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
AdjustDefaultMaterial.setWindowTitle(QCoreApplication.translate("AdjustDefaultMaterial", u"Adjust Default Material", None))
self.ambientInt.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Ambient Intensity", None))
self.specularInt.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Specular Intensity", None))
self.resetButton.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Reset", None))
self.doneButton.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Done", None))
# retranslateUi
File diff suppressed because it is too large. Load diff
Binary file not shown.
+172
View File
@@ -0,0 +1,172 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Qt Components
from .qt import QtCore, QtGui, QtWidgets
from .common import KeyboardShortcuts
class AppEventFilter(QtCore.QObject):
'''This class's primary responsibility is delivering key events to
"the right place". Given usdview's simplistic approach to shortcuts
(i.e. just uses the native Qt mechanism that does not allow for
context-sensitive keypress dispatching), we take a simplistic approach
to routing: use Qt's preferred mechanism of processing keyPresses
only in widgets that have focus; therefore, the primary behavior of this
filter is to track mouse-position in order to set widget focus, so that
widgets with keyboard navigation behaviors operate when the mouse is over
them.
We add one special behaviors on top of that, which is to turn unaccepted
left/right events into up/down events for TreeView widgets, because we
do not have a specialized class on which to provide this nice navigation
behavior.'''
# in future it would be a hotkey dispatcher instead of appController
# that we'd dispatch to, but we don't have one yet
def __init__(self, appController):
QtCore.QObject.__init__(self)
self._appController = appController
def IsNavKey(self, key, modifiers):
# Note that the arrow keys are considered part of the keypad on macOS.
return (key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right,
QtCore.Qt.Key_Up, QtCore.Qt.Key_Down,
QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown,
QtCore.Qt.Key_Home, QtCore.Qt.Key_End,
KeyboardShortcuts.FramingKey)
and modifiers in (QtCore.Qt.NoModifier,
QtCore.Qt.KeypadModifier))
def _IsWindow(self, obj):
if isinstance(obj, QtWidgets.QWidget):
return obj.isWindow()
else:
return isinstance(obj, QtGui.QWindow)
def TopLevelWindow(self, obj):
parent = obj.parent()
return obj if (self._IsWindow(obj) or not parent) else self.TopLevelWindow(parent)
def WantsNavKeys(self, w):
if not w or self._IsWindow(w):
return False
# The broader test would be QtWidgets.QAbstractItemView,
# but pragmatically, the TableViews in usdview don't really
# benefit much from keyboard navigation, and we'd rather
# allow the arrow keys drive the playhead when such widgets would
# otherwise get focus
elif isinstance(w, QtWidgets.QTreeView):
return True
else:
return self.WantsNavKeys(w.parent())
def NavigableOrTopLevelObject(self, w):
if (not w or
self._IsWindow(w) or
isinstance(w, QtWidgets.QTreeView) or
isinstance(w, QtWidgets.QDialog)):
return w
else:
parent = w.parent()
return w if not parent else self.NavigableOrTopLevelObject(parent)
def JealousFocus(self, w):
return (isinstance(w, QtWidgets.QLineEdit) or
isinstance(w, QtWidgets.QComboBox) or
isinstance(w, QtWidgets.QTextEdit) or
isinstance(w, QtWidgets.QAbstractSlider) or
isinstance(w, QtWidgets.QAbstractSpinBox) or
isinstance(w, QtWidgets.QWidget) and w.windowModality() in [QtCore.Qt.WindowModal,
QtCore.Qt.ApplicationModal])
def SetFocusFromMousePos(self, backupWidget):
# It's possible the mouse isn't over any of our windows at the time,
# in which case use the top-level window of backupWidget.
overObject = QtWidgets.QApplication.widgetAt(QtGui.QCursor.pos())
topLevelObject = self.NavigableOrTopLevelObject(overObject)
focusObject = topLevelObject if topLevelObject else self.TopLevelWindow(backupWidget)
if focusObject and isinstance(focusObject, QtWidgets.QWidget):
focusObject.setFocus()
def eventFilter(self, widget, event):
# There is currently no filtering we want to do for modal or popups
if (QtWidgets.QApplication.activeModalWidget() or
QtWidgets.QApplication.activePopupWidget()):
return False
currFocusWidget = QtWidgets.QApplication.focusWidget()
if event.type() == QtCore.QEvent.KeyPress:
key = event.key()
isNavKey = self.IsNavKey(key, event.modifiers())
if key == QtCore.Qt.Key_Escape:
# ESC resets focus based on mouse position, regardless of
# who currently holds focus
self.SetFocusFromMousePos(widget)
return True
elif currFocusWidget and self.JealousFocus(currFocusWidget):
# Don't touch if there's a greedy focus widget
return False
elif (isNavKey and self.WantsNavKeys(currFocusWidget)):
# Special handling for navigation keys:
# 1. When a "navigable" widget is focussed (a TreeView),
# route arrow keys to the widget and consume them
# 2. To make for snappier navigation, when the TreeView
# won't accept a left/right because an item is already
# opened or closed, turn it into an up/down event. It
# WBN if this behavior could be part of the widgets
# themselves, but currently, usdview does not specialize
# a class for its TreeView widgets.
event.setAccepted(False)
currFocusWidget.event(event)
accepted = event.isAccepted()
if (not accepted and
key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right)):
advance = (key == QtCore.Qt.Key_Right)
altNavKey = QtCore.Qt.Key_Down if advance else QtCore.Qt.Key_Up
subEvent = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
altNavKey,
event.modifiers())
QtWidgets.QApplication.postEvent(currFocusWidget, subEvent)
event.setAccepted(True)
return True
elif isNavKey:
if self._appController.processNavKeyEvent(event):
return True
elif (event.type() == QtCore.QEvent.MouseMove and
not self.JealousFocus(currFocusWidget)):
self.SetFocusFromMousePos(widget)
# Note we do not consume the event!
# During startup, Qt seems to queue up events on objects that may
# have disappeared by the time the eventFilter is called upon. This
# is true regardless of how late we install the eventFilter, and
# whether we process pending events before installing. So we
# silently ignore Runtime errors that occur as a result.
try:
return QtCore.QObject.eventFilter(self, widget, event)
except RuntimeError:
return True
Binary file not shown.
@@ -0,0 +1,245 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
def _GetLengthOfRange(start, stop, step):
if step == 0:
return 0
k = 1 if step > 0 else -1
num = 1 + (stop - k - start) // step
# note, sign(stop - start) != sign(step) when we have an empty range. In those
# cases, "num" ends up non-positive, so we can just take the max(num, 0)
return max(0, num)
class _ArrayAttributeModel(QtCore.QAbstractListModel):
'''This is a data model that represents a slice into some array data.
'''
RawDataRole = QtCore.Qt.UserRole + 0
def __init__(self):
super(_ArrayAttributeModel, self).__init__()
self._arrayData = None
self._scalarTypeName = ""
self._slice = slice(None)
self._fetchMoreTimer = QtCore.QTimer()
self._fetchMoreTimer.setInterval(1000)
self._fetchMoreTimer.timeout.connect(self.TryToFetchMore)
self._fetchMoreTimer.start()
self._rowCount = 0
self._publishedRows = 0
def SetArrayDataAndTypeName(self, arrayData, scalarTypeName):
self._arrayData = arrayData
self._scalarTypeName = scalarTypeName
self._Reset()
def SetSlice(self, slice_):
if self._slice == slice_:
return
self._slice = slice_
self._Reset()
def _Reset(self):
self._publishedRows = 0
self._rowCount = 0
if self._arrayData is not None:
self._rowCount = _GetLengthOfRange(*self._slice.indices(len(self._arrayData)))
self.modelReset.emit()
def GetArrayData(self):
return self._arrayData
def GetScalarTypeName(self):
return self._scalarTypeName
def index(self, row, col, parent=QtCore.QModelIndex()):
return self.createIndex(row, col)
def parent(self, index):
return QtCore.QModelIndex()
def rowCount(self, parent=QtCore.QModelIndex()):
if not parent.isValid():
return self._publishedRows
return 0
def columnCount(self, parent=QtCore.QModelIndex()):
return 1
def data(self, index, role=QtCore.Qt.DisplayRole):
start, _, step = self._slice.indices(len(self._arrayData))
idx = start + index.row() * step
dataVal = self._arrayData[idx]
if role == QtCore.Qt.DisplayRole:
from .scalarTypes import ToString
return str(idx) + ": " + ToString(
dataVal, self._scalarTypeName)
elif role == _ArrayAttributeModel.RawDataRole:
return dataVal
return None
def fetchMore(self, index):
left = self._rowCount - self._publishedRows
toFetch = min(5000 if self._publishedRows == 0 else 100, left)
self.beginInsertRows(
index, self._publishedRows, self._publishedRows + toFetch - 1)
self._publishedRows += toFetch
self.endInsertRows()
def canFetchMore(self, index):
return self._publishedRows < self._rowCount
def TryToFetchMore(self):
rootIndex = QtCore.QModelIndex()
if self.canFetchMore(rootIndex):
self.fetchMore(rootIndex)
class ArrayAttributeView(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ArrayAttributeView, self).__init__(parent)
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
sliceLayout = QtWidgets.QHBoxLayout()
layout.addLayout(sliceLayout)
sliceLayout.addWidget(QtWidgets.QLabel("Slice:"))
self._lineEdit = _SliceLineEdit()
self._lineEdit.setPlaceholderText('e.g.: "0:5000", "::-1"')
sliceLayout.addWidget(self._lineEdit)
self._arrayAttrModel = _ArrayAttributeModel()
self._listView = QtWidgets.QListView()
self._listView.setUniformItemSizes(True)
self._listView.setViewMode(QtWidgets.QListView.ListMode)
self._listView.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self._listView.setModel(self._arrayAttrModel)
layout.addWidget(self._listView)
self._lineEdit.SliceChanged.connect(self._arrayAttrModel.SetSlice)
self._SetupContextMenu()
def SetAttribute(self, attr, frame):
from .scalarTypes import GetScalarTypeFromAttr
arrayData = attr.Get(frame)
scalarTypeName, _ = GetScalarTypeFromAttr(attr)
self._arrayAttrModel.SetArrayDataAndTypeName(arrayData, scalarTypeName)
def CanView(self, attr):
return attr.GetTypeName().isArray
def keyPressEvent(self, e):
# XXX note, this is extremely finicky. it does not really
# have keyboard focus.
if e.matches(QtGui.QKeySequence.Copy):
self.Copy()
else:
return super(ArrayAttributeView, self).keyPressEvent(e)
# context menu stuff
def _SetupContextMenu(self):
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self._ShowContextMenu)
def _ShowContextMenu(self, point):
menu = QtWidgets.QMenu(self)
if self._listView.selectedIndexes():
menu.addAction("Copy Selected", self.CopySelected)
else:
menu.addAction("Copy All", self.CopyAll)
menu.addAction("Select All", self.SelectAll)
menu.exec_(QtGui.QCursor.pos())
def CopyAll(self):
self._CopyValsToClipboard(self._arrayAttrModel.GetArrayData())
def CopySelected(self):
selectedIndexes = self._listView.selectedIndexes()
self._CopyValsToClipboard([
self._listView.model().data(idx, _ArrayAttributeModel.RawDataRole)
for idx in selectedIndexes])
def _CopyValsToClipboard(self, vals):
from .scalarTypes import ToClipboard
scalarTypeName = self._arrayAttrModel.GetScalarTypeName()
copyText = "[ %s ]" % (", ".join(
ToClipboard(val, scalarTypeName)
for val in vals))
QtWidgets.QApplication.clipboard().setText(copyText)
def SelectAll(self):
self._listView.selectAll()
def _IntOrNone(s):
if not s:
return None
return int(s)
def _GetSliceFromString(s):
s = slice(*map(_IntOrNone, s.split(':')))
if s.step == 0:
raise ValueError("Slice cannot be 0")
return s
class _SliceLineEdit(QtWidgets.QLineEdit):
"""LineEdit for inputing strings that represent slices"""
SliceChanged = QtCore.Signal(object)
def __init__(self, parent=None):
super(_SliceLineEdit, self).__init__(parent)
self.setValidator(_SliceLineEdit.Validator())
self.editingFinished.connect(self._OnEditingFinished)
class Validator(QtGui.QValidator):
def validate(self, s, pos):
s = s.strip()
try:
_GetSliceFromString(s)
return (QtGui.QValidator.Acceptable, s, pos)
except:
return (QtGui.QValidator.Intermediate, s, pos)
def setText(self, t):
super(_SliceLineEdit, self).setText(t)
self._OnEditingFinished()
def _OnEditingFinished(self):
self.SliceChanged.emit(_GetSliceFromString(self.text()))
Binary file not shown.
@@ -0,0 +1,129 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Usd
from .qt import QtCore, QtWidgets
from .attributeValueEditorUI import Ui_AttributeValueEditor
from .common import GetPropertyColor, UIPropertyValueSourceColors
from .scalarTypes import ToString
# This is the widget that appears when selecting an attribute and
# opening the "Value" tab.
class AttributeValueEditor(QtWidgets.QWidget):
editComplete = QtCore.Signal('QString')
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self._ui = Ui_AttributeValueEditor()
self._ui.setupUi(self)
self._defaultView = self._ui.valueViewer
from .arrayAttributeView import ArrayAttributeView
self._extraAttrViews = [
ArrayAttributeView(self),
]
for attrView in self._extraAttrViews:
self._ui.stackedWidget.addWidget(attrView)
self.clear()
def setAppController(self, appController):
# pass the appController instance from which to retrieve
# variable data.
self._appController = appController
def populate(self, primPath, propName):
# called when the selected attribute has changed
self._primPath = primPath
try:
self._attribute = self._appController._propertiesDict[propName]
except KeyError:
self._attribute = None
self._isSet = True # an attribute is selected
self.refresh() # load the value at the current frame
def _FindView(self, attr):
# Early-out for CustomAttributes and Relationships
if not isinstance(attr, Usd.Attribute):
return None
for attrView in self._extraAttrViews:
if attrView.CanView(attr):
return attrView
return None
def refresh(self):
# usually called upon frame change or selected attribute change
if not self._isSet:
return
# attribute connections and relationship targets have no value to display
# in the value viewer.
if self._attribute is None:
return
# If the current attribute doesn't belong to the current prim, don't
# display its value.
if self._attribute.GetPrimPath() != self._primPath:
self._ui.valueViewer.setText("")
return
frame = self._appController._dataModel.currentFrame
# get the value of the attribute
if isinstance(self._attribute, Usd.Relationship):
self._val = self._attribute.GetTargets()
else: # Usd.Attribute or CustomAttribute
self._val = self._attribute.Get(frame)
whichView = self._FindView(self._attribute)
if whichView:
self._ui.stackedWidget.setCurrentWidget(whichView)
whichView.SetAttribute(self._attribute, frame)
else:
self._ui.stackedWidget.setCurrentWidget(self._defaultView)
txtColor = GetPropertyColor(self._attribute, frame)
# set text and color in the value viewer
self._ui.valueViewer.setTextColor(txtColor)
if isinstance(self._attribute, Usd.Relationship):
typeName = None
else:
typeName = self._attribute.GetTypeName()
rowText = ToString(self._val, typeName)
self._ui.valueViewer.setText(rowText)
def clear(self):
# set the value editor to 'no attribute selected' mode
self._isSet = False
self._ui.valueViewer.setText("")
# make sure we're showing the default view
self._ui.stackedWidget.setCurrentWidget(self._defaultView)
Binary file not shown.
@@ -0,0 +1,69 @@
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'attributeValueEditorUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_AttributeValueEditor(object):
def setupUi(self, AttributeValueEditor):
if not AttributeValueEditor.objectName():
AttributeValueEditor.setObjectName(u"AttributeValueEditor")
AttributeValueEditor.resize(400, 300)
self.verticalLayout = QVBoxLayout(AttributeValueEditor)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName(u"verticalLayout")
self.stackedWidget = QStackedWidget(AttributeValueEditor)
self.stackedWidget.setObjectName(u"stackedWidget")
self.stackedWidget.setLineWidth(0)
self.valueViewer = QTextBrowser()
self.valueViewer.setObjectName(u"valueViewer")
self.stackedWidget.addWidget(self.valueViewer)
self.verticalLayout.addWidget(self.stackedWidget)
self.retranslateUi(AttributeValueEditor)
self.stackedWidget.setCurrentIndex(0)
QMetaObject.connectSlotsByName(AttributeValueEditor)
# setupUi
def retranslateUi(self, AttributeValueEditor):
AttributeValueEditor.setWindowTitle(QCoreApplication.translate("AttributeValueEditor", u"Form", None))
AttributeValueEditor.setProperty("comment", QCoreApplication.translate("AttributeValueEditor", u"\n"
" Copyright 2016 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
# retranslateUi
@@ -0,0 +1,264 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtGui, QtWidgets, QtCore
from pxr import Sdf
from .usdviewContextMenuItem import UsdviewContextMenuItem
from .common import (PropertyViewIndex, PropertyViewDataRoles,
PrimNotFoundException, PropertyNotFoundException)
#
# Specialized context menu for running commands in the attribute viewer.
#
class AttributeViewContextMenu(QtWidgets.QMenu):
def __init__(self, parent, item, dataModel):
QtWidgets.QMenu.__init__(self, parent)
self._menuItems = _GetContextMenuItems(item, dataModel)
for menuItem in self._menuItems:
# create menu actions
if menuItem.isValid() and menuItem.ShouldDisplay():
action = self.addAction(menuItem.GetText(), menuItem.RunCommand)
# set enabled
if not menuItem.IsEnabled():
action.setEnabled(False)
def _GetContextMenuItems(item, dataModel):
return [ # Root selection methods
CopyAttributeNameMenuItem(dataModel, item),
CopyAttributeValueMenuItem(dataModel, item),
CopyAllTargetPathsMenuItem(dataModel, item),
SelectAllTargetPathsMenuItem(dataModel, item),
# Individual/multi target selection menus
CopyTargetPathMenuItem(dataModel, item),
SelectTargetPathMenuItem(dataModel, item)]
def _selectPrimsAndProps(dataModel, paths):
prims = []
props = []
for path in paths:
primPath = path.GetAbsoluteRootOrPrimPath()
prim = dataModel.stage.GetPrimAtPath(primPath)
if not prim:
raise PrimNotFoundException(primPath)
prims.append(prim)
if path.IsPropertyPath():
prop = prim.GetProperty(path.name)
if not prop:
raise PropertyNotFoundException(path)
props.append(prop)
with dataModel.selection.batchPrimChanges:
dataModel.selection.clearPrims()
for prim in prims:
dataModel.selection.addPrim(prim)
with dataModel.selection.batchPropChanges:
dataModel.selection.clearProps()
for prop in props:
dataModel.selection.addProp(prop)
dataModel.selection.clearComputedProps()
#
# The base class for propertyview context menu items.
#
class AttributeViewContextMenuItem(UsdviewContextMenuItem):
def __init__(self, dataModel, item):
self._dataModel = dataModel
self._item = item
self._role = self._item.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
self._name = self._item.text(PropertyViewIndex.NAME) if self._item else ""
self._value = self._item.text(PropertyViewIndex.VALUE) if self._item else ""
def IsEnabled(self):
return True
def ShouldDisplay(self):
return True
def GetText(self):
return ""
def RunCommand(self):
pass
#
# Copy the attribute's name to clipboard.
#
class CopyAttributeNameMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return self._role not in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)
def GetText(self):
return "Copy Property Name"
def RunCommand(self):
if self._name == "":
return
cb = QtWidgets.QApplication.clipboard()
cb.setText(self._name, QtGui.QClipboard.Selection)
cb.setText(self._name, QtGui.QClipboard.Clipboard)
#
# Copy the attribute's value to clipboard.
#
class CopyAttributeValueMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return self._role not in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)
def GetText(self):
return "Copy Property Value"
def RunCommand(self):
# We display relationships targets as:
# /f, /g/a ...
# But when we ask to copy the value, we'd like to get back:
# [Sdf.Path('/f'), Sdf.Path('/g/a')]
# Which is useful for pasting into a python interpreter.
if self._role == PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS:
valueStr = str([Sdf.Path("".join(p.split())) \
for p in self._value.split(",")])
else:
valueStr = self._value
if self._item:
rawVal = self._item.rawValue
if rawVal is not None:
valueStr = str(rawVal)
cb = QtWidgets.QApplication.clipboard()
cb.setText(valueStr, QtGui.QClipboard.Selection)
cb.setText(valueStr, QtGui.QClipboard.Clipboard)
# --------------------------------------------------------------------
# Individual target selection menus
# --------------------------------------------------------------------
#
# Copy the target path to clipboard.
#
class CopyTargetPathMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return self._role in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)
def GetText(self):
return "Copy Target Path As Text"
def GetSelectedOfType(self):
getRole = lambda s: s.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
return [s for s in self._item.treeWidget().selectedItems() \
if getRole(s) in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)]
def RunCommand(self):
if not self._item:
return
value = ", ".join([s.text(PropertyViewIndex.NAME) for s in self.GetSelectedOfType()])
cb = QtWidgets.QApplication.clipboard()
cb.setText(value, QtGui.QClipboard.Selection)
cb.setText(value, QtGui.QClipboard.Clipboard)
#
# Jump to the target path in the prim browser
# This will include all other highlighted paths of this type, if any.
#
class SelectTargetPathMenuItem(CopyTargetPathMenuItem):
def GetText(self):
return "Select Target Path"
def RunCommand(self):
paths = [Sdf.Path(s.text(PropertyViewIndex.NAME))
for s in self.GetSelectedOfType()]
_selectPrimsAndProps(self._dataModel, paths)
# --------------------------------------------------------------------
# Target owning property selection menus
# --------------------------------------------------------------------
def _GetTargetPathsForItem(item):
paths = [Sdf.Path(item.child(i).text(PropertyViewIndex.NAME)) for
i in range (0, item.childCount())]
# If there are no children, the value column must hold a valid path
# (since the command is enabled).
if len(paths) == 0:
itemText = item.text(PropertyViewIndex.VALUE)
if len(itemText) > 0:
paths.append(Sdf.Path(itemText))
return paths
#
# Select all target paths under the selected attribute
#
class SelectAllTargetPathsMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return (self._role == PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS
or self._role == PropertyViewDataRoles.ATTRIBUTE_WITH_CONNNECTIONS)
def IsEnabled(self):
if not self._item:
return False
# Enable the menu item if there are one or more targets for this
# rel/attribute connection
if self._item.childCount() > 0:
return True
# Enable the menu if the item holds a valid SdfPath.
itemText = self._item.text(2)
return Sdf.Path.IsValidPathString(itemText)
def GetText(self):
return "Select Target Path(s)"
def RunCommand(self):
if not self._item:
return
_selectPrimsAndProps(self._dataModel,
_GetTargetPathsForItem(self._item))
#
# Copy all target paths under the currently selected relationship to the clipboard
#
class CopyAllTargetPathsMenuItem(SelectAllTargetPathsMenuItem):
def GetText(self):
return "Copy Target Path(s) As Text"
def RunCommand(self):
if not self._item:
return
value = ", ".join(_GetTargetPathsForItem(self._item))
cb = QtWidgets.QApplication.clipboard()
cb.setText(value, QtGui.QClipboard.Selection)
cb.setText(value, QtGui.QClipboard.Clipboard)
Binary file not shown.
+694
View File
@@ -0,0 +1,694 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from .qt import QtCore, QtGui, QtWidgets
import os, time, sys, platform, math
from pxr import Ar, Tf, Sdf, Kind, Usd, UsdGeom, UsdShade
from .customAttributes import CustomAttribute
from pxr.UsdUtils.constantsGroup import ConstantsGroup
DEBUG_CLIPPING = "USDVIEWQ_DEBUG_CLIPPING"
class ClearColors(ConstantsGroup):
"""Names of available background colors."""
BLACK = "Black"
DARK_GREY = "Grey (Dark)"
LIGHT_GREY = "Grey (Light)"
WHITE = "White"
class DefaultFontFamily(ConstantsGroup):
"""Names of the default font family and monospace font family to be used
with usdview"""
FONT_FAMILY = "Roboto"
MONOSPACE_FONT_FAMILY = "Roboto Mono"
class HighlightColors(ConstantsGroup):
"""Names of available highlight colors for selected objects."""
WHITE = "White"
YELLOW = "Yellow"
CYAN = "Cyan"
class UIBaseColors(ConstantsGroup):
RED = QtGui.QBrush(QtGui.QColor(230, 132, 131))
LIGHT_SKY_BLUE = QtGui.QBrush(QtGui.QColor(135, 206, 250))
DARK_YELLOW = QtGui.QBrush(QtGui.QColor(222, 158, 46))
class UIPrimTypeColors(ConstantsGroup):
HAS_ARCS = UIBaseColors.DARK_YELLOW
NORMAL = QtGui.QBrush(QtGui.QColor(227, 227, 227))
INSTANCE = UIBaseColors.LIGHT_SKY_BLUE
PROTOTYPE = QtGui.QBrush(QtGui.QColor(118, 136, 217))
class UIPrimTreeColors(ConstantsGroup):
SELECTED = QtGui.QBrush(QtGui.QColor(189, 155, 84))
SELECTED_HOVER = QtGui.QBrush(QtGui.QColor(227, 186, 101))
ANCESTOR_OF_SELECTED = QtGui.QBrush(QtGui.QColor(189, 155, 84, 50))
ANCESTOR_OF_SELECTED_HOVER = QtGui.QBrush(QtGui.QColor(189, 155, 84, 100))
UNSELECTED_HOVER = QtGui.QBrush(QtGui.QColor(70, 70, 70))
class UIPropertyValueSourceColors(ConstantsGroup):
FALLBACK = UIBaseColors.DARK_YELLOW
TIME_SAMPLE = QtGui.QBrush(QtGui.QColor(177, 207, 153))
DEFAULT = UIBaseColors.LIGHT_SKY_BLUE
NONE = QtGui.QBrush(QtGui.QColor(140, 140, 140))
VALUE_CLIPS = QtGui.QBrush(QtGui.QColor(230, 150, 230))
class UIFonts(ConstantsGroup):
# Font constants. We use font in the prim browser to distinguish
# "resolved" prim specifier
# XXX - the use of weight here may need to be revised depending on font family
BASE_POINT_SIZE = 10
ITALIC = QtGui.QFont()
ITALIC.setWeight(QtGui.QFont.Light)
ITALIC.setItalic(True)
NORMAL = QtGui.QFont()
NORMAL.setWeight(QtGui.QFont.Normal)
BOLD = QtGui.QFont()
BOLD.setWeight(QtGui.QFont.Bold)
BOLD_ITALIC = QtGui.QFont()
BOLD_ITALIC.setWeight(QtGui.QFont.Bold)
BOLD_ITALIC.setItalic(True)
OVER_PRIM = ITALIC
DEFINED_PRIM = BOLD
ABSTRACT_PRIM = NORMAL
INHERITED = QtGui.QFont()
INHERITED.setPointSize(BASE_POINT_SIZE * 0.8)
INHERITED.setWeight(QtGui.QFont.Normal)
INHERITED.setItalic(True)
class KeyboardShortcuts(ConstantsGroup):
FramingKey = QtCore.Qt.Key_F
class PropertyViewIndex(ConstantsGroup):
TYPE, NAME, VALUE = range(3)
ICON_DIR_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'icons')
# We use deferred loading because icons can't be constructed before
# application initialization time.
_icons = {}
def _DeferredIconLoad(path):
fullPath = os.path.join(ICON_DIR_ROOT, path)
try:
icon = _icons[fullPath]
except KeyError:
icon = QtGui.QIcon(fullPath)
_icons[fullPath] = icon
return icon
class PropertyViewIcons(ConstantsGroup):
ATTRIBUTE = lambda: _DeferredIconLoad('usd-attr-plain-icon.png')
ATTRIBUTE_WITH_CONNECTIONS = lambda: _DeferredIconLoad('usd-attr-with-conn-icon.png')
RELATIONSHIP = lambda: _DeferredIconLoad('usd-rel-plain-icon.png')
RELATIONSHIP_WITH_TARGETS = lambda: _DeferredIconLoad('usd-rel-with-target-icon.png')
TARGET = lambda: _DeferredIconLoad('usd-target-icon.png')
CONNECTION = lambda: _DeferredIconLoad('usd-conn-icon.png')
COMPOSED = lambda: _DeferredIconLoad('usd-cmp-icon.png')
class PropertyViewDataRoles(ConstantsGroup):
ATTRIBUTE = "Attr"
RELATIONSHIP = "Rel"
ATTRIBUTE_WITH_CONNNECTIONS = "Attr_"
RELATIONSHIP_WITH_TARGETS = "Rel_"
TARGET = "Tgt"
CONNECTION = "Conn"
COMPOSED = "Cmp"
class RenderModes(ConstantsGroup):
# Render modes
WIREFRAME = "Wireframe"
WIREFRAME_ON_SURFACE = "WireframeOnSurface"
SMOOTH_SHADED = "Smooth Shaded"
FLAT_SHADED = "Flat Shaded"
POINTS = "Points"
GEOM_ONLY = "Geom Only"
GEOM_FLAT = "Geom Flat"
GEOM_SMOOTH = "Geom Smooth"
HIDDEN_SURFACE_WIREFRAME = "Hidden Surface Wireframe"
class ShadedRenderModes(ConstantsGroup):
# Render modes which use shading
SMOOTH_SHADED = RenderModes.SMOOTH_SHADED
FLAT_SHADED = RenderModes.FLAT_SHADED
WIREFRAME_ON_SURFACE = RenderModes.WIREFRAME_ON_SURFACE
GEOM_FLAT = RenderModes.GEOM_FLAT
GEOM_SMOOTH = RenderModes.GEOM_SMOOTH
class ColorCorrectionModes(ConstantsGroup):
# Color correction used when render is presented to screen
# These strings should match HdxColorCorrectionTokens
DISABLED = "disabled"
SRGB = "sRGB"
OPENCOLORIO = "openColorIO"
class PickModes(ConstantsGroup):
# Pick modes
PRIMS = "Prims"
MODELS = "Models"
INSTANCES = "Instances"
PROTOTYPES = "Prototypes"
class SelectionHighlightModes(ConstantsGroup):
# Selection highlight modes
NEVER = "Never"
ONLY_WHEN_PAUSED = "Only when paused"
ALWAYS = "Always"
class CameraMaskModes(ConstantsGroup):
NONE = "none"
PARTIAL = "partial"
FULL = "full"
class IncludedPurposes(ConstantsGroup):
DEFAULT = UsdGeom.Tokens.default_
PROXY = UsdGeom.Tokens.proxy
GUIDE = UsdGeom.Tokens.guide
RENDER = UsdGeom.Tokens.render
def _PropTreeWidgetGetRole(tw):
return tw.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
def PropTreeWidgetTypeIsRel(tw):
role = _PropTreeWidgetGetRole(tw)
return role in (PropertyViewDataRoles.RELATIONSHIP,
PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS)
def _UpdateLabelText(text, substring, mode):
return text.replace(substring, '<'+mode+'>'+substring+'</'+mode+'>')
def ItalicizeLabelText(text, substring):
return _UpdateLabelText(text, substring, 'i')
def BoldenLabelText(text, substring):
return _UpdateLabelText(text, substring, 'b')
def ColorizeLabelText(text, substring, r, g, b):
return _UpdateLabelText(text, substring,
"span style=\"color:rgb(%d, %d, %d);\"" % (r, g, b))
def PrintWarning(title, description):
msg = sys.stderr
print("------------------------------------------------------------", file=msg)
print("WARNING: %s" % title, file=msg)
print(description, file=msg)
print("------------------------------------------------------------", file=msg)
def GetValueAndDisplayString(prop, time):
"""If `prop` is a timeSampled Sdf.AttributeSpec, compute a string specifying
how many timeSamples it possesses. Otherwise, compute the single default
value, or targets for a relationship, or value at 'time' for a
Usd.Attribute. Return a tuple of a parameterless function that returns the
resolved value at 'time', and the computed brief string for display. We
return a value-producing function rather than the value itself because for
an Sdf.AttributeSpec with multiple timeSamples, the resolved value is
*all* of the timeSamples, which can be expensive to compute, and is
rarely needed.
"""
def _ValAndStr(val):
return (lambda: val, GetShortStringForValue(prop, val))
if isinstance(prop, Usd.Relationship):
return _ValAndStr(prop.GetTargets())
elif isinstance(prop, (Usd.Attribute, CustomAttribute)):
return _ValAndStr(prop.Get(time))
elif isinstance(prop, Sdf.AttributeSpec):
if time == Usd.TimeCode.Default():
return _ValAndStr(prop.default)
else:
numTimeSamples = prop.layer.GetNumTimeSamplesForPath(prop.path)
if numTimeSamples == 0:
return _ValAndStr(prop.default)
else:
def _GetAllTimeSamples(attrSpec):
l = attrSpec.layer
p = attrSpec.path
ordinates = l.ListTimeSamplesForPath(p)
return [(o, l.QueryTimeSample(p, o)) for o in ordinates]
if numTimeSamples == 1:
valStr = "1 time sample"
else:
valStr = str(numTimeSamples) + " time samples"
return (lambda prop=prop: _GetAllTimeSamples(prop), valStr)
elif isinstance(prop, Sdf.RelationshipSpec):
return _ValAndStr(prop.targetPathList)
return (lambda: None, "unrecognized property type")
def GetShortStringForValue(prop, val):
if isinstance(prop, Usd.Relationship):
val = ", ".join(str(p) for p in val)
elif isinstance(prop, Sdf.RelationshipSpec):
return str(prop.targetPathList)
# If there is no value opinion, we do not want to display anything,
# since python 'None' has a different meaning than usda-authored None,
# which is how we encode attribute value blocks (which evaluate to
# Sdf.ValueBlock)
if val is None:
return ''
from .scalarTypes import GetScalarTypeFromAttr
scalarType, isArray = GetScalarTypeFromAttr(prop)
result = ''
if isArray and not isinstance(val, Sdf.ValueBlock):
def arrayToStr(a):
from itertools import chain
elems = a if len(a) <= 6 else chain(a[:3], ['...'], a[-3:])
return '[' + ', '.join(map(str, elems)) + ']'
if val is not None and len(val):
result = "%s[%d]: %s" % (scalarType, len(val), arrayToStr(val))
else:
result = "%s[]" % scalarType
else:
result = str(val)
return result[:500]
# Return a string that reports size in metric units (units of 1000, not 1024).
def ReportMetricSize(sizeInBytes):
if sizeInBytes == 0:
return "0 B"
sizeSuffixes = ("B", "KB", "MB", "GB", "TB", "PB", "EB")
i = int(math.floor(math.log(sizeInBytes, 1000)))
if i >= len(sizeSuffixes):
i = len(sizeSuffixes) - 1
p = math.pow(1000, i)
s = round(sizeInBytes / p, 2)
return "%s %s" % (s, sizeSuffixes[i])
# Return attribute status at a certian frame (is it using the default, or the
# fallback? Is it authored at this frame? etc.
def _GetAttributeStatus(attribute, frame):
return attribute.GetResolveInfo(frame).GetSource()
# Return a Font corresponding to certain attribute properties.
# Currently this only applies italicization on interpolated time samples.
def GetPropertyTextFont(prop, frame):
if not isinstance(prop, Usd.Attribute):
# Early-out for non-attribute properties.
return None
frameVal = frame.GetValue()
bracketing = prop.GetBracketingTimeSamples(frameVal)
# Note that some attributes return an empty tuple, some None, from
# GetBracketingTimeSamples(), but all will be fed into this function.
if bracketing and (len(bracketing) == 2) and (bracketing[0] != frameVal):
return UIFonts.ITALIC
return None
# Helper function that takes attribute status and returns the display color
def GetPropertyColor(prop, frame, hasValue=None, hasAuthoredValue=None,
valueIsDefault=None):
if not isinstance(prop, Usd.Attribute):
# Early-out for non-attribute properties.
return UIBaseColors.RED.color()
statusToColor = {Usd.ResolveInfoSourceFallback : UIPropertyValueSourceColors.FALLBACK,
Usd.ResolveInfoSourceDefault : UIPropertyValueSourceColors.DEFAULT,
Usd.ResolveInfoSourceValueClips : UIPropertyValueSourceColors.VALUE_CLIPS,
Usd.ResolveInfoSourceTimeSamples: UIPropertyValueSourceColors.TIME_SAMPLE,
Usd.ResolveInfoSourceNone : UIPropertyValueSourceColors.NONE}
valueSource = _GetAttributeStatus(prop, frame)
return statusToColor[valueSource].color()
# Gathers information about a layer used as a subLayer, including its
# position in the layerStack hierarchy.
class SubLayerInfo(object):
def __init__(self, sublayer, offset, containingLayer, prefix):
self.layer = sublayer
self.offset = offset
self.parentLayer = containingLayer
self._prefix = prefix
def GetOffsetString(self):
o = self.offset.offset
s = self.offset.scale
if o == 0:
if s == 1:
return ""
else:
return str.format("(scale = {})", s)
elif s == 1:
return str.format("(offset = {})", o)
else:
return str.format("(offset = {0}; scale = {1})", o, s)
def GetHierarchicalDisplayString(self):
return self._prefix + self.layer.GetDisplayName()
def _AddSubLayers(layer, layerOffset, prefix, parentLayer, layers):
offsets = layer.subLayerOffsets
layers.append(SubLayerInfo(layer, layerOffset, parentLayer, prefix))
for i, l in enumerate(layer.subLayerPaths):
offset = offsets[i] if offsets is not None and len(offsets) > i else Sdf.LayerOffset()
subLayer = Sdf.Layer.FindRelativeToLayer(layer, l)
# Due to an unfortunate behavior of the Pixar studio resolver,
# FindRelativeToLayer() may fail to resolve certain paths. We will
# remove this extra Find() call as soon as we can retire the behavior;
# in the meantime, the extra call does not hurt (but should not, in
# general, be necessary)
if not subLayer:
subLayer = Sdf.Layer.Find(l)
if subLayer:
# This gives a 'tree'-ish presentation, but it looks sad in
# a QTableWidget. Just use spaces for now
# addedPrefix = "|-- " if parentLayer is None else "| "
addedPrefix = " "
_AddSubLayers(subLayer, offset, addedPrefix + prefix, layer, layers)
else:
print("Could not find layer " + l)
def GetRootLayerStackInfo(layer):
layers = []
_AddSubLayers(layer, Sdf.LayerOffset(), "", None, layers)
return layers
def PrettyFormatSize(sz):
k = 1024
meg = k * 1024
gig = meg * 1024
ter = gig * 1024
sz = float(sz)
if sz > ter:
return "%.1fT" % (sz/float(ter))
elif sz > gig:
return "%.1fG" % (sz/float(gig))
elif sz > meg:
return "%.1fM" % (sz/float(meg))
elif sz > k:
return "%.1fK" % (sz/float(k))
else:
return "%db" % sz
class Timer(object):
"""Use as a context object with python's "with" statement, like so:
with Timer() as t:
doSomeStuff()
t.PrintTime("did some stuff")
"""
def __enter__(self):
self._start = time.time()
self.interval = 0
return self
def __exit__(self, *args):
self._end = time.time()
self.interval = self._end - self._start
def PrintTime(self, action):
print("Time to %s: %2.3fs" % (action, self.interval))
class BusyContext(object):
"""When used as a context object with python's "with" statement,
will set Qt's busy cursor upon entry and pop it on exit.
"""
def __enter__(self):
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
def __exit__(self, *args):
QtWidgets.QApplication.restoreOverrideCursor()
def InvisRootPrims(stage):
"""Make all defined root prims of stage be invisible,
at Usd.TimeCode.Default()"""
for p in stage.GetPseudoRoot().GetChildren():
UsdGeom.Imageable(p).MakeInvisible()
def _RemoveVisibilityRecursive(primSpec):
try:
primSpec.RemoveProperty(primSpec.attributes[UsdGeom.Tokens.visibility])
except IndexError:
pass
for child in primSpec.nameChildren:
_RemoveVisibilityRecursive(child)
def ResetSessionVisibility(stage):
session = stage.GetSessionLayer()
with Sdf.ChangeBlock():
_RemoveVisibilityRecursive(session.pseudoRoot)
# This is unfortunate.. but until UsdAttribute will return you a ResolveInfo,
# we have little alternative, other than manually walking prim's PcpPrimIndex
def HasSessionVis(prim):
"""Is there a session-layer override for visibility for 'prim'?"""
session = prim.GetStage().GetSessionLayer()
primSpec = session.GetPrimAtPath(prim.GetPath())
return bool(primSpec and UsdGeom.Tokens.visibility in primSpec.attributes)
# This should be codified on UsdModelAPI, but maybe after 117137 is addressed...
def GetEnclosingModelPrim(prim):
"""If 'prim' is inside/under a model of any kind, return the closest
such ancestor prim - If 'prim' has no model ancestor, return None"""
if prim:
prim = prim.GetParent()
while prim:
# We use Kind here instead of prim.IsModel because point instancer
# prototypes currently don't register as models in IsModel. See
# bug: http://bugzilla.pixar.com/show_bug.cgi?id=117137
if Kind.Registry.IsA(Usd.ModelAPI(prim).GetKind(), Kind.Tokens.model):
break
prim = prim.GetParent()
return prim
def GetPrimLoadability(prim):
"""Return a tuple of (isLoadable, isLoaded) for 'prim', according to
the following rules:
A prim is loadable if it is active, and either of the following are true:
* prim has a payload
* prim is a model group
The latter is useful because loading is recursive on a UsdStage, and it
is convenient to be able to (e.g.) load everything loadable in a set.
A prim 'isLoaded' only if there are no unloaded prims beneath it, i.e.
it is stating whether the prim is "fully loaded". This
is a debatable definition, but seems useful for usdview's purposes."""
if not (prim.IsActive() and (prim.IsGroup() or prim.HasAuthoredPayloads())):
return (False, True)
# XXX Note that we are potentially traversing the entire stage here.
# If this becomes a performance issue, we can cast this query into C++,
# cache results, etc.
for p in Usd.PrimRange(prim, Usd.PrimIsActive):
if not p.IsLoaded():
return (True, False)
return (True, True)
def GetPrimsLoadability(prims):
"""Follow the logic of GetPrimLoadability for each prim, combining
results so that isLoadable is the disjunction of all prims, and
isLoaded is the conjunction."""
isLoadable = False
isLoaded = True
for prim in prims:
loadable, loaded = GetPrimLoadability(prim)
isLoadable = isLoadable or loadable
isLoaded = isLoaded and loaded
return (isLoadable, isLoaded)
def GetFileOwner(path):
try:
if platform.system() == 'Windows':
# This only works if pywin32 is installed.
# Try "pip install pypiwin32".
import win32security as w32s
fs = w32s.GetFileSecurity(path, w32s.OWNER_SECURITY_INFORMATION)
sdo = fs.GetSecurityDescriptorOwner()
name, domain, use = w32.LookupAccountSid(None, sdo)
return "%s\\%s" % (domain, name)
else:
import pwd
return pwd.getpwuid(os.stat(path).st_uid).pw_name
except:
return "<unknown>"
# In future when we have better introspection abilities in Usd core API,
# we will change this function to accept a prim rather than a primStack.
def GetAssetCreationTime(primStack, assetIdentifier):
"""Finds the weakest layer in which assetInfo.identifier is set to
'assetIdentifier', and considers that an "asset-defining layer". We then
retrieve the creation time for the asset by stat'ing the layer's
real path.
Returns a triple of strings: (fileDisplayName, creationTime, owner)"""
definingLayer = None
for spec in reversed(primStack):
if spec.HasInfo('assetInfo'):
identifier = spec.GetInfo('assetInfo')['identifier']
if identifier.path == assetIdentifier.path:
definingLayer = spec.layer
break
if definingLayer:
definingFile = definingLayer.realPath
else:
definingFile = primStack[-1].layer.realPath
print("Warning: Could not find expected asset-defining layer for %s" %
assetIdentifier)
if Ar.IsPackageRelativePath(definingFile):
definingFile = Ar.SplitPackageRelativePathOuter(definingFile)[0]
if not definingFile:
displayName = (definingLayer.GetDisplayName()
if definingLayer and definingLayer.anonymous else
"<in-memory layer>")
creationTime = "<unknown>"
owner = "<unknown>"
else:
displayName = definingFile.split('/')[-1]
try:
creationTime = time.ctime(os.stat(definingFile).st_ctime)
except:
creationTime = "<unknown>"
owner = GetFileOwner(definingFile)
return (displayName, creationTime, owner)
def DumpMallocTags(stage, contextStr):
if Tf.MallocTag.IsInitialized():
callTree = Tf.MallocTag.GetCallTree()
memInMb = Tf.MallocTag.GetTotalBytes() / (1024.0 * 1024.0)
import os.path as path
import tempfile
layerName = path.basename(stage.GetRootLayer().identifier)
# CallTree.Report() gives us the most informative (and processable)
# form of output, but it only accepts a fileName argument. So we
# use NamedTemporaryFile just to get a filename.
statsFile = tempfile.NamedTemporaryFile(prefix=layerName+'.',
suffix='.mallocTag',
delete=False)
statsFile.close()
reportName = statsFile.name
callTree.Report(reportName)
print("Memory consumption of %s for %s is %d Mb" % (contextStr,
layerName,
memInMb))
print("For detailed analysis, see " + reportName)
else:
print("Unable to accumulate memory usage since the Pxr MallocTag system was not initialized")
def GetInstanceIdForIndex(prim, instanceIndex, time):
'''Attempt to find an authored Id value for the instance at index
'instanceIndex' at time 'time', on the given prim 'prim', which we access
as a UsdGeom.PointInstancer (whether it actually is or not, to provide
some dynamic duck-typing for custom instancer types that support Ids.
Returns 'None' if no ids attribute was found, or if instanceIndex is
outside the bounds of the ids array.'''
if not prim or instanceIndex < 0:
return None
ids = UsdGeom.PointInstancer(prim).GetIdsAttr().Get(time)
if not ids or instanceIndex >= len(ids):
return None
return ids[instanceIndex]
def GetInstanceIndicesForIds(prim, instanceIds, time):
'''Attempt to find the instance indices of a list of authored instance IDs
for prim 'prim' at time 'time'. If the prim is not a PointInstancer or does
not have authored IDs, returns None. If any ID from 'instanceIds' does not
exist at the given time, its index is not added to the list (because it does
not have an index).'''
ids = UsdGeom.PointInstancer(prim).GetIdsAttr().Get(time)
if ids:
return [instanceIndex for instanceIndex, instanceId in enumerate(ids)
if instanceId in instanceIds]
else:
return None
def Drange(start, stop, step):
'''Return a list whose first element is 'start' and the following elements
(if any) are 'start' plus increasing whole multiples of 'step', up to but
not greater than 'stop'. For example:
Drange(1, 3, 0.3) -> [1, 1.3, 1.6, 1.9, 2.2, 2.5, 2.8]'''
lst = [start]
n = 1
while start + n * step <= stop:
lst.append(start + n * step)
n += 1
return lst
class PrimNotFoundException(Exception):
"""Raised when a prim does not exist at a valid path."""
def __init__(self, path):
super(PrimNotFoundException, self).__init__(
"Prim not found at path in stage: %s" % str(path))
class PropertyNotFoundException(Exception):
"""Raised when a property does not exist at a valid path."""
def __init__(self, path):
super(PropertyNotFoundException, self).__init__(
"Property not found at path in stage: %s" % str(path))
class FixableDoubleValidator(QtGui.QDoubleValidator):
"""This class implements a fixup() method for QDoubleValidator
(see method for specific behavior). To work around the brokenness
of Pyside's fixup() wrapping, we allow the validator to directly
update its parent if it is a QLineEdit, from within fixup(). Thus
every QLineEdit must possess its own unique FixableDoubleValidator.
The fixup method we supply (which can be usefully called directly)
applies clamping and rounding to enforce the QDoubleValidator's
range and decimals settings."""
def __init__(self, parent):
super(FixableDoubleValidator, self).__init__(parent)
self._lineEdit = parent if isinstance(parent, QtWidgets.QLineEdit) else None
def fixup(self, valStr):
# We implement this to fulfill the virtual for internal QLineEdit
# behavior, hoping that PySide will do the right thing, but it is
# useless to call from Python directly due to string immutability
try:
val = float(valStr)
val = max(val, self.bottom())
val = min(val, self.top())
val = round(val)
valStr = str(val)
if self._lineEdit:
self._lineEdit.setText(valStr)
except ValueError:
pass
Binary file not shown.
+177
View File
@@ -0,0 +1,177 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Usd, UsdGeom, UsdShade
from pxr.UsdUtils.constantsGroup import ConstantsGroup
class ComputedPropertyNames(ConstantsGroup):
"""Names of all available computed properties."""
WORLD_BBOX = "World Bounding Box"
LOCAL_WORLD_XFORM = "Local to World Xform"
RESOLVED_PREVIEW_MATERIAL = "Resolved Preview Material"
RESOLVED_FULL_MATERIAL = "Resolved Full Material"
#
# Edit the following to alter the set of custom attributes.
#
# Every entry should be an object derived from CustomAttribute,
# defined below.
#
def _GetCustomAttributes(currentPrim, rootDataModel):
currentPrimIsImageable = currentPrim.IsA(UsdGeom.Imageable)
# If the currentPrim is imageable or if it is a typeless def, it
# participates in imageable computations.
currentPrimGetsImageableComputations = currentPrim.IsA(UsdGeom.Imageable) \
or not currentPrim.GetTypeName()
if currentPrimGetsImageableComputations:
return [BoundingBoxAttribute(currentPrim, rootDataModel),
LocalToWorldXformAttribute(currentPrim,
rootDataModel),
ResolvedPreviewMaterial(currentPrim, rootDataModel),
ResolvedFullMaterial(currentPrim, rootDataModel)]
return []
#
# The base class for per-prim custom attributes.
#
class CustomAttribute:
def __init__(self, currentPrim, rootDataModel):
self._currentPrim = currentPrim
self._rootDataModel = rootDataModel
def IsVisible(self):
return True
# GetName function to match UsdAttribute API
def GetName(self):
return ""
# Get function to match UsdAttribute API
def Get(self, frame):
return ""
# convenience function to make this look more like a UsdAttribute
def GetTypeName(self):
return ""
# GetPrimPath function to match UsdAttribute API
def GetPrimPath(self):
return self._currentPrim.GetPath()
#
# Displays the bounding box of a prim
#
class BoundingBoxAttribute(CustomAttribute):
def __init__(self, currentPrim, rootDataModel):
CustomAttribute.__init__(self, currentPrim, rootDataModel)
def GetName(self):
return ComputedPropertyNames.WORLD_BBOX
def Get(self, frame):
try:
bbox = self._rootDataModel.computeWorldBound(self._currentPrim)
bbox = bbox.ComputeAlignedRange()
except RuntimeError as err:
bbox = "Invalid: " + str(err)
return bbox
#
# Displays the Local to world xform of a prim
#
class LocalToWorldXformAttribute(CustomAttribute):
def __init__(self, currentPrim, rootDataModel):
CustomAttribute.__init__(self, currentPrim, rootDataModel)
def GetName(self):
return ComputedPropertyNames.LOCAL_WORLD_XFORM
def Get(self, frame):
try:
pwt = self._rootDataModel.getLocalToWorldTransform(self._currentPrim)
except RuntimeError as err:
pwt = "Invalid: " + str(err)
return pwt
class ResolvedBoundMaterial(CustomAttribute):
def __init__(self, currentPrim, rootDataModel, purpose):
CustomAttribute.__init__(self, currentPrim, rootDataModel)
self._purpose = purpose
def GetName(self):
if self._purpose == UsdShade.Tokens.full:
return ComputedPropertyNames.RESOLVED_FULL_MATERIAL
elif self._purpose == UsdShade.Tokens.preview:
return ComputedPropertyNames.RESOLVED_PREVIEW_MATERIAL
else:
raise ValueError("Invalid purpose '{}'.".format(self._purpose))
def Get(self, frame):
try:
(boundMaterial, bindingRel) = \
self._rootDataModel.computeBoundMaterial(self._currentPrim,
self._purpose)
boundMatPath = boundMaterial.GetPrim().GetPath() if boundMaterial \
else "<unbound>"
except RuntimeError as err:
boundMatPath = "Invalid: " + str(err)
return boundMatPath
class ResolvedFullMaterial(ResolvedBoundMaterial):
def __init__(self, currentPrim, rootDataModel):
ResolvedBoundMaterial.__init__(self, currentPrim, rootDataModel,
UsdShade.Tokens.full)
class ResolvedPreviewMaterial(ResolvedBoundMaterial):
def __init__(self, currentPrim, rootDataModel):
ResolvedBoundMaterial.__init__(self, currentPrim, rootDataModel,
UsdShade.Tokens.preview)
class ComputedPropertyFactory:
"""Creates computed properties."""
def __init__(self, rootDataModel):
self._rootDataModel = rootDataModel
def getComputedProperty(self, prim, propName):
"""Create a new computed property from a prim and property name."""
if propName == ComputedPropertyNames.WORLD_BBOX:
return BoundingBoxAttribute(prim, self._rootDataModel)
elif propName == ComputedPropertyNames.LOCAL_WORLD_XFORM:
return LocalToWorldXformAttribute(prim, self._rootDataModel)
elif propName == ComputedPropertyNames.RESOLVED_FULL_MATERIAL:
return ResolvedFullMaterial(prim, self._rootDataModel)
elif propName == ComputedPropertyNames.RESOLVED_PREVIEW_MATERIAL:
return ResolvedPreviewMaterial(prim, self._rootDataModel)
else:
raise ValueError("Cannot create computed property '{}'.".format(
propName))
Binary file not shown.
+114
View File
@@ -0,0 +1,114 @@
#
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from pxr import Tf
# Returns a list of debug flags whose names are prefixed by debugFlagPrefix
# followed by an '_'.
#
def _GetDebugFlagsWithPrefix(debugFlagPrefix):
debugFlagPrefix += "_"
return [flag for flag in Tf.Debug.GetDebugSymbolNames()
if flag.startswith(debugFlagPrefix)]
# Main DebugFlags editor widget
#
class DebugFlagsWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(DebugFlagsWidget, self).__init__(parent)
self.setObjectName("Debug Flags")
self.setMinimumSize(640, 300)
self._listView = QtWidgets.QListView()
self._tableWidget = QtWidgets.QTableWidget(0, 2)
# Configure and populate the left list view
self._listView.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self._populateDebugFlagsListView(self._listView)
self._listView.selectionModel().selectionChanged.connect(
self._onFlagSelectionChanged)
# Configure the table widget
self._tableWidget.horizontalHeader().setStretchLastSection(True)
self._tableWidget.horizontalHeader().setDefaultSectionSize(200)
self._tableWidget.setHorizontalHeaderLabels(
['Debug Symbol', 'Description'])
self._tableWidget.verticalHeader().hide()
self._tableWidget.itemClicked.connect(self._onDebugFlagChecked)
# Set the layout
lay = QtWidgets.QHBoxLayout()
lay.addWidget(self._listView, 0)
lay.addWidget(self._tableWidget, 1)
self.setLayout(lay)
def _populateDebugFlagsListView(self, listView):
allDebugFlags = Tf.Debug.GetDebugSymbolNames()
allDebugPrefixes = [ x[:x.find('_')] if x.find('_') > 0 else x
for x in allDebugFlags]
self._allDebugFlagPrefixes = list(sorted(set(allDebugPrefixes)))
listModel = QtCore.QStringListModel(self._allDebugFlagPrefixes)
listView.setModel(listModel)
def _populateDebugFlagsTableView(self, debugFlagPrefix):
debugFlags = _GetDebugFlagsWithPrefix(debugFlagPrefix)
self._tableWidget.setRowCount(len(debugFlags))
row = 0
for f in debugFlags:
item = QtWidgets.QTableWidgetItem()
item.setFlags(QtCore.Qt.ItemIsUserCheckable |
QtCore.Qt.ItemIsEnabled)
if Tf.Debug.IsDebugSymbolNameEnabled(f):
item.setCheckState(QtCore.Qt.Checked)
else:
item.setCheckState(QtCore.Qt.Unchecked)
item.setText(f)
self._tableWidget.setItem(row, 0, item)
item = QtWidgets.QTableWidgetItem()
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
item.setText(Tf.Debug.GetDebugSymbolDescription(f))
self._tableWidget.setItem(row, 1, item)
row += 1
def _onFlagSelectionChanged(self, selected, deselected):
if len(selected.indexes()) > 0:
self._populateDebugFlagsTableView(self._allDebugFlagPrefixes[
selected.indexes()[0].row()])
def _onDebugFlagChecked(self, item):
value = (item.checkState() == QtCore.Qt.Checked)
Tf.Debug.SetDebugSymbolsByName(item.text(), value)
Binary file not shown.
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Binary file not shown.
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+85
View File
@@ -0,0 +1,85 @@
#
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets, QtGui
class FrameSlider(QtWidgets.QSlider):
"""Custom QSlider class to allow scrubbing on left-click."""
PAUSE_TIMER_INTERVAL = 500
def __init__(self, parent=None):
super(FrameSlider, self).__init__(parent=parent)
# Create a mouse pause timer to trigger an update if the slider
# scrubbing pauses.
self._mousePauseTimer = QtCore.QTimer(self)
self._mousePauseTimer.setInterval(self.PAUSE_TIMER_INTERVAL)
self._mousePauseTimer.timeout.connect(self.mousePaused)
def mousePaused(self):
"""Slot called when the slider scrubbing is paused."""
self._mousePauseTimer.stop()
self.valueChanged.emit(self.sliderPosition())
def mousePressEvent(self, event):
# This is a temporary solution that should revisited in future.
#
# The issue is that the current QStyle on the application
# only allows the slider position to be set on a MiddleButton
# MouseEvent.
#
# The correct solution is for us to create a QProxyStyle for the
# application so we can edit the value of the
# QStyle.SH_Slider_AbsoluteSetButtons property (to include
# LeftButton). Unfortunately QProxyStyle is not yet available
# in this version of PySide.
#
# Instead, we are forced to duplicate the MouseEvent as a
# MiddleButton event. This creates the exact behavior we
# want to see from the QSlider.
styleHint = QtWidgets.QStyle.SH_Slider_AbsoluteSetButtons
if self.style().styleHint(styleHint) == QtCore.Qt.MiddleButton:
if event.button() == QtCore.Qt.LeftButton:
event = QtGui.QMouseEvent(
event.type(),
event.pos(),
QtCore.Qt.MiddleButton,
QtCore.Qt.MiddleButton,
event.modifiers()
)
super(FrameSlider, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
super(FrameSlider, self).mouseMoveEvent(event)
# Start the pause timer if tracking is disabled.
if not self.hasTracking():
self._mousePauseTimer.start()
def mouseReleaseEvent(self, event):
# Stop the pause timer.
self._mousePauseTimer.stop()
super(FrameSlider, self).mouseReleaseEvent(event)
Binary file not shown.
+563
View File
@@ -0,0 +1,563 @@
#
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from math import atan, radians as rad
from pxr import Gf, Tf
from .qt import QtCore
from .common import DEBUG_CLIPPING
# FreeCamera inherits from QObject only so that it can send signals...
# which is really a pretty nice, easy to use notification system.
class FreeCamera(QtCore.QObject):
# Allows FreeCamera owner to act when the camera's relationship to
# its viewed content changes. For instance, to compute the value
# to supply for setClosestVisibleDistFromPoint()
signalFrustumChanged = QtCore.Signal()
defaultNear = 1
defaultFar = 2000000
# Experimentally on Nvidia M6000, if Far/Near is greater than this,
# then geometry in the back half of the volume will disappear
maxSafeZResolution = 1e6
# Experimentally on Nvidia M6000, if Far/Near is greater than this,
# then we will often see Z-fighting artifacts even for geometry that
# is close to camera, when rendering for picking
maxGoodZResolution = 5e4
def __init__(self, isZUp, fov=60.0):
"""FreeCamera can be either a Z up or Y up camera, based on 'zUp'"""
super(FreeCamera, self).__init__()
self._camera = Gf.Camera()
self._camera.SetPerspectiveFromAspectRatioAndFieldOfView(
1.0, fov, Gf.Camera.FOVVertical)
self._overrideNear = None
self._overrideFar = None
self.resetClippingPlanes()
self._isZUp = isZUp
self._cameraTransformDirty = True
self._rotTheta = 0
self._rotPhi = 0
self._rotPsi = 0
self._center = Gf.Vec3d(0,0,0)
self._dist = 100
self._camera.focusDistance = self._dist
self._closestVisibleDist = None
self._lastFramedDist = None
self._lastFramedClosestDist = None
self._selSize = 10
if isZUp:
# This is also Gf.Camera.Y_UP_TO_Z_UP_MATRIX
self._YZUpMatrix = Gf.Matrix4d().SetRotate(
Gf.Rotation(Gf.Vec3d.XAxis(), -90))
self._YZUpInvMatrix = self._YZUpMatrix.GetInverse()
else:
self._YZUpMatrix = Gf.Matrix4d(1.0)
self._YZUpInvMatrix = Gf.Matrix4d(1.0)
# Why a clone() method vs copy.deepcopy()ing the FreeCamera ?
# 1) Several of the Gf classes are not python-picklable (requirement of
# deepcopy), nor is GfCamera. Adding that infrastructure for this
# single client seems weighty.
# 2) We could make FreeCamera itself be picklable... that solution would
# require twice as much code as clone(). If we wind up extracting
# FreeCamera to be a more general building block, it may be worth it,
# and clone() would transition to __getstate__().
def clone(self):
clone = FreeCamera(self._isZUp)
clone._camera = Gf.Camera(self._camera)
# skipping stereo attrs for now
clone._rotTheta = self._rotTheta
clone._rotPhi = self._rotPhi
clone._rotPsi = self._rotPsi
clone._center = Gf.Vec3d(self._center)
clone._dist = self._dist
clone._closestVisibleDist = self._closestVisibleDist
clone._lastFramedClosestDist = self._lastFramedClosestDist
clone._lastFramedDist = self._lastFramedDist
clone._selSize = self._selSize
clone._overrideNear = self._overrideNear
clone._overrideFar = self._overrideFar
clone._YZUpMatrix = Gf.Matrix4d(self._YZUpMatrix)
clone._YZUpInvMatrix = Gf.Matrix4d(self._YZUpInvMatrix)
return clone
def _pushToCameraTransform(self):
"""
Updates the camera's transform matrix, that is, the matrix that brings
the camera to the origin, with the camera view pointing down:
+Y if this is a Zup camera, or
-Z if this is a Yup camera .
"""
if not self._cameraTransformDirty:
return
def RotMatrix(vec, angle):
return Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(vec, angle))
# self._YZUpInvMatrix influences the behavior about how the
# FreeCamera will tumble. It is the identity or a rotation about the
# x-Axis.
self._camera.transform = (
Gf.Matrix4d().SetTranslate(Gf.Vec3d.ZAxis() * self.dist) *
RotMatrix(Gf.Vec3d.ZAxis(), -self._rotPsi) *
RotMatrix(Gf.Vec3d.XAxis(), -self._rotPhi) *
RotMatrix(Gf.Vec3d.YAxis(), -self._rotTheta) *
self._YZUpInvMatrix *
Gf.Matrix4d().SetTranslate(self.center))
self._camera.focusDistance = self.dist
self._cameraTransformDirty = False
def _pullFromCameraTransform(self):
"""
Updates parameters (center, rotTheta, etc.) from the camera transform.
"""
# reads the transform set on the camera and updates all the other
# parameters. This is the inverse of _pushToCameraTransform
cam_transform = self._camera.transform
dist = self._camera.focusDistance
frustum = self._camera.frustum
cam_pos = frustum.position
cam_axis = frustum.ComputeViewDirection()
# Compute translational parts
self._dist = dist
self._selSize = dist / 10.0
self._center = cam_pos + dist * cam_axis
# self._YZUpMatrix influences the behavior about how the
# FreeCamera will tumble. It is the identity or a rotation about the
# x-Axis.
# Compute rotational part
transform = cam_transform * self._YZUpMatrix
transform.Orthonormalize()
rotation = transform.ExtractRotation()
# Decompose and set angles
self._rotTheta, self._rotPhi, self._rotPsi = -rotation.Decompose(
Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis(), Gf.Vec3d.ZAxis())
self._cameraTransformDirty = True
def _rangeOfBoxAlongRay(self, camRay, bbox, debugClipping=False):
maxDist = -float('inf')
minDist = float('inf')
boxRange = bbox.GetRange()
boxXform = bbox.GetMatrix()
for i in range (8):
# for each corner of the bounding box, transform to world
# space and project
point = boxXform.Transform(boxRange.GetCorner(i))
pointDist = camRay.FindClosestPoint(point)[1]
# find the projection of that point of the camera ray
# and find the farthest and closest point.
if pointDist > maxDist:
maxDist = pointDist
if pointDist < minDist:
minDist = pointDist
if debugClipping:
print("Projected bounds near/far: %f, %f" % (minDist, maxDist))
# if part of the bbox is behind the ray origin (i.e. camera),
# we clamp minDist to be positive. Otherwise, reduce minDist by a bit
# so that geometry at exactly the edge of the bounds won't be clipped -
# do the same for maxDist, also!
if minDist < FreeCamera.defaultNear:
minDist = FreeCamera.defaultNear
else:
minDist *= 0.99
maxDist *= 1.01
if debugClipping:
print("Contracted bounds near/far: %f, %f" % (minDist, maxDist))
return minDist, maxDist
def setClippingPlanes(self, stageBBox):
'''Computes and sets automatic clipping plane distances using the
camera's position and orientation, the bouding box
surrounding the stage, and the distance to the closest rendered
object in the central view of the camera (closestVisibleDist).
If either of the "override" clipping attributes are not None,
we use those instead'''
debugClipping = Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING)
# If the scene bounding box is empty, or we are fully on manual
# override, then just initialize to defaults.
if stageBBox.GetRange().IsEmpty() or \
(self._overrideNear and self._overrideFar) :
computedNear, computedFar = FreeCamera.defaultNear, FreeCamera.defaultFar
else:
# The problem: We want to include in the camera frustum all the
# geometry the viewer should be able to see, i.e. everything within
# the inifinite frustum starting at distance epsilon from the
# camera itself. However, the further the imageable geometry is
# from the near-clipping plane, the less depth precision we will
# have to resolve nearly colinear/incident polygons (which we get
# especially with any doubleSided geometry). We can run into such
# situations astonishingly easily with large sets when we are
# focussing in on just a part of a set that spans 10^5 units or
# more.
#
# Our solution: Begin by projecting the endpoints of the imageable
# world's bounds onto the ray piercing the center of the camera
# frustum, and take the near/far clipping distances from its
# extent, clamping at a positive value for near. To address the
# z-buffer precision issue, we rely on someone having told us how
# close the closest imageable geometry actually is to the camera,
# by having called setClosestVisibleDistFromPoint(). This gives us
# the most liberal near distance we can use and not clip the
# geometry we are looking at. We actually choose some fraction of
# that distance instead, because we do not expect the someone to
# recompute the closest point with every camera manipulation, as
# it can be expensive (we do emit signalFrustumChanged to notify
# them, however). We only use this if the current range of the
# bbox-based frustum will have precision issues.
frustum = self._camera.frustum
camPos = frustum.position
camRay = Gf.Ray(camPos, frustum.ComputeViewDirection())
computedNear, computedFar = self._rangeOfBoxAlongRay(camRay,
stageBBox,
debugClipping)
precisionNear = computedFar / FreeCamera.maxGoodZResolution
if debugClipping:
print("Proposed near for precision: {}, closestDist: {}"\
.format(precisionNear, self._closestVisibleDist))
if self._closestVisibleDist:
# Because of our concern about orbit/truck causing
# clipping, make sure we don't go closer than half the
# distance to the closest visible point
halfClose = self._closestVisibleDist / 2.0
if self._closestVisibleDist < self._lastFramedClosestDist:
# This can happen if we have zoomed in closer since
# the last time setClosestVisibleDistFromPoint() was called.
# Clamp to precisionNear, which gives a balance between
# clipping as we zoom in, vs bad z-fighting as we zoom in.
# See AdjustDistance() for comment about better solution.
halfClose = max(precisionNear, halfClose, computedNear)
if debugClipping:
print("ADJUSTING: Accounting for zoom-in")
if halfClose < computedNear:
# If there's stuff very very close to the camera, it
# may have been clipped by computedNear. Get it back!
computedNear = halfClose
if debugClipping:
print("ADJUSTING: closestDist was closer than bboxNear")
elif precisionNear > computedNear:
computedNear = min((precisionNear + halfClose) / 2.0,
halfClose)
if debugClipping:
print("ADJUSTING: gaining precision by pushing out")
near = self._overrideNear or computedNear
far = self._overrideFar or computedFar
# Make sure far is greater than near
far = max(near+1, far)
if debugClipping:
print("***Final Near/Far: {}, {}".format(near, far))
self._camera.clippingRange = Gf.Range1f(near, far)
def computeGfCamera(self, stageBBox, autoClip=False):
"""Makes sure the FreeCamera's computed parameters are up-to-date, and
returns the GfCamera object. If 'autoClip' is True, then compute
"optimal" positions for the near/far clipping planes based on the
current closestVisibleDist, in order to maximize Z-buffer resolution"""
self._pushToCameraTransform()
if autoClip:
self.setClippingPlanes(stageBBox)
else:
self.resetClippingPlanes()
return self._camera
def resetClippingPlanes(self):
"""Set near and far back to their uncomputed defaults."""
near = self._overrideNear or FreeCamera.defaultNear
far = self._overrideFar or FreeCamera.defaultFar
self._camera.clippingRange = Gf.Range1f(near, far)
def frameSelection(self, selBBox, frameFit):
# needs to be recomputed
self._closestVisibleDist = None
self.center = selBBox.ComputeCentroid()
selRange = selBBox.ComputeAlignedRange()
self._selSize = max(*selRange.GetSize())
if self.orthographic:
self.fov = self._selSize * frameFit
self.dist = self._selSize + FreeCamera.defaultNear
else:
halfFov = self.fov*0.5 or 0.5 # don't divide by zero
lengthToFit = self._selSize * frameFit * 0.5
self.dist = lengthToFit / atan(rad(halfFov))
# Very small objects that fill out their bounding boxes (like cubes)
# may well pierce our 1 unit default near-clipping plane. Make sure
# that doesn't happen.
if self.dist < FreeCamera.defaultNear + self._selSize * 0.5:
self.dist = FreeCamera.defaultNear + lengthToFit
def setClosestVisibleDistFromPoint(self, point):
frustum = self._camera.frustum
camPos = frustum.position
camRay = Gf.Ray(camPos, frustum.ComputeViewDirection())
self._closestVisibleDist = camRay.FindClosestPoint(point)[1]
self._lastFramedDist = self.dist
self._lastFramedClosestDist = self._closestVisibleDist
if Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING):
print("Resetting closest distance to {}; CameraPos: {}, closestPoint: {}".format(self._closestVisibleDist, camPos, point))
def ComputePixelsToWorldFactor(self, viewportHeight):
'''Computes the ratio that converts pixel distance into world units.
It treats the pixel distances as if they were projected to a plane going
through the camera center.'''
self._pushToCameraTransform()
if self.orthographic:
return self.fov / viewportHeight
else:
frustumHeight = self._camera.frustum.window.GetSize()[1]
return frustumHeight * self._dist / viewportHeight
def Tumble(self, dTheta, dPhi):
''' Tumbles the camera around the center point by (dTheta, dPhi) degrees. '''
self._rotTheta += dTheta
self._rotPhi += dPhi
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def AdjustDistance(self, scaleFactor):
'''Scales the distance of the freeCamera from it's center typically by
scaleFactor unless it puts the camera into a "stuck" state.'''
# When dist gets very small, you can get stuck and not be able to
# zoom back out, if you just keep multiplying. Switch to addition
# in that case, choosing an incr that works for the scale of the
# framed geometry.
if scaleFactor > 1 and self.dist < 2:
selBasedIncr = self._selSize / 25.0
scaleFactor -= 1.0
self.dist += min(selBasedIncr, scaleFactor)
else:
self.dist *= scaleFactor
# Make use of our knowledge that we are changing distance to camera
# to also adjust _closestVisibleDist to keep it useful. Make sure
# not to recede farther than the last *computed* closeDist, since that
# will generally cause unwanted clipping of close objects.
# XXX: This heuristic does a good job of preventing undesirable
# clipping as we zoom in and out, but sacrifices the z-buffer
# precision we worked hard to get. If Hd/UsdImaging could cheaply
# provide us with the closest-point from the last-rendered image,
# we could use it safely here to update _closestVisibleDist much
# more accurately than this calculation.
if self._closestVisibleDist:
if self.dist > self._lastFramedDist:
self._closestVisibleDist = self._lastFramedClosestDist
else:
self._closestVisibleDist = \
self._lastFramedClosestDist - \
self._lastFramedDist + \
self.dist
def Truck(self, deltaRight, deltaUp):
''' Moves the camera by (deltaRight, deltaUp) in worldspace coordinates.
This is similar to a camera Truck/Pedestal.
'''
# need to update the camera transform before we access the frustum
self._pushToCameraTransform()
frustum = self._camera.frustum
cam_up = frustum.ComputeUpVector()
cam_right = Gf.Cross(frustum.ComputeViewDirection(), cam_up)
self._center += (deltaRight * cam_right + deltaUp * cam_up)
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def PanTilt(self, dPan, dTilt):
''' Rotates the camera around the current camera base (approx. the film
plane). Both parameters are in degrees.
This moves the center point that we normally tumble around.
This is similar to a camera Pan/Tilt.
'''
self._camera.transform = (
Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(Gf.Vec3d.XAxis(), dTilt)) *
Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(Gf.Vec3d.YAxis(), dPan)) *
self._camera.transform)
self._pullFromCameraTransform()
# When we Pan/Tilt, we don't want to roll the camera so we just zero it
# out here.
self._rotPsi = 0.0
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def Walk(self, dForward, dRight):
''' Specialized camera movement that moves it on the "horizontal" plane
'''
# need to update the camera transform before we access the frustum
self._pushToCameraTransform()
frustum = self._camera.frustum
cam_up = frustum.ComputeUpVector().GetNormalized()
cam_forward = frustum.ComputeViewDirection().GetNormalized()
cam_right = Gf.Cross(cam_forward, cam_up)
delta = dForward * cam_forward + dRight * cam_right
self._center += delta
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@staticmethod
def FromGfCamera(gfCamera, isZUp):
self = FreeCamera(isZUp)
self._camera = gfCamera
self._pullFromCameraTransform()
return self
@property
def rotTheta(self):
return self._rotTheta
@rotTheta.setter
def rotTheta(self, value):
self._rotTheta = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def rotPhi(self):
return self._rotPhi
@rotPhi.setter
def rotPhi(self, value):
self._rotPhi = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def center(self):
return self._center
@center.setter
def center(self, value):
self._center = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def dist(self):
return self._dist
@dist.setter
def dist(self, value):
self._dist = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def orthographic(self):
return self._camera.projection == Gf.Camera.Orthographic
@orthographic.setter
def orthographic(self, orthographic):
if orthographic:
self._camera.projection = Gf.Camera.Orthographic
else:
self._camera.projection = Gf.Camera.Perspective
self.signalFrustumChanged.emit()
@property
def fov(self):
"""The vertical field of view, in degrees, for perspective cameras.
For orthographic cameras fov is the height of the view frustum, in
world units.
"""
if self._camera.projection == Gf.Camera.Perspective:
return self._camera.GetFieldOfView(Gf.Camera.FOVVertical)
else:
return (self._camera.verticalAperture * Gf.Camera.APERTURE_UNIT)
@fov.setter
def fov(self, value):
if self._camera.projection == Gf.Camera.Perspective:
self._camera.SetPerspectiveFromAspectRatioAndFieldOfView(
self._camera.aspectRatio, value, Gf.Camera.FOVVertical)
else:
self._camera.SetOrthographicFromAspectRatioAndSize(
self._camera.aspectRatio, value, Gf.Camera.FOVVertical)
self.signalFrustumChanged.emit()
@property
def near(self):
return self._camera.clippingRange.min
@property
def far(self):
return self._camera.clippingRange.max
# no setters for near and far - one must set overrideNear/Far instead
@property
def overrideNear(self):
return self._overrideNear
@overrideNear.setter
def overrideNear(self, value):
"""To remove the override, set to None"""
self._overrideNear = value
@property
def overrideFar(self):
return self._overrideFar
@overrideFar.setter
def overrideFar(self, value):
"""To remove the override, set to None"""
self._overrideFar = value
Binary file not shown.
@@ -0,0 +1,99 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets
from .usdviewContextMenuItem import UsdviewContextMenuItem
#
# Specialized context menu for adding and removing columns
# in the prim browser and attribute inspector.
#
class HeaderContextMenu(QtWidgets.QMenu):
def __init__(self, parent):
QtWidgets.QMenu.__init__(self, "Columns", parent)
self._menuItems = _GetContextMenuItems(parent)
for menuItem in self._menuItems:
if menuItem.isValid():
# create menu actions. Associate them with each Item, so that
# we can update them when we show, since column visibility can
# change.
action = self.addAction(menuItem.GetText(), menuItem.RunCommand)
action.setCheckable(True)
menuItem.action = action
self.aboutToShow.connect(self._prepForShow)
def _prepForShow(self):
for menuItem in self._menuItems:
if menuItem.action:
menuItem.action.setChecked(menuItem.IsChecked())
menuItem.action.setEnabled(menuItem.IsEnabled())
def _GetContextMenuItems(parent):
# create a list of HeaderContextMenuItem classes
# initialized with the parent object and column
itemList = []
return [HeaderContextMenuItem(parent, column) \
for column in range(parent.columnCount())]
# The base class for header context menus
class HeaderContextMenuItem(UsdviewContextMenuItem):
def __init__(self, parent, column):
self._parent = parent
self._column = column
self._action = None
if isinstance(parent, QtWidgets.QTreeWidget):
self._text = parent.headerItem().text(column)
else:
self._text = parent.horizontalHeaderItem(column).text()
def GetText(self):
# returns the text to be displayed in menu
return self._text
def IsEnabled(self):
# Enable context menu item for columns except the "Name" column.
return 'Name' not in self.GetText()
def IsChecked(self):
# true if the column is visible, false otherwise
return not self._parent.isColumnHidden(self._column)
def RunCommand(self):
# show or hide the column depending on its previous state
self._parent.setColumnHidden(self._column, self.IsChecked())
@property
def action(self):
return self._action
@action.setter
def action(self, action):
self._action = action
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 219 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 243 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

@@ -0,0 +1,219 @@
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .usdviewContextMenuItem import UsdviewContextMenuItem
import os, subprocess, sys
from pxr import Ar
#
# Specialized context menu for running commands in the layer stack view.
#
class LayerStackContextMenu(QtWidgets.QMenu):
def __init__(self, parent, item):
QtWidgets.QMenu.__init__(self, parent)
self._menuItems = _GetContextMenuItems(item)
for menuItem in self._menuItems:
if menuItem.isValid():
# create menu actions
action = self.addAction(menuItem.GetText(), menuItem.RunCommand)
# set enabled
if not menuItem.IsEnabled():
action.setEnabled(False)
def _GetContextMenuItems(item):
return [OpenLayerMenuItem(item),
UsdviewLayerMenuItem(item),
CopyLayerPathMenuItem(item),
CopyLayerIdentifierMenuItem(item),
CopyPathMenuItem(item)]
#
# The base class for layer stack context menu items.
#
class LayerStackContextMenuItem(UsdviewContextMenuItem):
def __init__(self, item):
self._item = item
def IsEnabled(self):
return True
def GetText(self):
return ""
def RunCommand(self):
pass
#
# Opens the layer using usdedit.
#
class OpenLayerMenuItem(LayerStackContextMenuItem):
# XXX: Note that this logic is duplicated from usddiff
# see bug 150247 for centralizing this API.
def _FindUsdEdit(self):
import platform
from distutils.spawn import find_executable
usdedit = find_executable('usdedit')
if not usdedit:
usdedit = find_executable('usdedit', path=os.path.abspath(os.path.dirname(sys.argv[0])))
if not usdedit and (platform.system() == 'Windows'):
for path in os.environ['PATH'].split(os.pathsep):
base = os.path.join(path, 'usdedit')
for ext in ['.cmd', '']:
if os.access(base + ext, os.X_OK):
usdedit = base + ext
return usdedit
def GetText(self):
from .common import PrettyFormatSize
fileSize = 0
if (hasattr(self._item, "layerPath")
and os.path.isfile(getattr(self._item, "layerPath"))):
fileSize = os.path.getsize(getattr(self._item, "layerPath"))
if fileSize:
return "Open Layer In Editor (%s)" % PrettyFormatSize(fileSize)
else:
return "Open Layer In Editor"
def IsEnabled(self):
return hasattr(self._item, "layerPath")
def RunCommand(self):
if not self._item:
return
# Get layer path from item
layerPath = getattr(self._item, "layerPath")
if not layerPath:
print("Error: Could not find layer file.")
return
if Ar.IsPackageRelativePath(layerPath):
layerName = os.path.basename(
Ar.SplitPackageRelativePathInner(layerPath)[1])
else:
layerName = os.path.basename(layerPath)
layerName += ".tmp"
usdeditExe = self._FindUsdEdit()
if not usdeditExe:
print("Warning: Could not find 'usdedit', expected it to be in PATH.")
return
print("Opening file: %s" % layerPath)
command = [usdeditExe,'-n',layerPath,'-p',layerName]
subprocess.Popen(command, close_fds=True)
#
# Opens the layer using usdview.
#
class UsdviewLayerMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Open Layer In usdview"
def IsEnabled(self):
return hasattr(self._item, "layerPath")
def RunCommand(self):
if not self._item:
return
# Get layer path from item
layerPath = getattr(self._item, "layerPath")
if not layerPath:
return
print("Spawning usdview %s" % layerPath)
os.system("usdview %s &" % layerPath)
#
# Copy the layer path to clipboard
#
class CopyLayerPathMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Copy Layer Path"
def RunCommand(self):
if not self._item:
return
layerPath = getattr(self._item, "layerPath")
if not layerPath:
return
cb = QtWidgets.QApplication.clipboard()
cb.setText(layerPath, QtGui.QClipboard.Selection )
cb.setText(layerPath, QtGui.QClipboard.Clipboard )
#
# Copy the layer identifier to clipboard
#
class CopyLayerIdentifierMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Copy Layer Identifier"
def RunCommand(self):
if not self._item:
return
identifier = getattr(self._item, "identifier")
if not identifier:
return
cb = QtWidgets.QApplication.clipboard()
cb.setText(identifier, QtGui.QClipboard.Selection )
cb.setText(identifier, QtGui.QClipboard.Clipboard )
#
# Copy the prim path to clipboard, if there is one
#
class CopyPathMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Copy Object Path"
def RunCommand(self):
if not self._item:
return
path = getattr(self._item, "path")
if not path:
return
path = str(path)
cb = QtWidgets.QApplication.clipboard()
cb.setText(path, QtGui.QClipboard.Selection )
cb.setText(path, QtGui.QClipboard.Clipboard )
def IsEnabled(self):
return hasattr(self._item, "path")
Binary file not shown.
+62
View File
@@ -0,0 +1,62 @@
#
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Functionality for expanding and collapsing legend components in usdview
LEGEND_BUTTON_SELECTEDSTYLE = ('background: rgb(189, 155, 84); '
'color: rgb(227, 227, 227);')
# Set the start/end points of an animation
def _SetAnimValues(anim, a1, a2):
anim.setStartValue(a1)
anim.setEndValue(a2)
# A function which takes a two-pane area and transforms it to
# open or close the bottom pane.
#
# legendHeight
# | separator height
# | | browser height
# | | |-> ___________ ___________
# | | | | | | |
# | | | | | | |
# | | |-> | | <---> | |
# |---|-------> +++++++++++++ | |
# | | | <---> | |
# | | | | |
# |-----------> ----------- +++++++++++
def ToggleLegendWithBrowser(legend, button, anim):
legend.ToggleMinimized()
# We are dragging downward, so collapse the legend and expand the
# attribute viewer panel to take up the remaining space.
if legend.IsMinimized():
button.setStyleSheet('')
_SetAnimValues(anim, legend.GetHeight(), 0)
# We are expanding, so do the opposite.
else:
button.setStyleSheet(LEGEND_BUTTON_SELECTEDSTYLE)
_SetAnimValues(anim, legend.GetHeight(), legend.GetResetHeight())
anim.start()
Loaded 100 of 15675 files, more files were not shown because too many files have changed in this diff. Show more