Esempio n. 1
0
    def test_RoundTrip(self):
        for fmt in allFormats:
            stage = Usd.Stage.CreateInMemory('TestRoundTrip.'+fmt)
            prims = map(stage.DefinePrim, ['/foo', '/bar', '/baz'])

            treeRange = Usd.PrimRange(stage.GetPseudoRoot())
            tripped = Usd._TestPrimRangeRoundTrip(treeRange)
            self.assertEqual(treeRange, tripped)
            self.assertEqual(list(treeRange), list(tripped))

            treeRange = Usd.PrimRange.PreAndPostVisit(stage.GetPseudoRoot())
            tripped = Usd._TestPrimRangeRoundTrip(treeRange)
            self.assertEqual(treeRange, tripped)
            self.assertEqual(list(treeRange), list(tripped))
Esempio n. 2
0
def _MakeFlattenedRegistryLayer(filePath):
    # We flatten the schema classes to 'eliminate' composition when querying
    # the schema registry.
    stage = Usd.Stage.Open(filePath)

    # Certain qualities on builtin properties are not overridable in scene
    # description.  For example, builtin attributes' types always come from the
    # definition registry, never from scene description.  That's problematic in
    # this case where we're trying to *establish* the definition registry.
    # Since the classes in schema.usda use the real prim type names
    # (e.g. 'Mesh') Usd will pick up these built-in qualities from the existing
    # prim definition.  To side-step this, we temporarily override the prim type
    # names in the session layer so they do not pick up these special
    # nonoverridable qualities when we flatten.  Then after the fact we repair
    # all the type names.

    def mangle(typeName):
        return '__MANGLED_TO_AVOID_BUILTINS__' + typeName

    def demangle(typeName):
        return typeName.replace('__MANGLED_TO_AVOID_BUILTINS__', '')

    # Mangle the typeNames.
    with Usd.EditContext(stage, editTarget=stage.GetSessionLayer()):
        for cls in stage.GetPseudoRoot().GetAllChildren():
            if cls.GetTypeName():
                cls.SetTypeName(mangle(cls.GetTypeName()))

    flatLayer = stage.Flatten(addSourceFileComment=False)

    # Demangle the typeNames.
    for cls in flatLayer.rootPrims:
        if cls.typeName:
            cls.typeName = demangle(cls.typeName)

    # In order to prevent derived classes from inheriting base class
    # documentation metadata, we must manually replace docs here.
    for layer in stage.GetLayerStack():
        for cls in layer.rootPrims:
            flatCls = flatLayer.GetPrimAtPath(cls.path)
            if cls.HasInfo('documentation'):
                flatCls.SetInfo('documentation', cls.documentation)
            else:
                flatCls.ClearInfo('documentation')

    return flatLayer
Esempio n. 3
0
    def _set_blendshape_weights(self, skel_anim, usd_node, gltf_node):
        animations = self.gltf_loader.get_animations()
        if (len(animations) > 0): # only support first animation group
            animation = animations[0]

            animation_channels = animation.get_animation_channels_for_node(gltf_node)
            for animation_channel in animation_channels:
                if animation_channel.target.path == 'weights':
                    output_data = animation_channel.sampler.get_output_data()
                    input_data = animation_channel.sampler.get_input_data()
                    
                    output_data_entries = []
                    for index in range(0, len(output_data)/2):
                        output_data_entries.append([output_data[index * 2], output_data[index * 2 + 1]])
                    usd_blend_shape_weights = skel_anim.CreateBlendShapeWeightsAttr()
                    for entry in zip(output_data_entries, input_data):
                        usd_blend_shape_weights.Set(Vt.FloatArray(entry[0]), Usd.TimeCode(entry[1] * self.fps))
Esempio n. 4
0
def TestBug113044():
    stage = Usd.Stage.Open("animVis.usda")
    bboxCache = UsdGeom.BBoxCache(Usd.TimeCode(0.0),
                                  includedPurposes=[UsdGeom.Tokens.default_])
    pseudoRoot = stage.GetPrimAtPath("/")
    assert bboxCache.ComputeWorldBound(pseudoRoot).GetRange().IsEmpty()

    # The cube is visible at frame 1. This should invalidate the bounds at '/'
    # and cause the bbox to be non-empty.
    bboxCache.SetTime(1.0)
    assert not bboxCache.ComputeWorldBound(pseudoRoot).GetRange().IsEmpty()

    bboxCache.SetTime(2.0)
    assert bboxCache.ComputeWorldBound(pseudoRoot).GetRange().IsEmpty()

    bboxCache.SetTime(3.0)
    assert not bboxCache.ComputeWorldBound(pseudoRoot).GetRange().IsEmpty()
