def setUpClass(cls): pr = Plug.Registry() testPlugins = pr.RegisterPlugins(os.path.abspath("resources")) assert len(testPlugins) == 1, \ "Failed to load expected test plugin" assert testPlugins[0].name == "testUsdAppliedAPISchemas", \ "Failed to load expected test plugin" cls.SingleApplyAPIType = \ Tf.Type(Usd.SchemaBase).FindDerivedByName("TestSingleApplyAPI") cls.MultiApplyAPIType = \ Tf.Type(Usd.SchemaBase).FindDerivedByName("TestMultiApplyAPI")
def setUpClass(cls): # Register applied schemas and auto applied schemas pr = Plug.Registry() testPlugins = pr.RegisterPlugins(os.path.abspath("resources")) assert len(testPlugins) == 1, \ "Failed to load expected test plugin" assert testPlugins[0].name == "testUsdShadeConnectableAPIBehavior", \ "Failed to load expected test plugin" cls.AutoApplyDefaultConnectableBehaviorAPI = \ Tf.Type(Usd.SchemaBase).FindDerivedByName("\ AutoApplyDefaultConnectableBehaviorAPI" ) cls.DefaultConnectableBehaviorAPI = \ Tf.Type(Usd.SchemaBase).FindDerivedByName("\ DefaultConnectableBehaviorAPI" ) return True
def setUp(self): self.tUnknown = Tf.Type() self.tRoot = Tf.Type.GetRoot() self.tBase = Tf.Type.Find(Base) self.tDerived = Tf.Type.Find(Derived) self.tConcreteChild = Tf.Type.Find(ConcreteChild) self.tAbstractInterface = Tf.Type.Find(AbstractInterface)
def test_ManufacturingPythonDerivedClasses(self): ppd1 = Plug.Registry().GetPluginForType( 'TestPlugModule1.TestPlugPythonDerived1') self.assertIsNotNone(ppd1) self.assertFalse(ppd1.isLoaded) self.assertTrue(ppd1.isPythonModule) ppd2 = Plug.Registry().GetPluginForType( 'TestPlugModule2.TestPlugPythonDerived2') self.assertIsNotNone(ppd2) self.assertFalse(ppd2.isLoaded) self.assertTrue(ppd2.isPythonModule) # Load and construct an instance of TestPlugPythonDerived1 # (Loading should add TestPlugModule1 to the namespace) ppd1.Load() tpd1 = TestPlugModule1.TestPlugPythonDerived1() self.assertEqual(tpd1.GetTypeName(), 'TestPlugModule1.TestPlugPythonDerived1') self.assertTrue(ppd1.isLoaded) # Load and construct an instance of TestPlugPythonDerived2 # (Loading should add TestPlugModule2 to the namespace) ppd2.Load() tpd2 = TestPlugModule2.TestPlugPythonDerived2() self.assertEqual(tpd2.GetTypeName(), 'TestPlugModule2.TestPlugPythonDerived2') self.assertTrue(ppd2.isLoaded) # Check that loading an already loaded plugin is a noop. ppd2.Load() # Check that plugin correctly reports its declared types. self.assertFalse( ppd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=False)) self.assertTrue( ppd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=True)) self.assertTrue( ppd1.DeclaresType( Tf.Type('TestPlugModule1.TestPlugPythonDerived1'), includeSubclasses=False)) self.assertTrue( ppd1.DeclaresType( Tf.Type('TestPlugModule1.TestPlugPythonDerived1'), includeSubclasses=True))
def test_BytesOrUnicodeArgs(self): expectedType = Tf.Type.FindByName('int') self.assertTrue(expectedType) # test bytes arg typeNameBytes = b'int' t = Tf.Type.FindByName(typeNameBytes) self.assertEqual(expectedType, t) t = Tf.Type(typeNameBytes) self.assertEqual(expectedType, t) #test unicode arg typeNameUnicode = u'int' t = Tf.Type.FindByName(typeNameUnicode) self.assertEqual(expectedType, t) t = Tf.Type(typeNameUnicode) self.assertEqual(expectedType, t)
def test_RootType(self): self._TestCppType(self.tRoot) self.assertFalse(self.tRoot.baseTypes) # We should already have some builtInTypes defined: self.assertGreater(len(self.tRoot.derivedTypes), 1) self.assertEqual(hash(self.tRoot), hash(Tf.Type.GetRoot())) self.assertNotEqual(hash(self.tRoot), hash(Tf.Type()))
def test_GetUsdSchemaTypeName(self): modelAPI = Tf.Type.FindByName("UsdModelAPI") clipsAPI = Tf.Type.FindByName("UsdClipsAPI") collectionAPI = Tf.Type.FindByName("UsdCollectionAPI") self.assertEqual(Usd.SchemaRegistry().GetSchemaTypeName(modelAPI), "ModelAPI") self.assertEqual(Usd.SchemaRegistry().GetSchemaTypeName(clipsAPI), "ClipsAPI") self.assertEqual(Usd.SchemaRegistry().GetSchemaTypeName(collectionAPI), "CollectionAPI") # A valid type without an associated schema prim definition returns an # empty type name. self.assertTrue(Tf.Type(Usd.Typed)) self.assertEqual( Usd.SchemaRegistry().GetSchemaTypeName(Tf.Type(Usd.Typed)), "")
def test_ManufacturingCppDerivedClasses(self): # Construct and verify an instance of _TestPlugBase<1> tb1 = Plug._TestPlugBase1() self.assertEqual(tb1.GetTypeName(), '_TestPlugBase<1>') # Get the plugin for TestPlugDerived1 pd1 = Plug.Registry().GetPluginForType('TestPlugDerived1') self.assertIsNotNone(pd1) self.assertFalse(pd1.isLoaded) # Manufacture and verify an instance of TestPlugDerived1 td1 = Plug._TestPlugBase1('TestPlugDerived1') self.assertTrue(td1 and not td1.expired) self.assertEqual(td1.GetTypeName(), 'TestPlugDerived1') self.assertTrue(pd1.isLoaded) # Construct and verify an instance of _TestPlugBase<2> tb2 = Plug._TestPlugBase2() self.assertEqual(tb2.GetTypeName(), '_TestPlugBase<2>') # Get the plugin for TestPlugDerived2 pd2 = Plug.Registry().GetPluginForType('TestPlugDerived2') self.assertIsNotNone(pd2) self.assertFalse(pd2.isLoaded) # Manufacture and verify an instance of TestPlugDerived2 td2 = Plug._TestPlugBase2('TestPlugDerived2') self.assertTrue(td2 and not td2.expired) self.assertEqual(td2.GetTypeName(), 'TestPlugDerived2') self.assertTrue(pd2.isLoaded) # Check that plugin correctly reports its declared types. self.assertFalse( pd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=False)) self.assertTrue( pd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=True)) self.assertTrue( pd1.DeclaresType(Tf.Type('TestPlugDerived1'), includeSubclasses=False)) self.assertTrue( pd1.DeclaresType(Tf.Type('TestPlugDerived1'), includeSubclasses=True))
def test_UntypedPrimOnStage(self): """ Tests the fallback properties of untyped prims on a stage when API schemas are applied """ stage = Usd.Stage.CreateInMemory() # Add a prim with no type. It has no applied schemas or properties. untypedPrim = stage.DefinePrim("/Untyped") self.assertEqual(untypedPrim.GetTypeName(), '') self.assertEqual(untypedPrim.GetAppliedSchemas(), []) self.assertEqual(untypedPrim.GetPropertyNames(), []) # Add an api schema to the prim's metadata. l = Sdf.TokenListOp() l.explicitItems = ["TestSingleApplyAPI"] untypedPrim.SetMetadata("apiSchemas", l) # Prim still has no type but does have applied schemas self.assertEqual(untypedPrim.GetTypeName(), '') self.assertEqual(untypedPrim.GetAppliedSchemas(), ["TestSingleApplyAPI"]) self.assertTrue( untypedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestSingleApplyAPI"))) # The prim has properties from the applied schema and value resolution # returns the applied schema's property fallback value. self.assertEqual( untypedPrim.GetPropertyNames(), ["single:bool_attr", "single:relationship", "single:token_attr"]) self.assertEqual( untypedPrim.GetAttribute("single:token_attr").Get(), "bar") # Applied schemas are unable to define fallback metadata values for # prims. Just verifying that no fallback exists for "hidden" here as # a contrast to the other cases below where this metadata fallback will # be defined. self.assertFalse("hidden" in untypedPrim.GetAllMetadata()) self.assertIsNone(untypedPrim.GetMetadata("hidden")) self.assertFalse(untypedPrim.HasAuthoredMetadata("hidden")) # Untyped prim still has no documentation even with API schemas applied. self.assertIsNone(untypedPrim.GetMetadata("documentation"))
def getTranslatedType(self): return Tf.Type()
def test_InheritanceResolution(self): def CheckTfTypeOrderVsPython(classObj): '''Assert that the order of GetAllAncestorTypes() matches Python's native 'mro' method resolution order -- while accounting for the extra root TfType.''' t = Tf.Type.Find( classObj ) # We should have a valid TfType. self.assertFalse(t.isUnknown) # Get Python's mro and convert the results to TfTypes. pythonOrder = map( Tf.Type.Find, classObj.mro() ) self.assertEqual(tuple(pythonOrder + [self.tRoot,]), t.GetAllAncestorTypes()) # Unknown type with self.assertRaises(Tf.ErrorException): Tf.Type().GetAllAncestorTypes() # Root type self.tRoot = Tf.Type.GetRoot() self.assertEqual((self.tRoot,), self.tRoot.GetAllAncestorTypes()) # Python 'object' class tObject = Tf.Type.Find(object) self.assertFalse(tObject.isUnknown) self.assertEqual((tObject, self.tRoot,), tObject.GetAllAncestorTypes()) CheckTfTypeOrderVsPython( object ) # Single custom class class T1_Z(object): pass tT1_Z = Tf.Type.Define(T1_Z) self.assertEqual((tT1_Z, tObject, self.tRoot), tT1_Z.GetAllAncestorTypes()) CheckTfTypeOrderVsPython( T1_Z ) # Single inheritance test class T2_A(object): pass class T2_B(T2_A): pass class T2_Z(T2_B): pass tT2_A = Tf.Type.Define(T2_A) tT2_B = Tf.Type.Define(T2_B) tT2_Z = Tf.Type.Define(T2_Z) self.assertEqual((tT2_Z, tT2_B, tT2_A, tObject, self.tRoot), tT2_Z.GetAllAncestorTypes()) CheckTfTypeOrderVsPython( T2_Z ) # Simple multiple inheritance test class T3_A(object): pass class T3_B(object): pass class T3_Z(T3_A, T3_B): pass tT3_A = Tf.Type.Define(T3_A) tT3_B = Tf.Type.Define(T3_B) tT3_Z = Tf.Type.Define(T3_Z) self.assertEqual((tT3_Z, tT3_A, tT3_B, tObject, self.tRoot), tT3_Z.GetAllAncestorTypes()) CheckTfTypeOrderVsPython( T3_Z ) # Complex multiple inheritance test. # # This is an example where a simple depth-first traversal of base types # gives non-intuitive results. This was taken from the Python 2.3 release # notes, here: # # http://www.python.org/download/releases/2.3/mro/ # class T4_A(object): pass class T4_B(object): pass class T4_C(object): pass class T4_D(object): pass class T4_E(object): pass class T4_K1(T4_A,T4_B,T4_C): pass class T4_K2(T4_D,T4_B,T4_E): pass class T4_K3(T4_D,T4_A): pass class T4_Z(T4_K1,T4_K2,T4_K3): pass tT4_A = Tf.Type.Define(T4_A) tT4_B = Tf.Type.Define(T4_B) tT4_C = Tf.Type.Define(T4_C) tT4_D = Tf.Type.Define(T4_D) tT4_E = Tf.Type.Define(T4_E) tT4_K1 = Tf.Type.Define(T4_K1) tT4_K2 = Tf.Type.Define(T4_K2) tT4_K3 = Tf.Type.Define(T4_K3) tT4_Z = Tf.Type.Define(T4_Z) self.assertEqual(tT4_Z.GetAllAncestorTypes(), (tT4_Z, tT4_K1, tT4_K2, tT4_K3, tT4_D, tT4_A, tT4_B, tT4_C, tT4_E, tObject, self.tRoot)) CheckTfTypeOrderVsPython( T4_Z )
def test_TypedPrimsOnStageWithFallbackReapply(self): """ Tests the fallback properties of typed prims on a stage when the same API schemas are applied again to a prim whose type already has applied API schemas. """ stage = Usd.Stage.CreateInMemory() # Add a typed prim. It has API schemas already from its prim definition # and has properties from both its type and its APIs. typedPrim = stage.DefinePrim("/TypedPrim", "TestWithFallbackAppliedSchema") self.assertEqual(typedPrim.GetTypeName(), 'TestWithFallbackAppliedSchema') self.assertEqual(typedPrim.GetAppliedSchemas(), ["TestMultiApplyAPI:fallback", "TestSingleApplyAPI"]) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestSingleApplyAPI"))) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestMultiApplyAPI"))) self.assertEqual(typedPrim.GetPropertyNames(), [ "multi:fallback:bool_attr", "multi:fallback:relationship", "multi:fallback:token_attr", "single:bool_attr", "single:relationship", "single:token_attr", "testAttr", "testRel" ]) # Property fallback comes from TestSingleApplyAPI attr = typedPrim.GetAttribute("single:token_attr") self.assertEqual(attr.Get(), "bar") self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Property fallback actually comes from TestTypedSchema as the typed # schema overrides this property from its fallback API schema. attr = typedPrim.GetAttribute("multi:fallback:bool_attr") self.assertEqual(attr.Get(), False) self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Property fallback comes from TestTypedSchema attr = typedPrim.GetAttribute("testAttr") self.assertEqual(attr.Get(), "foo") self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Add the fallback api schemas again to the prim's metadata. l = Sdf.TokenListOp() l.explicitItems = ["TestMultiApplyAPI:fallback", "TestSingleApplyAPI"] typedPrim.SetMetadata("apiSchemas", l) # Prim has the same type and now has both its original API schemas and # plus the same schemas again appended to the list (i.e. both schemas # now show up twice). self.assertEqual(typedPrim.GetTypeName(), 'TestWithFallbackAppliedSchema') self.assertEqual(typedPrim.GetAppliedSchemas(), [ "TestMultiApplyAPI:fallback", "TestSingleApplyAPI", "TestMultiApplyAPI:fallback", "TestSingleApplyAPI" ]) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestSingleApplyAPI"))) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestMultiApplyAPI"))) # The list of properties hasn't changed as there are no "new" schemas, # however the defaults may have changed. self.assertEqual(typedPrim.GetPropertyNames(), [ "multi:fallback:bool_attr", "multi:fallback:relationship", "multi:fallback:token_attr", "single:bool_attr", "single:relationship", "single:token_attr", "testAttr", "testRel" ]) # Property fallback comes from TestSingleApplyAPI - no change attr = typedPrim.GetAttribute("single:token_attr") self.assertEqual(attr.Get(), "bar") self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Property fallback has now change to True to False as the # TestTypedSchema originally overrode the fallback from # TestMultiApplyAPI. But by applying TestMultiApplyAPI again with the # same instance, we've re-overridden the attribute getting the default # from the applied schema. attr = typedPrim.GetAttribute("multi:fallback:bool_attr") self.assertEqual(attr.Get(), True) self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Property fallback comes from TestTypedSchema - no change attr = typedPrim.GetAttribute("testAttr") self.assertEqual(attr.Get(), "foo") self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Prim metadata is unchanged from the case above as there is still # no way for applied API schemas to impart prim metadata defaults. self.assertEqual(typedPrim.GetAllMetadata()["hidden"], False) self.assertEqual(typedPrim.GetMetadata("hidden"), False) self.assertFalse(typedPrim.HasAuthoredMetadata("hidden")) self.assertFalse("hidden" in typedPrim.GetAllAuthoredMetadata()) # Documentation metadata comes from prim type definition even with API # schemas applied. self.assertEqual(typedPrim.GetMetadata("documentation"), "Test with fallback API schemas")
def test_TypedPrimsOnStageWithFallback(self): """ Tests the fallback properties of typed prims on a stage when new API schemas are applied to a prim whose type already has applied API schemas. """ stage = Usd.Stage.CreateInMemory() # Add a typed prim. It has API schemas already from its prim definition # and has properties from both its type and its APIs. typedPrim = stage.DefinePrim("/TypedPrim", "TestWithFallbackAppliedSchema") self.assertEqual(typedPrim.GetTypeName(), 'TestWithFallbackAppliedSchema') self.assertEqual(typedPrim.GetAppliedSchemas(), ["TestMultiApplyAPI:fallback", "TestSingleApplyAPI"]) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestSingleApplyAPI"))) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestMultiApplyAPI"))) self.assertEqual(typedPrim.GetPropertyNames(), [ "multi:fallback:bool_attr", "multi:fallback:relationship", "multi:fallback:token_attr", "single:bool_attr", "single:relationship", "single:token_attr", "testAttr", "testRel" ]) # Add a new api schemas to the prim's metadata. l = Sdf.TokenListOp() l.explicitItems = ["TestMultiApplyAPI:garply"] typedPrim.SetMetadata("apiSchemas", l) # Prim has the same type and now has both its original API schemas and # the new one. Note that the new schema was added using an explicit # list op but was still appended to the original list. Fallback API # schemas cannot be deleted and any authored API schemas will always be # appended to the fallbacks. self.assertEqual(typedPrim.GetTypeName(), 'TestWithFallbackAppliedSchema') self.assertEqual(typedPrim.GetAppliedSchemas(), [ "TestMultiApplyAPI:fallback", "TestSingleApplyAPI", "TestMultiApplyAPI:garply" ]) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestSingleApplyAPI"))) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestMultiApplyAPI"))) # Properties have been expanded to include the new API schema self.assertEqual(typedPrim.GetPropertyNames(), [ "multi:fallback:bool_attr", "multi:fallback:relationship", "multi:fallback:token_attr", "multi:garply:bool_attr", "multi:garply:relationship", "multi:garply:token_attr", "single:bool_attr", "single:relationship", "single:token_attr", "testAttr", "testRel" ]) # Property fallback comes from TestSingleApplyAPI attr = typedPrim.GetAttribute("single:token_attr") self.assertEqual(attr.Get(), "bar") self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Property fallback comes from TestMultiApplyAPI attr = typedPrim.GetAttribute("multi:garply:bool_attr") self.assertEqual(attr.Get(), True) self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Property fallback actually comes from TestWithFallbackAppliedSchema as # the typed schema overrides this property from its fallback API schema. attr = typedPrim.GetAttribute("multi:fallback:bool_attr") self.assertEqual(attr.Get(), False) self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Property fallback comes from TestWithFallbackAppliedSchema attr = typedPrim.GetAttribute("testAttr") self.assertEqual(attr.Get(), "foo") self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Metadata "hidden" has a fallback value defined in # TestWithFallbackAppliedSchema. It will be returned by GetMetadata and # GetAllMetadata but will return false for queries about whether it's # authored self.assertEqual(typedPrim.GetAllMetadata()["hidden"], False) self.assertEqual(typedPrim.GetMetadata("hidden"), False) self.assertFalse(typedPrim.HasAuthoredMetadata("hidden")) self.assertFalse("hidden" in typedPrim.GetAllAuthoredMetadata()) # Documentation metadata comes from prim type definition even with API # schemas applied. self.assertEqual(typedPrim.GetMetadata("documentation"), "Test with fallback API schemas")
def test_TypedPrimOnStage(self): """ Tests the fallback properties of typed prims on a stage when API schemas are applied when the prim type does not start with API schemas. """ stage = Usd.Stage.CreateInMemory() # Add a typed prim. It has no API schemas but has properties from its # type schema. typedPrim = stage.DefinePrim("/TypedPrim", "TestTypedSchema") self.assertEqual(typedPrim.GetTypeName(), 'TestTypedSchema') self.assertEqual(typedPrim.GetAppliedSchemas(), []) self.assertEqual(typedPrim.GetPropertyNames(), ["testAttr", "testRel"]) # Add an api schemas to the prim's metadata. l = Sdf.TokenListOp() l.explicitItems = ["TestSingleApplyAPI", "TestMultiApplyAPI:garply"] typedPrim.SetMetadata("apiSchemas", l) # Prim has the same type and now has API schemas. The properties have # been expanded to include properties from the API schemas self.assertEqual(typedPrim.GetTypeName(), 'TestTypedSchema') self.assertEqual(typedPrim.GetAppliedSchemas(), ["TestSingleApplyAPI", "TestMultiApplyAPI:garply"]) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestSingleApplyAPI"))) self.assertTrue( typedPrim.HasAPI( Tf.Type( Usd.SchemaBase).FindDerivedByName("TestMultiApplyAPI"))) self.assertEqual(typedPrim.GetPropertyNames(), [ "multi:garply:bool_attr", "multi:garply:relationship", "multi:garply:token_attr", "single:bool_attr", "single:relationship", "single:token_attr", "testAttr", "testRel" ]) # Property fallback comes from TestSingleApplyAPI attr = typedPrim.GetAttribute("single:token_attr") self.assertEqual(attr.Get(), "bar") self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Property fallback comes from TestMultiApplyAPI attr = typedPrim.GetAttribute("multi:garply:bool_attr") self.assertEqual(attr.Get(), True) self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Property fallback comes from TestTypedSchema attr = typedPrim.GetAttribute("testAttr") self.assertEqual(attr.Get(), "foo") self.assertEqual(attr.GetResolveInfo().GetSource(), Usd.ResolveInfoSourceFallback) # Metadata "hidden" has a fallback value defined in TestTypedSchema. It # will be returned by GetMetadata and GetAllMetadata but will return # false for queries about whether it's authored self.assertEqual(typedPrim.GetAllMetadata()["hidden"], True) self.assertEqual(typedPrim.GetMetadata("hidden"), True) self.assertFalse(typedPrim.HasAuthoredMetadata("hidden")) self.assertFalse("hidden" in typedPrim.GetAllAuthoredMetadata()) # Documentation metadata comes from prim type definition even with API # schemas applied. self.assertEqual(typedPrim.GetMetadata("documentation"), "Testing typed schema")
def test_SdrShaderNodesForLights(self): """ Test the automatic registration of SdrShaderNodes for all the UsdLux light types. """ # Get all the derived types of UsdLuxLight lightTypes = Tf.Type(UsdLux.Light).GetAllDerivedTypes() self.assertTrue(lightTypes) # Verify that at least one known light type is in our list to guard # against this giving false positives if no light types are available. self.assertIn(UsdLux.RectLight, lightTypes) stage = Usd.Stage.CreateInMemory() prim = stage.DefinePrim("/Prim") for lightType in lightTypes: # Every concrete light type will have an SdrShaderNode with source # type 'USD' registered for it under its USD schema type name. typeName = Usd.SchemaRegistry.GetConcreteSchemaTypeName(lightType) node = Sdr.Registry().GetNodeByName(typeName, ['USD']) self.assertTrue(node.IsValid()) # Set the prim to the light type so we can cross check node inputs # with the light prim built-in properties. prim.SetTypeName(typeName) light = UsdLux.Light(prim) self.assertTrue(light) # Names, identifier, and role for the node all match the USD schema # type name self.assertEqual(node.GetIdentifier(), typeName) self.assertEqual(node.GetName(), typeName) self.assertEqual(node.GetImplementationName(), typeName) self.assertEqual(node.GetRole(), typeName) self.assertTrue(node.GetInfoString().startswith(typeName)) # The context is always 'light'. Source type is 'USD' self.assertEqual(node.GetContext(), 'light') self.assertEqual(node.GetSourceType(), 'USD') # Help string is generated and encoded in the node's metadata (no # need to verify the specific wording). self.assertTrue(set(node.GetMetadata().keys()), {'primvars', 'help'}) self.assertEqual(node.GetMetadata()["help"], node.GetHelp()) # Source code and URIs are all empty. self.assertFalse(node.GetSourceCode()) self.assertFalse(node.GetResolvedDefinitionURI()) self.assertFalse(node.GetResolvedImplementationURI()) # Other classifications are left empty. self.assertFalse(node.GetCategory()) self.assertFalse(node.GetDepartments()) self.assertFalse(node.GetFamily()) self.assertFalse(node.GetLabel()) self.assertFalse(node.GetVersion()) self.assertFalse(node.GetAllVstructNames()) self.assertEqual(node.GetPages(), ['']) # Helper for comparing an SdrShaderProperty from node to the # corresponding UsdShadeInput/UsdShadeOutput from a UsdLuxLight def _CompareLightPropToNodeProp(nodeInput, lightInput): # Input names and default values match. self.assertEqual(nodeInput.GetName(), lightInput.GetBaseName()) self.assertEqual(nodeInput.GetDefaultValue(), lightInput.GetAttr().Get()) # Some USD property types don't match exactly one to one and are # converted to different types. In particular relevance to # lights, Bool becomes Int and Token becomes String. expectedTypeName = lightInput.GetTypeName() if expectedTypeName == Sdf.ValueTypeNames.Bool: expectedTypeName = Sdf.ValueTypeNames.Int elif expectedTypeName == Sdf.ValueTypeNames.Token: expectedTypeName = Sdf.ValueTypeNames.String # Verify the node's input type maps back to USD property's type # (with the noted above exceptions). self.assertEqual( nodeInput.GetTypeAsSdfType()[0], expectedTypeName, msg="Type {} != {}".format( str(nodeInput.GetTypeAsSdfType()[0]), str(expectedTypeName))) # If the USD property type is an Asset, it will be listed in # the node's asset indentifier inputs. if expectedTypeName == Sdf.ValueTypeNames.Asset: self.assertIn(nodeInput.GetName(), node.GetAssetIdentifierInputNames()) # There will be a one to one correspondence between node inputs # and light prim inputs. nodeInputs = [node.GetInput(i) for i in node.GetInputNames()] lightInputs = light.GetInputs() for nodeInput, lightInput in zip(nodeInputs, lightInputs): self.assertFalse(nodeInput.IsOutput()) _CompareLightPropToNodeProp(nodeInput, lightInput) # There will also be a one to one correspondence between node # outputs and light prim outputs. nodeOutputs = [node.GetOutput(i) for i in node.GetOutputNames()] lightOutputs = light.GetOutputs() for nodeOutput, lightOutput in zip(nodeOutputs, lightOutputs): self.assertTrue(nodeOutput.IsOutput()) _CompareLightPropToNodeProp(nodeOutput, lightOutput) # The reverse is tested just above, but for all asset identifier # inputs listed for the node there is a corresponding asset value # input property on the light prim. for inputName in node.GetAssetIdentifierInputNames(): self.assertEqual(light.GetInput(inputName).GetTypeName(), Sdf.ValueTypeNames.Asset) # These primvars come from sdrMetadata on the prim itself which # isn't supported for light schemas so it will alwasy be empty. self.assertFalse(node.GetPrimvars()) # sdrMetadata on input properties is supported so additional # primvar properties will correspond to light inputs with that # metadata set. for propName in node.GetAdditionalPrimvarProperties(): self.assertTrue(light.GetInput(propName).GetSdrMetadataByKey( 'primvarProperty')) # Default input can also be specified in the property's sdrMetadata. if node.GetDefaultInput(): defaultLightInput = light.GetInput( node.GetDefaultInput().GetName()) self.assertTrue(lightInput.GetSdrMetadataByKey('defaultInput'))
def test_SdrShaderNodesForLights(self): """ Test the automatic registration of SdrShaderNodes for all the UsdLux light types. """ # The expected shader node inputs that should be found for all of our # UsdLux light types. expectedLightInputNames = [ # LightAPI 'color', 'colorTemperature', 'diffuse', 'enableColorTemperature', 'exposure', 'intensity', 'normalize', 'specular', # ShadowAPI 'shadow:color', 'shadow:distance', 'shadow:enable', 'shadow:falloff', 'shadow:falloffGamma', # ShapingAPI 'shaping:cone:angle', 'shaping:cone:softness', 'shaping:focus', 'shaping:focusTint', 'shaping:ies:angleScale', 'shaping:ies:file', 'shaping:ies:normalize' ] # Map of the names of the expected light nodes to the additional inputs # we expect for those types. expectedLightNodes = { 'CylinderLight' : ['length', 'radius'], 'DiskLight' : ['radius'], 'DistantLight' : ['angle'], 'DomeLight' : ['texture:file', 'texture:format'], 'GeometryLight' : [], 'PortalLight' : [], 'RectLight' : ['width', 'height', 'texture:file'], 'SphereLight' : ['radius'], 'MeshLight' : [], 'VolumeLight' : [] } # Get all the derived types of UsdLuxBoundableLightBase and # UsdLuxNonboundableLightBase that are defined in UsdLux lightTypes = list(filter( Plug.Registry().GetPluginWithName("usdLux").DeclaresType, Tf.Type(UsdLux.BoundableLightBase).GetAllDerivedTypes() + Tf.Type(UsdLux.NonboundableLightBase).GetAllDerivedTypes())) self.assertTrue(lightTypes) # Augment lightTypes to include MeshLightAPI and VolumeLightAPI lightTypes.append( Tf.Type.FindByName('UsdLuxMeshLightAPI')) lightTypes.append( Tf.Type.FindByName('UsdLuxVolumeLightAPI')) # Verify that at least one known light type is in our list to guard # against this giving false positives if no light types are available. self.assertIn(UsdLux.RectLight, lightTypes) self.assertEqual(len(lightTypes), len(expectedLightNodes)) stage = Usd.Stage.CreateInMemory() prim = stage.DefinePrim("/Prim") usdSchemaReg = Usd.SchemaRegistry() for lightType in lightTypes: print("Test SdrNode for schema type " + str(lightType)) if usdSchemaReg.IsAppliedAPISchema(lightType): prim.ApplyAPI(lightType) else: typeName = usdSchemaReg.GetConcreteSchemaTypeName(lightType) if not typeName: continue prim.SetTypeName(typeName) light = UsdLux.LightAPI(prim) self.assertTrue(light) sdrIdentifier = light.GetShaderId([]) self.assertTrue(sdrIdentifier) prim.ApplyAPI(UsdLux.ShadowAPI) prim.ApplyAPI(UsdLux.ShapingAPI) # Every concrete light type and some API schemas (with appropriate # shaderId as sdr Identifier) in usdLux domain will have an # SdrShaderNode with source type 'USD' registered for it under its # USD schema type name. node = Sdr.Registry().GetNodeByIdentifier(sdrIdentifier, ['USD']) self.assertTrue(node is not None) self.assertIn(sdrIdentifier, expectedLightNodes) # Names, identifier, and role for the node all match the USD schema # type name self.assertEqual(node.GetIdentifier(), sdrIdentifier) self.assertEqual(node.GetName(), sdrIdentifier) self.assertEqual(node.GetImplementationName(), sdrIdentifier) self.assertEqual(node.GetRole(), sdrIdentifier) self.assertTrue(node.GetInfoString().startswith(sdrIdentifier)) # The context is always 'light' for lights. # Source type is 'USD' self.assertEqual(node.GetContext(), 'light') self.assertEqual(node.GetSourceType(), 'USD') # Help string is generated and encoded in the node's metadata (no # need to verify the specific wording). self.assertTrue(set(node.GetMetadata().keys()), {'primvars', 'help'}) self.assertEqual(node.GetMetadata()["help"], node.GetHelp()) # Source code and URIs are all empty. self.assertFalse(node.GetSourceCode()) self.assertFalse(node.GetResolvedDefinitionURI()) self.assertFalse(node.GetResolvedImplementationURI()) # Other classifications are left empty. self.assertFalse(node.GetCategory()) self.assertFalse(node.GetDepartments()) self.assertFalse(node.GetFamily()) self.assertFalse(node.GetLabel()) self.assertFalse(node.GetVersion()) self.assertFalse(node.GetAllVstructNames()) self.assertEqual(node.GetPages(), ['']) # The node will be valid for our light types. self.assertTrue(node.IsValid()) # Helper for comparing an SdrShaderProperty from node to the # corresponding UsdShadeInput/UsdShadeOutput from a UsdLux light def _CompareLightPropToNodeProp(nodeInput, primInput): # Input names and default values match. primDefaultValue = primInput.GetAttr().Get() self.assertEqual(nodeInput.GetName(), primInput.GetBaseName()) self.assertEqual(nodeInput.GetDefaultValue(), primDefaultValue) # Some USD property types don't match exactly one to one and are # converted to different types. In particular relevance to # lights and Token becomes String. expectedTypeName = primInput.GetTypeName() # Array valued attributes have their array size determined from # the default value and will be converted to scalar in the # SdrProperty if the array size is zero. if expectedTypeName.isArray: if not primDefaultValue or len(primDefaultValue) == 0: expectedTypeName = expectedTypeName.scalarType elif expectedTypeName == Sdf.ValueTypeNames.Token: expectedTypeName = Sdf.ValueTypeNames.String # Bool SdfTypes should Have Int SdrTypes, but still return as # Bool when queried for GetTypeAsSdfType if expectedTypeName == Sdf.ValueTypeNames.Bool: self.assertEqual(nodeInput.GetType(), Sdf.ValueTypeNames.Int) # Verify the node's input type maps back to USD property's type # (with the noted above exceptions). self.assertEqual( nodeInput.GetTypeAsSdfType()[0], expectedTypeName, msg="{}.{} Type {} != {}".format( str(node.GetName()), str(nodeInput.GetName()), str(nodeInput.GetTypeAsSdfType()[0]), str(expectedTypeName))) # If the USD property type is an Asset, it will be listed in # the node's asset identifier inputs. if expectedTypeName == Sdf.ValueTypeNames.Asset: self.assertIn(nodeInput.GetName(), node.GetAssetIdentifierInputNames()) # There will be a one to one correspondence between node inputs # and prim inputs. Note that the prim may have additional inputs # because of auto applied API schemas, but we only need to verify # that the node has ONLY the expected inputs and the prim at least # has those input proerties. expectedInputNames = \ expectedLightInputNames + expectedLightNodes[sdrIdentifier] # Verify node has exactly the expected inputs. self.assertEqual(sorted(expectedInputNames), sorted(node.GetInputNames())) # Verify each node input matches a prim input. for inputName in expectedInputNames: nodeInput = node.GetInput(inputName) primInput = light.GetInput(inputName) self.assertFalse(nodeInput.IsOutput()) _CompareLightPropToNodeProp(nodeInput, primInput) # None of the UsdLux base lights have outputs self.assertEqual(node.GetOutputNames(), []) self.assertEqual(light.GetOutputs(onlyAuthored=False), []) # The reverse is tested just above, but for all asset identifier # inputs listed for the node there is a corresponding asset value # input property on the prim. for inputName in node.GetAssetIdentifierInputNames(): self.assertEqual(light.GetInput(inputName).GetTypeName(), Sdf.ValueTypeNames.Asset) # These primvars come from sdrMetadata on the prim itself which # isn't supported for light schemas so it will always be empty. self.assertFalse(node.GetPrimvars()) # sdrMetadata on input properties is supported so additional # primvar properties will correspond to prim inputs with that # metadata set. for propName in node.GetAdditionalPrimvarProperties(): self.assertTrue(light.GetInput(propName).GetSdrMetadataByKey( 'primvarProperty')) # Default input can also be specified in the property's sdrMetadata. if node.GetDefaultInput(): defaultInput = light.GetInput( node.GetDefaultInput().GetName()) self.assertTrue(defaultInput.GetSdrMetadataByKey('defaultInput'))
def test_GetUsdSchemaTypeName(self): abstractTest = Tf.Type.FindByName("TestUsdSchemaRegistryAbstractTest") concreteTest = Tf.Type.FindByName("TestUsdSchemaRegistryMetadataTest") modelAPI = Tf.Type.FindByName("UsdModelAPI") collectionAPI = Tf.Type.FindByName("UsdCollectionAPI") # Test getting a schema type name from a TfType for a concrete typed # schema. self.assertEqual(Usd.SchemaRegistry.GetSchemaTypeName(concreteTest), "MetadataTest") self.assertEqual( Usd.SchemaRegistry.GetConcreteSchemaTypeName(concreteTest), "MetadataTest") self.assertEqual(Usd.SchemaRegistry.GetAPISchemaTypeName(concreteTest), "") # Test the reverse of getting the TfType for concrete typed schema name. self.assertEqual( Usd.SchemaRegistry.GetTypeFromSchemaTypeName("MetadataTest"), concreteTest) self.assertEqual( Usd.SchemaRegistry.GetConcreteTypeFromSchemaTypeName( "MetadataTest"), concreteTest) self.assertEqual( Usd.SchemaRegistry.GetAPITypeFromSchemaTypeName("MetadataTest"), Tf.Type.Unknown) # Test getting a schema type name from a TfType for an abstract typed # schema. self.assertEqual(Usd.SchemaRegistry.GetSchemaTypeName(abstractTest), "AbstractTest") self.assertEqual( Usd.SchemaRegistry.GetConcreteSchemaTypeName(abstractTest), "") self.assertEqual(Usd.SchemaRegistry.GetAPISchemaTypeName(abstractTest), "") # Test the reverse of getting the TfType for abastract typed schema name. self.assertEqual( Usd.SchemaRegistry.GetTypeFromSchemaTypeName("AbstractTest"), abstractTest) self.assertEqual( Usd.SchemaRegistry.GetConcreteTypeFromSchemaTypeName( "AbstractTest"), Tf.Type.Unknown) self.assertEqual( Usd.SchemaRegistry.GetAPITypeFromSchemaTypeName("MetadataTest"), Tf.Type.Unknown) # Test getting a schema type name from a TfType for an applied API # schema. self.assertEqual(Usd.SchemaRegistry.GetSchemaTypeName(collectionAPI), "CollectionAPI") self.assertEqual( Usd.SchemaRegistry.GetConcreteSchemaTypeName(collectionAPI), "") self.assertEqual( Usd.SchemaRegistry.GetAPISchemaTypeName(collectionAPI), "CollectionAPI") # Test the reverse of getting the TfType for an applied API schema name. self.assertEqual( Usd.SchemaRegistry.GetTypeFromSchemaTypeName("CollectionAPI"), collectionAPI) self.assertEqual( Usd.SchemaRegistry.GetConcreteTypeFromSchemaTypeName( "CollectionAPI"), Tf.Type.Unknown) self.assertEqual( Usd.SchemaRegistry.GetAPITypeFromSchemaTypeName("CollectionAPI"), collectionAPI) # Test getting a schema type name from a TfType for a non-apply API # schema. This is the same API as for applied API schemas but may change # in the future? self.assertEqual(Usd.SchemaRegistry.GetSchemaTypeName(modelAPI), "ModelAPI") self.assertEqual( Usd.SchemaRegistry.GetConcreteSchemaTypeName(modelAPI), "") self.assertEqual(Usd.SchemaRegistry.GetAPISchemaTypeName(modelAPI), "ModelAPI") # Test the reverse of getting the TfType for a non-apply API schema name self.assertEqual( Usd.SchemaRegistry.GetTypeFromSchemaTypeName("ModelAPI"), modelAPI) self.assertEqual( Usd.SchemaRegistry.GetConcreteTypeFromSchemaTypeName("ModelAPI"), Tf.Type.Unknown) self.assertEqual( Usd.SchemaRegistry.GetAPITypeFromSchemaTypeName("ModelAPI"), modelAPI) # A valid type without an associated schema prim definition returns an # empty type name. self.assertTrue(Tf.Type(Usd.Typed)) self.assertEqual( Usd.SchemaRegistry().GetSchemaTypeName(Tf.Type(Usd.Typed)), "")
def _SchemaTypeFindByName(name): result = Tf.Type(Usd.SchemaBase).FindDerivedByName(name) assert not result.isUnknown return result