Exemplo n.º 1
0
    def test_RmanConversions(self):
        from pxr import UsdRi

        # Note that we have the old names as the first elements in
        # the list, our conversion test relies on this fact. This is only
        # really relevant in the case of Rman's '1' value, in which we have
        # some ambiguity(it could be cornersPlus1, cornersPlus2, or cornersOnly)
        # since we don't currently express the propogateCorners argument through
        # the system.
        faceVaryingConversionTable = [
            (["all"], 0), (["cornersPlus1", "cornersPlus2", "cornersOnly"], 1),
            (["none"], 2), (["boundaries"], 3)
        ]

        for tokens, rmanValue in faceVaryingConversionTable:
            # Check all tokens, old and new
            for token in tokens:
                # Convert to renderman values
                self.assertEqual(
                    UsdRi.ConvertToRManFaceVaryingLinearInterpolation(token),
                    rmanValue)

            # Convert from renderman values
            # Note that we only map to the new tokens.
            self.assertEqual(
                UsdRi.ConvertFromRManFaceVaryingLinearInterpolation(rmanValue),
                tokens[0])
Exemplo n.º 2
0
    def test_Basic(self):
        stage = Usd.Stage.CreateInMemory()

        # can't use these if not properly initialized
        bogusSpline = UsdRi.SplineAPI()
        with self.assertRaises(RuntimeError):
            bogusSpline.Validate()[0]

        light = UsdLux.SphereLight.Define(stage, '/Light')
        rod = stage.DefinePrim("/Light/Rod", "PxrRodLightFilter")
        light.GetFiltersRel().SetTargets([rod.GetPath()])

        # Create SplineAPI for "fallOffRamp" spline for the Rod prim
        falloffRamp = UsdRi.SplineAPI(rod, "falloffRamp",
                                      Sdf.ValueTypeNames.FloatArray, True)
        # Create SplineAPI for "colorRamp" spline for the Rod prim
        colorRamp = UsdRi.SplineAPI(rod, "colorRamp",
                                    Sdf.ValueTypeNames.Color3fArray, True)

        # initially invalid since no spline exists
        assert not IsValid(falloffRamp)
        assert not IsValid(colorRamp)

        # set a simple ease-out falloff spline
        SetEaseOut(falloffRamp)
        assert IsValid(falloffRamp)

        # try a mismatch of values & positions
        falloffRamp.CreateValuesAttr().Set([1.0, 0.8, 0.2])
        assert not IsValid(falloffRamp)

        # try a bogus interpolation value
        SetEaseOut(falloffRamp)
        assert IsValid(falloffRamp)
        falloffRamp.CreateInterpolationAttr().Set('bogus')
        assert not IsValid(falloffRamp)

        # check all known interp types
        for interp in ['linear', 'constant', 'catmull-rom', 'bspline']:
            falloffRamp.CreateInterpolationAttr().Set(interp)
            assert IsValid(falloffRamp)

        # try non-sorted positions
        falloffRamp.CreatePositionsAttr().Set([1.0, 0.7, 0.3, 0.0])
        assert not IsValid(falloffRamp)

        # set a red->green->blue color ramp
        colorRamp.CreateInterpolationAttr().Set(UsdRi.Tokens.linear)
        colorRamp.CreatePositionsAttr().Set([0.0, 0.5, 1.0])
        colorRamp.CreateValuesAttr().Set([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0),
                                          (0.0, 0.0, 1.0)])
        assert IsValid(colorRamp)
Exemplo n.º 3
0
    def _ValidateAllAttributes(self, usdPrim, exportedAttrsDict):
        """
        Validates that USD attributes, primvars, and UsdRi attributes exist,
        have the correct value, and have the correct type for each attribute
        prefix in exportedAttrsDict.
        """
        self.assertTrue(usdPrim)

        gprim = UsdGeom.Gprim(usdPrim)
        self.assertTrue(gprim)

        # Do a quick check to see whether we have the right number of attributes
        # by counting the primvars and UsdRi attributes.
        # Getting all primvars will also include the built-in displayColor,
        # displayOpacity, and st, so we add 3 to the length of the
        # exportedAttrsDict for that check.
        primvars = gprim.GetPrimvars()
        self.assertEqual(len(primvars), len(exportedAttrsDict) + 3)

        riStatements = UsdRi.Statements(usdPrim)
        self.assertTrue(riStatements)

        riAttrs = riStatements.GetRiAttributes()
        self.assertEqual(len(riAttrs), len(exportedAttrsDict))

        # UsdRi attributes store vector and point array data as just arrays of
        # three doubles/floats.
        riAttrMapping = {
            Sdf.ValueTypeNames.Vector3dArray: Sdf.ValueTypeNames.Double3Array,
            Sdf.ValueTypeNames.Vector3fArray: Sdf.ValueTypeNames.Float3Array,
            Sdf.ValueTypeNames.Point3dArray: Sdf.ValueTypeNames.Double3Array,
            Sdf.ValueTypeNames.Point3fArray: Sdf.ValueTypeNames.Float3Array
        }

        for attrPrefix in exportedAttrsDict:
            # Test regular USD attributes.
            usdAttr = usdPrim.GetAttribute('userProperties:%sUsdAttr' % attrPrefix)
            value = exportedAttrsDict[attrPrefix]['value']
            self.assertTrue(usdAttr)
            self.assertEqual(usdAttr.GetTypeName(),
                             exportedAttrsDict[attrPrefix]['typeName'])
            self.assertTrue(usdAttr.IsCustom())
            self._assertAlmostEqualWithFallback(usdAttr.Get(), value)

            # Test primvars.
            primvar = gprim.GetPrimvar('%sPrimvar' % attrPrefix)
            self.assertTrue(primvar)
            self.assertTrue(UsdGeom.Primvar.IsPrimvar(primvar))
            self._assertAlmostEqualWithFallback(primvar.Get(), value)
            self.assertEqual(primvar.GetTypeName(), exportedAttrsDict[attrPrefix]['typeName'])

            # Test UsdRi attributes.
            riAttr = usdPrim.GetAttribute('ri:attributes:user:%sUsdRiAttr' % attrPrefix)
            self.assertTrue(riAttr)
            self.assertTrue(UsdRi.Statements.IsRiAttribute(riAttr))
            self._assertAlmostEqualWithFallback(riAttr.Get(), value)

            riAttrType = exportedAttrsDict[attrPrefix]['typeName']
            riAttrType = riAttrMapping.get(riAttrType, riAttrType)
            self.assertEqual(riAttr.GetTypeName(), riAttrType)