Esempio n. 5
0
    def ResetPrim(self, prim):
        self.beginResetModel()
        if prim is None:
            self.__valid = False
            self.__prim = Usd.Prim()
        else:
            self.__valid = True
            self.__prim = prim
            self.__listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged,
                                                 self.__OnObjectsChanged,
                                                 self.__prim.GetStage())

        if self.__prim:
            self.__primTree = self._GetPrimTree(prim)
        else:
            self.__primTree = []
        self.endResetModel()
Esempio n. 6
0
    def test_TimeSamplesMetadata(self):
        '''Test timeSamples composition, with layer offsets'''
        for fmt in allFormats:
            s = Usd.Stage.CreateInMemory(
                'TestTimeSamplesMetadata.'+fmt)

            # Create two prims, 'weaker' and 'stronger', 'stronger' references
            # 'weaker'.
            weaker = s.OverridePrim('/weaker')
            stronger = s.OverridePrim('/stronger')
            # Use a layer offset on the reference arc to shift timeSamples
            # later in time by 10.
            if Usd.UsesInverseLayerOffset():
                refOffset = Sdf.LayerOffset(scale=1.0, offset=-10.0)
            else:
                refOffset = Sdf.LayerOffset(scale=1.0, offset=10.0)
            stronger.GetReferences().AddReference(
                s.GetRootLayer().identifier, weaker.GetPath(), refOffset)

            # Set some time samples on the reference.
            weaker_attr = \
                weaker.CreateAttribute("attr", Sdf.ValueTypeNames.String)
            # We write directly to the weaker_attr, as opposed to
            # writing to stronger_attr with an edit target (which
            # would give the same result).
            weaker_attr.Set("abc_0", 0.0)
            weaker_attr.Set("def_10", 10.0)
            stronger_attr = stronger.GetAttribute('attr')

            # Confirm resolved metadata.
            weaker_expectedTimeSamples = {0.0: 'abc_0', 10.0: 'def_10'}
            self.assertEqual(
                weaker_attr.GetTimeSamples(),
                sorted(weaker_expectedTimeSamples.keys()))
            self.assertEqual(
                weaker_attr.GetMetadata('timeSamples'),
                weaker_expectedTimeSamples)
            # Stronger attribute will be affected by the offset.
            stronger_expectedTimeSamples = {10.0: 'abc_0', 20.0: 'def_10'}
            self.assertEqual(
                stronger_attr.GetTimeSamples(),
                sorted(stronger_expectedTimeSamples.keys()))
            self.assertEqual(
                stronger_attr.GetMetadata('timeSamples'),
                stronger_expectedTimeSamples)
Esempio n. 7
0
    def testCopySpecToLayer(self):

        destStage = Usd.Stage.CreateInMemory()
        destLayer = Sdf.Layer.CreateAnonymous()
        destStage.GetSessionLayer().subLayerPaths.append(destLayer.identifier)
        destStage.SetEditTarget(Usd.EditTarget(destLayer))
        destPrim = destStage.DefinePrim("/primsState/root", "Xform")

        primPath = Sdf.Path("/root")
        self.usdPrimDisplayManager.swapPrimPurposes(primPath)

        self.usdPrimDisplayManager.copySpecToLayer(primPath, destLayer, destPrim.GetPath())

        self.assertEqual(destStage.GetAttributeAtPath("/primsState/root/Sphere/PROXY.purpose").Get(), "default")
        self.assertEqual(destStage.GetAttributeAtPath("/primsState/root/Cone/PROXY.purpose").Get(), "default")
        self.assertFalse(destStage.GetPrimAtPath("/primsState/root/Sphere/HIGH").IsActive())
        self.assertFalse(destStage.GetPrimAtPath("/primsState/root/Cone/HIGH").IsActive())
        self.assertFalse(destStage.GetPrimAtPath("/primsState/root/Cylinder/HIGH").IsValid())
Esempio n. 8
0
    def __init__(self, mainWindow, item):
        NodeContextMenuItem.__init__(self, mainWindow, item)

        self._assetName = None
        if len(self._currentNodes) == 1:
            from pxr import Usd
            model = Usd.ModelAPI(self._currentNodes[0])
            name = model.GetAssetName()
            identifier = model.GetAssetIdentifier()
            if name and identifier:
                # Ar API is still settling out...
                # from pxr import Ar
                # identifier = Ar.GetResolver().Resolve("", identifier.path)
                from pxr import Sdf
                layer = Sdf.Layer.Find(identifier.path)
                if layer:
                    self._assetName = name
                    self._filePath = layer.realPath
