def createTextureShader(parentPath, imgFile, diffuseColor, uv, stage): # we need to do some introspection on the imgFile, since it might # be only greyscale (especially for a scan) sPath = os.path.join(parentPath, "Texture") sSchema = UsdShade.Shader.Define(stage, sPath) # is this predefined as a token somewhere? Too fragile... sSchema.CreateIdAttr().Set("UsdUVTexture") rgb = sSchema.CreateOutput("rgb", Sdf.ValueTypeNames.Float3) diffuseColor.ConnectToSource(rgb) path = Sdf.AssetPath(imgFile) sSchema.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(path) sSchema.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("clamp") sSchema.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("clamp") st = sSchema.CreateInput("st", Sdf.ValueTypeNames.Float2) st.ConnectToSource(uv)
def test_LayerColorConfig(self): filePath = 'testSdfColorConfig.testenv/colorConfig.sdf' layer = Sdf.Layer.FindOrOpen(filePath) self.assertTrue(layer is not None) expectedValue = Sdf.AssetPath( 'https://github.com/imageworks/OpenColorIO-Configs/blob/master/aces_1.0.1/config.ocio' ) self.assertEqual(layer.colorConfiguration, expectedValue) self.assertTrue(layer.HasColorConfiguration()) layer.ClearColorConfiguration() self.assertFalse(layer.HasColorConfiguration()) newValue = Sdf.AssetPath( 'https://github.com/imageworks/OpenColorIO-Configs/blob/master/aces_1.0.3/config.ocio' ) layer.colorConfiguration = newValue self.assertEqual(layer.colorConfiguration, newValue) self.assertTrue(layer.HasColorConfiguration()) layer.ClearColorConfiguration() self.assertFalse(layer.HasColorConfiguration())
def test_EmptyAssetPaths(self): src_stage = Usd.Stage.Open('emptyAssetPaths.usda') src_layer_stack = src_stage._GetPcpCache().layerStack layer = Usd.FlattenLayerStack(src_layer_stack, tag='emptyAssetPaths') result_stage = Usd.Stage.Open(layer) # Verify that empty asset paths do not trigger coding errors during # flattening. prim = result_stage.GetPrimAtPath('/Test') self.assertTrue(prim.HasAuthoredReferences()) primSpec = layer.GetPrimAtPath('/Test') expectedRefs = Sdf.ReferenceListOp() expectedRefs.explicitItems = [Sdf.Reference(primPath="/Ref")] self.assertEqual(primSpec.GetInfo('references'), expectedRefs) assetAttr = prim.GetAttribute('a') self.assertEqual(assetAttr.Get(), Sdf.AssetPath()) assetArrayAttr = prim.GetAttribute('b') self.assertEqual(list(assetArrayAttr.Get()), [Sdf.AssetPath(), Sdf.AssetPath()])
def testSetMayaAttr(self): cmds.file(new=True, force=True) cmds.group(name="group1", empty=True) attrName = mayaUsdLib.ReadUtil.FindOrCreateMayaAttr( Sdf.ValueTypeNames.Asset, Sdf.VariabilityUniform, "group1", "myAssetPath", "kittens") self.assertTrue( mayaUsdLib.ReadUtil.SetMayaAttr(attrName, Sdf.AssetPath("kittens.png"))) self.assertEqual(cmds.getAttr("group1.myAssetPath"), "kittens.png") self.assertEqual( mayaUsdLib.WriteUtil.GetVtValue(attrName, Sdf.ValueTypeNames.Asset), Sdf.AssetPath("kittens.png")) # Test color conversion from linear to display. attrName = mayaUsdLib.ReadUtil.FindOrCreateMayaAttr( Sdf.ValueTypeNames.Color3f, Sdf.VariabilityUniform, "group1", "furColor") self.assertTrue( mayaUsdLib.ReadUtil.SetMayaAttr(attrName, Gf.Vec3f(0.2176376))) self.assertAlmostEqual( mayaUsdLib.WriteUtil.GetVtValue(attrName, Sdf.ValueTypeNames.Color3f)[0], 0.2176376) self.assertAlmostEqual( mayaUsdLib.WriteUtil.GetVtValue(attrName, Sdf.ValueTypeNames.Vector3f)[0], 0.5) # Should even work on Maya built-in attrs. self.assertTrue( mayaUsdLib.ReadUtil.SetMayaAttr("group1.scale", Gf.Vec3d(1.0, 2.0, 3.0))) self.assertEqual(cmds.getAttr("group1.scale"), [(1.0, 2.0, 3.0)])
def __init__(self, inputFile, arkit=False, skipARKitRootLayerCheck=False, rootPackageOnly=False, skipVariants=False, verbose=False): self._arkit = arkit self._skipARKitRootLayerCheck = skipARKitRootLayerCheck self._rootPackageOnly = rootPackageOnly self._doVariants = not skipVariants self._verbose = verbose self._failedChecks = [] self._errors = [] self._violatedRules = set() self._checkedPackages = set() from pxr import Ar, Sdf, Usd, UsdUtils if not Usd.Stage.IsSupportedFile(inputFile): _AddError("Cannot open file '%s' on a USD stage." % args.inputFile) return # Collect all warnings using a diagnostic delegate. delegate = UsdUtils.CoalescingDiagnosticDelegate() usdStage = Usd.Stage.Open(inputFile) allDiagnostics = delegate.TakeUncoalescedDiagnostics() if self._arkit: for diag in allDiagnostics: # "_ReportErrors" is the name of the function that issues # warnings about unresolved references, sublayers and other # composition arcs. if '_ReportErrors' in diag.sourceFunction and \ 'usd/stage.cpp' in diag.sourceFileName: self._AddFailedCheck(diag.commentary, ruleNum=4) with Ar.ResolverContextBinder(usdStage.GetPathResolverContext()): # This recursively computes all of inputFiles's external # dependencies. (allLayerDeps, allAssetDeps, unresolvedPaths) = \ UsdUtils.ComputeAllDependencies(Sdf.AssetPath(inputFile)) self._CheckDependencies(usdStage, allLayerDeps, allAssetDeps, unresolvedPaths) self._CheckStage(usdStage, allLayerDeps)
def sync(root_prim, world: bpy.types.World, **kwargs): is_gl_mode = kwargs.get('is_gl_delegate', False) if is_gl_mode: # TODO export correct Dome light with texture for GL mode return # get the World IBL image data = WorldData.init_from_world(world) stage = root_prim.GetStage() if not data.cycles_ibl.image: # TODO create image from environment color data if no image used return # create Dome light xform = UsdGeom.Xform.Define(stage, root_prim.GetPath().AppendChild("_world")) obj_prim = xform.GetPrim() usd_light = UsdLux.DomeLight.Define( stage, obj_prim.GetPath().AppendChild(sdf_path(world.name))) usd_light.ClearXformOpOrder() usd_light.OrientToStageUpAxis() p = Sdf.AssetPath(data.cycles_ibl.image) usd_light.CreateTextureFileAttr(p) # set correct Dome light rotation matrix = np.identity(4) rotation = data.cycles_ibl.rotation euler = mathutils.Euler( (-rotation[0], -rotation[1] + np.pi, -rotation[2] - np.pi / 2)) rotation_matrix = np.array(euler.to_matrix(), dtype=np.float32) matrix[:3, :3] = rotation_matrix[:, :] xform.ClearXformOpOrder() xform.AddTransformOp().Set(Gf.Matrix4d(matrix))
def testMayaReferenceAttributes(self): layer = Sdf.Layer.CreateAnonymous() stageOut = Usd.Stage.Open(layer.identifier) primPath = Sdf.AssetPath('/MayaReference') mayaReferencePath = '/somewherenice/path.ma' mayaNamespace = 'nsp' primOut = stageOut.DefinePrim(primPath.path, 'MayaReference') self.assertTrue(primOut.IsValid()) mayaReferenceOut = mayaUsdSchemas.MayaReference(primOut) self.assertTrue(mayaReferenceOut.GetPrim()) if Usd.GetVersion() > (0, 20, 2): typeName = Usd.SchemaRegistry().GetSchemaTypeName( mayaReferenceOut._GetStaticTfType()) else: typeName = mayaReferenceOut.GetSchemaClassPrimDefinition().typeName self.assertEqual(typeName, 'MayaReference') mayaReferenceAttr = primOut.CreateAttribute('mayaReference', Sdf.ValueTypeNames.Asset) mayaReferenceAttr.Set(mayaReferencePath) mayaNamespaceAttr = primOut.CreateAttribute('mayaNamespace', Sdf.ValueTypeNames.String) mayaNamespaceAttr.Set(mayaNamespace) stageIn = Usd.Stage.Open(stageOut.Flatten()) primIn = stageIn.GetPrimAtPath(primPath.path) self.assertTrue(primIn.IsValid()) mayaReferenceIn = mayaUsdSchemas.MayaReference(primIn) self.assertTrue(mayaReferenceIn.GetMayaReferenceAttr().Get(), mayaReferencePath) self.assertTrue(mayaReferenceIn.GetMayaNamespaceAttr().Get(), mayaNamespace)
def _read_data(data): if 'value' in data: if hasattr(data['value'], '__len__') and len(data['value']) > 1: return tuple(data['value']), True else: return data['value'], True elif 'file' in data and data['file']: fp = posixpath.join( texture_file_path, data['file'].get('value', Sdf.AssetPath()).path) if 'colorspace' in data: colorspace = data['colorspace']['value'] else: colorspace = 'auto' try: return cls._read_image(fp, colorspace=colorspace), False except MaterialLoadError: warnings.warn( f'An error was encountered while processing the data {data["file"]}.' ) if 'fallback' in data: return data['fallback']['value'], True return None, False
def main(): stage = Usd.Stage.CreateInMemory() # Method A: Set using methods some_sphere = UsdGeom.Sphere.Define(stage, "/SomeSphere") model = Usd.ModelAPI(some_sphere.GetPrim()) model.SetAssetName("some_asset") model.SetAssetVersion("v1") model.SetAssetIdentifier("some/path/to/file.usda") model.SetPayloadAssetDependencies( Sdf.AssetPathArray( [Sdf.AssetPath("something.usd"), Sdf.AssetPath("another/thing.usd")] ) ) # Method B: Set-by-key another_sphere = UsdGeom.Sphere.Define(stage, "/AnotherSphere") another_prim = another_sphere.GetPrim() another_prim.SetAssetInfoByKey("version", "v1") another_prim.SetAssetInfoByKey("name", "some_asset") another_prim.SetAssetInfoByKey("identifier", "some/path/to/file.usda") another_prim.SetAssetInfoByKey( "payloadAssetDependencies", Sdf.AssetPathArray( [Sdf.AssetPath("something.usd"), Sdf.AssetPath("another/thing.usd")] ), ) # Method C: Set-by-dict last_sphere = UsdGeom.Sphere.Define(stage, "/LastSphere") last_sphere.GetPrim().SetAssetInfo( { "identifier": "some/path/to/file.usda", "name": "some_asset", "version": "v1", "payloadAssetDependencies": Sdf.AssetPathArray( [Sdf.AssetPath("something.usd"), Sdf.AssetPath("another/thing.usd")] ), } ) print(stage.GetRootLayer().ExportToString())
def main(): parser = argparse.ArgumentParser( description='Utility for creating a .usdz ' 'file containging 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 " "creatinga 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
def test_ClipAuthoring(self): """Tests clip authoring API on Usd.ClipsAPI""" allFormats = ['usd' + x for x in 'ac'] for fmt in allFormats: stage = Usd.Stage.CreateInMemory('TestClipAuthoring.' + fmt) prim = stage.DefinePrim('/Model') model = Usd.ClipsAPI(prim) prim2 = stage.DefinePrim('/Model2') model2 = Usd.ClipsAPI(prim2) # Clip authoring API supports the use of lists as well as Vt arrays. clipAssetPaths = [ Sdf.AssetPath('clip1.usda'), Sdf.AssetPath('clip2.usda') ] model.SetClipAssetPaths(clipAssetPaths) self.assertEqual(model.GetClipAssetPaths(), clipAssetPaths) model2.SetClipAssetPaths( Sdf.AssetPathArray( [Sdf.AssetPath('clip1.usda'), Sdf.AssetPath('clip2.usda')])) self.assertEqual(model2.GetClipAssetPaths(), clipAssetPaths) clipPrimPath = "/Clip" model.SetClipPrimPath(clipPrimPath) self.assertEqual(model.GetClipPrimPath(), clipPrimPath) clipTimes = Vt.Vec2dArray([(0.0, 0.0), (10.0, 10.0), (20.0, 20.0)]) model.SetClipTimes(clipTimes) self.assertEqual(model.GetClipTimes(), clipTimes) model2.SetClipTimes( Vt.Vec2dArray([ Gf.Vec2d(0.0, 0.0), Gf.Vec2d(10.0, 10.0), Gf.Vec2d(20.0, 20.0) ])) self.assertEqual(model2.GetClipTimes(), clipTimes) clipActive = [(0.0, 0.0), (10.0, 1.0), (20.0, 0.0)] model.SetClipActive(clipActive) self.assertEqual(model.GetClipActive(), Vt.Vec2dArray(clipActive)) model2.SetClipActive( Vt.Vec2dArray([ Gf.Vec2d(0.0, 0.0), Gf.Vec2d(10.0, 1.0), Gf.Vec2d(20.0, 0.0) ])) self.assertEqual(model2.GetClipActive(), Vt.Vec2dArray(clipActive)) clipManifestAssetPath = Sdf.AssetPath('clip_manifest.usda') model.SetClipManifestAssetPath(clipManifestAssetPath) self.assertEqual(model.GetClipManifestAssetPath(), clipManifestAssetPath) # Test authoring of template clip metadata model.SetClipTemplateAssetPath('clip.###.usda') self.assertEqual(model.GetClipTemplateAssetPath(), 'clip.###.usda') model.SetClipTemplateStride(4.5) self.assertEqual(model.GetClipTemplateStride(), 4.5) model.SetClipTemplateStartTime(1) self.assertEqual(model.GetClipTemplateStartTime(), 1) model.SetClipTemplateEndTime(5) self.assertEqual(model.GetClipTemplateEndTime(), 5) # Ensure we can't set the clipTemplateStride to 0 with self.assertRaises(Tf.ErrorException) as e: model.SetClipTemplateStride(0)
def test_GetPropertyStackWithClips(self): clipPath = '/root/fx/test' attrName = 'extent' fullPath = clipPath + '.' + attrName for fmt in allFormats: clipA = Sdf.Layer.CreateNew('clipA.' + fmt) clipB = Sdf.Layer.CreateNew('clipB.' + fmt) clipC = Sdf.Layer.CreateNew('clipC.' + fmt) clips = [clipA, clipB, clipC] clipTime = 102.0 for c in clips: stage = Usd.Stage.Open(c.identifier) prim = stage.DefinePrim(clipPath) attr = prim.CreateAttribute('extent', Sdf.ValueTypeNames.Double) attr.Set(clipTime, clipTime) stage.SetStartTimeCode(clipTime) clipTime += 1.0 stage.SetEndTimeCode(clipTime) # Generate our necessary topology layer topologyLayer = Sdf.Layer.CreateNew('root.topology.' + fmt) stage = Usd.Stage.Open(topologyLayer) prim = stage.DefinePrim(clipPath) prim.CreateAttribute(attrName, Sdf.ValueTypeNames.Double) # Generate our necessary clip metadata root = Sdf.Layer.CreateNew('root.' + fmt) stage = Usd.Stage.Open(root) prim = stage.DefinePrim(clipPath) clipPrim = Usd.ClipsAPI(prim) clipPrim.SetClipAssetPaths( [Sdf.AssetPath(c.identifier) for c in clips]) clipPrim.SetClipPrimPath(clipPath) clipPrim.SetClipManifestAssetPath('root.topology.' + fmt) # Add a reference to our topology layer rootPath = Sdf.Path('/root') rootPrim = stage.GetPrimAtPath(rootPath) rootPrim.GetReferences().AppendReference( Sdf.Reference(topologyLayer.identifier, rootPath)) clipTime = 102.0 stageTime = 0.0 for c in clips: currentClipActive = list(clipPrim.GetClipActive()) currentClipActive.append([clipTime, stageTime]) clipPrim.SetClipActive(currentClipActive) currentClipTimes = list(clipPrim.GetClipTimes()) currentClipTimes.append([clipTime, clipTime]) clipPrim.SetClipTimes(currentClipTimes) clipTime += 1.0 stageTime += 1.0 stage = Usd.Stage.Open(root.identifier) prim = stage.GetPrimAtPath(clipPath) attr = prim.GetAttribute(attrName) # Ensure we only pick up relevant clips # In the case of a default time code we don't want any of the # value clips to show up in our stack of properties stack = attr.GetPropertyStack(Usd.TimeCode.Default()) self.assertEqual(stack, [topologyLayer.GetPropertyAtPath(fullPath)]) # ensure that clip 'c' is in the result when the time code # being used is exactly on 'c's endpoints clipTime = 102 for i in xrange(0, len(clips)): stack = attr.GetPropertyStack(clipTime) self.assertEqual(stack, [ clips[i].GetPropertyAtPath(fullPath), topologyLayer.GetPropertyAtPath(fullPath) ]) clipTime += 1
def test_Basic(self): # Test all combinations of the following keyword arguments. args = [ ['assetPath', '//unit/layer.sdf'], ['primPath', '/rootPrim'], ['layerOffset', Sdf.LayerOffset(48, -2)], ['customData', { 'key': 42, 'other': 'yes' }], ] for n in range(1 << len(args)): kw = {} for i in range(len(args)): if (1 << i) & n: kw[args[i][0]] = args[i][1] ref = Sdf.Reference(**kw) print(' Testing Repr for: ' + repr(ref)) self.assertEqual(ref, eval(repr(ref))) for arg, value in args: if arg in kw: self.assertEqual(eval('ref.' + arg), value) else: self.assertEqual(eval('ref.' + arg), eval('Sdf.Reference().' + arg)) print("\nTesting Sdf.Reference immutability.") # There is no proxy for the Reference yet (we don't have a good # way to support nested proxies). Make sure the user can't modify # temporary Reference objects. with self.assertRaises(AttributeError): Sdf.Reference().assetPath = '//unit/blah.sdf' with self.assertRaises(AttributeError): Sdf.Reference().primPath = '/root' with self.assertRaises(AttributeError): Sdf.Reference().layerOffset = Sdf.LayerOffset() with self.assertRaises(AttributeError): Sdf.Reference().layerOffset.offset = 24 with self.assertRaises(AttributeError): Sdf.Reference().layerOffset.scale = 2 with self.assertRaises(AttributeError): Sdf.Reference().customData = {'refCustomData': {'refFloat': 1.0}} # Code coverage. ref0 = Sdf.Reference(customData={'a': 0}) ref1 = Sdf.Reference(customData={'a': 0, 'b': 1}) self.assertTrue(ref0 == ref0) self.assertTrue(ref0 != ref1) self.assertTrue(ref0 < ref1) self.assertTrue(ref1 > ref0) self.assertTrue(ref0 <= ref1) self.assertTrue(ref1 >= ref0) # Regression test for bug USD-5000 where less than operator was not # fully anti-symmetric r1 = Sdf.Reference() r2 = Sdf.Reference('//test/layer.sdf', layerOffset=Sdf.LayerOffset(48, -2)) self.assertTrue(r1 < r2) self.assertFalse(r2 < r1) # Test IsInternal() # r2 can not be an internal reference since it's assetPath is not empty self.assertFalse(r2.IsInternal()) # ref0 is an internal referennce because it has an empty assetPath self.assertTrue(ref0.IsInternal()) # Test invalid asset paths. with self.assertRaises(Tf.ErrorException): p = Sdf.Reference('\x01\x02\x03') with self.assertRaises(Tf.ErrorException): p = Sdf.AssetPath('\x01\x02\x03') p = Sdf.AssetPath('foobar', '\x01\x02\x03')
def test_ShaderDefParser(self, useForwardedAPI=True): stage = Usd.Stage.CreateNew( 'shaderDef.usda' if useForwardedAPI else 'shaderDef2.usda') shaderPrim = UsdShade.Shader.Define(stage, "/Primvar_float_2") if useForwardedAPI: # UsdShadeShader has API that covers UsdShadeNodeDefAPI methods; # test that they work. nodeDefAPI = shaderPrim else: # Use the methods as implemented on UsdShadeNodeDefAPI. nodeDefAPI = UsdShade.NodeDefAPI(shaderPrim) shaderPrim.SetSdrMetadataByKey(Sdr.NodeMetadata.Role, Sdr.NodeRole.Primvar) nodeDefAPI.GetImplementationSourceAttr().Set( UsdShade.Tokens.sourceAsset) # Create the files referenced by the sourceAsset attributes. osoPath = os.path.normpath(os.path.join(os.getcwd(), 'primvar_2.oso')) glslfxPath = os.path.normpath( os.path.join(os.getcwd(), 'primvar_2.glslfx')) # Create the files referenced by the sourceAsset attributes. # These files need to exist for node discovery to succeed. open(osoPath, "a").close() open(glslfxPath, "a").close() nodeDefAPI.SetSourceAsset(Sdf.AssetPath(osoPath), "OSL") nodeDefAPI.SetSourceAsset(Sdf.AssetPath(glslfxPath), "glslfx") primvarNameInput = shaderPrim.CreateInput('primvarName', Sdf.ValueTypeNames.Token) primvarNameInput.SetConnectability(UsdShade.Tokens.interfaceOnly) primvarNameInput.SetSdrMetadataByKey('primvarProperty', "1") primvarFileInput = shaderPrim.CreateInput('primvarFile', Sdf.ValueTypeNames.Asset) primvarFileInput.SetConnectability(UsdShade.Tokens.interfaceOnly) fallbackInput = shaderPrim.CreateInput('fallback', Sdf.ValueTypeNames.Float) fallbackInput.SetSdrMetadataByKey('defaultInput', "1") # Create dummy inputs of other types for testing. float2Input = shaderPrim.CreateInput('float2Val', Sdf.ValueTypeNames.Float2) float3Input = shaderPrim.CreateInput('float3Val', Sdf.ValueTypeNames.Float3) float4Input = shaderPrim.CreateInput('float4Val', Sdf.ValueTypeNames.Float4) colorInput = shaderPrim.CreateInput('someColor', Sdf.ValueTypeNames.Color3f) vectorInput = shaderPrim.CreateInput('someVector', Sdf.ValueTypeNames.Vector3f) normalInput = shaderPrim.CreateInput('normalVector', Sdf.ValueTypeNames.Normal3f) matrixInput = shaderPrim.CreateInput('someVector', Sdf.ValueTypeNames.Matrix4d) resultOutput = shaderPrim.CreateOutput('result', Sdf.ValueTypeNames.Float) result2Output = shaderPrim.CreateOutput('result2', Sdf.ValueTypeNames.Float2) discoveryResults = UsdShade.ShaderDefUtils.GetNodeDiscoveryResults( shaderPrim, stage.GetRootLayer().realPath) self.assertEqual(len(discoveryResults), 2) parserPlugin = UsdShade.ShaderDefParserPlugin() nodes = [ parserPlugin.Parse(discResult) for discResult in discoveryResults ] self.assertEqual(len(nodes), 2) for n in nodes: self.assertEqual(n.GetVersion(), Ndr.Version(2, 0)) self.assertTrue(n.IsValid()) self.assertEqual(n.GetFamily(), 'Primvar') self.assertEqual(n.GetIdentifier(), 'Primvar_float_2') self.assertEqual(n.GetImplementationName(), 'Primvar_float') self.assertEqual(n.GetRole(), Sdr.NodeRole.Primvar) assetIdentifierInputNames = n.GetAssetIdentifierInputNames() self.assertEqual(len(assetIdentifierInputNames), 1) self.assertEqual(n.GetDefaultInput().GetName(), 'fallback') self.assertEqual(assetIdentifierInputNames[0], 'primvarFile') self.assertEqual(n.GetMetadata(), { 'primvars': '$primvarName', 'role': 'primvar' }) self.assertEqual(n.GetInputNames(), [ 'fallback', 'float2Val', 'float3Val', 'float4Val', 'normalVector', 'primvarFile', 'primvarName', 'someColor', 'someVector' ]) self.assertEqual(n.GetOutputNames(), ['result', 'result2']) if n.GetSourceType() == "OSL": self.assertEqual( os.path.normcase(n.GetResolvedImplementationURI()), os.path.normcase(osoPath)) elif n.GetSourceType() == "glslfx": self.assertEqual( os.path.normcase(n.GetResolvedImplementationURI()), os.path.normcase(glslfxPath)) # Clean-up files. os.remove(stage.GetRootLayer().realPath) os.remove(osoPath) os.remove(glslfxPath)
def createMayaReferencePrim( ufePathStr, mayaReferencePath, mayaNamespace, mayaReferencePrimName=mayaRefUtils.defaultMayaReferencePrimName(), groupPrim=None, variantSet=None, mayaAutoEdit=kDefaultEditAsMayaData): '''Create a Maya reference prim and optional group prim parented to the argument path. Optionally create a variant set and name and placed the edits inside that variant. Naming of Maya Reference prim is supported, otherwise default name is used. The group prim is optional. The variant set and name are optional Parameters: ----------- ufePathStr : str : Ufe PathString of parent prim to add Maya Reference mayaReferencePath : str : File path of Maya Reference (for attribute) mayaNamespace : str : Namespace (for attribute) mayaReferencePrimName : str [optional] : Name for the Maya Reference prim groupPrim : tuple(str,str,str) [optional] : The Group prim Name, Type & Kind to create Note: the name is optional and will be auto-computed if empty or not provided. Note: Type and Kind are both mandatory, but Kind is allowed to be empty string. variantSet : tuple(str,str) [optional] : The Variant Set Name and Variant Name to create Return: ------- The Usd prim of the newly created Maya Reference or an invalid prim if there is an error. ''' # Make sure the prim name is valid and doesn't already exist. parentPrim = mayaUsd.ufe.ufePathToPrim(ufePathStr) # There are special conditions when we are given the ProxyShape gateway node. ufePath = ufe.PathString.path(ufePathStr) isGateway = (ufePath.nbSegments() == 1) # Were we given a Group prim to create? groupPrimName = None groupPrimType = None groupPrimKind = None if groupPrim: if (len(groupPrim) == 2): groupPrimType, groupPrimKind = groupPrim elif (len(groupPrim) == 3): groupPrimName, groupPrimType, groupPrimKind = groupPrim # Make sure the input Group prim name doesn't exist already # and validate the input name. # Note: it is allowed to be input as empty in which case a default is used. if groupPrimName: checkGroupPrimName = mayaUsd.ufe.uniqueChildName( parentPrim, groupPrimName) if checkGroupPrimName != groupPrimName: errorMsgFormat = getMayaUsdLibString( 'kErrorGroupPrimExists') errorMsg = cmds.format(errorMsgFormat, stringArg=(groupPrimName, ufePathStr)) om.MGlobal.displayError(errorMsg) return Usd.Prim() groupPrimName = Tf.MakeValidIdentifier(checkGroupPrimName) # If the group prim was either not provided or empty we use a default name. if not groupPrimName: groupPrimName = getDefaultGroupPrimName(parentPrim, mayaNamespace) # When the input is a gateway we cannot have in variant unless group is also given. if isGateway and variantSet and not groupPrimName: errorMsg = getMayaUsdLibString('kErrorCannotAddToProxyShape') om.MGlobal.displayError(errorMsg) return Usd.Prim() # Make sure the input Maya Reference prim name doesn't exist already # and validate the input name. # Note: if we are given a group prim to create, then we know that the # Maya Reference prim name will be unique since it will be the # only child (of the newly created group prim). checkName = mayaUsd.ufe.uniqueChildName( parentPrim, mayaReferencePrimName) if groupPrim is None else mayaReferencePrimName if checkName != mayaReferencePrimName: errorMsgFormat = getMayaUsdLibString('kErrorMayaRefPrimExists') errorMsg = cmds.format(errorMsgFormat, stringArg=(mayaReferencePrimName, ufePathStr)) om.MGlobal.displayError(errorMsg) return Usd.Prim() validatedPrimName = Tf.MakeValidIdentifier(checkName) # Extract the USD path segment from the UFE path and append the Maya # reference prim to it. parentPath = str(ufePath.segments[1]) if ufePath.nbSegments() > 1 else '' stage = mayaUsd.ufe.getStage(ufePathStr) # Optionally insert a Group prim as a parent of the Maya reference prim. groupPrim = None if groupPrimName: groupPath = Sdf.AssetPath(parentPath + '/' + groupPrimName) try: groupPrim = stage.DefinePrim(groupPath.path, groupPrimType) except (Tf.ErrorException): groupPrim = Usd.Prim() if not groupPrim.IsValid(): errorMsgFormat = getMayaUsdLibString('kErrorCreatingGroupPrim') errorMsg = cmds.format(errorMsgFormat, stringArg=(ufePathStr)) om.MGlobal.displayError(errorMsg) return Usd.Prim() if groupPrimKind: model = Usd.ModelAPI(groupPrim) model.SetKind(groupPrimKind) if groupPrim: primPath = Sdf.AssetPath(groupPrim.GetPath().pathString + '/' + validatedPrimName) else: primPath = Sdf.AssetPath(parentPath + '/' + validatedPrimName) # Were we given a Variant Set to create? variantSetName = None variantName = None if variantSet and (len(variantSet) == 2): variantSetName, variantName = variantSet if variantSetName and variantName: validatedVariantSetName = Tf.MakeValidIdentifier(variantSetName) validatedVariantName = Tf.MakeValidIdentifier(variantName) # If we created a group prim add the variant set there, otherwise add it # to the prim that corresponds to the input ufe path. variantPrim = groupPrim if groupPrim else mayaUsd.ufe.ufePathToPrim( ufePathStr) vset = variantPrim.GetVariantSet(validatedVariantSetName) vset.AddVariant(validatedVariantName) vset.SetVariantSelection(validatedVariantName) with vset.GetVariantEditContext(): # Now all of our subsequent edits will go "inside" the # 'variantName' variant of 'variantSetName'. prim = createPrimAndAttributes(stage, primPath, mayaReferencePath, mayaNamespace, mayaAutoEdit) else: prim = createPrimAndAttributes(stage, primPath, mayaReferencePath, mayaNamespace, mayaAutoEdit) if prim is None or not prim.IsValid(): errorMsgFormat = getMayaUsdLibString('kErrorCreatingMayaRefPrim') errorMsg = cmds.format(errorMsgFormat, stringArg=(ufePathStr)) om.MGlobal.displayError(errorMsg) return Usd.Prim() return prim
def test_Registry(self): """ Test basic registry operations. Also ensures that the discovery process works correctly. """ # Test that the registry does not see 'RmanCpp' twice as a source type, # and that it finds 'glslfx' as a source type assert sorted(self.reg.GetAllNodeSourceTypes()) == \ [self.oslType, self.argsType, self.glslfxType] # Calling SdrRegistry::GetShaderNodesByFamily() will actually parse the # discovery results. # Notice that in the five node names we find, we get 'TestNodeSameName' # twice because there are two nodes with different source types that # have the same name. # Notice that we do not see 'TestNodeGLSLFX' because we don't have a # parser plugin to support it nodes = self.reg.GetShaderNodesByFamily() shaderNodeNames = [node.GetName() for node in nodes] assert set(shaderNodeNames) == { "TestNodeARGS", "TestNodeARGS2", "TestNodeOSL", "TestNodeSameName", "TestNodeSameName" } assert self.reg.GetSearchURIs() == [ "/TestSearchPath", "/TestSearchPath2" ] # Calling SdrRegistry::GetNodeNames only looks at discovery results # without parsing them. # Notice that we get 'TestNodeSameName' only once because we only show # unique names. # Notice that we see 'TestNodeGLSLFX' because it is in our discovery # results even though we do not have a parser plugin that supports its # source type. assert set(self.reg.GetNodeNames()) == { "TestNodeARGS", "TestNodeARGS2", "TestNodeOSL", "TestNodeSameName", "TestNodeGLSLFX" } # Verify that GetNodeIdentifiers follows the same rules as GetNodeNames. # Note that the names and identifiers do happen to be the same in this # test case which is common. assert set(self.reg.GetNodeIdentifiers()) == { "TestNodeARGS", "TestNodeARGS2", "TestNodeOSL", "TestNodeSameName", "TestNodeGLSLFX" } assert id(self.reg.GetShaderNodeByName(nodes[0].GetName())) == id( nodes[0]) nodeName = "TestNodeSameName" nodeIdentifier = "TestNodeSameName" # Ensure that the registry can retrieve two nodes of the same name but # different source types assert len(self.reg.GetShaderNodesByName(nodeName)) == 2 node = self.reg.GetShaderNodeByNameAndType(nodeName, self.oslType) assert node is not None node = self.reg.GetShaderNodeByNameAndType(nodeName, self.argsType) assert node is not None node = self.reg.GetShaderNodeByName(nodeName, [self.oslType, self.argsType]) assert node.GetSourceType() == self.oslType node = self.reg.GetShaderNodeByName(nodeName, [self.argsType, self.oslType]) assert node.GetSourceType() == self.argsType # Ensure that the registry can retrieve these same nodes via identifier, # which, in these cases, are the same as the node names. assert len(self.reg.GetShaderNodesByIdentifier(nodeIdentifier)) == 2 node = self.reg.GetShaderNodeByIdentifierAndType( nodeIdentifier, self.oslType) assert node is not None node = self.reg.GetShaderNodeByIdentifierAndType( nodeIdentifier, self.argsType) assert node is not None node = self.reg.GetShaderNodeByIdentifier( nodeIdentifier, [self.oslType, self.argsType]) assert node.GetSourceType() == self.oslType node = self.reg.GetShaderNodeByIdentifier( nodeIdentifier, [self.argsType, self.oslType]) assert node.GetSourceType() == self.argsType # Test GetShaderNodeFromAsset to check that a subidentifier is part of # the node's identifier if one is specified node = self.reg.GetShaderNodeFromAsset( Sdf.AssetPath('TestNodeSourceAsset.oso'), # shaderAsset {}, # metadata "mySubIdentifier") # subIdentifier assert node.GetIdentifier().endswith("<mySubIdentifier><>") assert node.GetName() == "TestNodeSourceAsset.oso" # Test GetShaderNodeFromAsset to check that a sourceType is part of # the node's identifier if one is specified node = self.reg.GetShaderNodeFromAsset( Sdf.AssetPath('TestNodeSourceAsset.oso'), # shaderAsset {}, # metadata "mySubIdentifier", # subIdentifier "OSL") # sourceType assert node.GetIdentifier().endswith("<mySubIdentifier><OSL>")
def GetValue(self): text = str(self._lineEdit.text()) return Sdf.AssetPath(text) if text else Sdf.AssetPath()
default=0, type=int, action='store') parser.add_argument('--numErrors', dest='numErrors', default=0, type=int, action='store') args = parser.parse_args() context = Ar.GetResolver().CreateDefaultContextForAsset(args.assetPath) with Ar.ResolverContextBinder(context): if not args.arkit: assert UsdUtils.CreateNewUsdzPackage( Sdf.AssetPath(args.assetPath), args.usdzFile, args.rename if args.rename else '') else: assert UsdUtils.CreateNewARKitUsdzPackage( Sdf.AssetPath(args.assetPath), args.usdzFile, args.rename if args.rename else '') zipFile = Usd.ZipFile.Open(args.usdzFile) assert zipFile with stream(args.outfile, 'w') as ofp: for fileName in zipFile.GetFileNames(): print >> ofp, fileName # Validate that the usdz file can be opened on a stage. stage = Usd.Stage.Open(args.usdzFile)
def test_ImplementationSource(self): stage = self._SetupStage() ################################ print('Testing Implementation Source API') ################################ pale = UsdShade.Shader.Get(stage, palePath) self.assertTrue(pale) whiterPale = UsdShade.Shader.Get(stage, whiterPalePath) self.assertTrue(whiterPale) self.assertEqual(pale.GetImplementationSource(), UsdShade.Tokens.id) self.assertEqual(whiterPale.GetImplementationSource(), UsdShade.Tokens.id) self.assertTrue(pale.SetShaderId('SharedFloat_1')) self.assertEqual(pale.GetShaderId(), 'SharedFloat_1') self.assertTrue(whiterPale.SetShaderId('SharedColor_1')) self.assertEqual(whiterPale.GetShaderId(), 'SharedColor_1') pale.GetImplementationSourceAttr().Set(UsdShade.Tokens.sourceAsset) self.assertTrue(pale.GetShaderId() is None) whiterPale.GetImplementationSourceAttr().Set( UsdShade.Tokens.sourceCode) self.assertTrue(whiterPale.GetShaderId() is None) glslfxSource = "This is the shader source" self.assertTrue( pale.SetSourceCode(sourceCode=glslfxSource, sourceType="glslfx")) # Calling SetSourceCode() updates the implementationSource to 'code'. self.assertEqual(pale.GetImplementationSource(), UsdShade.Tokens.sourceCode) self.assertTrue(pale.GetShaderId() is None) self.assertTrue(pale.GetSourceAsset() is None) self.assertTrue(pale.GetSourceAsset(sourceType="glslfx") is None) self.assertTrue(pale.GetSourceCode(sourceType="osl") is None) self.assertTrue(pale.GetSourceCode() is None) self.assertEqual(pale.GetSourceCode(sourceType="glslfx"), glslfxSource) oslAssetPath = Sdf.AssetPath("/source/asset.osl") self.assertTrue( whiterPale.SetSourceAsset( sourceAsset=oslAssetPath, sourceType=UsdShade.Tokens.universalSourceType)) # Calling SetSourceAsset() updates the implementationSource to 'asset'. self.assertEqual(whiterPale.GetImplementationSource(), UsdShade.Tokens.sourceAsset) self.assertTrue(whiterPale.GetShaderId() is None) # Since the sourceAsset was set with universal sourceType, we can fetch # it successfully irrespective of the sourceType that's passed in. self.assertEqual(whiterPale.GetSourceAsset(sourceType="osl"), oslAssetPath) self.assertTrue(whiterPale.GetSourceAsset(sourceType="glslfx"), oslAssetPath) self.assertEqual(whiterPale.GetSourceAsset(), oslAssetPath) self.assertTrue(whiterPale.GetSourceCode() is None) self.assertTrue(whiterPale.GetSourceCode(sourceType="osl") is None) # Set another sourceAsset corresponding to a specific sourceType. glslfxAssetPath = Sdf.AssetPath("/source/asset.glslfx") self.assertTrue( whiterPale.SetSourceAsset(sourceAsset=glslfxAssetPath, sourceType="glslfx")) self.assertEqual(whiterPale.GetSourceAsset(sourceType="osl"), oslAssetPath) self.assertTrue(whiterPale.GetSourceAsset(sourceType="glslfx"), glslfxAssetPath) self.assertEqual(whiterPale.GetSourceAsset(), oslAssetPath)
def test_ImplementationSource(self): stage = self._SetupStage() ################################ print('Testing Implementation Source API') ################################ pale = UsdShade.Shader.Get(stage, palePath) self.assertTrue(pale) whiterPale = UsdShade.Shader.Get(stage, whiterPalePath) self.assertTrue(whiterPale) self.assertEqual(pale.GetImplementationSource(), UsdShade.Tokens.id) self.assertEqual(whiterPale.GetImplementationSource(), UsdShade.Tokens.id) self.assertTrue(pale.SetShaderId('SharedFloat_1')) self.assertEqual(pale.GetShaderId(), 'SharedFloat_1') self.assertTrue(whiterPale.SetShaderId('SharedColor_1')) self.assertEqual(whiterPale.GetShaderId(), 'SharedColor_1') pale.GetImplementationSourceAttr().Set(UsdShade.Tokens.sourceAsset) self.assertTrue(pale.GetShaderId() is None) whiterPale.GetImplementationSourceAttr().Set( UsdShade.Tokens.sourceCode) self.assertTrue(whiterPale.GetShaderId() is None) glslfxSource = "This is the shader source" self.assertTrue( pale.SetSourceCode(sourceCode=glslfxSource, sourceType="glslfx")) # Calling SetSourceCode() updates the implementationSource to 'code'. self.assertEqual(pale.GetImplementationSource(), UsdShade.Tokens.sourceCode) self.assertTrue(pale.GetShaderId() is None) self.assertTrue(pale.GetSourceAsset() is None) self.assertTrue(pale.GetSourceAsset(sourceType="glslfx") is None) self.assertTrue(pale.GetSourceCode(sourceType="osl") is None) self.assertTrue(pale.GetSourceCode() is None) self.assertEqual(pale.GetSourceCode(sourceType="glslfx"), glslfxSource) oslAssetPath = Sdf.AssetPath("/source/asset.osl") self.assertTrue( whiterPale.SetSourceAsset( sourceAsset=oslAssetPath, sourceType=UsdShade.Tokens.universalSourceType)) # Calling SetSourceAsset() updates the implementationSource to 'asset'. self.assertEqual(whiterPale.GetImplementationSource(), UsdShade.Tokens.sourceAsset) self.assertTrue(whiterPale.GetShaderId() is None) # Since the sourceAsset was set with universal sourceType, we can fetch # it successfully irrespective of the sourceType that's passed in. self.assertEqual(whiterPale.GetSourceAsset(sourceType="osl"), oslAssetPath) self.assertTrue(whiterPale.GetSourceAsset(sourceType="glslfx"), oslAssetPath) self.assertEqual(whiterPale.GetSourceAsset(), oslAssetPath) self.assertTrue(whiterPale.GetSourceCode() is None) self.assertTrue(whiterPale.GetSourceCode(sourceType="osl") is None) # Set another sourceAsset corresponding to a specific sourceType. glslfxAssetPath = Sdf.AssetPath("/source/asset.glslfx") self.assertTrue( whiterPale.SetSourceAsset(sourceAsset=glslfxAssetPath, sourceType="glslfx")) self.assertEqual(whiterPale.GetSourceAsset(sourceType="osl"), oslAssetPath) self.assertTrue(whiterPale.GetSourceAsset(sourceType="glslfx"), glslfxAssetPath) self.assertEqual(whiterPale.GetSourceAsset(), oslAssetPath) # Test getting a sub identifier before it has been set self.assertTrue(whiterPale.GetSourceAssetSubIdentifier() is None) self.assertTrue( whiterPale.GetSourceAssetSubIdentifier( sourceType="glslfx") is None) # Reset implementation source to not be 'sourceAsset' whiterPale.GetImplementationSourceAttr().Set(UsdShade.Tokens.id) self.assertEqual(whiterPale.GetImplementationSource(), UsdShade.Tokens.id) # Check that calling SetSourceAssetSubIdentifier updates # implementationSource to 'asset; subId = "mySubIdentifier" self.assertTrue( whiterPale.SetSourceAssetSubIdentifier( subIdentifier=subId, sourceType=UsdShade.Tokens.universalSourceType)) self.assertEqual( whiterPale.GetSourceAssetSubIdentifier( sourceType=UsdShade.Tokens.universalSourceType), subId) self.assertEqual(whiterPale.GetImplementationSource(), UsdShade.Tokens.sourceAsset) # Test that setting a source asset and sub identifier will update the # correct attributes for a variety source types. sourceAsset = Sdf.AssetPath("someSourceAsset") sourceTypes = [UsdShade.Tokens.universalSourceType, "osl"] subIds = ["myUniversalSubIdentifier", "myOSLSubIdentifier"] for sourceType, subId in zip(sourceTypes, subIds): self.assertTrue( whiterPale.SetSourceAsset(sourceAsset=sourceAsset, sourceType=sourceType)) self.assertTrue( whiterPale.SetSourceAssetSubIdentifier(subIdentifier=subId, sourceType=sourceType)) self.assertEqual( whiterPale.GetSourceAssetSubIdentifier(sourceType), subId)
def test_Registry(self): """ Test basic registry operations. Also ensures that the discovery process works correctly. """ # Register test plugins and verify they have been found pr = Plug.Registry() plugins = pr.RegisterPlugins(testPluginsDsoSearch) # Verify the test plugins have been found. When building monolithic # we should find at least these derived types. self.assertEqual(len(plugins), 1) tdpType = Tf.Type.FindByName('_NdrTestDiscoveryPlugin') tdp2Type = Tf.Type.FindByName('_NdrTestDiscoveryPlugin2') tppType = Tf.Type.FindByName('_NdrArgsTestParserPlugin') tpp2Type = Tf.Type.FindByName('_NdrOslTestParserPlugin') # We don't check for all the derived types of NdrDiscoveryPlugin # because this test only uses the discovery and parser plugins # that are defined in this testenv assert {tdpType, tdp2Type }.issubset(set(pr.GetAllDerivedTypes('NdrDiscoveryPlugin'))) assert {tppType, tpp2Type }.issubset(set(pr.GetAllDerivedTypes('NdrParserPlugin'))) # The following source types are what we expect to discover from # _NdrTestDiscoveryPlugin and _NdrTestDiscoveryPlugin2. Note that there # is no glslfx parser plugin provided in this test. argsType = "RmanCpp" oslType = "OSL" glslfxType = "glslfx" # Instantiating the registry will kick off the discovery process. # This test assumes the PXR_NDR_SKIP_DISCOVERY_PLUGIN_DISCOVERY # and PXR_NDR_SKIP_PARSER_PLUGIN_DISCOVERY has been set prior to # being run to ensure built-in plugins are not found. Instead # we'll list the plugins we want explicitly. # Setting this from within the script does not work on Windows. # os.environ["PXR_NDR_SKIP_DISCOVERY_PLUGIN_DISCOVERY"] = "" # os.environ["PXR_NDR_SKIP_PARSER_PLUGIN_DISCOVERY"] = "" reg = Sdr.Registry() # Set up the test parser plugins. reg.SetExtraParserPlugins([tppType, tpp2Type]) # We will register the discovery plugins one by one so that we can check # source types are not duplicated in the registry if we have plugins # that discover nodes of the same source type # The _NdrTestDiscoveryPlugin should find discovery results that have # source types of RmanCpp and OSL reg.SetExtraDiscoveryPlugins([tdpType]) assert reg.GetAllNodeSourceTypes() == [oslType, argsType] # The _NdrTestDiscoveryPlugin2 should find discovery results that have # source types of RmanCpp and glslfx reg.SetExtraDiscoveryPlugins([tdp2Type]) # Test that the registry does not see 'RmanCpp' twice as a source type, # and that it finds 'glslfx' as a source type assert reg.GetAllNodeSourceTypes() == [oslType, argsType, glslfxType] # Calling SdrRegistry::GetShaderNodesByFamily() will actually parse the # discovery results. # Notice that in the five node names we find, we get 'TestNodeSameName' # twice because there are two nodes with different source types that # have the same name. # Notice that we do not see 'TestNodeGLSLFX' because we don't have a # parser plugin to support it nodes = reg.GetShaderNodesByFamily() shaderNodeNames = [node.GetName() for node in nodes] assert set(shaderNodeNames) == { "TestNodeARGS", "TestNodeARGS2", "TestNodeOSL", "TestNodeSameName", "TestNodeSameName" } assert reg.GetSearchURIs() == ["/TestSearchPath", "/TestSearchPath2"] # Calling SdrRegistry::GetNodeNames only looks at discovery results # without parsing them. # Notice that we get 'TestNodeSameName' only once because we only show # unique names. # Notice that we see 'TestNodeGLSLFX' because it is in our discovery # results even though we do not have a parser plugin that supports its # source type. assert set(reg.GetNodeNames()) == { "TestNodeARGS", "TestNodeARGS2", "TestNodeOSL", "TestNodeSameName", "TestNodeGLSLFX" } assert id(reg.GetShaderNodeByName(nodes[0].GetName())) == id(nodes[0]) # Ensure that the registry can retrieve two nodes of the same name but # different source types assert len(reg.GetShaderNodesByName("TestNodeSameName")) == 2 assert reg.GetShaderNodeByNameAndType("TestNodeSameName", oslType) is not None assert reg.GetShaderNodeByNameAndType("TestNodeSameName", argsType) is not None assert reg.GetShaderNodeByName("TestNodeSameName", [oslType, argsType])\ .GetSourceType() == oslType assert reg.GetShaderNodeByName("TestNodeSameName", [argsType, oslType])\ .GetSourceType() == argsType # Test GetShaderNodeFromAsset to check that a subidentifier is part of # the node's identifier if one is specified node = reg.GetShaderNodeFromAsset( Sdf.AssetPath('TestNodeSourceAsset.oso'), # shaderAsset {}, # metadata "mySubIdentifier") # subIdentifier assert node.GetIdentifier().endswith("<mySubIdentifier><>") # Test GetShaderNodeFromAsset to check that a sourceType is part of # the node's identifier if one is specified node = reg.GetShaderNodeFromAsset( Sdf.AssetPath('TestNodeSourceAsset.oso'), # shaderAsset {}, # metadata "mySubIdentifier", # subIdentifier "OSL") # sourceType assert node.GetIdentifier().endswith("<mySubIdentifier><OSL>")
def _convertValueFromPy(cls, pyValue): if pyValue is not None: return Sdf.AssetPath(pyValue)
def GetValue(self): return Sdf.AssetPath(str(self.__lineEdit.text()))
def test_CustomSetName(self): """ Test authoring with a custom set name 'bob' """ # template case resultLayer = Sdf.Layer.CreateNew('customSetName.usd') topLayer = Sdf.Layer.CreateNew('customSetName.topology.usd') UsdUtils.StitchClipsTemplate(resultLayer, topLayer, self.clipPath, 'asset.#.usd', 101, 120, 1, 0.3, 'bob') self.assertEqual(list(resultLayer.subLayerPaths), ['./customSetName.topology.usd']) self.assertEqual(resultLayer.endTimeCode, 120) self.assertEqual(resultLayer.startTimeCode, 101) prim = resultLayer.GetPrimAtPath('/World/fx/Particles_Splash') self.assertTrue('clips' in prim.GetMetaDataInfoKeys()) expectedValues = { 'templateStartTime': 101.0, 'templateStride': 1.0, 'templateActiveOffset': 0.3, 'primPath': '/World/fx/Particles_Splash', 'templateAssetPath': 'asset.#.usd', 'templateEndTime': 120.0 } # Ensure that our custom set name applied actualValues = prim.GetInfo('clips')['bob'] self.assertTrue(actualValues is not None) # Ensure all of our values were written out for k in [ 'templateStartTime', 'templateStride', 'templateEndTime', 'primPath', 'templateAssetPath' ]: self.assertEqual(expectedValues[k], actualValues[k]) # non template case resultLayer = Sdf.Layer.CreateNew('customSetNameNonTemplate.usd') UsdUtils.StitchClips(resultLayer, self.layerFileNames[:7], self.clipPath, clipSet='bob') self.assertEqual(resultLayer.startTimeCode, 101) self.assertEqual(resultLayer.endTimeCode, 107) self.assertEqual(list(resultLayer.subLayerPaths), ['./customSetNameNonTemplate.topology.usd']) prim = resultLayer.GetPrimAtPath('/World/fx/Particles_Splash') expectedValues = { 'active': Vt.Vec2dArray([(101.0, 0.0), (102.0, 1.0), (103.0, 2.0), (104.0, 3.0), (105.0, 4.0), (106.0, 5.0), (107.0, 6.0)]), 'times': Vt.Vec2dArray([(101.0, 101.0), (102.0, 102.0), (103.0, 103.0), (104.0, 104.0), (105.0, 105.0), (106.0, 106.0), (107.0, 107.0)]), 'manifestAssetPath': Sdf.AssetPath('./customSetNameNonTemplate.topology.usd'), 'assetPaths': Sdf.AssetPathArray([ Sdf.AssetPath('./src/Particles_Splash.101.usd'), Sdf.AssetPath('./src/Particles_Splash.102.usd'), Sdf.AssetPath('./src/Particles_Splash.103.usd'), Sdf.AssetPath('./src/Particles_Splash.104.usd'), Sdf.AssetPath('./src/Particles_Splash.105.usd'), Sdf.AssetPath('./src/Particles_Splash.106.usd'), Sdf.AssetPath('./src/Particles_Splash.107.usd') ]), 'primPath': '/World/fx/Particles_Splash' } # Ensure that our custom set name applied actualValues = prim.GetInfo('clips')['bob'] self.assertTrue(actualValues is not None) # Ensure all of our values were written out for k in [ 'active', 'times', 'manifestAssetPath', 'primPath', 'assetPaths' ]: self.assertEqual(expectedValues[k], actualValues[k])
def Main(): s = Usd.Stage.CreateInMemory() # Setup a quad mesh gprim = s.DefinePrim("/Model/Geom/Mesh", "Mesh") gprim.GetAttribute("faceVertexCounts").Set([4]) gprim.GetAttribute("faceVertexIndices").Set([0, 1, 3, 2]) gprim.GetAttribute("points").Set([(-2, -2, -2), (2, -2, -2), (-2, -2, 2), (2, -2, 2)]) UsdGeom.Gprim(gprim).CreatePrimvar( "somePrimvar", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.constant).Set([1.0, 1.0, 1.0]) UsdGeom.Gprim(gprim).CreatePrimvar("map1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.faceVarying).Set( [1.0, 1.0]) lookPrim = UsdShade.Look.Define(s, "/Model/Looks/Pbs") lookPrim.Bind(gprim) # Add a Hydra shader and surface relationship from the look to the shader hydraShader = UsdHydra.Shader( UsdShade.Shader.Define(s, "/Model/Looks/Pbs/PolPbs")) hydraShader.CreateIdAttr("PolPbs_1") hydraLook = UsdHydra.LookAPI(lookPrim) hydraLook.CreateBxdfRel().SetTargets([hydraShader.GetPath()]) uv = UsdHydra.Primvar( UsdShade.Shader.Define(s, "/Model/Looks/Pbs/UvPrimvar")) attr = uv.CreateVarnameAttr("map1") faceIndex = UsdHydra.Primvar( UsdShade.Shader.Define(s, "/Model/Looks/Pbs/FaceIndexPrimvar")) attr = uv.CreateVarnameAttr("ptexFaceIndex") faceOffset = UsdHydra.Primvar( UsdShade.Shader.Define(s, "/Model/Looks/Pbs/FaceOffsetPrimvar")) attr = uv.CreateVarnameAttr("ptexFaceOffset") tex = UsdHydra.UvTexture( UsdShade.Shader.Define(s, "/Model/Looks/Pbs/UvTex")) tex.CreateIdAttr("HwUvTexture_1") tex.CreateWrapSAttr(UsdHydra.Tokens.clamp) tex.CreateWrapTAttr(UsdHydra.Tokens.repeat) tex.CreateMinFilterAttr(UsdHydra.Tokens.linearMipmapLinear) tex.CreateMagFilterAttr(UsdHydra.Tokens.linear) tex.CreateTextureMemoryAttr(100.0) tex.CreateFilenameAttr("/foo/bar.jpg") tex.CreateParameter("outputs:color", Sdf.ValueTypeNames.Color3f) param = UsdShade.Parameter(tex.CreateUvAttr()) param.ConnectToSource(uv, "result", False) texturePath = Sdf.AssetPath("/foo.tex") ptex = UsdHydra.PtexTexture( UsdShade.Shader.Define(s, "/Model/Looks/Pbs/Ptex")) ptex.CreateIdAttr("HwPtexTexture_1") ptex.CreateTextureMemoryAttr(100.0) ptex.CreateFilenameAttr("/foo/bar.ptex") ptex.CreateParameter("outputs:color", Sdf.ValueTypeNames.Color3f) param = UsdShade.Parameter(ptex.CreateFaceIndexAttr()) param.ConnectToSource(faceIndex, "result", False) param = UsdShade.Parameter(ptex.CreateFaceOffsetAttr()) param.ConnectToSource(faceOffset, "result", False) # hydraShader.CreateFilenameAttr(Sdf.AssetPath("PbsSurface.glslfx")) # param = hydraShader.CreateParameter("colorFromUv", Sdf.ValueTypeNames.Color3f) param.ConnectToSource(tex, "color", False) # param = hydraShader.CreateParameter("colorFromPtex1", Sdf.ValueTypeNames.Color3f) param.ConnectToSource(ptex, "color", False) # color = UsdHydra.Primvar( UsdShade.Shader.Define(s, "/Model/Looks/Pbs/ColorPrimvar")) attr = uv.CreateVarnameAttr("displayColor") param = hydraShader.CreateParameter("colorFromPrimvar", Sdf.ValueTypeNames.Color3f) param.ConnectToSource(color, "result", False) print hydraShader.GetConnectedPrimvar(param.GetAttr()) print hydraShader.IsConnectedToPrimvar(param.GetAttr()) print s.GetRootLayer().ExportToString()