Exemplo n.º 4
0
    def _ValidateUsdRiPxrEnvDayLight(self):
        lightPrimPath = '/RfMLightsTest/Lights/EnvDayLight'
        lightPrim = self._stage.GetPrimAtPath(lightPrimPath)
        self.assertTrue(lightPrim)

        envDayLight = UsdRi.PxrEnvDayLight(lightPrim)
        self.assertTrue(envDayLight)

        expectedDay = 8
        self.assertEqual(envDayLight.GetDayAttr().Get(), expectedDay)

        expectedHaziness = 1.8
        self.assertTrue(
            Gf.IsClose(envDayLight.GetHazinessAttr().Get(), expectedHaziness,
                       1e-6))

        expectedHour = 8.8
        self.assertTrue(
            Gf.IsClose(envDayLight.GetHourAttr().Get(), expectedHour, 1e-6))

        expectedLatitude = 80.0
        self.assertTrue(
            Gf.IsClose(envDayLight.GetLatitudeAttr().Get(), expectedLatitude,
                       1e-6))

        expectedLongitude = -80.0
        self.assertTrue(
            Gf.IsClose(envDayLight.GetLongitudeAttr().Get(), expectedLongitude,
                       1e-6))

        expectedMonth = 8
        self.assertEqual(envDayLight.GetMonthAttr().Get(), expectedMonth)

        expectedSkyTint = Gf.Vec3f(0.8)
        self.assertTrue(
            Gf.IsClose(envDayLight.GetSkyTintAttr().Get(), expectedSkyTint,
                       1e-6))

        expectedSunDirection = Gf.Vec3f(0.0, 0.0, 0.8)
        self.assertTrue(
            Gf.IsClose(envDayLight.GetSunDirectionAttr().Get(),
                       expectedSunDirection, 1e-6))

        expectedSunSize = 0.8
        self.assertTrue(
            Gf.IsClose(envDayLight.GetSunSizeAttr().Get(), expectedSunSize,
                       1e-6))

        expectedSunTint = Gf.Vec3f(0.8)
        self.assertTrue(
            Gf.IsClose(envDayLight.GetSunTintAttr().Get(), expectedSunTint,
                       1e-6))

        expectedYear = 2018
        self.assertEqual(envDayLight.GetYearAttr().Get(), expectedYear)

        expectedZone = 8.0
        self.assertTrue(
            Gf.IsClose(envDayLight.GetZoneAttr().Get(), expectedZone, 1e-6))