Esempio n. 9
0
    def __init__(self, appController, item):
        PrimContextMenuItem.__init__(self, appController, item)

        self._assetName = None
        if len(self._selectionDataModel.getPrims()) == 1:
            from pxr import Usd
            model = Usd.ModelAPI(self._selectionDataModel.getFocusPrim())
            name = model.GetAssetName()
            identifier = model.GetAssetIdentifier()
            if name and identifier:
                # Ar API is still settling out...
                # from pxr import Ar
                # identifier = Ar.GetResolver().Resolve("", identifier.path)
                from pxr import Sdf
                layer = Sdf.Layer.Find(identifier.path)
                if layer:
                    self._assetName = name
                    self._filePath = layer.realPath
Esempio n. 10
0
def main():
    """Run the main execution of this module."""
    stage = Usd.Stage.CreateInMemory()
    stage.SetStartTimeCode(0)
    stage.SetEndTimeCode(12)

    prim = stage.DefinePrim("/Prim")
    model = Usd.ClipsAPI(prim)
    model.SetClipActive([(0, 0), (2, 1)])
    model.SetClipAssetPaths(
        [Sdf.AssetPath("./clip_1.usda"),
         Sdf.AssetPath("./clip_2.usda")])
    model.SetClipPrimPath("/Clip")
    model.SetClipTimes([(0, 0), (1, 1), (2, 0), (3, 1)])
    model.SetClipManifestAssetPath("./clip_manifest.usda")

    prim.GetReferences().AddReference(assetPath="./ref.usda", primPath="/Ref")
    print(stage.GetRootLayer().ExportToString())
Esempio n. 11
0
def defineParentXforms(stage, primPath):
    '''
    Ensure parent group prims are built.

    Parameters
    ----------
    stage : Sdf.Stage
    primPath : str
    '''
    # this is from the usd tutorial...
    from pxr import UsdGeom
    path = ''
    parentPrims = primPath.strip('/').split('/')[:-1]
    for nextPrim in parentPrims:
        path += ('/' + nextPrim)
        # Make sure the model-parents we need are well-specified
        Usd.ModelAPI(UsdGeom.Xform.Define(stage,
                                          path)).SetKind(Kind.Tokens.group)
Esempio n. 12
0
    def FromUsdFile(cls, usdFile, role=None, parent=None):
        # type: (str, Optional[Union[Type[OutlinerRole], OutlinerRole]], Optional[QtGui.QWidget]) -> UsdOutliner
        """
        Parameters
        ----------
        usdFile : str
        role : Optional[Union[Type[OutlinerRole], OutlinerRole]]
        parent : Optional[QtGui.QWidget]

        Returns
        -------
        UsdOutliner
        """
        with Usd.StageCacheContext(Usd.BlockStageCaches):
            stage = Usd.Stage.Open(usdFile, Usd.Stage.LoadNone)
            assert stage, 'Failed to open stage'
            stage.SetEditTarget(stage.GetSessionLayer())
        return cls(stage, role=role, parent=parent)
Esempio n. 13
0
 def _SetDefaultWithEditTarget(editTarget, attr, resolvedValue,
                               expectedAuthoredValue):
     # Set the edit target on the stage.
     stage.SetEditTarget(editTarget)
     # Set the value at time to the resolved value and verify we get the
     # same resolved value back from both the attr and a
     # UsdAttributeQuery
     attr.Set(resolvedValue)
     self.assertEqual(attr.Get(), resolvedValue)
     # Note that we create the attribute query in this function for the
     # same attribute because we're making changes that affect value
     # resolution
     attrQuery = Usd.AttributeQuery(attr)
     self.assertEqual(attrQuery.Get(), resolvedValue)
     # Verify that the default value authored on the edit target's layer
     # matches the expected authored value.
     self._VerifyAuthoredValue(editTarget, attr.GetPath(), "default",
                               expectedAuthoredValue)
