add usd-21-11-win64_py39
This commit is contained in:
1 parent
41d23e71ba
commit
ba5e1f7e67
15684 files changed
+3069957
No files matched your search
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+171
@@ -0,0 +1,171 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
|
||||
# This is a wrapper around Usdview's launcher code to allow injection of a
|
||||
# script for testing purposes. Tests can be supplied in the form of a python
|
||||
# script which provides a function testUsdviewInputFunction(appController)
|
||||
# as the entry point. This is passed to testusdview with the (required)
|
||||
# --testScript argument. Other than this signature requirement, scripts are
|
||||
# free to do whatever they want with mainwindow for testing.
|
||||
|
||||
import pxr.Usdviewq as Usdviewq
|
||||
from pxr.Usdviewq import AppController
|
||||
from pxr.Usdviewq.qt import QtWidgets
|
||||
|
||||
import sys, os, inspect, argparse
|
||||
|
||||
TEST_USD_VIEW_CALLBACK_IDENT = "testUsdviewInputFunction"
|
||||
|
||||
class TestUsdView(Usdviewq.Launcher):
|
||||
def RegisterOptions(self, parser):
|
||||
super(TestUsdView, self).RegisterOptions(parser)
|
||||
parser.add_argument('--testScript', action='store', required=True,
|
||||
help="The test script to run after loading. "
|
||||
"This script must expect to take a single")
|
||||
|
||||
def Run(self):
|
||||
parser = argparse.ArgumentParser(prog=sys.argv[0],
|
||||
description=self.GetHelpDescription())
|
||||
self.RegisterOptions(parser)
|
||||
super(TestUsdView, self).RegisterPositionals(parser)
|
||||
arg_parse_result = super(TestUsdView, self).ParseOptions(parser)
|
||||
|
||||
# We always set --defaultsettings to ensure a consistent test
|
||||
# environment for our test scripts.
|
||||
arg_parse_result.defaultSettings = True
|
||||
super(TestUsdView, self).ValidateOptions(arg_parse_result)
|
||||
|
||||
# Further, we ensure usdview won't try to create any state directory
|
||||
# to save its state, as that would be bad for running multiple tests
|
||||
# in parallel
|
||||
os.environ['PXR_USDVIEW_SUPPRESS_STATE_SAVING'] = "1"
|
||||
|
||||
self.__LaunchProcess(arg_parse_result)
|
||||
|
||||
def __LaunchProcess(self, arg_parse_result):
|
||||
callBack = self._ValidateTestFile(arg_parse_result.testScript)
|
||||
(app, appController) = (
|
||||
super(TestUsdView, self).LaunchPreamble(arg_parse_result))
|
||||
|
||||
# Set a fixed size on the stage view so that any image tests get a
|
||||
# consistent resolution - but only if we've created a viewer
|
||||
if appController._stageView:
|
||||
appController._stageView.setFixedSize(597,540)
|
||||
|
||||
# Process initial loading events
|
||||
app.processEvents()
|
||||
callBack(appController)
|
||||
# Process event triggered by the callbacks
|
||||
app.processEvents()
|
||||
# Trigger application shutdown.
|
||||
app.instance().closeAllWindows()
|
||||
return
|
||||
|
||||
# Verify that we have a valid file as input, and it contains
|
||||
# our expected entry point for testing.
|
||||
#
|
||||
# Upon success, this will return the callback to be called after
|
||||
# launching Usdview and doing the initial load pass
|
||||
def _ValidateTestFile(self, filePath):
|
||||
if not os.path.exists(filePath):
|
||||
sys.stderr.write('Invalid file supplied, does not exist: {}\n'
|
||||
.format(filePath))
|
||||
sys.exit(1)
|
||||
|
||||
if not os.access(filePath, os.R_OK):
|
||||
sys.stderr.write('Invalid file supplied, must be readable: {}\n'
|
||||
.format(filePath))
|
||||
|
||||
# Ensure that we are passed a valid python file
|
||||
_, ext = os.path.splitext(filePath)
|
||||
if ext != '.py':
|
||||
sys.stderr.write('Invalid file supplied, must be a python file: '
|
||||
'{}\n'.format(filePath))
|
||||
sys.exit(1)
|
||||
|
||||
# Grab the function from the input python file
|
||||
# if it doesn't contain our expected callback fn, bail
|
||||
localVars = {}
|
||||
with open(filePath) as inputFile:
|
||||
code = compile(inputFile.read(), filePath, 'exec')
|
||||
exec(code, localVars)
|
||||
callBack = localVars.get(TEST_USD_VIEW_CALLBACK_IDENT)
|
||||
if not callBack:
|
||||
sys.stderr.write('Invalid file supplied, must contain a function of '
|
||||
'the signature' + TEST_USD_VIEW_CALLBACK_IDENT +
|
||||
'(appController): {}\n'.format(filePath))
|
||||
sys.exit(1)
|
||||
|
||||
errorMsg = ('Invalid function signature, must be of the form: \n ' +
|
||||
TEST_USD_VIEW_CALLBACK_IDENT + ' (appController)\n'
|
||||
'File: ' + filePath + '\n'
|
||||
'Error: %s')
|
||||
|
||||
if sys.version_info.major >= 3:
|
||||
(args, varargs, keywords, defaults, _, _, _) = \
|
||||
inspect.getfullargspec(callBack)
|
||||
else:
|
||||
(args, varargs, keywords, defaults) = inspect.getargspec(callBack)
|
||||
|
||||
assert not varargs, errorMsg % 'Varargs are disallowed'
|
||||
assert not keywords, errorMsg % 'Kwargs are disallowed'
|
||||
assert not defaults, errorMsg % 'Defaults are disallowed'
|
||||
assert len(args) == 1, errorMsg % 'Incorrect number of args (1 expected)'
|
||||
|
||||
return callBack
|
||||
|
||||
|
||||
# Monkey patch AppController to add helper test interface methods
|
||||
|
||||
def _processEvents(self, iterations=10, waitForConvergence=False):
|
||||
# Qt does not guarantee that a single call to processEvents() will
|
||||
# process all events in the event queue, and in some builds, on
|
||||
# some platforms, we sporadically or even repeatably see test failures
|
||||
# in which the selection does not change, presumably because the
|
||||
# events were not all getting processed, when we simply called
|
||||
# processEvents once. So we do it a handful of times whenever we
|
||||
# generate an event, to increase our odds of success.
|
||||
for x in range(iterations):
|
||||
QtWidgets.QApplication.processEvents()
|
||||
|
||||
# Need to wait extra for progressive rendering images to converge
|
||||
if (waitForConvergence):
|
||||
# Wait until the image is converged
|
||||
while not self._stageView._renderer.IsConverged():
|
||||
QtWidgets.QApplication.processEvents()
|
||||
|
||||
AppController._processEvents = _processEvents
|
||||
|
||||
# Take a shot of the viewport and save it to a file.
|
||||
def _takeShot(self, fileName, iterations=10, waitForConvergence=False):
|
||||
self._processEvents(iterations, waitForConvergence)
|
||||
viewportShot = self.GrabViewportShot()
|
||||
viewportShot.save(fileName, "PNG")
|
||||
|
||||
AppController._takeShot = _takeShot
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
TestUsdView().Run()
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0testusdview" %*
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
import argparse, sys, os
|
||||
|
||||
def _Msg(msg):
|
||||
sys.stdout.write(msg + '\n')
|
||||
|
||||
def _Err(msg):
|
||||
sys.stderr.write(msg + '\n')
|
||||
|
||||
def GetUsdData(filePath):
|
||||
from pxr import Sdf
|
||||
return Sdf.Layer.FindOrOpen(filePath)
|
||||
|
||||
def GetUsdLayerMetaData(filePath):
|
||||
"""Return an SdfLayer holding just the layer metadata of the given layer."""
|
||||
from pxr import Sdf, UsdUtils
|
||||
srcLayer = Sdf.Layer.OpenAsAnonymous(filePath, metadataOnly=True)
|
||||
# Not all file format plugins support metadata-only parsing.
|
||||
# Create a new anonymous layer and copy just the layer metadata.
|
||||
layer = Sdf.Layer.CreateAnonymous(filePath, Sdf.FileFormat.FindById('usda'))
|
||||
UsdUtils.CopyLayerMetadata(srcLayer, layer)
|
||||
return layer
|
||||
|
||||
def GetFlattenedUsdData(filePath, populationMaskPaths):
|
||||
from pxr import Ar, Usd
|
||||
|
||||
if hasattr(Ar.Resolver, "ConfigureResolverForAsset"):
|
||||
Ar.GetResolver().ConfigureResolverForAsset(filePath)
|
||||
popMask = (None if populationMaskPaths is None
|
||||
else Usd.StagePopulationMask())
|
||||
if popMask:
|
||||
for path in populationMaskPaths:
|
||||
popMask.Add(path)
|
||||
return Usd.Stage.OpenMasked(filePath, popMask)
|
||||
else:
|
||||
return Usd.Stage.Open(filePath)
|
||||
|
||||
def GetFlattenedLayerStack(filePath):
|
||||
from pxr import Ar, Sdf, Pcp, Usd, UsdUtils
|
||||
|
||||
if hasattr(Ar.Resolver, "ConfigureResolverForAsset"):
|
||||
Ar.GetResolver().ConfigureResolverForAsset(filePath)
|
||||
stage = Usd.Stage.Open(filePath, Usd.Stage.LoadNone)
|
||||
return UsdUtils.FlattenLayerStack(stage)
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Write usd file(s) either as text to stdout or to a '
|
||||
'specified output file.')
|
||||
|
||||
parser.add_argument('inputFiles', nargs='+')
|
||||
parser.add_argument(
|
||||
'-o', '--out', metavar='file', action='store',
|
||||
help='Write a single input file to this output file instead of stdout.')
|
||||
parser.add_argument(
|
||||
'--usdFormat', metavar='usda|usdc', action='store',
|
||||
help="Use this underlying file format "
|
||||
"for output files with the extension 'usd'. For example, passing "
|
||||
"'-o output.usd --usdFormat usda' will create output.usd as a text "
|
||||
"file. The USD_DEFAULT_FILE_FORMAT environment variable is another "
|
||||
"way to achieve this.")
|
||||
parser.add_argument(
|
||||
'-l', '--loadOnly', action='store_true',
|
||||
help="Attempt to load the specified input files and report 'OK' or "
|
||||
"'ERR' for each one. After all files are processed, this script will "
|
||||
"exit with a non-zero exit code if any files failed to load.")
|
||||
parser.add_argument(
|
||||
'-f', '--flatten', action='store_true', help='Compose stages with the '
|
||||
'input files as root layers and write their flattened content.')
|
||||
parser.add_argument(
|
||||
'--flattenLayerStack', action='store_true',
|
||||
help='Flatten the layer stack with the given root layer, and write '
|
||||
'out the result. Unlike --flatten, this does not flatten composition '
|
||||
'arcs (such as references).')
|
||||
parser.add_argument(
|
||||
'--skipSourceFileComment', action='store_true',
|
||||
help='If --flatten is specified, skip adding a comment regarding the '
|
||||
'source of the flattened layer in the documentation field of the '
|
||||
'output layer.')
|
||||
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. Requires --flatten.')
|
||||
parser.add_argument('--layerMetadata', action='store_true',
|
||||
help='Load only layer metadata in the USD file. '
|
||||
'This option cannot be combined with either '
|
||||
'--flatten or --flattenStack')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
formatArgsDict = {}
|
||||
|
||||
# If --out was specified, it must either not exist or must be writable, the
|
||||
# extension must correspond to a known Sdf file format, and we must have
|
||||
# exactly one input file.
|
||||
if args.out:
|
||||
if os.path.isfile(args.out) and not os.access(args.out, os.W_OK):
|
||||
_Err("%s: error: no write permission for existing output file '%s'"
|
||||
% (parser.prog, args.out))
|
||||
return 1
|
||||
if len(args.inputFiles) != 1:
|
||||
_Err("%s: error: must supply exactly one input file with -o/--out" %
|
||||
parser.prog)
|
||||
return 1
|
||||
ext = os.path.splitext(args.out)[1][1:]
|
||||
if args.usdFormat:
|
||||
if ext != 'usd':
|
||||
_Err("%s: error: use of --usdFormat requires output file end "
|
||||
"with '.usd' extension" % parser.prog)
|
||||
return 1
|
||||
formatArgsDict.update(dict(format=args.usdFormat))
|
||||
from pxr import Sdf
|
||||
if Sdf.FileFormat.FindByExtension(ext) is None:
|
||||
_Err("%s: error: unknown output file extension '.%s'"
|
||||
% (parser.prog, ext))
|
||||
return 1
|
||||
# If --out was not specified, then --usdFormat must be unspecified or must
|
||||
# be 'usda'.
|
||||
elif args.usdFormat and args.usdFormat != 'usda':
|
||||
_Err("%s: error: can only write 'usda' format to stdout; specify an "
|
||||
"output file with -o/--out to write other formats" % parser.prog)
|
||||
return 1
|
||||
|
||||
# split args.populationMask into paths.
|
||||
if args.populationMask:
|
||||
if not args.flatten:
|
||||
# You can only mask a stage, not a layer.
|
||||
_Err("%s: error: --mask requires --flatten" % parser.prog)
|
||||
return 1
|
||||
args.populationMask = args.populationMask.replace(',', ' ').split()
|
||||
|
||||
if args.layerMetadata:
|
||||
if args.flatten:
|
||||
# Cannot parse only metadata when flattening.
|
||||
_Err("%s: error: --layerMetadata cannot be used "
|
||||
"together with --flatten" % parser.prog)
|
||||
if args.flattenLayerStack:
|
||||
# Cannot parse only metadata when flattening.
|
||||
_Err("%s: error: --layerMetadata cannot be used "
|
||||
"together with --flattenLayerStack" % parser.prog)
|
||||
|
||||
from pxr import Usd
|
||||
|
||||
exitCode = 0
|
||||
|
||||
for inputFile in args.inputFiles:
|
||||
# Either open a layer or compose a stage, depending on whether or not
|
||||
# --flatten was specified. Note that 'usdData' will be either a
|
||||
# Usd.Stage or an Sdf.Layer.
|
||||
try:
|
||||
if args.flatten:
|
||||
usdData = GetFlattenedUsdData(inputFile, args.populationMask)
|
||||
elif args.flattenLayerStack:
|
||||
usdData = GetFlattenedLayerStack(inputFile)
|
||||
elif args.layerMetadata:
|
||||
usdData = GetUsdLayerMetaData(inputFile)
|
||||
else:
|
||||
usdData = GetUsdData(inputFile)
|
||||
if not usdData:
|
||||
raise Exception("Could not open layer")
|
||||
|
||||
if args.loadOnly:
|
||||
_Msg("{:3} {}".format("OK", inputFile))
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
if args.loadOnly:
|
||||
_Msg("{:3} {}".format("ERR", inputFile))
|
||||
_Msg("{}".format(e))
|
||||
else:
|
||||
_Err("Failed to open '%s' - %s" % (inputFile, e))
|
||||
exitCode = 1
|
||||
continue
|
||||
|
||||
# Write to either stdout or the specified output file
|
||||
if args.out:
|
||||
try:
|
||||
if args.flatten:
|
||||
usdData.Export(args.out,
|
||||
addSourceFileComment=not args.skipSourceFileComment,
|
||||
args=formatArgsDict)
|
||||
else:
|
||||
usdData.Export(args.out, args=formatArgsDict)
|
||||
except Exception as e:
|
||||
# Let the user know an error occurred.
|
||||
_Err("Error exporting '%s' to '%s' - %s" %
|
||||
(inputFile, args.out, e))
|
||||
|
||||
# If the output file exists, let's try to rename it with
|
||||
# '.quarantine' appended and let the user know. Do this
|
||||
# after the above error report because os.rename() can
|
||||
# fail and we don't want to lose the above error.
|
||||
if os.path.isfile(args.out):
|
||||
newName = args.out + '.quarantine'
|
||||
try:
|
||||
os.rename(args.out, newName)
|
||||
_Err("Possibly corrupt output file renamed to %s" %
|
||||
(newName, ))
|
||||
except Exception as e:
|
||||
_Err("Failed to rename possibly corrupt output " +
|
||||
"file from %s to %s" % (args.out, newName))
|
||||
exitCode = 1
|
||||
else:
|
||||
try:
|
||||
sys.stdout.write(usdData.ExportToString())
|
||||
except Exception as e:
|
||||
_Err("Error writing '%s' to stdout; %s" % (inputFile, e))
|
||||
exitCode = 1
|
||||
|
||||
return exitCode
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Restore signal handling defaults to allow output redirection and the like.
|
||||
import platform
|
||||
if platform.system() != 'Windows':
|
||||
import signal
|
||||
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdcat" %*
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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
|
||||
import argparse
|
||||
import itertools
|
||||
import sys
|
||||
|
||||
from contextlib import contextmanager
|
||||
|
||||
from pxr import Ar, Sdf, Usd, UsdGeom, UsdShade, UsdUtils
|
||||
|
||||
class TermColors:
|
||||
WARN = '\033[93m'
|
||||
FAIL = '\033[91m'
|
||||
END = '\033[0m'
|
||||
|
||||
@contextmanager
|
||||
def _Stream(path, *args, **kwargs):
|
||||
if path == '-':
|
||||
yield sys.stdout
|
||||
else:
|
||||
with open(path, *args, **kwargs) as fp:
|
||||
yield fp
|
||||
|
||||
def _Print(stream, msg):
|
||||
print(msg, file=stream)
|
||||
|
||||
def _Err(msg):
|
||||
sys.stderr.write(TermColors.FAIL + msg + TermColors.END + '\n')
|
||||
|
||||
def _Warn(msg):
|
||||
sys.stderr.write(TermColors.WARN + msg + TermColors.END + '\n')
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="""Utility for checking the
|
||||
compliance of a given USD stage or a USDZ package. Only the first sample
|
||||
of any relevant time-sampled attribute is checked, currently. General
|
||||
USD checks are always performed, and more restrictive checks targeted at
|
||||
distributable consumer content are also applied when the "--arkit" option
|
||||
is specified.""")
|
||||
|
||||
parser.add_argument('inputFile', type=str, nargs='?',
|
||||
help='Name of the input file to inspect.')
|
||||
parser.add_argument('-s', '--skipVariants', dest='skipVariants',
|
||||
action='store_true', help='If specified, only the prims'
|
||||
' that are present in the default (i.e. selected) '
|
||||
'variants are checked. When this option is not '
|
||||
'specified, prims in all possible combinations of '
|
||||
'variant selections are checked.')
|
||||
parser.add_argument('-p', '--rootPackageOnly', dest='rootPackageOnly',
|
||||
action="store_true", help='Check only the specified'
|
||||
'package. Nested packages, dependencies and their '
|
||||
'contents are not validated.')
|
||||
parser.add_argument('-o', '--out', dest='outFile', type=str, nargs='?',
|
||||
default='-', help='The file to which all the failed '
|
||||
'checks are output. If unspecified, the failed checks '
|
||||
'are output to stdout.')
|
||||
parser.add_argument('--noAssetChecks', dest='noAssetChecks',
|
||||
action='store_true', help='If specified, do NOT perform '
|
||||
'extra checks to help ensure the stage or '
|
||||
'package can be easily and safely referenced into '
|
||||
'aggregate stages.')
|
||||
parser.add_argument('--arkit', dest='arkit', action='store_true',
|
||||
help='Check if the given USD stage is compatible with '
|
||||
'ARKit\'s initial implementation of usdz. These assets '
|
||||
'operate under greater constraints that usdz files for '
|
||||
'more general in-house uses, and this option attempts '
|
||||
'to ensure that these constraints are met.')
|
||||
parser.add_argument('-d', '--dumpRules', dest='dumpRules',
|
||||
action='store_true', help='Dump the enumerated set of '
|
||||
'rules being checked for the given set of options.')
|
||||
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
|
||||
help='Enable verbose output mode.')
|
||||
|
||||
args = parser.parse_args()
|
||||
inputFile = args.inputFile
|
||||
outFile = args.outFile
|
||||
|
||||
checker = UsdUtils.ComplianceChecker(arkit=args.arkit,
|
||||
skipARKitRootLayerCheck=False,
|
||||
rootPackageOnly=args.rootPackageOnly,
|
||||
skipVariants=args.skipVariants,
|
||||
verbose=args.verbose,
|
||||
assetLevelChecks=not args.noAssetChecks)
|
||||
|
||||
if not args.dumpRules and not args.inputFile:
|
||||
parser.error("Either an inputFile or the --dumpRules option must be"
|
||||
"specified.")
|
||||
|
||||
if args.dumpRules:
|
||||
checker.DumpRules()
|
||||
# If there's no input file to check, exit after dumping the rules.
|
||||
if args.inputFile is None:
|
||||
return 0
|
||||
|
||||
checker.CheckCompliance(inputFile)
|
||||
|
||||
warnings = checker.GetWarnings()
|
||||
errors = checker.GetErrors()
|
||||
failedChecks = checker.GetFailedChecks()
|
||||
|
||||
with _Stream(outFile, 'w') as ofp:
|
||||
if len(warnings) > 0:
|
||||
for msg in warnings:
|
||||
# Add color if we're outputting to a terminal.
|
||||
if outFile == '-':
|
||||
msg = TermColors.WARN + msg + TermColors.END
|
||||
_Print(ofp, msg)
|
||||
|
||||
if len(errors)> 0 or len(failedChecks) > 0:
|
||||
for msg in errors + failedChecks:
|
||||
# Add color if we're outputting to a terminal.
|
||||
if outFile == '-':
|
||||
msg = TermColors.FAIL + msg + TermColors.END
|
||||
_Print(ofp, msg)
|
||||
print("Failed!")
|
||||
return 1
|
||||
|
||||
if len(warnings) > 0:
|
||||
print("Success with warnings...")
|
||||
else:
|
||||
print("Success!")
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdchecker" %*
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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 difflib, os, sys
|
||||
from subprocess import call
|
||||
|
||||
import platform
|
||||
isWindows = (platform.system() == 'Windows')
|
||||
|
||||
NO_DIFF_FOUND_EXIT_CODE = 0
|
||||
DIFF_FOUND_EXIT_CODE = 1
|
||||
ERROR_EXIT_CODE = 2
|
||||
|
||||
def _exit(msg, exitCode):
|
||||
if msg is not None:
|
||||
sys.stderr.write(msg + "\n")
|
||||
sys.exit(exitCode)
|
||||
|
||||
# generates a command list representing a call which will generate
|
||||
# a temporary ascii file used during diffing.
|
||||
def _generateCatCommand(usdcatCmd, inPath, outPath, flatten=None, fmt=None):
|
||||
command = [usdcatCmd, inPath, '--out', outPath]
|
||||
if flatten:
|
||||
command.append('--flatten')
|
||||
|
||||
if fmt and os.path.splitext(outPath)[1] == '.usd':
|
||||
command.append('--usdFormat')
|
||||
command.append(fmt)
|
||||
|
||||
return command
|
||||
|
||||
def _findExe(name):
|
||||
from distutils.spawn import find_executable
|
||||
cmd = find_executable(name)
|
||||
|
||||
if cmd:
|
||||
return cmd
|
||||
else:
|
||||
cmd = find_executable(name, path=os.path.abspath(os.path.dirname(sys.argv[0])))
|
||||
if cmd:
|
||||
return cmd
|
||||
|
||||
if isWindows:
|
||||
# find_executable under Windows only returns *.EXE files
|
||||
# so we need to traverse PATH.
|
||||
for path in os.environ['PATH'].split(os.pathsep):
|
||||
base = os.path.join(path, name)
|
||||
# We need to test for name.cmd first because on Windows, the USD
|
||||
# executables are wrapped due to lack of N*IX style shebang support
|
||||
# on Windows.
|
||||
for ext in ['.cmd', '']:
|
||||
cmd = base + ext
|
||||
if os.access(cmd, os.X_OK):
|
||||
return cmd
|
||||
return None
|
||||
|
||||
# looks up a suitable diff tool, and locates usdcat
|
||||
def _findDiffTools():
|
||||
usdcatCmd = _findExe("usdcat")
|
||||
if not usdcatCmd:
|
||||
_exit("Error: Could not find 'usdcat'. Expected it to be in PATH",
|
||||
ERROR_EXIT_CODE)
|
||||
|
||||
# prefer USD_DIFF, then DIFF, else use the internal unified diff.
|
||||
diffCmd = (os.environ.get('USD_DIFF') or os.environ.get('DIFF'))
|
||||
diffCmdArgs = list()
|
||||
if diffCmd:
|
||||
diffCmdList = diffCmd.split()
|
||||
diffCmd = diffCmdList[0]
|
||||
if diffCmdList[1:]:
|
||||
diffCmdArgs = diffCmdList[1:]
|
||||
if diffCmd and not _findExe(diffCmd):
|
||||
_exit("Error: Failed to find diff tool %s." % (diffCmd, ),
|
||||
ERROR_EXIT_CODE)
|
||||
|
||||
return (usdcatCmd, diffCmd, diffCmdArgs)
|
||||
|
||||
def _getFileFormat(path):
|
||||
from pxr import Sdf, Ar
|
||||
|
||||
# Note that python's os.path.splitext retains the '.' portion
|
||||
# when obtaining an extension, but Sdf's Fileformat API doesn't
|
||||
# expect one. We also make sure to prune out any version specifiers.
|
||||
_, ext = os.path.splitext(path)
|
||||
path = Ar.GetResolver().Resolve(path)
|
||||
if path is None:
|
||||
return None
|
||||
|
||||
if len(ext) <= 1:
|
||||
fileFormat = Sdf.FileFormat.FindByExtension('usd')
|
||||
else:
|
||||
prunedExtension = ext[1:]
|
||||
versionSpecifierPos = prunedExtension.rfind('#')
|
||||
if versionSpecifierPos != -1:
|
||||
prunedExtension = prunedExtension[:versionSpecifierPos]
|
||||
|
||||
fileFormat = Sdf.FileFormat.FindByExtension(prunedExtension)
|
||||
|
||||
# Don't check if file exists - this should be handled by resolver (and
|
||||
# path may not exist / have been fetched yet)
|
||||
if fileFormat:
|
||||
return fileFormat.formatId
|
||||
|
||||
return None
|
||||
|
||||
def _convertTo(inPath, outPath, usdcatCmd, flatten=None, fmt=None):
|
||||
# Just copy empty files -- we want something to diff against but
|
||||
# the file isn't valid usd.
|
||||
try:
|
||||
if os.stat(inPath).st_size == 0:
|
||||
import shutil
|
||||
try:
|
||||
shutil.copy(inPath, outPath)
|
||||
return 0
|
||||
except:
|
||||
return 1
|
||||
except (IOError, OSError):
|
||||
# assume it's because file doesn't exist yet, because it's an unresolved
|
||||
# path...
|
||||
pass
|
||||
return call(_generateCatCommand(usdcatCmd, inPath, outPath, flatten, fmt))
|
||||
|
||||
def _tryEdit(fileName, tempFileName, usdcatCmd, fileType, flattened):
|
||||
if flattened:
|
||||
_exit('Error: Cannot write out flattened result.', ERROR_EXIT_CODE)
|
||||
|
||||
if not os.access(fileName, os.W_OK):
|
||||
_exit('Error: Cannot write to %s, insufficient permissions' % fileName,
|
||||
ERROR_EXIT_CODE)
|
||||
|
||||
return _convertTo(tempFileName, fileName, usdcatCmd, flatten=None, fmt=fileType)
|
||||
|
||||
def _runDiff(baseline, comparison, flatten, noeffect, brief):
|
||||
from pxr import Tf
|
||||
|
||||
diffResult = 0
|
||||
|
||||
usdcatCmd, diffCmd, diffCmdArgs = _findDiffTools()
|
||||
baselineFileType = _getFileFormat(baseline)
|
||||
comparisonFileType = _getFileFormat(comparison)
|
||||
|
||||
pluginError = 'Error: Cannot find supported file format plugin for %s'
|
||||
if baselineFileType is None:
|
||||
_exit(pluginError % baseline, ERROR_EXIT_CODE)
|
||||
|
||||
if comparisonFileType is None:
|
||||
_exit(pluginError % comparison, ERROR_EXIT_CODE)
|
||||
|
||||
# Generate recognizable suffixes for our files in the temp dir
|
||||
# location of the form /temp/string__originalFileName.usda
|
||||
# where originalFileName is the basename(no extension) of the original file.
|
||||
# This allows users to tell which file is which when diffing.
|
||||
tempBaselineFileName = ("__" +
|
||||
os.path.splitext(os.path.basename(baseline))[0] + '.usda')
|
||||
tempComparisonFileName = ("__" +
|
||||
os.path.splitext(os.path.basename(comparison))[0] + '.usda')
|
||||
|
||||
with Tf.NamedTemporaryFile(suffix=tempBaselineFileName) as tempBaseline, \
|
||||
Tf.NamedTemporaryFile(suffix=tempComparisonFileName) as tempComparison:
|
||||
|
||||
# Dump the contents of our files into the temporaries
|
||||
convertError = 'Error: failed to convert from %s to %s.'
|
||||
if _convertTo(baseline, tempBaseline.name, usdcatCmd,
|
||||
flatten, fmt=None) != 0:
|
||||
_exit(convertError % (baseline, tempBaseline.name),
|
||||
ERROR_EXIT_CODE)
|
||||
if _convertTo(comparison, tempComparison.name, usdcatCmd,
|
||||
flatten, fmt=None) != 0:
|
||||
_exit(convertError % (comparison, tempComparison.name),
|
||||
ERROR_EXIT_CODE)
|
||||
|
||||
tempBaselineTimestamp = os.path.getmtime(tempBaseline.name)
|
||||
tempComparisonTimestamp = os.path.getmtime(tempComparison.name)
|
||||
|
||||
if diffCmd:
|
||||
# Run the external diff tool.
|
||||
if brief:
|
||||
diffCmdArgs.append("--brief")
|
||||
diffResult = call([diffCmd] + diffCmdArgs + [tempBaseline.name, tempComparison.name])
|
||||
|
||||
else:
|
||||
# Read the files.
|
||||
with open(tempBaseline.name, "r") as f:
|
||||
baselineData = f.readlines()
|
||||
with open(tempComparison.name, "r") as f:
|
||||
comparisonData = f.readlines()
|
||||
|
||||
if baselineData != comparisonData:
|
||||
if brief:
|
||||
print("Files %s and %s differ" % (baseline, comparison))
|
||||
else:
|
||||
# Generate unified diff and output if there are any differences.
|
||||
diff = list(difflib.unified_diff(
|
||||
baselineData, comparisonData,
|
||||
tempBaseline.name, tempComparison.name, n=0))
|
||||
# Skip the file names.
|
||||
for line in diff[2:]:
|
||||
print(line, end='')
|
||||
diffResult = 1
|
||||
|
||||
tempBaselineChanged = (
|
||||
os.path.getmtime(tempBaseline.name) != tempBaselineTimestamp)
|
||||
tempComparisonChanged = (
|
||||
os.path.getmtime(tempComparison.name) != tempComparisonTimestamp)
|
||||
|
||||
# If we intend to edit either of the files
|
||||
if not noeffect:
|
||||
if tempBaselineChanged:
|
||||
if _tryEdit(baseline, tempBaseline.name,
|
||||
usdcatCmd, baselineFileType, flatten) != 0:
|
||||
_exit(convertError % (baseline, tempBaseline.name),
|
||||
ERROR_EXIT_CODE)
|
||||
if tempComparisonChanged:
|
||||
if _tryEdit(comparison, tempComparison.name,
|
||||
usdcatCmd, comparisonFileType, flatten) != 0:
|
||||
_exit(convertError % (comparison, tempComparison.name),
|
||||
ERROR_EXIT_CODE)
|
||||
return diffResult
|
||||
|
||||
def _findFiles(args):
|
||||
'''Return a 3-tuple of lists: (baseline-only, matching, comparison-only).
|
||||
baseline-only and comparison-only are lists of individual files, while
|
||||
matching is a list of corresponding pairs of files.'''
|
||||
import os
|
||||
import stat
|
||||
from pxr import Ar
|
||||
|
||||
join = os.path.join
|
||||
basename = os.path.basename
|
||||
exists = os.path.exists
|
||||
|
||||
def listFiles(dirpath):
|
||||
ret = []
|
||||
for root, _, files in os.walk(dirpath):
|
||||
ret += [os.path.relpath(join(root, file), dirpath)
|
||||
for file in files]
|
||||
return set(ret)
|
||||
|
||||
# Must have FILE FILE, DIR DIR, DIR FILES... or FILES... DIR.
|
||||
err = ValueError("Error: File arguments must be one of: "
|
||||
"FILE FILE, DIR DIR, DIR FILES..., or FILES... DIR.")
|
||||
if len(args) < 2:
|
||||
raise err
|
||||
|
||||
# For speed, since filestats can be slow, stat all args once, then reuse that
|
||||
# to determine isdir/isfile
|
||||
resolver = Ar.GetResolver()
|
||||
stats = []
|
||||
for arg in args:
|
||||
try:
|
||||
st = os.stat(arg)
|
||||
except (OSError, IOError):
|
||||
if not resolver.Resolve(arg):
|
||||
raise ValueError("Error: %s does not exist, and cannot be "
|
||||
"resolved" % arg)
|
||||
st = None
|
||||
stats.append(st)
|
||||
|
||||
def isdir(st):
|
||||
return st and stat.S_ISDIR(st.st_mode)
|
||||
|
||||
# if any of the directory forms are used, no paths may be unresolved assets
|
||||
def validateFiles():
|
||||
for i, st in enumerate(stats):
|
||||
if st is None:
|
||||
raise ValueError("Error: %s did not exist on disk, and using a "
|
||||
"directory comparison form" % args[i])
|
||||
|
||||
# DIR FILES...
|
||||
if isdir(stats[0]) and not any(map(isdir, stats[1:])):
|
||||
validateFiles()
|
||||
dirpath = args[0]
|
||||
files = set(map(os.path.relpath, args[1:]))
|
||||
dirfiles = listFiles(dirpath)
|
||||
return ([],
|
||||
[(join(dirpath, p), p) for p in files & dirfiles],
|
||||
[p for p in files - dirfiles])
|
||||
# FILES... DIR
|
||||
elif not any(map(isdir, stats[:-1])) and isdir(stats[-1]):
|
||||
validateFiles()
|
||||
dirpath = args[-1]
|
||||
files = set(map(os.path.relpath, args[:-1]))
|
||||
dirfiles = listFiles(dirpath)
|
||||
return ([p for p in files - dirfiles],
|
||||
[(p, join(dirpath, p)) for p in files & dirfiles],
|
||||
[])
|
||||
# FILE FILE or DIR DIR
|
||||
elif len(args) == 2:
|
||||
# DIR DIR
|
||||
if all(map(isdir, stats)):
|
||||
ldir, rdir = args[0], args[1]
|
||||
lhs, rhs = map(listFiles, args)
|
||||
return (
|
||||
# baseline only
|
||||
sorted([join(ldir, p) for p in lhs - rhs]),
|
||||
# corresponding
|
||||
sorted([(join(ldir, p), join(rdir, p)) for p in lhs & rhs]),
|
||||
# comparison only
|
||||
sorted([join(rdir, p) for p in rhs - lhs]))
|
||||
# FILE FILE
|
||||
elif not any(map(isdir, stats)):
|
||||
return ([], [(args[0], args[1])], [])
|
||||
|
||||
raise err
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),
|
||||
description="Compares two usd-readable files using a selected"
|
||||
" diff program. This is chosen by looking at the"
|
||||
" $USD_DIFF environment variable. If this is unset,"
|
||||
" it will consult the $DIFF environment variable. "
|
||||
" Lastly, if neither of these is set, it will try"
|
||||
" to use the canonical unix program, diff."
|
||||
" This will relay the exit code of the selected"
|
||||
" diff program.")
|
||||
parser.add_argument('files', nargs='+',
|
||||
help='The files to compare. These must be of the form '
|
||||
'DIR DIR, FILE... DIR, DIR FILE... or FILE FILE. ')
|
||||
parser.add_argument('-n', '--noeffect', action='store_true',
|
||||
help='Do not edit either file.')
|
||||
parser.add_argument('-f', '--flatten', action='store_true',
|
||||
help='Fully compose both layers as Usd Stages and '
|
||||
'flatten into single layers.')
|
||||
parser.add_argument('-q', '--brief', action='store_true',
|
||||
help='Do not return full results of diffs. Passes --brief to the diff command.')
|
||||
|
||||
results = parser.parse_args()
|
||||
diffResult = NO_DIFF_FOUND_EXIT_CODE
|
||||
|
||||
try:
|
||||
baselineOnly, common, comparisonOnly = _findFiles(results.files)
|
||||
|
||||
for (baseline, comparison) in common:
|
||||
if _runDiff(baseline, comparison,
|
||||
results.flatten, results.noeffect, results.brief):
|
||||
diffResult = DIFF_FOUND_EXIT_CODE
|
||||
|
||||
mismatchMsg = 'No corresponding file found for %s, skipping.'
|
||||
for b in baselineOnly:
|
||||
print(mismatchMsg % b)
|
||||
|
||||
for c in comparisonOnly:
|
||||
print(mismatchMsg % c)
|
||||
|
||||
except ValueError as err:
|
||||
_exit(str(err), ERROR_EXIT_CODE)
|
||||
|
||||
_exit(None, diffResult)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usddiff" %*
|
||||
@@ -0,0 +1,77 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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 argparse, sys, os
|
||||
from pxr import Sdf, Usd
|
||||
|
||||
def Err(msg):
|
||||
print('Error: ' + msg, file=sys.stderr)
|
||||
|
||||
def PrintReport(fname, info, summaryOnly):
|
||||
print('@%s@' % fname, 'file version', info.GetFileVersion())
|
||||
ss = info.GetSummaryStats()
|
||||
print (' %s specs, %s paths, %s tokens, %s strings, '
|
||||
'%s fields, %s field sets' %
|
||||
(ss.numSpecs, ss.numUniquePaths, ss.numUniqueTokens,
|
||||
ss.numUniqueStrings, ss.numUniqueFields, ss.numUniqueFieldSets))
|
||||
if summaryOnly:
|
||||
return
|
||||
print(' Structural Sections:')
|
||||
for sec in info.GetSections():
|
||||
print(' %16s %16d bytes at offset 0x%X' % (
|
||||
sec.name, sec.size, sec.start))
|
||||
print()
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog=os.path.basename(sys.argv[0]),
|
||||
description='Write information about a usd crate (usdc) file to stdout')
|
||||
|
||||
parser.add_argument('inputFiles', nargs='+')
|
||||
parser.add_argument('-s', '--summary', action='store_true',
|
||||
help='report only a short summary')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
print('Usd crate software version', Usd.CrateInfo().GetSoftwareVersion())
|
||||
|
||||
for fname in args.inputFiles:
|
||||
try:
|
||||
info = Usd.CrateInfo.Open(fname)
|
||||
if not info:
|
||||
Err('Failed to read %s' % fname)
|
||||
continue
|
||||
except Exception as e:
|
||||
Err('Failed to read %s\n %s' % (fname,e))
|
||||
continue
|
||||
PrintReport(fname, info, args.summary)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Restore signal handling defaults to allow output redirection and the like.
|
||||
import platform
|
||||
if platform.system() != 'Windows':
|
||||
import signal
|
||||
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usddumpcrate" %*
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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 os, sys
|
||||
|
||||
import platform
|
||||
isWindows = (platform.system() == 'Windows')
|
||||
|
||||
def _findExe(name):
|
||||
from distutils.spawn import find_executable
|
||||
cmd = find_executable(name)
|
||||
if cmd:
|
||||
return cmd
|
||||
else:
|
||||
cmd = find_executable(name, path=os.path.abspath(os.path.dirname(sys.argv[0])))
|
||||
if cmd:
|
||||
return cmd
|
||||
|
||||
if isWindows:
|
||||
# find_executable under Windows only returns *.EXE files
|
||||
# so we need to traverse PATH.
|
||||
for path in os.environ['PATH'].split(os.pathsep):
|
||||
base = os.path.join(path, name)
|
||||
# We need to test for name.cmd first because on Windows, the USD
|
||||
# executables are wrapped due to lack of N*IX style shebang support
|
||||
# on Windows.
|
||||
for ext in ['.cmd', '']:
|
||||
cmd = base + ext
|
||||
if os.access(cmd, os.X_OK):
|
||||
return cmd
|
||||
return None
|
||||
|
||||
# lookup usdcat and a suitable text editor. if none are available,
|
||||
# this will cause the program to abort with a suitable error message.
|
||||
def _findEditorTools(usdFileName, readOnly):
|
||||
# Ensure the usdcat executable has been installed
|
||||
usdcatCmd = _findExe("usdcat")
|
||||
if not usdcatCmd:
|
||||
sys.exit("Error: Couldn't find 'usdcat'. Expected it to be in PATH.")
|
||||
|
||||
# Ensure we have a suitable editor available
|
||||
editorCmd = (os.getenv("USD_EDITOR") or
|
||||
os.getenv("EDITOR") or
|
||||
_findExe("emacs") or
|
||||
_findExe("vim") or
|
||||
_findExe("notepad"))
|
||||
|
||||
if not editorCmd:
|
||||
sys.exit("Error: Couldn't find a suitable text editor to use. Expected "
|
||||
"$USD_EDITOR or $EDITOR to be set, or emacs/vim/notepad to "
|
||||
"be installed and available in PATH.")
|
||||
|
||||
# special handling for emacs users
|
||||
if 'emacs' in editorCmd:
|
||||
title = '"usdedit %s%s"' % ("--noeffect " if readOnly else "",
|
||||
usdFileName)
|
||||
editorCmd += " -name %s" % title
|
||||
|
||||
return (usdcatCmd, editorCmd)
|
||||
|
||||
# this generates a temporary usd file which the user will edit.
|
||||
def _generateTemporaryFile(usdcatCmd, usdFileName, readOnly, prefix):
|
||||
# gets the base name of the USD file opened
|
||||
usdFileNameBasename = os.path.splitext(os.path.basename(usdFileName))[0]
|
||||
|
||||
fullPrefix = prefix or usdFileNameBasename + "_tmp"
|
||||
import tempfile
|
||||
(usdaFile, usdaFileName) = tempfile.mkstemp(
|
||||
prefix=fullPrefix, suffix='.usda', dir=os.getcwd())
|
||||
|
||||
# No need for an open file descriptor, as it locks the file in Windows.
|
||||
os.close(usdaFile)
|
||||
|
||||
os.system(usdcatCmd + ' ' + usdFileName + '> ' + usdaFileName)
|
||||
|
||||
if readOnly:
|
||||
os.chmod(usdaFileName, 0o444)
|
||||
|
||||
# Thrown if failed to open temp file Could be caused by
|
||||
# failure to read USD file
|
||||
if os.stat(usdaFileName).st_size == 0:
|
||||
sys.exit("Error: Failed to open file %s, exiting." % usdFileName)
|
||||
|
||||
return usdaFileName
|
||||
|
||||
# allow the user to edit the temporary file, and return whether or
|
||||
# not they made any changes.
|
||||
def _editTemporaryFile(editorCmd, usdaFileName):
|
||||
# check the timestamp before updating a file's mtime
|
||||
initialTimeStamp = os.path.getmtime(usdaFileName)
|
||||
os.system(editorCmd + ' ' + usdaFileName)
|
||||
newTimeStamp = os.path.getmtime(usdaFileName)
|
||||
|
||||
# indicate whether the file was changed
|
||||
return initialTimeStamp != newTimeStamp
|
||||
|
||||
# attempt to write out our changes to the actual usd file
|
||||
def _writeOutChanges(temporaryFileName, permanentFileName):
|
||||
from pxr import Sdf, Tf
|
||||
|
||||
try:
|
||||
temporaryLayer = Sdf.Layer.FindOrOpen(temporaryFileName)
|
||||
except Tf.ErrorException as err:
|
||||
sys.exit("Error: Failed to open temporary layer %s, and therefore cannot save your edits back to original file %s"
|
||||
". An error occurred trying to parse the file: %s" % (temporaryFileName, permanentFileName, str(err)))
|
||||
|
||||
# Note that we attempt to overwrite the permanent file's contents
|
||||
# rather than explicitly creating a new layer. This avoids aligning
|
||||
# file format paremeters from the original to the new.
|
||||
outLayer = Sdf.Layer.FindOrOpen(permanentFileName)
|
||||
if not outLayer:
|
||||
sys.exit("Error: Unable to save edits back to the original file %s"
|
||||
". Your edits can be found in %s." \
|
||||
%(permanentFileName, temporaryFileName))
|
||||
outLayer.TransferContent(temporaryLayer)
|
||||
return outLayer.Save()
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),
|
||||
description= 'Convert a usd-readable file to the usd ascii format in \n'
|
||||
'a temporary location and invoke an editor on it. After \n'
|
||||
'saving and quitting the editor, the edited file will be \n'
|
||||
'converted back to the original format and OVERWRITE the \n'
|
||||
'original file, unless you supply the "-n" (--noeffect) flag, \n'
|
||||
'in which case no changes will be saved back to the original '
|
||||
'file. \n'
|
||||
'The editor to use will be looked up as follows: \n'
|
||||
' - USD_EDITOR environment variable \n'
|
||||
' - EDITOR environment variable \n'
|
||||
' - emacs in PATH \n'
|
||||
' - vim in PATH \n'
|
||||
' - notepad in PATH \n'
|
||||
'\n\n')
|
||||
parser.add_argument('-n', '--noeffect',
|
||||
dest='readOnly', action='store_true',
|
||||
help='Do not edit the file.')
|
||||
parser.add_argument('-f', '--forcewrite',
|
||||
dest='forceWrite', action='store_true',
|
||||
help='Override file permissions to allow writing.')
|
||||
parser.add_argument('-p', '--prefix',
|
||||
dest='prefix', action='store', type=str, default=None,
|
||||
help='Provide a prefix for the temporary file name.')
|
||||
parser.add_argument('usdFileName', help='The usd file to edit.')
|
||||
results = parser.parse_args()
|
||||
|
||||
# pull args from result map so we don't need to write result. for each
|
||||
readOnly, forceWrite, usdFileName, prefix = (
|
||||
results.readOnly,
|
||||
results.forceWrite,
|
||||
results.usdFileName,
|
||||
results.prefix)
|
||||
|
||||
# verify our usd file exists, and permissions args are sane
|
||||
if readOnly and forceWrite:
|
||||
sys.exit("Error: Cannot set read only(-n) and force "
|
||||
" write(-f) together.")
|
||||
|
||||
from pxr import Ar
|
||||
resolvedPath = Ar.GetResolver().Resolve(usdFileName)
|
||||
if not resolvedPath:
|
||||
sys.exit("Error: Cannot find file %s" % usdFileName)
|
||||
|
||||
# Layers in packages cannot be written using the Sdf API.
|
||||
from pxr import Ar, Sdf
|
||||
(package, packaged) = Ar.SplitPackageRelativePathOuter(resolvedPath)
|
||||
|
||||
extension = Sdf.FileFormat.GetFileExtension(package)
|
||||
fileFormat = Sdf.FileFormat.FindByExtension(extension)
|
||||
if not fileFormat:
|
||||
sys.exit("Error: Unknown file format")
|
||||
|
||||
if fileFormat.IsPackage():
|
||||
print("Warning: Edits cannot be saved to layers in %s files. "
|
||||
"Starting in no-effect mode." % extension)
|
||||
readOnly = True
|
||||
forceWrite = False
|
||||
|
||||
writable = os.path.isfile(usdFileName) and os.access(usdFileName, os.W_OK)
|
||||
if not (writable or readOnly or forceWrite):
|
||||
sys.exit("Error: File isn't writable, and "
|
||||
"readOnly(-n)/forceWrite(-f) haven't been marked.")
|
||||
|
||||
# ensure we have both a text editor and usdcat available
|
||||
usdcatCmd, editorCmd = _findEditorTools(usdFileName, readOnly)
|
||||
|
||||
# generate our temporary file with proper permissions and edit.
|
||||
usdaFileName = _generateTemporaryFile(usdcatCmd, usdFileName,
|
||||
readOnly, prefix)
|
||||
tempFileChanged = _editTemporaryFile(editorCmd, usdaFileName)
|
||||
|
||||
|
||||
if (not readOnly or forceWrite) and tempFileChanged:
|
||||
# note that we need not overwrite usdFileName's write permissions
|
||||
# because we will be creating a new layer at that path.
|
||||
if not _writeOutChanges(temporaryFileName=usdaFileName,
|
||||
permanentFileName=usdFileName):
|
||||
sys.exit("Error: Unable to save edits back to the original file %s"
|
||||
". Your edits can be found in %s. " \
|
||||
%(usdFileName, usdaFileName))
|
||||
|
||||
if readOnly:
|
||||
os.chmod(usdaFileName, 0o644)
|
||||
os.remove(usdaFileName)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdedit" %*
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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 pxr import Usd
|
||||
from pxr import UsdAppUtils
|
||||
from pxr import Tf
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def _Msg(msg):
|
||||
sys.stdout.write(msg + '\n')
|
||||
|
||||
def _Err(msg):
|
||||
sys.stderr.write(msg + '\n')
|
||||
|
||||
def _SetupOpenGLContext(width=100, height=100):
|
||||
try:
|
||||
from PySide2 import QtOpenGL
|
||||
from PySide2.QtWidgets import QApplication
|
||||
except ImportError:
|
||||
from PySide import QtOpenGL
|
||||
from PySide.QtGui import QApplication
|
||||
|
||||
application = QApplication(sys.argv)
|
||||
|
||||
glFormat = QtOpenGL.QGLFormat()
|
||||
glFormat.setSampleBuffers(True)
|
||||
glFormat.setSamples(4)
|
||||
|
||||
glWidget = QtOpenGL.QGLWidget(glFormat)
|
||||
glWidget.setFixedSize(width, height)
|
||||
# note that we need to bind the gl context here, instead of explicitly
|
||||
# showing the glWidget. Binding the gl context will make sure framebuffer is
|
||||
# ready for gl operations.
|
||||
glWidget.makeCurrent()
|
||||
|
||||
return glWidget
|
||||
|
||||
def main():
|
||||
programName = os.path.basename(sys.argv[0])
|
||||
parser = argparse.ArgumentParser(prog=programName,
|
||||
description='Generates images from a USD file')
|
||||
|
||||
# Positional (required) arguments.
|
||||
parser.add_argument('usdFilePath', action='store', type=str,
|
||||
help='USD file to record')
|
||||
parser.add_argument('outputImagePath', action='store', type=str,
|
||||
help=(
|
||||
'Output image path. For frame ranges, the path must contain '
|
||||
'exactly one frame number placeholder of the form "###" or '
|
||||
'"###.###". Note that the number of hash marks is variable in '
|
||||
'each group.'))
|
||||
|
||||
# Optional arguments.
|
||||
parser.add_argument('--mask', action='store', type=str,
|
||||
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('--purposes', action='store', type=str,
|
||||
dest='purposes', metavar='PURPOSE[,PURPOSE...]', default='proxy',
|
||||
help=(
|
||||
'Specify which UsdGeomImageable purposes should be included '
|
||||
'in the renders. The "default" purpose is automatically included, '
|
||||
'so you need specify only the *additional* purposes. If you want '
|
||||
'more than one extra purpose, either use commas with no spaces or '
|
||||
'quote the argument and separate purposes by commas and/or spaces.'))
|
||||
|
||||
UsdAppUtils.cameraArgs.AddCmdlineArgs(parser)
|
||||
UsdAppUtils.framesArgs.AddCmdlineArgs(parser)
|
||||
UsdAppUtils.complexityArgs.AddCmdlineArgs(parser)
|
||||
UsdAppUtils.colorArgs.AddCmdlineArgs(parser)
|
||||
UsdAppUtils.rendererArgs.AddCmdlineArgs(parser)
|
||||
|
||||
parser.add_argument('--imageWidth', '-w', action='store', type=int,
|
||||
default=960,
|
||||
help=(
|
||||
'Width of the output image. The height will be computed from this '
|
||||
'value and the camera\'s aspect ratio (default=%(default)s)'))
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
UsdAppUtils.framesArgs.ValidateCmdlineArgs(parser, args,
|
||||
frameFormatArgName='outputImagePath')
|
||||
|
||||
args.imageWidth = max(args.imageWidth, 1)
|
||||
|
||||
purposes = args.purposes.replace(',', ' ').split()
|
||||
|
||||
# Open the USD stage, using a population mask if paths were given.
|
||||
if args.populationMask:
|
||||
populationMaskPaths = args.populationMask.replace(',', ' ').split()
|
||||
|
||||
populationMask = Usd.StagePopulationMask()
|
||||
for maskPath in populationMaskPaths:
|
||||
populationMask.Add(maskPath)
|
||||
|
||||
usdStage = Usd.Stage.OpenMasked(args.usdFilePath, populationMask)
|
||||
else:
|
||||
usdStage = Usd.Stage.Open(args.usdFilePath)
|
||||
|
||||
if not usdStage:
|
||||
_Err('Could not open USD stage: %s' % args.usdFilePath)
|
||||
return 1
|
||||
|
||||
# Get the camera at the given path (or with the given name).
|
||||
usdCamera = UsdAppUtils.GetCameraAtPath(usdStage, args.camera)
|
||||
|
||||
# Frame-independent initialization.
|
||||
# Note that the size of the widget doesn't actually affect the size of the
|
||||
# output image. We just pass it along for cleanliness.
|
||||
glWidget = _SetupOpenGLContext(args.imageWidth, args.imageWidth)
|
||||
|
||||
frameRecorder = UsdAppUtils.FrameRecorder()
|
||||
if args.rendererPlugin:
|
||||
frameRecorder.SetRendererPlugin(
|
||||
UsdAppUtils.rendererArgs.GetPluginIdFromArgument(
|
||||
args.rendererPlugin))
|
||||
frameRecorder.SetImageWidth(args.imageWidth)
|
||||
frameRecorder.SetComplexity(args.complexity.value)
|
||||
frameRecorder.SetColorCorrectionMode(args.colorCorrectionMode)
|
||||
frameRecorder.SetIncludedPurposes(purposes)
|
||||
|
||||
_Msg('Camera: %s' % usdCamera.GetPath().pathString)
|
||||
_Msg('Renderer plugin: %s' % frameRecorder.GetCurrentRendererId())
|
||||
|
||||
for timeCode in args.frames:
|
||||
_Msg('Recording time code: %s' % timeCode)
|
||||
outputImagePath = args.outputImagePath.format(frame=timeCode.GetValue())
|
||||
try:
|
||||
frameRecorder.Record(usdStage, usdCamera, timeCode, outputImagePath)
|
||||
except Tf.ErrorException as e:
|
||||
|
||||
_Err("Recording aborted due to the following failure at time code "
|
||||
"{0}: {1}".format(timeCode, str(e)))
|
||||
break
|
||||
|
||||
# Release our reference to the frame recorder so it can be deleted before
|
||||
# the Qt stuff.
|
||||
frameRecorder = None
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdrecord" %*
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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
|
||||
|
||||
import argparse, sys, os
|
||||
|
||||
from pxr import Ar
|
||||
|
||||
def _HasCreateIdentifier():
|
||||
return hasattr(Ar.Resolver, "CreateIdentifier")
|
||||
|
||||
def _HasConfigureResolverForAsset():
|
||||
return hasattr(Ar.Resolver, "ConfigureResolverForAsset")
|
||||
|
||||
def _Msg(msg):
|
||||
sys.stdout.write(msg + '\n')
|
||||
|
||||
def _Err(msg):
|
||||
sys.stderr.write(msg + '\n')
|
||||
|
||||
def _ConfigureAssetResolver(args, resolver):
|
||||
if _HasConfigureResolverForAsset():
|
||||
configurePath = args.configureAssetPath or args.inputPath
|
||||
resolver.ConfigureResolverForAsset(configurePath)
|
||||
else:
|
||||
if args.createContextForAsset:
|
||||
return resolver.CreateDefaultContextForAsset(
|
||||
args.createContextForAsset)
|
||||
elif args.createContextFromString:
|
||||
configStrs = []
|
||||
for s in args.createContextFromString:
|
||||
try:
|
||||
uriScheme, config = s.split(":", 1)
|
||||
configStrs.append((uriScheme, config))
|
||||
except ValueError:
|
||||
configStrs.append(("", s))
|
||||
return resolver.CreateContextFromStrings(configStrs)
|
||||
|
||||
return resolver.CreateDefaultContextForAsset(args.inputPath)
|
||||
|
||||
def _AnchorRelativePath(args, resolver):
|
||||
if args.anchorPath:
|
||||
if _HasCreateIdentifier():
|
||||
return resolver.CreateIdentifier(
|
||||
args.inputPath, Ar.ResolvedPath(args.anchorPath))
|
||||
elif resolver.IsRelativePath(args.inputPath):
|
||||
return resolver.AnchorRelativePath(args.anchorPath, args.inputPath)
|
||||
return args.inputPath
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Resolves an asset path using a fully configured USD Asset Resolver.')
|
||||
|
||||
parser.add_argument('inputPath',
|
||||
help="An asset path to be resolved by the USD Asset Resolver.")
|
||||
|
||||
if _HasConfigureResolverForAsset():
|
||||
parser.add_argument(
|
||||
'--configureAssetPath',
|
||||
help="Run ConfigureResolverForAsset on the given asset path.")
|
||||
else:
|
||||
subparser = parser.add_mutually_exclusive_group()
|
||||
subparser.add_argument(
|
||||
'--createContextForAsset',
|
||||
help=("Run CreateDefaultContextForAsset with the given asset path "
|
||||
"to create the context used for resolution."))
|
||||
subparser.add_argument(
|
||||
'--createContextFromString', action='append',
|
||||
help=("Run CreateContextFromString with the given string to create "
|
||||
"the context used for resolution. This accepts strings like "
|
||||
"[<URI Scheme>:]<Configuration String> and may be specified "
|
||||
"multiple times.\n\n"
|
||||
"ex: usdresolve --createContextFromString 'config_primary' "
|
||||
"--createContextFromString 'my_uri_scheme:config_uri'"))
|
||||
|
||||
if _HasCreateIdentifier():
|
||||
parser.add_argument(
|
||||
'--anchorPath',
|
||||
help=("Run CreateIdentifier with the input path and this anchor "
|
||||
"asset path and resolve the result.\n\n"
|
||||
"ex: usdresolve --anchorPath /asset/asset.usd sublayer.usd"))
|
||||
else:
|
||||
parser.add_argument(
|
||||
'--anchorPath',
|
||||
help="Run AnchorRelativePath on the given asset path.")
|
||||
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
exitCode = 0
|
||||
|
||||
resolver = Ar.GetResolver()
|
||||
|
||||
try:
|
||||
resolverContext = _ConfigureAssetResolver(args, resolver)
|
||||
with Ar.ResolverContextBinder(resolverContext):
|
||||
inputPath = _AnchorRelativePath(args, resolver)
|
||||
resolved = resolver.Resolve(inputPath)
|
||||
except Exception as e:
|
||||
_Err("Failed to resolve '%s' - %s" % (args.inputPath, e))
|
||||
exitCode = 1
|
||||
|
||||
if not resolved:
|
||||
_Err("Failed to resolve '%s'" % args.inputPath)
|
||||
exitCode = 1
|
||||
else:
|
||||
print(resolved)
|
||||
|
||||
return exitCode
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Restore signal handling defaults to allow output redirection and the like.
|
||||
import platform
|
||||
if platform.system() != 'Windows':
|
||||
import signal
|
||||
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdresolve" %*
|
||||
@@ -0,0 +1,76 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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 argparse, os, sys
|
||||
from pxr import UsdUtils, Sdf, Tf
|
||||
|
||||
parser = argparse.ArgumentParser( \
|
||||
prog=sys.argv[0],
|
||||
description='Stitch multiple usd file(s) together '
|
||||
'into one. Opinion strength is determined by '
|
||||
'the order in which the file is given, with the '
|
||||
'first file getting the highest strength. '
|
||||
'The exception to this general behavior is in '
|
||||
'time samples, which are merged together as a '
|
||||
'union across the input layers. It is consistent '
|
||||
'in that, if two time sample keys conflict, the '
|
||||
'strong layer takes precedence.')
|
||||
|
||||
parser.add_argument('usdFiles', nargs='+')
|
||||
parser.add_argument('-o', '--out', action='store',
|
||||
help='specify a file to write out to')
|
||||
results = parser.parse_args()
|
||||
assert results.out != None, "must specify output file"
|
||||
|
||||
if os.path.isfile(results.out):
|
||||
print("Warning: overwriting pre-existing file")
|
||||
|
||||
# fold over the files, left file takes precedence on op. strength
|
||||
outLayer = Sdf.Layer.CreateNew(results.out)
|
||||
|
||||
# open up all of the files into memory before stitching.
|
||||
# if one is missing, this will allow us to fail without doing
|
||||
#
|
||||
# try opening all files
|
||||
openedFiles = [Sdf.Layer.FindOrOpen(fname) for fname in results.usdFiles]
|
||||
# grab the index of all, if any, files which failed to open
|
||||
unopened = [i for i, unopened in enumerate(openedFiles) if unopened == None ]
|
||||
# grab the filenames of the failed files for error messaging
|
||||
erroredFiles = ' '.join([results.usdFiles[i] for i in unopened])
|
||||
# if we failed to open any files, error out
|
||||
assert len(unopened) == 0, 'unable to open file(s) %s' %erroredFiles
|
||||
|
||||
# the extra computation and fail more gracefully
|
||||
try:
|
||||
for usdFile in openedFiles:
|
||||
UsdUtils.StitchLayers(outLayer, usdFile)
|
||||
outLayer.Save()
|
||||
# if something in the authoring fails, remove the output file
|
||||
except Exception as e:
|
||||
print('Failed to complete stitching, removing output file %s' % results.out)
|
||||
print(e)
|
||||
os.remove(results.out)
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdstitch" %*
|
||||
@@ -0,0 +1,167 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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 argparse, os, sys
|
||||
from pxr import UsdUtils, Sdf, Tf
|
||||
|
||||
parser = argparse.ArgumentParser( \
|
||||
prog=os.path.basename(sys.argv[0]),
|
||||
description='Stitch multiple usd file(s) together '
|
||||
'into one using value clips.\n'
|
||||
'An example command is:\n\n'
|
||||
'usdstitchclips --out result.usd --clipPath '
|
||||
'/World/fx/Particles_Splash clip1.usd clip2.usd '
|
||||
'\n\n'
|
||||
'This will produce two files, a result.topology.usd '
|
||||
'and a result.usd.',
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
|
||||
parser.add_argument('usdFiles', nargs='+')
|
||||
parser.add_argument('-o', '--out', action='store',
|
||||
help='specify the filename for the top-level result file, which also serves as base-name for the topology and manifest files.')
|
||||
parser.add_argument('-c', '--clipPath', action='store',
|
||||
help='specify a prim path at which to begin stitching clip data.')
|
||||
parser.add_argument('-s', '--startTimeCode', action='store',
|
||||
help='specify the time at which the clips will become active')
|
||||
parser.add_argument('-r', '--stride', action='store',
|
||||
help='specify a stride for the numeric component of filenames for template metadata')
|
||||
parser.add_argument('-e', '--endTimeCode', action='store',
|
||||
help='specify the time at which the clips will cease being active')
|
||||
parser.add_argument('-t', '--templateMetadata', action='store_true',
|
||||
help='author template clip metadata in the root layer.')
|
||||
parser.add_argument('-p', '--templatePath', action='store',
|
||||
help='specify a template asset path to author')
|
||||
parser.add_argument('--clipSet', action='store',
|
||||
help='specify a named clipSet in which to author clip metadata, so that multiple sets of clips can be applied on the same prim.')
|
||||
parser.add_argument('--activeOffset', action='store', required=False,
|
||||
help='specify an offset for template-based clips, offsetting the frame number of each clip file.')
|
||||
parser.add_argument('--interpolateMissingClipValues', action='store_true',
|
||||
help=('specify whether values for clips without authored '
|
||||
'samples are interpolated from surrounding clips '
|
||||
'if no default value is authored in any clip.'))
|
||||
# useful for debugging with diffs
|
||||
parser.add_argument('-n', '--noComment', action='store_true',
|
||||
help='do not write a comment specifying how the usd file was generated')
|
||||
results = parser.parse_args()
|
||||
|
||||
# verify the integrity of the inputs
|
||||
assert results.out is not None, "must specify output file(--out)"
|
||||
assert results.clipPath is not None, "must specify a clip path(--clipPath)"
|
||||
assert results.usdFiles is not None, "must specify clip files"
|
||||
|
||||
if os.path.isfile(results.out):
|
||||
print("Warning: merging with current result layer")
|
||||
|
||||
outLayerGenerated = False
|
||||
topologyLayerGenerated = False
|
||||
topologyLayerName = ""
|
||||
|
||||
try:
|
||||
outLayer = Sdf.Layer.FindOrOpen(results.out)
|
||||
if not outLayer:
|
||||
outLayerGenerated = True
|
||||
outLayer = Sdf.Layer.CreateNew(results.out)
|
||||
|
||||
topologyLayerName = UsdUtils.GenerateClipTopologyName(results.out)
|
||||
topologyLayer = Sdf.Layer.FindOrOpen(topologyLayerName)
|
||||
if not topologyLayer:
|
||||
topologyLayerGenerated = True
|
||||
topologyLayer = Sdf.Layer.CreateNew(topologyLayerName)
|
||||
|
||||
manifestLayerName = UsdUtils.GenerateClipManifestName(results.out)
|
||||
manifestLayer = Sdf.Layer.FindOrOpen(manifestLayerName)
|
||||
if not manifestLayer:
|
||||
manifestLayerGenerated = True
|
||||
manifestLayer = Sdf.Layer.CreateNew(manifestLayerName)
|
||||
|
||||
if results.startTimeCode:
|
||||
results.startTimeCode = float(results.startTimeCode)
|
||||
|
||||
if results.endTimeCode:
|
||||
results.endTimeCode = float(results.endTimeCode)
|
||||
|
||||
if results.stride:
|
||||
results.stride = float(results.stride)
|
||||
|
||||
if results.activeOffset:
|
||||
results.activeOffset = float(results.activeOffset)
|
||||
|
||||
if results.templateMetadata:
|
||||
def _checkMissingTemplateArg(argName, argValue):
|
||||
if not argValue:
|
||||
raise Tf.ErrorException('Error: %s must be specified '
|
||||
'when --templateMetadata is' % argName)
|
||||
|
||||
_checkMissingTemplateArg('templatePath', results.templatePath)
|
||||
_checkMissingTemplateArg('endTimeCode', results.endTimeCode)
|
||||
_checkMissingTemplateArg('startTimeCode', results.startTimeCode)
|
||||
_checkMissingTemplateArg('stride', results.stride)
|
||||
|
||||
UsdUtils.StitchClipsTopology(topologyLayer, results.usdFiles)
|
||||
UsdUtils.StitchClipsManifest(manifestLayer, topologyLayer,
|
||||
results.usdFiles, results.clipPath)
|
||||
UsdUtils.StitchClipsTemplate(outLayer,
|
||||
topologyLayer,
|
||||
manifestLayer,
|
||||
results.clipPath,
|
||||
results.templatePath,
|
||||
results.startTimeCode,
|
||||
results.endTimeCode,
|
||||
results.stride,
|
||||
results.activeOffset,
|
||||
results.interpolateMissingClipValues,
|
||||
results.clipSet)
|
||||
else:
|
||||
if results.templatePath:
|
||||
raise Tf.ErrorException('Error: templatePath cannot be specified '
|
||||
'without --templateMetadata')
|
||||
if results.activeOffset:
|
||||
raise Tf.ErrorException('Error: activeOffset cannot be specified '
|
||||
'without --templateMetadata')
|
||||
if results.stride:
|
||||
raise Tf.ErrorException('Error: stride cannot be specified '
|
||||
'without --templateMetadata')
|
||||
|
||||
UsdUtils.StitchClips(outLayer, results.usdFiles, results.clipPath,
|
||||
results.startTimeCode, results.endTimeCode,
|
||||
results.interpolateMissingClipValues,
|
||||
results.clipSet)
|
||||
|
||||
|
||||
if not results.noComment:
|
||||
outLayer.comment = 'Generated with ' + ' '.join(sys.argv)
|
||||
outLayer.Save()
|
||||
|
||||
except Tf.ErrorException as e:
|
||||
# if something in the authoring fails, remove the output file
|
||||
if outLayerGenerated and os.path.isfile(results.out):
|
||||
os.remove(results.out)
|
||||
if topologyLayerGenerated and os.path.isfile(topologyLayerName):
|
||||
os.remove(topologyLayerName)
|
||||
if manifestLayerGenerated and os.path.isfile(manifestLayerName):
|
||||
os.remove(manifestLayerName)
|
||||
sys.exit(e)
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdstitchclips" %*
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
from pxr import Usd
|
||||
|
||||
|
||||
METADATA_KEYS_TO_SKIP = ('typeName', 'specifier', 'kind', 'active')
|
||||
|
||||
|
||||
def _Msg(msg):
|
||||
sys.stdout.write(msg + '\n')
|
||||
|
||||
def _Err(msg):
|
||||
sys.stderr.write(msg + '\n')
|
||||
|
||||
|
||||
class USDAccessor(object):
|
||||
@staticmethod
|
||||
def GetChildren(prim):
|
||||
return prim.GetAllChildren()
|
||||
|
||||
@staticmethod
|
||||
def GetProperties(prim):
|
||||
return prim.GetAuthoredProperties()
|
||||
|
||||
@staticmethod
|
||||
def GetPropertyName(prop):
|
||||
return prop.GetName()
|
||||
|
||||
@staticmethod
|
||||
def GetMetadata(prim):
|
||||
return prim.GetAllAuthoredMetadata().keys()
|
||||
|
||||
@staticmethod
|
||||
def GetName(prim):
|
||||
return prim.GetName()
|
||||
|
||||
@staticmethod
|
||||
def GetTypeName(prim):
|
||||
return prim.GetTypeName()
|
||||
|
||||
@staticmethod
|
||||
def GetSpecifier(prim):
|
||||
return prim.GetSpecifier()
|
||||
|
||||
@staticmethod
|
||||
def GetKind(prim):
|
||||
return Usd.ModelAPI(prim).GetKind()
|
||||
|
||||
@staticmethod
|
||||
def HasAuthoredActive(prim):
|
||||
return prim.HasAuthoredActive()
|
||||
|
||||
@staticmethod
|
||||
def IsActive(prim):
|
||||
return prim.IsActive()
|
||||
|
||||
|
||||
class SdfAccessor(object):
|
||||
@staticmethod
|
||||
def GetChildren(prim):
|
||||
return prim.nameChildren
|
||||
|
||||
@staticmethod
|
||||
def GetProperties(prim):
|
||||
return prim.properties
|
||||
|
||||
@staticmethod
|
||||
def GetPropertyName(prop):
|
||||
return prop.name
|
||||
|
||||
@staticmethod
|
||||
def GetMetadata(prim):
|
||||
return prim.ListInfoKeys()
|
||||
|
||||
@staticmethod
|
||||
def GetName(prim):
|
||||
return prim.name
|
||||
|
||||
@staticmethod
|
||||
def GetTypeName(prim):
|
||||
return prim.typeName
|
||||
|
||||
@staticmethod
|
||||
def GetSpecifier(prim):
|
||||
return prim.specifier
|
||||
|
||||
@staticmethod
|
||||
def GetKind(prim):
|
||||
return prim.kind
|
||||
|
||||
@staticmethod
|
||||
def HasAuthoredActive(prim):
|
||||
return 'active' in prim.ListInfoKeys()
|
||||
|
||||
@staticmethod
|
||||
def IsActive(prim):
|
||||
return prim.active
|
||||
|
||||
|
||||
def GetPrimLabel(acc, prim):
|
||||
spec = acc.GetSpecifier(prim).displayName.lower()
|
||||
typeName = acc.GetTypeName(prim)
|
||||
if typeName:
|
||||
definition = '{} {}'.format(spec, typeName)
|
||||
else:
|
||||
definition = spec
|
||||
label = '{} [{}]'.format(acc.GetName(prim), definition)
|
||||
|
||||
shortMetadata = []
|
||||
|
||||
if not acc.IsActive(prim):
|
||||
shortMetadata.append('active = false')
|
||||
elif acc.HasAuthoredActive(prim):
|
||||
shortMetadata.append('active = true')
|
||||
|
||||
kind = acc.GetKind(prim)
|
||||
if kind:
|
||||
shortMetadata.append('kind = {}'.format(kind))
|
||||
|
||||
if shortMetadata:
|
||||
label += ' ({})'.format(', '.join(shortMetadata))
|
||||
return label
|
||||
|
||||
|
||||
def PrintPrim(args, acc, prim, prefix, isLast):
|
||||
if not isLast:
|
||||
lastStep = ' |--'
|
||||
if acc.GetChildren(prim):
|
||||
attrStep = ' | |'
|
||||
else:
|
||||
attrStep = ' | '
|
||||
else:
|
||||
lastStep = ' `--'
|
||||
if acc.GetChildren(prim):
|
||||
attrStep = ' |'
|
||||
else:
|
||||
attrStep = ' '
|
||||
|
||||
if args.simple:
|
||||
label = acc.GetName(prim)
|
||||
else:
|
||||
label = GetPrimLabel(acc, prim)
|
||||
|
||||
_Msg('{}{}{}'.format(prefix, lastStep, label))
|
||||
|
||||
attrs = []
|
||||
if args.metadata:
|
||||
mdKeys = filter(lambda x: x not in METADATA_KEYS_TO_SKIP, sorted(acc.GetMetadata(prim)))
|
||||
attrs.extend('({})'.format(md) for md in mdKeys)
|
||||
|
||||
if args.attributes:
|
||||
attrs.extend('.{}'.format(acc.GetPropertyName(prop)) for prop in acc.GetProperties(prim))
|
||||
|
||||
numAttrs = len(attrs)
|
||||
for i, attr in enumerate(attrs):
|
||||
if i < numAttrs - 1:
|
||||
_Msg('{}{} :--{}'.format(prefix, attrStep, attr))
|
||||
else:
|
||||
_Msg('{}{} `--{}'.format(prefix, attrStep, attr))
|
||||
|
||||
|
||||
def PrintChildren(args, acc, prim, prefix):
|
||||
children = acc.GetChildren(prim)
|
||||
numChildren = len(children)
|
||||
for i, child in enumerate(children):
|
||||
if i < numChildren - 1:
|
||||
PrintPrim(args, acc, child, prefix, isLast=False)
|
||||
PrintChildren(args, acc, child, prefix + ' | ')
|
||||
else:
|
||||
PrintPrim(args, acc, child, prefix, isLast=True)
|
||||
PrintChildren(args, acc, child, prefix + ' ')
|
||||
|
||||
|
||||
def PrintStage(args, stage):
|
||||
_Msg('/')
|
||||
PrintChildren(args, USDAccessor, stage.GetPseudoRoot(), '')
|
||||
|
||||
|
||||
def PrintLayer(args, layer):
|
||||
_Msg('/')
|
||||
PrintChildren(args, SdfAccessor, layer.pseudoRoot, '')
|
||||
|
||||
|
||||
def PrintTree(args, path):
|
||||
if args.flatten:
|
||||
popMask = (None if args.populationMask is None else Usd.StagePopulationMask())
|
||||
if popMask:
|
||||
for mask in args.populationMask:
|
||||
popMask.Add(mask)
|
||||
if popMask:
|
||||
if args.unloaded:
|
||||
stage = Usd.Stage.OpenMasked(path, popMask, Usd.Stage.LoadNone)
|
||||
else:
|
||||
stage = Usd.Stage.OpenMasked(path, popMask)
|
||||
else:
|
||||
if args.unloaded:
|
||||
stage = Usd.Stage.Open(path, Usd.Stage.LoadNone)
|
||||
else:
|
||||
stage = Usd.Stage.Open(path)
|
||||
PrintStage(args, stage)
|
||||
elif args.flattenLayerStack:
|
||||
from pxr import UsdUtils
|
||||
stage = Usd.Stage.Open(path, Usd.Stage.LoadNone)
|
||||
layer = UsdUtils.FlattenLayerStack(stage)
|
||||
PrintLayer(args, layer)
|
||||
else:
|
||||
from pxr import Sdf
|
||||
layer = Sdf.Layer.FindOrOpen(path)
|
||||
PrintLayer(args, layer)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description='''Writes the tree structure of a USD file. The default is to inspect a single USD file.
|
||||
Use the --flatten argument to see the flattened (or composed) Stage tree.
|
||||
Special metadata "kind" and "active" are always shown if authored unless --simple is provided.''')
|
||||
|
||||
parser.add_argument('inputPath')
|
||||
parser.add_argument(
|
||||
'--unloaded', action='store_true',
|
||||
dest='unloaded',
|
||||
help='Do not load payloads')
|
||||
parser.add_argument(
|
||||
'--attributes', '-a', action='store_true',
|
||||
dest='attributes',
|
||||
help='Display authored attributes')
|
||||
parser.add_argument(
|
||||
'--metadata', '-m', action='store_true',
|
||||
dest='metadata',
|
||||
help='Display authored metadata (active and kind are part of the label and not shown as individual items)')
|
||||
parser.add_argument(
|
||||
'--simple', '-s', action='store_true',
|
||||
dest='simple',
|
||||
help='Only display prim names: no specifier, kind or active state.')
|
||||
parser.add_argument(
|
||||
'--flatten', '-f', action='store_true', help='Compose the stage with the '
|
||||
'input file as root layer and write the flattened content.')
|
||||
parser.add_argument(
|
||||
'--flattenLayerStack', action='store_true',
|
||||
help='Flatten the layer stack with the given root layer. '
|
||||
'Unlike --flatten, this does not flatten composition arcs (such as references).')
|
||||
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. Requires --flatten.')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# split args.populationMask into paths.
|
||||
if args.populationMask:
|
||||
if not args.flatten:
|
||||
# You can only mask a stage, not a layer.
|
||||
_Err("%s: error: --mask requires --flatten" % parser.prog)
|
||||
return 1
|
||||
args.populationMask = args.populationMask.replace(',', ' ').split()
|
||||
|
||||
from pxr import Ar
|
||||
resolver = Ar.GetResolver()
|
||||
|
||||
try:
|
||||
if hasattr(Ar.Resolver, "ConfigureResolverForAsset"):
|
||||
resolver.ConfigureResolverForAsset(args.inputPath)
|
||||
resolverContext = resolver.CreateDefaultContextForAsset(args.inputPath)
|
||||
with Ar.ResolverContextBinder(resolverContext):
|
||||
resolved = resolver.Resolve(args.inputPath)
|
||||
if not resolved:
|
||||
_Err('Cannot resolve inputPath %r'%resolved)
|
||||
return 1
|
||||
PrintTree(args, resolved)
|
||||
except Exception as e:
|
||||
_Err("Failed to process '%s' - %s" % (args.inputPath, e))
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Restore signal handling defaults to allow output redirection and the like.
|
||||
import platform
|
||||
if platform.system() != 'Windows':
|
||||
import signal
|
||||
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdtree" %*
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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
|
||||
import pxr.Usdviewq as Usdviewq
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Let Ctrl-C kill the app.
|
||||
import signal
|
||||
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
||||
try:
|
||||
Usdviewq.Launcher().Run()
|
||||
except Usdviewq.InvalidUsdviewOption as e:
|
||||
print("ERROR: " + e.message, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdview" %*
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
|
||||
#
|
||||
# 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
|
||||
import argparse
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
|
||||
from pxr import Ar, Sdf, Tf, Usd, UsdUtils
|
||||
from contextlib import contextmanager
|
||||
|
||||
@contextmanager
|
||||
def _Stream(path, *args, **kwargs):
|
||||
if path == '-':
|
||||
yield sys.stdout
|
||||
else:
|
||||
with open(path, *args, **kwargs) as fp:
|
||||
yield fp
|
||||
|
||||
def _Print(stream, msg):
|
||||
print(msg, file=stream)
|
||||
|
||||
def _Err(msg):
|
||||
sys.stderr.write(msg + '\n')
|
||||
|
||||
def _CheckCompliance(rootLayer, arkit=False):
|
||||
checker = UsdUtils.ComplianceChecker(arkit=arkit,
|
||||
# We're going to flatten the USD stage and convert the root layer to
|
||||
# crate file format before packaging, if necessary. Hence, skip these
|
||||
# checks.
|
||||
skipARKitRootLayerCheck=True)
|
||||
checker.CheckCompliance(rootLayer)
|
||||
errors = checker.GetErrors()
|
||||
failedChecks = checker.GetFailedChecks()
|
||||
warnings = checker.GetWarnings()
|
||||
for msg in errors + failedChecks:
|
||||
_Err(msg)
|
||||
if len(warnings) > 0:
|
||||
_Err("*********************************************\n"
|
||||
"Possible correctness problems to investigate:\n"
|
||||
"*********************************************\n")
|
||||
for msg in warnings:
|
||||
_Err(msg)
|
||||
return len(errors) == 0 and len(failedChecks) == 0
|
||||
|
||||
def _CreateUsdzPackage(usdzFile, filesToAdd, recurse, checkCompliance, verbose):
|
||||
with Usd.ZipFileWriter.CreateNew(usdzFile) as usdzWriter:
|
||||
fileList = []
|
||||
while filesToAdd:
|
||||
# Pop front (first file) from the list of files to add.
|
||||
f = filesToAdd[0]
|
||||
filesToAdd = filesToAdd[1:]
|
||||
|
||||
if os.path.isdir(f):
|
||||
# If a directory is specified, add all files in the directory.
|
||||
filesInDir = glob.glob(os.path.join(f, '*'))
|
||||
# If the recurse flag is not specified, remove sub-directories.
|
||||
if not recurse:
|
||||
filesInDir = [f for f in filesInDir if not os.path.isdir(f)]
|
||||
# glob.glob returns files in arbitrary order. Hence, sort them
|
||||
# here to get consistent ordering of files in the package.
|
||||
filesInDir.sort()
|
||||
filesToAdd += filesInDir
|
||||
else:
|
||||
if verbose:
|
||||
print('.. adding: %s' % f)
|
||||
if os.path.getsize(f) > 0:
|
||||
fileList.append(f)
|
||||
else:
|
||||
_Err("Skipping empty file '%s'." % f)
|
||||
|
||||
if checkCompliance and len(fileList) > 0:
|
||||
rootLayer = fileList[0]
|
||||
if not _CheckCompliance(rootLayer):
|
||||
return False
|
||||
|
||||
for f in fileList:
|
||||
try:
|
||||
usdzWriter.AddFile(f)
|
||||
except Tf.ErrorException as e:
|
||||
_Err('Failed to add file \'%s\' to package. Discarding '
|
||||
'package.' % f)
|
||||
# When the "with" block exits, Discard() will be called on
|
||||
# usdzWriter automatically if an exception occurs.
|
||||
raise
|
||||
return True
|
||||
|
||||
def _DumpContents(dumpLocation, zipFile):
|
||||
with _Stream(dumpLocation, "w") as ofp:
|
||||
_Print(ofp, " Offset\t Comp\t Uncomp\tName")
|
||||
_Print(ofp, " ------\t ----\t ------\t----")
|
||||
fileNames = zipFile.GetFileNames()
|
||||
for fileName in fileNames:
|
||||
fileInfo = zipFile.GetFileInfo(fileName)
|
||||
_Print(ofp, "%10d\t%10d\t%10d\t%s" %
|
||||
(fileInfo.dataOffset, fileInfo.size,
|
||||
fileInfo.uncompressedSize, fileName))
|
||||
|
||||
_Print(ofp, "----------")
|
||||
_Print(ofp, "%d files total" % len(fileNames))
|
||||
|
||||
def _ListContents(listLocation, zipFile):
|
||||
with _Stream(listLocation, "w") as ofp:
|
||||
for fileName in zipFile.GetFileNames():
|
||||
_Print(ofp, fileName)
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Utility for creating a .usdz '
|
||||
'file containing USD assets and for inspecting existing .usdz files.')
|
||||
|
||||
parser.add_argument('usdzFile', type=str, nargs='?',
|
||||
help='Name of the .usdz file to create or to inspect '
|
||||
'the contents of.')
|
||||
|
||||
parser.add_argument('inputFiles', type=str, nargs='*',
|
||||
help='Files to include in the .usdz file.')
|
||||
parser.add_argument('-r', '--recurse', dest='recurse', action='store_true',
|
||||
help='If specified, files in sub-directories are '
|
||||
'recursively added to the package.')
|
||||
|
||||
parser.add_argument('-a', '--asset', dest='asset', type=str,
|
||||
help='Resolvable asset path pointing to the root layer '
|
||||
'of the asset to be isolated and copied into the '
|
||||
'package.')
|
||||
parser.add_argument("--arkitAsset", dest="arkitAsset", type=str,
|
||||
help="Similar to the --asset option, the --arkitAsset "
|
||||
"option packages all of the dependencies of the named "
|
||||
"scene file. Assets targeted at the initial usdz "
|
||||
"implementation in ARKit operate under greater "
|
||||
"constraints than usdz files for more general 'in "
|
||||
"house' uses, and this option attempts to ensure that "
|
||||
"these constraints are honored; this may involve more "
|
||||
"transformations to the data, which may cause loss of "
|
||||
"features such as VariantSets.")
|
||||
|
||||
parser.add_argument('-c', '--checkCompliance', dest='checkCompliance',
|
||||
action='store_true', help='Perform compliance checking '
|
||||
'of the input files. If the input asset or \"root\" '
|
||||
'layer fails any of the compliance checks, the package '
|
||||
'is not created and the program fails.')
|
||||
|
||||
parser.add_argument('-l', '--list', dest='listTarget', type=str,
|
||||
nargs='?', default=None, const='-',
|
||||
help='List contents of the specified usdz file. If '
|
||||
'a file-path argument is provided, the list is output '
|
||||
'to a file at the given path. If no argument is '
|
||||
'provided or if \'-\' is specified as the argument, the'
|
||||
' list is output to stdout.')
|
||||
parser.add_argument('-d', '--dump', dest='dumpTarget', type=str,
|
||||
nargs='?', default=None, const='-',
|
||||
help='Dump contents of the specified usdz file. If '
|
||||
'a file-path argument is provided, the contents are '
|
||||
'output to a file at the given path. If no argument is '
|
||||
'provided or if \'-\' is specified as the argument, the'
|
||||
' contents are output to stdout.')
|
||||
|
||||
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
|
||||
help='Enable verbose mode, which causes messages '
|
||||
'regarding files being added to the package to be '
|
||||
'output to stdout.')
|
||||
|
||||
args = parser.parse_args()
|
||||
usdzFile = args.usdzFile
|
||||
inputFiles = args.inputFiles
|
||||
|
||||
if args.asset and args.arkitAsset:
|
||||
parser.error("Specify either --asset or --arkitAsset, not both.")
|
||||
|
||||
elif (args.arkitAsset or args.asset) and len(inputFiles)>0:
|
||||
parser.error("Specify either inputFiles or an asset (via --asset or "
|
||||
"--arkitAsset, not both.")
|
||||
|
||||
# If usdzFile is not specified directly as an argument, check if it has been
|
||||
# specified as an argument to the --list or --dump options. In these cases,
|
||||
# output the list or the contents to stdout.
|
||||
if not usdzFile:
|
||||
if args.listTarget and args.listTarget != '-' and \
|
||||
args.listTarget.endswith('.usdz') and \
|
||||
os.path.exists(args.listTarget):
|
||||
usdzFile = args.listTarget
|
||||
args.listTarget = '-'
|
||||
elif args.dumpTarget and args.dumpTarget != '-' and \
|
||||
args.dumpTarget.endswith('.usdz') and \
|
||||
os.path.exists(args.dumpTarget):
|
||||
usdzFile = args.dumpTarget
|
||||
args.dumpTarget = '-'
|
||||
else:
|
||||
parser.error("No usdz file specified!")
|
||||
|
||||
# Check if we're in package creation mode and verbose mode is enabled,
|
||||
# print some useful information.
|
||||
if (args.asset or args.arkitAsset or len(inputFiles)>0):
|
||||
# Ensure that the usdz file has the right extension.
|
||||
if not usdzFile.endswith('.usdz'):
|
||||
usdzFile += '.usdz'
|
||||
|
||||
if args.verbose:
|
||||
if os.path.exists(usdzFile):
|
||||
print("File at path '%s' already exists. Overwriting file." %
|
||||
usdzFile)
|
||||
|
||||
if args.inputFiles:
|
||||
print('Creating package \'%s\' with files %s.' %
|
||||
(usdzFile, inputFiles))
|
||||
|
||||
if args.asset or args.arkitAsset:
|
||||
Tf.Debug.SetDebugSymbolsByName("USDUTILS_CREATE_USDZ_PACKAGE", 1)
|
||||
|
||||
if not args.recurse:
|
||||
print('Not recursing into sub-directories.')
|
||||
else:
|
||||
if args.checkCompliance:
|
||||
parser.error("--checkCompliance should only be specified when "
|
||||
"creating a usdz package. Please use 'usdchecker' to check "
|
||||
"compliance of an existing .usdz file.")
|
||||
|
||||
|
||||
success = True
|
||||
if len(inputFiles) > 0:
|
||||
success = _CreateUsdzPackage(usdzFile, inputFiles, args.recurse,
|
||||
args.checkCompliance, args.verbose) and success
|
||||
|
||||
elif args.asset:
|
||||
r = Ar.GetResolver()
|
||||
resolvedAsset = r.Resolve(args.asset)
|
||||
if args.checkCompliance:
|
||||
success = _CheckCompliance(resolvedAsset, arkit=False) and success
|
||||
|
||||
context = r.CreateDefaultContextForAsset(resolvedAsset)
|
||||
with Ar.ResolverContextBinder(context):
|
||||
# Create the package only if the compliance check was passed.
|
||||
success = success and UsdUtils.CreateNewUsdzPackage(
|
||||
Sdf.AssetPath(args.asset), usdzFile)
|
||||
|
||||
elif args.arkitAsset:
|
||||
r = Ar.GetResolver()
|
||||
resolvedAsset = r.Resolve(args.arkitAsset)
|
||||
if args.checkCompliance:
|
||||
success = _CheckCompliance(resolvedAsset, arkit=True) and success
|
||||
|
||||
context = r.CreateDefaultContextForAsset(resolvedAsset)
|
||||
with Ar.ResolverContextBinder(context):
|
||||
# Create the package only if the compliance check was passed.
|
||||
success = success and UsdUtils.CreateNewARKitUsdzPackage(
|
||||
Sdf.AssetPath(args.arkitAsset), usdzFile)
|
||||
|
||||
if args.listTarget or args.dumpTarget:
|
||||
if os.path.exists(usdzFile):
|
||||
zipFile = Usd.ZipFile.Open(usdzFile)
|
||||
if zipFile:
|
||||
if args.dumpTarget:
|
||||
if args.dumpTarget == usdzFile:
|
||||
_Err("The file into which to dump the contents of the "
|
||||
"usdz file '%s' must be different from the file "
|
||||
"itself." % usdzFile)
|
||||
return 1
|
||||
_DumpContents(args.dumpTarget, zipFile)
|
||||
if args.listTarget:
|
||||
if args.listTarget == usdzFile:
|
||||
_Err("The file into which to list the contents of the "
|
||||
"usdz file '%s' must be different from the file "
|
||||
"itself." % usdzFile)
|
||||
return 1
|
||||
_ListContents(args.listTarget, zipFile)
|
||||
else:
|
||||
_Err("Failed to open usdz file at path '%s'." % usdzFile)
|
||||
else:
|
||||
_Err("Can't find usdz file at path '%s'." % usdzFile)
|
||||
|
||||
return 0 if success else 1
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
@python "%~dp0usdzip" %*
|
||||
Binary file not shown.
Reference in new issue
Block a user