Exemplo n.º 5
0
def _AddShadingToBall(stage):
    from pxr import Sdf, UsdRi
    model = stage.OverridePrim('/Ball')
    texDir = os.path.join(ASSET_BASE, 'Ball/tex')
    mesh = stage.OverridePrim('/Ball/mesh')

    ballTextureNode = UsdRi.RisObject(
        stage.OverridePrim(
            model.GetPath().AppendPath('Looks/BallMaterial/BallTexture')))

    # now we'll show adding some shading variants to the ball as well.
    shadingVariantsInfo = [
        ('Cue', '', _Color(0.996, 0.992, 0.874)),  # white
        ('Ball_1', '', _Color(1.000, 0.929, 0.184)),  # yellow
        ('Ball_2', '', _Color(0.157, 0.243, 0.631)),  # blue
        ('Ball_3', '', _Color(0.976, 0.212, 0.141)),  # red
        ('Ball_4', '', _Color(0.250, 0.156, 0.400)),  # purple
        ('Ball_5', '', _Color(0.980, 0.498, 0.184)),  # orange
        ('Ball_6', '', _Color(0.050, 0.255, 0.239)),  # green
        ('Ball_7', '', _Color(0.607, 0.059, 0.094)),  # darkred
        ('Ball_8', '', _Color(0.122, 0.118, 0.110)),  # black
        ('Ball_9', 'striped', _Color(1.000, 0.929, 0.184)),  # yellow
        ('Ball_10', 'striped', _Color(0.157, 0.243, 0.631)),  # blue
        ('Ball_11', 'striped', _Color(0.976, 0.212, 0.141)),  # red
        ('Ball_12', 'striped', _Color(0.250, 0.156, 0.400)),  # purple
        ('Ball_13', 'striped', _Color(0.980, 0.498, 0.184)),  # orange
        ('Ball_14', 'striped', _Color(0.050, 0.255, 0.239)),  # green
        ('Ball_15', 'striped', _Color(0.607, 0.059, 0.094)),  # darkred
    ]

    # create the shadingVariant variantSet
    shadingVariant = model.GetVariantSets().AddVariantSet('shadingVariant')
    for variantName, decoration, color in shadingVariantsInfo:
        # creates a variant inside 'shadingVariant'
        shadingVariant.AddVariant(variantName)

        # switch to that variant
        shadingVariant.SetVariantSelection(variantName)

        # this 'with' construct here tells Usd that authoring operations should
        # write to the shadingVariant.
        with shadingVariant.GetVariantEditContext():
            whichBall = variantName.split('_')[-1]
            texPath = os.path.join(texDir, 'ball%s.tex' % whichBall)
            # in the current variant, modify the color
            _SetParameters(ballTextureNode, [
                ('filename', Sdf.ValueTypeNames.String, texPath),
            ])

            # set the display color for hydra
            _SetDisplayColor(mesh, color)

            # currently not doing anything with decoration, but we could maybe
            # use this to make the solid vs. stripes.

    # now make the variant selection 'Cue' instead of the last variant that we
    # created above.
    shadingVariant.SetVariantSelection('Cue')
    def testExportPxrRisShading(self):
        """
        Tests that exporting a Maya mesh with a simple Maya shading setup
        results in the correct shading on the USD mesh.
        """
        cubePrim = self._stage.GetPrimAtPath('/MarbleCube/Geom/Cube')
        self.assertTrue(cubePrim)

        # Validate the Material prim bound to the Mesh prim.
        material = UsdShade.Material.GetBoundMaterial(cubePrim)
        self.assertTrue(material)
        materialPath = material.GetPath().pathString
        self.assertEqual(materialPath, '/MarbleCube/Looks/MarbleCubeSG')

        # Validate the surface shader that is connected to the material.
        # XXX: Note that the expected number of outputs here is two rather than
        # one, since we are still authoring the UsdRi Bxdf source in addition
        # to the surface terminal for backwards compatibility. When consumers
        # are updated to use the surface terminal instead, this test will have
        # to be updated.
        materialOutputs = material.GetOutputs()
        self.assertEqual(len(materialOutputs), 2)
        materialOutput = material.GetOutput('surface')
        (connectableAPI, outputName,
         outputType) = materialOutput.GetConnectedSource()
        self.assertEqual(outputName, 'out')
        shader = UsdShade.Shader(connectableAPI)
        self.assertTrue(shader)

        # XXX: Validate the UsdRi Bxdf. This must also be removed when we no
        # longer author it.
        from pxr import UsdRi
        usdRiMaterialAPI = UsdRi.MaterialAPI(material.GetPrim())
        self.assertTrue(usdRiMaterialAPI)
        bxdf = usdRiMaterialAPI.GetBxdf()
        self.assertEqual(bxdf.GetPrim(), shader.GetPrim())

        shaderId = shader.GetIdAttr().Get()
        self.assertEqual(shaderId, 'PxrMayaMarble')

        # Validate the connected input on the surface shader.
        shaderInput = shader.GetInput('placementMatrix')
        self.assertTrue(shaderInput)

        (connectableAPI, outputName,
         outputType) = shaderInput.GetConnectedSource()
        self.assertEqual(outputName, 'worldInverseMatrix')
        shader = UsdShade.Shader(connectableAPI)
        self.assertTrue(shader)

        shaderId = shader.GetIdAttr().Get()
        self.assertEqual(shaderId, 'PxrMayaPlacement3d')
Exemplo n.º 7
0
    def test_Basic(self):
        stage = Usd.Stage.CreateInMemory()

        # can't use these if not properly initialized
        bogusSpline = UsdRi.SplineAPI()
        assert not bogusSpline.Validate()[0]

        light = UsdLux.SphereLight.Define(stage, '/Light')
        rod = UsdRi.PxrRodLightFilter.Define(stage, '/Light/Rod')
        light.GetFiltersRel().SetTargets([rod.GetPath()])

        falloffRamp = rod.GetFalloffRampAPI()
        colorRamp = rod.GetColorRampAPI()

        # initially invalid since no spline exists
        assert not IsValid(falloffRamp)
        assert not IsValid(colorRamp)

        # set a simple ease-out falloff spline
        SetEaseOut(falloffRamp)
        assert IsValid(falloffRamp)

        # try a mismatch of values & positions
        falloffRamp.CreateValuesAttr().Set([1.0, 0.8, 0.2])
        assert not IsValid(falloffRamp)

        # try a bogus interpolation value
        SetEaseOut(falloffRamp)
        assert IsValid(falloffRamp)
        falloffRamp.CreateInterpolationAttr().Set('bogus')
        assert not IsValid(falloffRamp)

        # check all known interp types
        for interp in ['linear', 'constant', 'catmullRom', 'bspline']:
            falloffRamp.CreateInterpolationAttr().Set(interp)
            assert IsValid(falloffRamp)

        # try non-sorted positions
        falloffRamp.CreatePositionsAttr().Set([1.0, 0.7, 0.3, 0.0])
        assert not IsValid(falloffRamp)

        # set a red->green->blue color ramp
        colorRamp.CreateInterpolationAttr().Set(UsdRi.Tokens.linear)
        colorRamp.CreatePositionsAttr().Set([0.0, 0.5, 1.0])
        colorRamp.CreateValuesAttr().Set([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0),
                                          (0.0, 0.0, 1.0)])
        assert IsValid(colorRamp)