Esempio n. 14
0
def ValidateExpectedInstances(stage, expectedInstances):
    """
    Validate the expected instances and prototypes on the given stage.
    expectedInstances is a mapping from:
        prototype prim path -> list of expected instance prim paths
    """
    for (prototypePath, instancePaths) in expectedInstances.items():
        # Validate that all prims expected to be instances of the same prototype
        # are associated with the same prototype prim.
        prototype = stage.GetPrimAtPath(prototypePath)
        assert prototype, "Expected prototype <%s> does not exist" % prototypePath
        for p in instancePaths:
            prim = stage.GetPrimAtPath(p)
            assert prim, "Prim <%s> does not exist" % p
            assert prim.IsInstance(), "Prim <%s> is not an instance" % p
            assert prim.GetPrototype() == prototype, \
                "Instance <%s> does not have expected prototype <%s>" % \
                (p, prototype.GetPath())

        # Validate that the prototype prim's source prim index is one of
        # the instance's prim indexes.
        prototypePrimIndexPath = prototype._GetSourcePrimIndex().rootNode.path
        instancePrimIndexPaths = [
            stage.GetPrimAtPath(p)._GetSourcePrimIndex().rootNode.path
            for p in instancePaths
        ]

        assert prototypePrimIndexPath in instancePrimIndexPaths, \
            "Prototype <%s> using unexpected prim index <%s>, expected " \
            "one of %s" % (prototype.GetPath(), prototypePrimIndexPath,
                           instancePrimIndexPaths)

    # Validate that we don't have any unexpected prototypes or instances.
    for prototype in stage.GetPrototypes():
        assert str(prototype.GetPath()) in expectedInstances

    for root in [stage.GetPseudoRoot()] + stage.GetPrototypes():
        for prim in Usd.PrimRange(root):
            if prim.IsInstance():
                assert str(prim.GetPath()) in \
                    expectedInstances.get(
                        str(prim.GetPrototype().GetPath()), []), \
                    "Found unexpected instance prim <%s> with prototype <%s>" %\
                    (prim.GetPath(), prim.GetPrototype().GetPath())
Esempio n. 15
0
    def test_SetFromCamera(self):
        camera = Gf.Camera()

        usdStage = Usd.Stage.CreateInMemory()
        usdCamera = UsdGeom.Camera.Define(usdStage, '/camera')
        usdCameraProj = usdCamera.GetProjectionAttr()

        # test fall-back values
        self._CheckValues(camera, usdCamera, 1.0)
        self.assertEqual(usdCameraProj.GetResolveInfo().GetSource(),
                         Usd.ResolveInfoSourceFallback)

        camera.transform = (
            Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(1.0, 2.0, 3.0), 10.0))
            * Gf.Matrix4d().SetTranslate(Gf.Vec3d(4.0, 5.0, 6.0)))
        camera.projection = Gf.Camera.Orthographic
        camera.horizontalAperture = 5.1
        camera.verticalAperture = 2.0
        camera.horizontalApertureOffset = 0.13
        camera.verticalApertureOffset = -0.14
        camera.focalLength = 28
        camera.clippingRange = Gf.Range1f(5, 15)
        camera.clippingPlanes = [[1, 2, 3, 4], [8, 7, 6, 5]]
        camera.fStop = 1.2
        camera.focusDistance = 300

        usdCamera.SetFromCamera(camera, 1.0)

        # test assigned values
        self._CheckValues(camera, usdCamera, 1.0)
        self.assertEqual(usdCameraProj.GetResolveInfo().GetSource(),
                         Usd.ResolveInfoSourceTimeSamples)

        usdCamera.SetFromCamera(camera, 1.0)

        actual = usdCamera.GetLocalTransformation(Usd.TimeCode(1.0))
        expected = Gf.Matrix4d(0.9858929135, 0.14139860385, -0.089563373740,
                               0.0, -0.1370579618, 0.98914839500,
                               0.052920390613, 0.0, 0.0960743367,
                               -0.03989846462, 0.994574197504, 0.0, 4.0, 5.0,
                               6.0, 1.0)

        for a, e in zip(actual, expected):
            self.assertTrue(Gf.IsClose(a, e, 1e-2))
Esempio n. 16
0
def traverse_instanced_children(prim):
    """Get every Prim child beneath `prim`, even if `prim` is instanced.

    Important:
        If `prim` is instanced, any child that this function yields will
        be an instance proxy.

    Args:
        prim (`pxr.Usd.Prim`): Some Prim to check for children.

    Yields:
        `pxr.Usd.Prim`: The children of `prim`.

    """
    for child in prim.GetFilteredChildren(Usd.TraverseInstanceProxies()):
        yield child

        for subchild in traverse_instanced_children(child):
            yield subchild
Esempio n. 17
0
    def test_VariantSelectionPathAbstraction(self):
        for fmt in allFormats:
            s = Usd.Stage.CreateInMemory(
                'TestVariantSelectionPathAbstraction.' + fmt)
            p = s.OverridePrim("/Foo")
            vss = p.GetVariantSets()
            self.assertFalse(p.HasVariantSets())
            vs = vss.AddVariantSet("LOD")
            self.assertTrue(p.HasVariantSets())
            self.assertTrue(vs)
            self.assertTrue(vs.AddVariant("High"))
            self.assertTrue(p.HasVariantSets())

            # This call triggers the bug. This happens because it triggers the
            # computation of a PcpPrimIndex for the variant prim, which then causes
            # the prim with a variant selection to be included in the UsdStage's
            # scene graph later when the next round of change processing occurs.
            #
            # XXX: WBN to indicate the bug # above.  This code changed when the
            # variant API changed during the switch to using EditTargets instead of
            # UsdPrimVariant.  It's unclear whether or not the mystery bug is still
            # reproduced. Leaving the test in place as much as possible..
            self.assertFalse(p.GetAttribute("bar").IsDefined())

            # This triggers change processing which will include the prim with the
            # variant selection and put it on the stage.
            vs.SetVariantSelection('High')
            editTarget = vs.GetVariantEditTarget()
            self.assertTrue(editTarget)
            with Usd.EditContext(s, editTarget):
                s.DefinePrim(p.GetPath().AppendChild('Foobar'), 'Scope')

            self.assertTrue(s.GetPrimAtPath(p.GetPath().AppendChild('Foobar')))

            # Here's the actual manifestation of the bug: We should still not have
            # this prim on the stage, but when the bug is present, we do. Paths
            # containing variant selections can never identify objects on a stage.
            # Verify that the stage does not contain a prim for the variant prim
            # spec we just created at </Foo{LOD=High}Foobar>
            testPath = p.GetPath().AppendVariantSelection(
                'LOD', 'High').AppendChild('Foobar')
            self.assertFalse(s.GetPrimAtPath(testPath))
Esempio n. 18
0
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())
Esempio n. 19
0
def createPrimAndAttributes(stage, primPath, mayaReferencePath, mayaNamespace,
                            mayaAutoEdit):
    try:
        prim = stage.DefinePrim(primPath.path, 'MayaReference')
    except (Tf.ErrorException):
        return Usd.Prim()

    mayaReferenceAttr = prim.CreateAttribute('mayaReference',
                                             Sdf.ValueTypeNames.Asset)
    mayaReferenceAttr.Set(mayaReferencePath)

    mayaNamespaceAttr = prim.CreateAttribute('mayaNamespace',
                                             Sdf.ValueTypeNames.String)
    mayaNamespaceAttr.Set(mayaNamespace)

    mayaAutoEditAttr = prim.CreateAttribute('mayaAutoEdit',
                                            Sdf.ValueTypeNames.Bool)
    mayaAutoEditAttr.Set(mayaAutoEdit)

    return prim
Esempio n. 20
0
def export_mesh_to_usd(full_name,smc, directory):
    task = unreal.AssetExportTask()
    task.object = smc.static_mesh
    task.filename = get_usd_asset_filename(full_name, directory)
    task.selected = False
    task.replace_identical = True
    task.prompt = False
    task.automated = True
    unreal.Exporter.run_asset_export_task(task)

    #let's add the asset information
    unreal.log_warning("adding asset information for :" + full_name)
    stage = Usd.Stage.Open(task.filename)
    usd_prim = stage.GetDefaultPrim()
    model = Usd.ModelAPI(usd_prim)
    model.SetAssetIdentifier(task.filename)
    model.SetAssetName(full_name.rsplit('.')[1])
    stage.Save()

    return task.filename
Esempio n. 21
0
    def test_ResolveAssetPathFn(self):
        src_stage = Usd.Stage.Open('emptyAssetPaths.usda')
        def replaceWithFoo(layer, s):
            return 'foo'

        src_layer_stack = src_stage._GetPcpCache().layerStack
        layer = Usd.FlattenLayerStack(src_layer_stack, 
                resolveAssetPathFn=replaceWithFoo,
                tag='resolveAssetPathFn')
        result_stage = Usd.Stage.Open(layer)

        # verify that we replaced asset paths with "foo"

        prim = result_stage.GetPrimAtPath('/Test')
        assetAttr = prim.GetAttribute('a')
        self.assertEqual(assetAttr.Get(), Sdf.AssetPath('foo'))

        assetArrayAttr = prim.GetAttribute('b')
        self.assertEqual(list(assetArrayAttr.Get()), 
                         [Sdf.AssetPath('foo'), Sdf.AssetPath('foo')])