Exemplo n.º 8
0
    def _ValidateUsdRiPxrAovLight(self):
        lightPrimPath = '/RfMLightsTest/Lights/AovLight'
        lightPrim = self._stage.GetPrimAtPath(lightPrimPath)
        self.assertTrue(lightPrim)

        aovLight = UsdRi.PxrAovLight(lightPrim)
        self.assertTrue(aovLight)

        expectedAovName = 'testAovName'
        self.assertEqual(aovLight.GetAovNameAttr().Get(), expectedAovName)

        expectedInPrimaryHit = False
        self.assertEqual(aovLight.GetInPrimaryHitAttr().Get(),
            expectedInPrimaryHit)

        expectedInReflection = True
        self.assertEqual(aovLight.GetInReflectionAttr().Get(),
            expectedInReflection)

        expectedInRefraction = True
        self.assertEqual(aovLight.GetInRefractionAttr().Get(),
            expectedInRefraction)

        expectedInvert = True
        self.assertEqual(aovLight.GetInvertAttr().Get(), expectedInvert)

        expectedOnVolumeBoundaries = False
        self.assertEqual(aovLight.GetOnVolumeBoundariesAttr().Get(),
            expectedOnVolumeBoundaries)

        expectedUseColor = True
        self.assertEqual(aovLight.GetUseColorAttr().Get(), expectedUseColor)

        expectedUseThroughput = False
        self.assertEqual(aovLight.GetUseThroughputAttr().Get(),
            expectedUseThroughput)