Esempio n. 22
0
    def setUp(self):
        # DefineStage
        self.stage = Usd.Stage.CreateInMemory()
        self.stage.DefinePrim("/root", "Xform")

        sphere = UsdGeom.Xform.Define(self.stage, "/root/Sphere")
        sphere.AddTranslateOp().Set(value=(8, 0, 0))
        self.sphereRender = self.stage.DefinePrim("/root/Sphere/HIGH", "Sphere")
        self.sphereProxy = self.stage.DefinePrim("/root/Sphere/PROXY", "Sphere")
        self.sphereRender.GetAttribute("purpose").Set("render")
        self.sphereProxy.GetAttribute("purpose").Set("proxy")

        cone = UsdGeom.Xform.Define(self.stage, "/root/Cone")
        cone.AddTranslateOp().Set(value=(4, 0, 0))
        self.coneRender = self.stage.DefinePrim("/root/Cone/HIGH", "Cone")
        self.coneProxy = self.stage.DefinePrim("/root/Cone/PROXY", "Cone")
        self.coneRender.GetAttribute("purpose").Set("render")
        self.coneProxy.GetAttribute("purpose").Set("proxy")

        cylinder = UsdGeom.Xform.Define(self.stage, "/root/Cylinder")
        self.cylinderRender = self.stage.DefinePrim("/root/Cylinder/HIGH", "Cylinder")
        self.cylinderRender.GetAttribute("purpose").Set("render")

        self.usdPrimDisplayManager = UsdPrimsDisplayManager(self.stage)

        # Add payload
        self.assetPrim = self.stage.DefinePrim("/root/Asset", "Xform")
        assetPath = "{}/data/simple_asset.usda".format(os.path.dirname(os.path.realpath(__file__)))
        self.assetPrim.GetPayloads().AddPayload(assetPath)
        self.assetRender = self.stage.GetPrimAtPath("/root/Asset/assetCube/HIGH")
        self.assetProxy = self.stage.GetPrimAtPath("/root/Asset/assetCube/PROXY")

        self.assetPrim2 = self.stage.DefinePrim("/root/Asset2", "Xform")
        assetPath = "{}/data/simple_asset.usda".format(os.path.dirname(os.path.realpath(__file__)))
        self.assetPrim2.GetPayloads().AddPayload(assetPath)
        self.asset2Render = self.stage.GetPrimAtPath("/root/Asset2/assetCube/HIGH")
        self.asset2Proxy = self.stage.GetPrimAtPath("/root/Asset2/assetCube/PROXY")

        sessLayer = self.stage.GetSessionLayer()
        self.stage.SetEditTarget(Usd.EditTarget(sessLayer))
        self.usdPrimDisplayManager.setLayerMuted(False)
Esempio n. 23
0
def export(name):
    global file_path
    global relative_directory
    global root_name
    global USDExportLevel
    global selection_only

    set_file_path()
    filename = file_path + '/'+name
    root_name = '/' + unreal.EditorLevelLibrary.get_editor_world().get_name()
    
    #first we export all the different assets that we will reference after
    if export_assets == True :
        export_all_meshes_as_usd_assets(file_path)

    #onto the usda layer that will reference those assets
    stagecache =  UsdUtils.StageCache.Get()
    stagecachecontext = Usd.StageCacheContext(stagecache)
    stage = Usd.Stage.CreateNew(filename)
    nf = stage.DefinePrim(root_name, 'Xform')
    stage.SetDefaultPrim(nf)
    UsdGeom.SetStageUpAxis(stage,'Z')

    #now we add the actors to the usd stage, referencing the usd asset files we exported above.

    if selection_only == False :
        listActors = unreal.EditorLevelLibrary.get_all_level_actors()
    else :
        listActors = unreal.EditorLevelLibrary.get_selected_level_actors()
    
    for actor in listActors :
        if isinstance(actor,unreal.StaticMeshActor):
            add_actor_to_stage(actor, stage)
        elif isinstance(actor, unreal.CineCameraActor):
            add_camera_to_stage(actor, stage)
        elif USDExportLevel.should_export_actor(actor):
            sm_array = actor.get_components_by_class(unreal.StaticMeshComponent.static_class())
            for smc in sm_array:
                add_static_mesh_component_to_stage(smc,stage)

    stage.GetRootLayer().Save()