Exemplo n.º 9
0
    def test_Basic(self):
        l = Sdf.Layer.CreateAnonymous()
        stage = Usd.Stage.Open(l.identifier)

        world = stage.DefinePrim("/World", "Xform")
        assert world
        world.SetMetadata('kind', 'group')
        assert world.IsModel()
        assert world.IsGroup()

        group = stage.DefinePrim("/World/Group", "Xform")
        assert group
        group.SetMetadata('kind', 'group')
        assert group.IsModel()
        assert group.IsGroup()

        model = stage.DefinePrim("/World/Group/Model", "Xform")
        assert model
        model.SetMetadata('kind', 'component')
        assert model.IsModel()

        p = stage.DefinePrim("/World/Group/Model/Mesh", "Scope")
        assert p

        print("Test Material")
        material = UsdShade.Material.Define(stage,
                                            "/World/Group/Model/Material")
        assert material
        assert material.GetPrim()
        material.Bind(p)

        print("Test shader")
        shader = UsdRi.RslShader.Define(stage, '/World/Group/Model/Shader')
        assert shader
        assert shader.GetPrim()
        assert not UsdRi.StatementsAPI.IsRiAttribute(shader.GetSloPathAttr())
        shader.GetSloPathAttr().Set('foo')

        print("Test RiMaterialAPI")
        riMaterial = UsdRi.MaterialAPI(material)
        assert riMaterial
        assert riMaterial.GetPrim()

        # Test surface output
        self._TestOutput(riMaterial, UsdRi.MaterialAPI.GetSurfaceOutput,
                         UsdRi.MaterialAPI.SetSurfaceSource,
                         UsdRi.MaterialAPI.GetSurface, shader.GetPath())

        # Test displacement output
        self._TestOutput(riMaterial, UsdRi.MaterialAPI.GetDisplacementOutput,
                         UsdRi.MaterialAPI.SetDisplacementSource,
                         UsdRi.MaterialAPI.GetDisplacement, shader.GetPath())

        # Test volume output
        self._TestOutput(riMaterial, UsdRi.MaterialAPI.GetVolumeOutput,
                         UsdRi.MaterialAPI.SetVolumeSource,
                         UsdRi.MaterialAPI.GetVolume, shader.GetPath())

        print("Test pattern")
        pattern = UsdRi.RisPattern.Define(stage, '/World/Group/Model/Pattern')
        assert pattern
        assert pattern.GetPrim()
        pattern.GetFilePathAttr().Set('foo')
        self.assertEqual(pattern.GetFilePathAttr().Get(), 'foo')
        pattern.GetArgsPathAttr().Set('argspath')
        self.assertEqual(pattern.GetArgsPathAttr().Get(), 'argspath')

        print("Test oslPattern")
        oslPattern = UsdRi.RisOslPattern.Define(
            stage, '/World/Group/Model/OslPattern')
        assert oslPattern
        assert oslPattern.GetPrim()
        self.assertEqual(oslPattern.GetFilePathAttr().Get(), 'PxrOSL')

        print("Test bxdf")
        bxdf = UsdRi.RisBxdf.Define(stage, '/World/Group/Model/Bxdf')
        assert bxdf
        assert bxdf.GetPrim()
        bxdf.GetFilePathAttr().Set('foo')
        bxdf.GetArgsPathAttr().Set('argspath')

        print("Test RIS Material")
        risMaterial = UsdRi.MaterialAPI(material.GetPrim())
        assert risMaterial
        assert risMaterial.GetPrim()
        assert not risMaterial.GetBxdf()

        # Test the bxdf output
        self._TestOutput(risMaterial, UsdRi.MaterialAPI.GetBxdfOutput,
                         UsdRi.MaterialAPI.SetBxdfSource,
                         UsdRi.MaterialAPI.GetBxdf, bxdf.GetPath())

        print("Test riStatements")
        riStatements = UsdRi.StatementsAPI(shader.GetPrim())
        assert riStatements
        assert riStatements.GetPrim()
        attr = riStatements.CreateRiAttribute("ModelName", "string").\
            Set('someModelName')
        assert attr
        props = riStatements.GetRiAttributes()
        assert props
        # this is so convoluted
        attr = riStatements.GetPrim().GetAttribute(props[0].GetName())
        assert attr
        self.assertEqual(attr.GetName(), 'ri:attributes:user:ModelName')
        self.assertEqual(attr.Get(), 'someModelName')
        self.assertEqual(UsdRi.StatementsAPI.GetRiAttributeName(attr),
                         'ModelName')
        self.assertEqual(UsdRi.StatementsAPI.GetRiAttributeNameSpace(attr),
                         'user')
        assert UsdRi.StatementsAPI.IsRiAttribute(attr)

        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('myattr'),
            'ri:attributes:user:myattr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice:myattr'),
            'ri:attributes:dice:myattr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice.myattr'),
            'ri:attributes:dice:myattr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_myattr'),
            'ri:attributes:dice:myattr')
        # period is stronger separator than underscore, when both are present
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_my.attr'),
            'ri:attributes:dice_my:attr')
        # multiple tokens concatted with underscores
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName(
                'dice:my1:long:attr'), 'ri:attributes:dice:my1_long_attr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName(
                'dice.my2.long.attr'), 'ri:attributes:dice:my2_long_attr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName(
                'dice_my3_long_attr'), 'ri:attributes:dice:my3_long_attr')

        self.assertEqual(riStatements.GetCoordinateSystem(), '')
        self.assertEqual(
            UsdRi.StatementsAPI(model).GetModelCoordinateSystems(), [])
        self.assertEqual(
            UsdRi.StatementsAPI(model).GetModelScopedCoordinateSystems(), [])
        riStatements.SetCoordinateSystem('LEyeSpace')
        self.assertEqual(riStatements.GetCoordinateSystem(), 'LEyeSpace')
        self.assertEqual(
            UsdRi.StatementsAPI(model).GetModelCoordinateSystems(),
            [Sdf.Path('/World/Group/Model/Shader')])
        riStatements.SetScopedCoordinateSystem('ScopedLEyeSpace')
        self.assertEqual(riStatements.GetScopedCoordinateSystem(),
                         'ScopedLEyeSpace')
        self.assertEqual(
            UsdRi.StatementsAPI(model).GetModelScopedCoordinateSystems(),
            [Sdf.Path('/World/Group/Model/Shader')])
        self.assertEqual(
            UsdRi.StatementsAPI(group).GetModelCoordinateSystems(), [])
        self.assertEqual(
            UsdRi.StatementsAPI(group).GetModelScopedCoordinateSystems(), [])
        self.assertEqual(
            UsdRi.StatementsAPI(world).GetModelCoordinateSystems(), [])
        self.assertEqual(
            UsdRi.StatementsAPI(world).GetModelScopedCoordinateSystems(), [])

        self.assertFalse(riStatements.GetFocusRegionAttr().IsValid())
        assert (riStatements.CreateFocusRegionAttr() is not None)
        assert (riStatements.GetFocusRegionAttr() is not None)
        self.assertTrue(riStatements.GetFocusRegionAttr().IsValid())
        self.assertEqual(riStatements.GetFocusRegionAttr().Get(), None)
        riStatements.CreateFocusRegionAttr(9.0, True)
        self.assertEqual(riStatements.GetFocusRegionAttr().Get(), 9.0)