Esempio n. 24
0
 def __init__(self, stage=None, columns=None, parent=None):
     # type: (Optional[Usd.Stage], Optional[Union[List[str], Tuple[str]]], Optional[QtCore.QObject]) -> None
     """
     Parameters
     ----------
     stage : Optional[Usd.Stage]
     columns : Optional[List[str]]
     parent : Optional[QtCore.QObject]
     """
     super(HierarchyStandardModel, self).__init__(
         stage,
         Usd.TraverseInstanceProxies(Usd.PrimIsDefined
                                     | ~Usd.PrimIsDefined), parent)
     if not columns:
         # By default show all possible columns.
         self.columns = [
             HierarchyStandardModel.Name, HierarchyStandardModel.Type,
             HierarchyStandardModel.Kind
         ]
     else:
         self.columns = columns
Esempio n. 25
0
def GetPrimLoadability(prim):
    """Return a tuple of (isLoadable, isLoaded) for 'prim', according to
    the following rules:
    A prim is loadable if it is active, and either of the following are true:
       * prim has a payload
       * prim is a model group
    The latter is useful because loading is recursive on a UsdStage, and it
    is convenient to be able to (e.g.) load everything loadable in a set.
    
    A prim 'isLoaded' only if there are no unloaded prims beneath it, i.e.
    it is stating whether the prim is "fully loaded".  This
    is a debatable definition, but seems useful for usdview's purposes."""
    if not (prim.IsActive() and (prim.IsGroup() or prim.HasPayload())):
        return (False, True)
    # XXX Note that we are potentially traversing the entire stage here.
    # If this becomes a performance issue, we can cast this query into C++,
    # cache results, etc.
    for p in Usd.PrimRange(prim, Usd.PrimIsActive):
        if not p.IsLoaded():
            return (True, False)
    return (True, True)
Esempio n. 26
0
    def test_InvalidXformOps(self):
        s = Usd.Stage.CreateInMemory()
        p = s.DefinePrim('/World', 'Xform')
        x = UsdGeom.Xformable(p)

        # Create an attribute that is not in the xformOp namespace.
        attr1 = p.CreateAttribute("myXformOp:transform", Sdf.ValueTypeNames.Matrix4d)
        self._TestInvalidXformOp(attr1)

        # Create an xform op with an invalid optype.
        attr2 = p.CreateAttribute("xformOp:translateXYZ", Sdf.ValueTypeNames.Double3)
        self._TestInvalidXformOp(attr2)

        # Create an xform op with opType=transform and typeName=Matrix4f.
        with self.assertRaises(RuntimeError):
            xformOp = x.AddTransformOp(precision=UsdGeom.XformOp.PrecisionFloat)

        # Test Validity of XformOp with no attr
        xformOp = UsdGeom.XformOp(Usd.Attribute())
        self.assertFalse(xformOp.IsDefined())
        self.assertFalse(bool(xformOp))
 def test_TimeSampled(self):
     extents = {
         '/capsule' :  Vt.Vec3fArray(2, (Gf.Vec3f(-4.0, -4.0, -6.0),
                                         Gf.Vec3f(4.0, 4.0, 6.0))),
         '/cone' :     Vt.Vec3fArray(2, (Gf.Vec3f(-4.0, -4.0, -3.0),
                                         Gf.Vec3f(4.0, 4.0, 3.0))),
         '/cube' :     Vt.Vec3fArray(2, (Gf.Vec3f(-3.0, -3.0, -3.0),
                                         Gf.Vec3f(3.0, 3.0, 3.0))),
         '/cylinder' : Vt.Vec3fArray(2, (Gf.Vec3f(-4.0, -4.0, -3.0),
                                         Gf.Vec3f(4.0, 4.0, 3.0))),
         '/sphere' :   Vt.Vec3fArray(2, (Gf.Vec3f(-4.0, -4.0, -4.0),
                                         Gf.Vec3f(4.0, 4.0, 4.0)))
     }
     testFile = "test.usda"
     s = Usd.Stage.Open(testFile)
     for primpath in self.primpaths:
         p = s.GetPrimAtPath(primpath)
         b = UsdGeom.Boundable(p)
         tc = Usd.TimeCode(2.0)
         e = UsdGeom.Boundable.ComputeExtentFromPlugins(b, tc)
         self.assertEqual(extents[primpath], e)