Exemplo n.º 10
0
    def test_Basic(self):
        l = Sdf.Layer.CreateAnonymous()
        stage = Usd.Stage.Open(l.identifier)

        world = stage.DefinePrim("/World", "Xform")
        assert world
        world.SetMetadata('kind', 'group')
        assert world.IsModel()
        assert world.IsGroup()

        group = stage.DefinePrim("/World/Group", "Xform")
        assert group
        group.SetMetadata('kind', 'group')
        assert group.IsModel()
        assert group.IsGroup()

        model = stage.DefinePrim("/World/Group/Model", "Xform")
        assert model
        model.SetMetadata('kind', 'component')
        assert model.IsModel()

        p = stage.DefinePrim("/World/Group/Model/Mesh", "Scope")
        assert p

        print("Test Material")
        material = UsdShade.Material.Define(stage,
                                            "/World/Group/Model/Material")
        assert material
        assert material.GetPrim()
        UsdShade.MaterialBindingAPI(p).Bind(material)

        print("Test shader")
        shader = UsdRi.RslShader.Define(stage, '/World/Group/Model/Shader')
        assert shader
        assert shader.GetPrim()
        assert not UsdRi.StatementsAPI.IsRiAttribute(shader.GetSloPathAttr())
        shader.GetSloPathAttr().Set('foo')

        print("Test RiMaterialAPI")
        riMaterial = UsdRi.MaterialAPI.Apply(material.GetPrim())
        assert riMaterial
        assert riMaterial.GetPrim()

        # Test surface output
        self._TestOutput(riMaterial, UsdRi.MaterialAPI.GetSurfaceOutput,
                         UsdRi.MaterialAPI.SetSurfaceSource,
                         UsdRi.MaterialAPI.GetSurface, shader.GetPath())

        # Test displacement output
        self._TestOutput(riMaterial, UsdRi.MaterialAPI.GetDisplacementOutput,
                         UsdRi.MaterialAPI.SetDisplacementSource,
                         UsdRi.MaterialAPI.GetDisplacement, shader.GetPath())

        # Test volume output
        self._TestOutput(riMaterial, UsdRi.MaterialAPI.GetVolumeOutput,
                         UsdRi.MaterialAPI.SetVolumeSource,
                         UsdRi.MaterialAPI.GetVolume, shader.GetPath())

        print("Test pattern")
        pattern = UsdRi.RisPattern.Define(stage, '/World/Group/Model/Pattern')
        assert pattern
        assert pattern.GetPrim()
        pattern.GetFilePathAttr().Set('foo')
        self.assertEqual(pattern.GetFilePathAttr().Get(), 'foo')
        pattern.GetArgsPathAttr().Set('argspath')
        self.assertEqual(pattern.GetArgsPathAttr().Get(), 'argspath')

        print("Test oslPattern")
        oslPattern = UsdRi.RisOslPattern.Define(
            stage, '/World/Group/Model/OslPattern')
        assert oslPattern
        assert oslPattern.GetPrim()
        self.assertEqual(oslPattern.GetFilePathAttr().Get(), 'PxrOSL')

        print("Test bxdf")
        bxdf = UsdRi.RisBxdf.Define(stage, '/World/Group/Model/Bxdf')
        assert bxdf
        assert bxdf.GetPrim()
        bxdf.GetFilePathAttr().Set('foo')
        bxdf.GetArgsPathAttr().Set('argspath')

        print("Test RIS Material")
        risMaterial = UsdRi.MaterialAPI(material.GetPrim())
        assert risMaterial
        assert risMaterial.GetPrim()

        print("Test riStatements")
        riStatements = UsdRi.StatementsAPI.Apply(shader.GetPrim())
        assert riStatements
        assert riStatements.GetPrim()
        attr = riStatements.CreateRiAttribute("ModelName", "string").\
            Set('someModelName')
        assert attr
        props = riStatements.GetRiAttributes()
        assert props
        # this is so convoluted
        attr = riStatements.GetPrim().GetAttribute(props[0].GetName())
        assert attr
        prefix = ('primvars:' if
                  Tf.GetEnvSetting('USDRI_STATEMENTS_WRITE_NEW_ATTR_ENCODING')
                  else '')
        self.assertEqual(attr.GetName(),
                         prefix + 'ri:attributes:user:ModelName')
        self.assertEqual(attr.Get(), 'someModelName')
        self.assertEqual(UsdRi.StatementsAPI.GetRiAttributeName(attr),
                         'ModelName')
        self.assertEqual(UsdRi.StatementsAPI.GetRiAttributeNameSpace(attr),
                         'user')
        assert UsdRi.StatementsAPI.IsRiAttribute(attr)

        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('myattr'),
            prefix + 'ri:attributes:user:myattr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice:myattr'),
            prefix + 'ri:attributes:dice:myattr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice.myattr'),
            prefix + 'ri:attributes:dice:myattr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_myattr'),
            prefix + 'ri:attributes:dice:myattr')
        # period is stronger separator than underscore, when both are present
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_my.attr'),
            prefix + 'ri:attributes:dice_my:attr')
        # multiple tokens concatted with underscores
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName(
                'dice:my1:long:attr'),
            prefix + 'ri:attributes:dice:my1_long_attr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName(
                'dice.my2.long.attr'),
            prefix + 'ri:attributes:dice:my2_long_attr')
        self.assertEqual(
            UsdRi.StatementsAPI.MakeRiAttributePropertyName(
                'dice_my3_long_attr'),
            prefix + 'ri:attributes:dice:my3_long_attr')

        self.assertEqual(riStatements.GetCoordinateSystem(), '')
        self.assertEqual(
            UsdRi.StatementsAPI(model).GetModelCoordinateSystems(), [])
        self.assertEqual(
            UsdRi.StatementsAPI(model).GetModelScopedCoordinateSystems(), [])
        riStatements.SetCoordinateSystem('LEyeSpace')
        self.assertEqual(riStatements.GetCoordinateSystem(), 'LEyeSpace')
        self.assertEqual(
            UsdRi.StatementsAPI(model).GetModelCoordinateSystems(),
            [Sdf.Path('/World/Group/Model/Shader')])
        riStatements.SetScopedCoordinateSystem('ScopedLEyeSpace')
        self.assertEqual(riStatements.GetScopedCoordinateSystem(),
                         'ScopedLEyeSpace')
        self.assertEqual(
            UsdRi.StatementsAPI(model).GetModelScopedCoordinateSystems(),
            [Sdf.Path('/World/Group/Model/Shader')])
        self.assertEqual(
            UsdRi.StatementsAPI(group).GetModelCoordinateSystems(), [])
        self.assertEqual(
            UsdRi.StatementsAPI(group).GetModelScopedCoordinateSystems(), [])
        self.assertEqual(
            UsdRi.StatementsAPI(world).GetModelCoordinateSystems(), [])
        self.assertEqual(
            UsdRi.StatementsAPI(world).GetModelScopedCoordinateSystems(), [])

        # Test mixed old & new style encodings
        if (Tf.GetEnvSetting('USDRI_STATEMENTS_WRITE_NEW_ATTR_ENCODING') and
                Tf.GetEnvSetting('USDRI_STATEMENTS_READ_OLD_ATTR_ENCODING')):
            prim = stage.DefinePrim("/prim")
            riStatements = UsdRi.StatementsAPI.Apply(prim)
            self.assertEqual(len(riStatements.GetRiAttributes()), 0)
            # Add new-style
            newStyleAttr = riStatements.CreateRiAttribute('newStyle', 'string')
            newStyleAttr.Set('new')
            self.assertEqual(len(riStatements.GetRiAttributes()), 1)
            # Add old-style (note that we can't use UsdRi API for this,
            # since it doesn't let the caller choose the encoding)
            oldStyleAttr = prim.CreateAttribute('ri:attributes:user:oldStyle',
                                                Sdf.ValueTypeNames.String)
            oldStyleAttr.Set('old')
            self.assertEqual(len(riStatements.GetRiAttributes()), 2)
            # Exercise the case of an Ri attribute encoded in both
            # old and new styles.
            ignoredAttr = prim.CreateAttribute('ri:attributes:user:newStyle',
                                               Sdf.ValueTypeNames.String)
            self.assertEqual(len(riStatements.GetRiAttributes()), 2)
            self.assertFalse(ignoredAttr in riStatements.GetRiAttributes())
Exemplo n.º 11
0
    def testExportAttributeTypes(self):
        """
        Tests that attributes tagged to be exported as different attribute types
        (Usd attributes, primvars, UsdRi attributes) are exported correctly.
        """
        stage = self._GetExportedStage()

        prim = stage.GetPrimAtPath('/UserExportedAttributesTest/Geom/CubeTypedAttrs')
        self.assertTrue(prim)

        # Validate Usd attributes.
        attrName = 'userProperties:myIntArrayAttr'
        attr = prim.GetAttribute(attrName)
        self.assertTrue(attr)
        expectedValue = Vt.IntArray([99, 98, 97, 96, 95, 94, 93, 92, 91, 90])
        self.assertEqual(attr.Get(), expectedValue)
        self.assertEqual(attr.GetTypeName(), Sdf.ValueTypeNames.IntArray)
        self.assertTrue(attr.IsCustom())

        # Validate UsdRi attributes.
        expectedRiAttrs = {
            'ri:attributes:user:myIntRiAttr':
                {'value': 42,
                 'typeName': Sdf.ValueTypeNames.Int},
            'ri:attributes:user:myNamespace:myAttr':
                {'value': 'UsdRi string',
                 'typeName': Sdf.ValueTypeNames.String},
            'ri:attributes:user:myStringArrayRiAttr':
                {'value': Vt.StringArray(['the', 'quick', 'brown', 'fox']),
                 'typeName': Sdf.ValueTypeNames.StringArray},
        }
        expectedRiAttrNames = set(expectedRiAttrs.keys())

        riStatements = UsdRi.Statements(prim)
        self.assertTrue(riStatements)

        riAttrs = riStatements.GetRiAttributes()
        self.assertEqual(len(riAttrs), 3)

        riAttrNames = {attr.GetName() for attr in riAttrs}
        self.assertEqual(riAttrNames, expectedRiAttrNames)

        for riAttrName in expectedRiAttrs:
            riAttr = prim.GetAttribute(riAttrName)
            self.assertTrue(riAttr)
            self.assertTrue(UsdRi.Statements.IsRiAttribute(riAttr))
            self.assertEqual(riAttr.Get(), expectedRiAttrs[riAttrName]['value'])
            self.assertEqual(riAttr.GetTypeName(), expectedRiAttrs[riAttrName]['typeName'])

        # Validate primvars.
        expectedPrimvars = {
            'myConstantIntPrimvar':
                {'value': 123,
                 'typeName': Sdf.ValueTypeNames.Int,
                 'interpolation': UsdGeom.Tokens.constant},
            'myFaceVaryingIntPrimvar':
                {'value': 999,
                 'typeName': Sdf.ValueTypeNames.Int,
                 'interpolation': UsdGeom.Tokens.faceVarying},
            'myFloatArrayPrimvar':
                {'value': Vt.FloatArray([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8]),
                 'typeName': Sdf.ValueTypeNames.FloatArray,
                 'interpolation': UsdGeom.Tokens.vertex},
            'myStringPrimvar':
                {'value': 'no interp string',
                 'typeName': Sdf.ValueTypeNames.String,
                 'interpolation': None},
            'myUniformDoublePrimvar':
                {'value': 3.140,
                 'typeName': Sdf.ValueTypeNames.Double,
                 'interpolation': UsdGeom.Tokens.uniform},
            'myVertexStringPrimvar':
                {'value': 'a vertex string',
                 'typeName': Sdf.ValueTypeNames.String,
                 'interpolation': UsdGeom.Tokens.vertex},
        }
        expectedPrimvarNames = set(expectedPrimvars.keys())
        # Getting all primvars will also include the built-in displayColor,
        # displayOpacity, and st.
        expectedPrimvarNames.update(['displayColor', 'displayOpacity', 'st'])

        gprim = UsdGeom.Gprim(prim)
        self.assertTrue(gprim)

        primvars = gprim.GetPrimvars()
        self.assertEqual(len(primvars), 9)

        primvarNames = {primvar.GetPrimvarName() for primvar in primvars}
        self.assertEqual(primvarNames, expectedPrimvarNames)

        for primvarName in expectedPrimvars:
            primvar = gprim.GetPrimvar(primvarName)
            self.assertTrue(primvar)
            self.assertTrue(UsdGeom.Primvar.IsPrimvar(primvar))
            self._assertAlmostEqualWithFallback(
                primvar.Get(),
                expectedPrimvars[primvarName]['value'])
            self.assertEqual(primvar.GetTypeName(), expectedPrimvars[primvarName]['typeName'])

            expectedInterpolation = expectedPrimvars[primvarName]['interpolation']
            if expectedInterpolation is None:
                self.assertFalse(primvar.HasAuthoredInterpolation())
            else:
                self.assertTrue(primvar.HasAuthoredInterpolation())
                self.assertEqual(primvar.GetInterpolation(), expectedInterpolation)