Esempio n. 28
0
    def buildUI(self):
        usdSch = Usd.SchemaRegistry()

        self.suppressArrayAttribute()

        # We use UFE for the ancestor node types since it caches the
        # results by node type.
        for schemaType in self.item.ancestorNodeTypes():
            schemaType = usdSch.GetTypeFromName(schemaType)
            schemaTypeName = schemaType.typeName
            sectionName = self.sectionNameFromSchema(schemaTypeName)
            if schemaType.pythonClass:
                attrsToAdd = schemaType.pythonClass.GetSchemaAttributeNames(
                    False)

                # We have a special case when building the Xformable section.
                if schemaTypeName == 'UsdGeomXformable':
                    self.createTransformAttributesSection(
                        sectionName, attrsToAdd)
                else:
                    self.createSection(sectionName, attrsToAdd)
Esempio n. 29
0
    def test_Bug145873(self):
        # The payload inclusion predicate wasn't being invoked on ancestors of
        # requested index paths in pcp.
        payload = Usd.Stage.CreateInMemory()
        for n in ('One', 'Two', 'Three'):
            payload.DefinePrim('/CubesModel/Geom/Cube' + n)

        root = Usd.Stage.CreateInMemory()
        cubes = root.DefinePrim('/Cubes')
        cubes.SetPayload(payload.GetRootLayer().identifier, '/CubesModel')

        testStage = Usd.Stage.OpenMasked(
            root.GetRootLayer(),
            Usd.StagePopulationMask(['/Cubes/Geom/CubeTwo']))

        # Only /Cubes/Geom/CubeTwo (and ancestors) should be present.
        assert testStage.GetPrimAtPath('/Cubes')
        assert testStage.GetPrimAtPath('/Cubes/Geom')
        assert not testStage.GetPrimAtPath('/Cubes/Geom/CubeOne')
        assert testStage.GetPrimAtPath('/Cubes/Geom/CubeTwo')
        assert not testStage.GetPrimAtPath('/Cubes/Geom/CubeThree')
Esempio n. 30
0
    def test_FlattenWithOffsets(self):
        """Tests that layer offsets are taken into account when flattening
        attribute time samples."""
        srcAttr = self.srcStage.GetPrimAtPath("/OffsetTimeSamples") \
                            .GetAttribute("a")

        self.assertEqual(self._GetTimeSamples(srcAttr), {10: 100, 20: 1000})

        for dstStage in [self.srcStage, self.stage2]:
            dstAttr = srcAttr.FlattenTo(
                dstStage.OverridePrim("/OffsetTimeSamplesRoot"))

            self.assertEqual(self._GetTimeSamples(dstAttr), {
                10: 100,
                20: 1000
            })
            self.assertEqual(
                self._GetTimeSamplesInLayer(dstStage.GetRootLayer(),
                                            dstAttr.GetPath()), {
                                                10: 100,
                                                20: 1000
                                            })

            dstSubLayer = dstStage.GetLayerStack()[-1]
            with Usd.EditContext(
                    dstStage,
                    dstStage.GetEditTargetForLocalLayer(dstSubLayer)):
                dstAttr = srcAttr.FlattenTo(
                    dstStage.OverridePrim("/OffsetTimeSamplesSublayer"))

                # flattened time samples
                self.assertEqual(self._GetTimeSamples(dstAttr), {
                    10: 100,
                    20: 1000
                })
                # time samples from the offset sublayer
                self.assertEqual(
                    self._GetTimeSamplesInLayer(dstSubLayer,
                                                dstAttr.GetPath()),
                    self.expectedTimeSampleOffsetSublayer[dstStage])
Esempio n. 31
0
def reportModelInfo(stage):
    _resolveAr = Ar.GetResolver().Resolve

    @lru_cache
    def resolve(identifier):
        return _resolveAr(str(Path(identifier)))

    missing_info = set()
    incomplete_info = defaultdict(set)
    unresolved_ids = defaultdict(set)

    with Ar.ResolverContextBinder(stage.GetPathResolverContext()):
        for prim in stage.Traverse(predicate=Usd.PrimIsModel):
            model = Usd.ModelAPI(prim)
            if not (model.IsKind("component") or model.IsKind("assembly")):
                continue  # only check for "important" kinds
            elif (info := model.GetAssetInfo()):
                if (missing := frozenset({"name", "identifier"} - set(info))):
                    incomplete_info[missing].add(prim)
                elif not resolve(info['identifier'].path):
                    unresolved_ids[info['identifier']].add(prim)
                continue