Exemplo n.º 12
0
    def testExportDisplayColorShading(self):
        """
        Tests that exporting a Maya mesh with a simple Maya shading setup
        results in the correct shading on the USD mesh.
        """
        # Validate the displayColor on the mesh prim.
        cubePrim = self._stage.GetPrimAtPath('/RedCube/Geom/Cube')
        self.assertTrue(cubePrim)

        cubeMesh = UsdGeom.Mesh(cubePrim)
        self.assertTrue(cubeMesh)

        meshDisplayColors = cubeMesh.GetDisplayColorPrimvar().Get()
        self.assertEqual(len(meshDisplayColors), 1)
        self.assertTrue(Gf.IsClose(meshDisplayColors[0], self.RED_COLOR, 1e-6))

        # Validate the Material prim bound to the Mesh prim.
        material = UsdShade.Material.GetBoundMaterial(cubePrim)
        self.assertTrue(material)
        materialPath = material.GetPath().pathString
        self.assertEqual(materialPath, '/RedCube/Looks/RedLambertSG')

        materialInputs = material.GetInputs()
        self.assertEqual(len(materialInputs), 3)

        materialInput = material.GetInput('displayColor')
        matDisplayColor = materialInput.Get()
        self.assertTrue(Gf.IsClose(matDisplayColor, self.RED_COLOR, 1e-6))

        # Just verify that displayOpacity and transparency exist.
        materialInput = material.GetInput('displayOpacity')
        self.assertTrue(materialInput)

        materialInput = material.GetInput('transparency')
        self.assertTrue(materialInput)

        # Validate the surface shader that is connected to the material.
        # XXX: Note that the expected number of outputs here is two rather than
        # one, since we are still authoring the UsdRi Bxdf source in addition
        # to the surface terminal for backwards compatibility. When consumers
        # are updated to use the surface terminal instead, this test will have
        # to be updated.
        materialOutputs = material.GetOutputs()
        self.assertEqual(len(materialOutputs), 2)
        materialOutput = material.GetOutput('surface')
        (connectableAPI, outputName,
         outputType) = materialOutput.GetConnectedSource()
        self.assertEqual(outputName, 'out')
        shader = UsdShade.Shader(connectableAPI)
        self.assertTrue(shader)
        self.assertEqual(shader.GetPrim().GetName(), 'RedLambertSG_lambert')

        # XXX: Validate the UsdRi Bxdf. This must also be removed when we no
        # longer author it.
        from pxr import UsdRi
        usdRiMaterialAPI = UsdRi.MaterialAPI(material.GetPrim())
        self.assertTrue(usdRiMaterialAPI)
        bxdf = usdRiMaterialAPI.GetBxdf()
        self.assertEqual(bxdf.GetPrim(), shader.GetPrim())

        shaderId = shader.GetIdAttr().Get()
        self.assertEqual(shaderId, 'PxrDiffuse')

        shaderInputs = shader.GetInputs()
        self.assertEqual(len(shaderInputs), 2)

        diffuseInput = shader.GetInput('diffuseColor')
        self.assertTrue(diffuseInput)
        (connectableAPI, outputName,
         outputType) = diffuseInput.GetConnectedSource()
        self.assertEqual(outputName, 'displayColor')
        self.assertTrue(connectableAPI)
        self.assertEqual(connectableAPI.GetPath().pathString, materialPath)

        transmissionInput = shader.GetInput('transmissionColor')
        self.assertTrue(transmissionInput)
        (connectableAPI, outputName,
         outputType) = transmissionInput.GetConnectedSource()
        self.assertEqual(outputName, 'transparency')
        self.assertTrue(connectableAPI)
        self.assertEqual(connectableAPI.GetPath().pathString, materialPath)