def _AddCueRigAndCacheVariants(stage):
    from pxr import Kind, Sdf, Usd, UsdGeom
    from AL.usd import schemas

    # Make sure the model-parents we need are well-specified
    Usd.ModelAPI(UsdGeom.Xform.Define(stage,
                                      '/World')).SetKind(Kind.Tokens.group)
    animModel = Usd.ModelAPI(UsdGeom.Xform.Define(stage, '/World/anim'))
    animModel.SetKind(Kind.Tokens.group)

    animVariant = animModel.GetPrim().GetVariantSets().AddVariantSet(
        'animVariant')
    animVariant.AddVariant('rig')
    animVariant.SetVariantSelection('rig')
    with animVariant.GetVariantEditContext():
        # Creating maya rig for CueBall
        cueBallRig = schemas.MayaReference.Define(stage, '/World/anim/CueBall')
        cueBallRig.CreateMayaNamespaceAttr().Set('cueball_rig')
        cueBallRig.CreateMayaReferenceAttr().Set(
            os.path.join(ASSET_BASE, 'Ball/Ball_rig.ma'))

    animVariant.AddVariant('cache')
    animVariant.SetVariantSelection('cache')
    with animVariant.GetVariantEditContext():
        # Creating cache layer and bring in as payload
        cueCacheLayerPath = 'shots/s00_01/s00_01_animcue.usd'
        if not os.path.exists(cueCacheLayerPath):
            payload = Usd.Stage.CreateNew(cueCacheLayerPath)
            payload.DefinePrim("/Ball")
            payload.Save()
        cueBallCache = UsdGeom.Xform.Define(stage, '/World/anim/CueBall')
        cueBallCache.GetPrim().SetPayload(cueCacheLayerPath, '/Ball')
Esempio n. 2
0
def main():
    sequenceFilePath = 'shots/s00/s00.usd'
    setsLayoutLayerFilePath = 'shots/s00/s00_sets.usd'

    from pxr import Kind, Usd, UsdGeom, Sdf
    stage = Usd.Stage.Open(sequenceFilePath)

    # we use Sdf, a lower level library, to obtain the 'sets' layer.
    workingLayer = Sdf.Layer.FindOrOpen(setsLayoutLayerFilePath)
    assert stage.HasLocalLayer(workingLayer)

    # this makes the workingLayer the target for authoring operations by the
    # stage.
    stage.SetEditTarget(workingLayer)

    # Make sure the model-parents we need are well-specified
    Usd.ModelAPI(UsdGeom.Xform.Define(stage,
                                      '/World')).SetKind(Kind.Tokens.group)
    Usd.ModelAPI(UsdGeom.Xform.Define(stage, '/World/sets')).SetKind(
        Kind.Tokens.group)

    # in previous examples, we've been using GetReferences().AppendReference(...).  The
    # following uses .SetItems() instead which lets us explicitly set (replace)
    # the references at once instead of adding.
    stage.DefinePrim('/World/sets/Room_set').GetReferences().SetReferences(
        [Sdf.Reference(os.path.join(ASSET_BASE, 'Room_set/Room_set.usd'))])

    stage.GetEditTarget().GetLayer().Save()

    print '==='
    print 'usdview %s' % sequenceFilePath
    print 'usdcat %s' % setsLayoutLayerFilePath
Esempio n. 3
0
    def testExportWithKindAttrAndKindFlag(self):
        """
        Tests exporting a Maya file with both USD_kind custom attributes and
        using the usdExport -kind flag; there should be an error if the USD_kind
        is not derived from the kind specified in the -kind flag.
        """
        cmds.file(os.path.abspath('KindTestUsdKindAttr.ma'),
                  open=True,
                  force=True)
        cmds.loadPlugin('pxrUsd')

        usdFilePath = os.path.abspath('KindTestUsdKindAttr.usda')
        with self.assertRaises(RuntimeError):
            cmds.usdExport(mergeTransformAndShape=True,
                           file=usdFilePath,
                           kind='assembly')

        cmds.usdExport(mergeTransformAndShape=True,
                       file=usdFilePath,
                       kind='model')
        stage = Usd.Stage.Open(usdFilePath)
        self.assertTrue(stage)

        rootPrim = stage.GetPrimAtPath('/KindTest')
        self.assertTrue(Kind.Registry().IsA(
            Usd.ModelAPI(rootPrim).GetKind(), 'component'))
        rootPrim2 = stage.GetPrimAtPath('/KindTest2')
        self.assertTrue(Kind.Registry().IsA(
            Usd.ModelAPI(rootPrim2).GetKind(), 'assembly'))
Esempio n. 4
0
    def test_PrimIsModelOrGroup(self):
        for fmt in allFormats:
            s = Usd.Stage.CreateInMemory('TestPrimIsModelOrGroup.' + fmt)
            group = s.DefinePrim("/Group", "Xform")
            Usd.ModelAPI(group).SetKind('group')
            model = s.DefinePrim("/Group/Model", "Model")
            Usd.ModelAPI(model).SetKind('model')
            mesh = s.DefinePrim("/Group/Model/Sbdv", "Mesh")

            x1 = list(Usd.PrimRange(group, Usd.PrimIsModel))
            self.assertEqual(x1, [group, model])

            x2 = list(Usd.PrimRange(group, Usd.PrimIsGroup))
            self.assertEqual(x2, [group])

            x3 = list(Usd.PrimRange(group, ~Usd.PrimIsModel))
            self.assertEqual(x3, [])

            x4 = list(Usd.PrimRange(mesh, ~Usd.PrimIsModel))
            self.assertEqual(x4, [mesh])

            x5 = list(Usd.PrimRange(group, Usd.PrimIsModel | Usd.PrimIsGroup))
            self.assertEqual(x5, [group, model])

            x6 = list(Usd.PrimRange(group, Usd.PrimIsModel & Usd.PrimIsGroup))
            self.assertEqual(x6, [group])
Esempio n. 5
0
    def testExport(self):
        """
        Tests that the built-in metadata attribute converters can export
        USD_hidden, USD_instanceable, and USD_kind attributes by setting
        the correct metadata in the output USD file.
        """
        newUsdFilePath = os.path.abspath('UsdAttrsNew.usda')
        cmds.usdExport(file=newUsdFilePath, shadingMode='none')
        newUsdStage = Usd.Stage.Open(newUsdFilePath)

        # pCube1 and pCube2 have USD_kind.
        prim1 = newUsdStage.GetPrimAtPath('/World/pCube1')
        self.assertEqual(Usd.ModelAPI(prim1).GetKind(), 'potato')
        prim2 = newUsdStage.GetPrimAtPath('/World/pCube2')
        self.assertEqual(Usd.ModelAPI(prim2).GetKind(), 'bakedpotato')

        # pCube2 and pCube4 have USD_hidden.
        self.assertTrue(newUsdStage.GetPrimAtPath('/World/pCube2').IsHidden())
        self.assertTrue(newUsdStage.GetPrimAtPath('/World/pCube4').IsHidden())

        # pCube3 and pCube4 have USD_instanceable.
        self.assertTrue(
            newUsdStage.GetPrimAtPath('/World/pCube3').IsInstanceable())
        self.assertTrue(
            newUsdStage.GetPrimAtPath('/World/pCube4').IsInstanceable())
Esempio n. 6
0
def createDefalut():
    try:
        chrStage = Usd.Stage.CreateNew(FILEBASE + 'chr.usda')
    except:
        chrStage = Usd.Stage.Open(FILEBASE + 'chr.usda')
    setChrPrim = UsdGeom.Xform.Define(chrStage, '/chr').GetPrim()
    chrStage.SetDefaultPrim(setChrPrim)
    UsdGeom.SetStageUpAxis(chrStage, UsdGeom.Tokens.y)
    Usd.ModelAPI(setChrPrim).SetKind(Kind.Tokens.assembly)
    chrStage.GetRootLayer().Save()

    try:
        prpStage = Usd.Stage.CreateNew(FILEBASE + 'prp.usda')
    except:
        prpStage = Usd.Stage.Open(FILEBASE + 'prp.usda')
    setPrpPrim = UsdGeom.Xform.Define(prpStage, '/prp').GetPrim()
    prpStage.SetDefaultPrim(setPrpPrim)
    UsdGeom.SetStageUpAxis(prpStage, UsdGeom.Tokens.y)
    Usd.ModelAPI(setPrpPrim).SetKind(Kind.Tokens.assembly)
    prpStage.GetRootLayer().Save()

    try:
        scnStage = Usd.Stage.CreateNew(FILEBASE + 'scn.usda')
    except:
        scnStage = Usd.Stage.Open(FILEBASE + 'scn.usda')
    setScnPrim = UsdGeom.Xform.Define(scnStage, '/scn').GetPrim()
    scnStage.SetDefaultPrim(setScnPrim)
    UsdGeom.SetStageUpAxis(scnStage, UsdGeom.Tokens.y)
    Usd.ModelAPI(setScnPrim).SetKind(Kind.Tokens.assembly)
    scnStage.GetRootLayer().Save()
Esempio n. 7
0
    def _TestPrototypes(self, instancerName):
        """
        Tests that all of the instancer prototypes made it to USD.
        """
        self.assertTrue(self.stage)
        instancer = OMFX.MFnInstancer(self._GetDagPath(instancerName))

        # Move to the last frame so that we can ensure all of the prototypes
        # are in use.
        cmds.currentTime(self.END_TIMECODE, edit=True)
        paths = OM.MDagPathArray()
        matrices = OM.MMatrixArray()
        particlePathStartIndices = OM.MIntArray()
        pathIndices = OM.MIntArray()
        instancer.allInstances(paths, matrices, particlePathStartIndices,
                               pathIndices)

        # Check that the Maya instanced objects are what we think they are.
        pathStrings = [paths[i].fullPathName() for i in range(paths.length())]
        self.assertEqual(
            pathStrings,
            [
                # 0 (logical 0) - Cube
                "|dummyGroup|pCube1|pCubeShape1",
                "|dummyGroup|pCube1|pSphere1|pSphereShape1",
                # 1 (logical 2) - Sphere
                "|InstancerTest|%s|prototypeUnderInstancer|prototypeUnderInstancerShape"
                % instancerName,
                # 2 (logical 3) - Reference
                "|referencePrototype|NS_referencePrototype:Geom|NS_referencePrototype:Cone|NS_referencePrototype:ConeShape"
            ])

        # Check that the USD prims have correct type name, references, kinds,
        # kinds, instancerTranslate xformOps.
        instancerPrim = self.stage.GetPrimAtPath("/InstancerTest/%s" %
                                                 instancerName)
        self.assertEqual(
            Usd.ModelAPI(instancerPrim).GetKind(), Kind.Tokens.subcomponent)

        prototypesPrim = instancerPrim.GetChild("Prototypes")
        self.assertEqual(len(prototypesPrim.GetChildren()), 3)
        self.assertEqual(
            Usd.ModelAPI(prototypesPrim).GetKind(), Kind.Tokens.subcomponent)

        # Note that pCube1_0 is a special case where instancerTranslate
        # isn't the opposite of translate, so both have to be left in.
        prototype0 = prototypesPrim.GetChild("pCube1_0")
        self._AssertPrototype(prototype0, "Xform", 2, True)

        prototype1 = prototypesPrim.GetChild("prototypeUnderInstancer_1")
        self._AssertPrototype(prototype1, "Mesh", 0, False)

        prototype2 = prototypesPrim.GetChild("referencePrototype_2")
        self._AssertPrototype(prototype2, "Xform", 1, False)
        self.assertEqual(
            Usd.ModelAPI(prototype2).GetAssetName(), "ConeAssetName")
Esempio n. 8
0
    def test_ModelAPI(self):
        for fmt in allFormats:
            s = Usd.Stage.CreateInMemory('TestModelAPI.' + fmt)
            p = s.DefinePrim('/World', 'Xform')
            model = Usd.ModelAPI(p)
            self.assertEqual(model.GetKind(), '')
            self.assertFalse(model.IsModel())
            self.assertFalse(model.IsGroup())

            model.SetKind(Kind.Tokens.group)

            # Testing that initializing a schema from another schema works
            newSchema = Usd.ModelAPI(model)
            self.assertEqual(newSchema.GetKind(), model.GetKind())
Esempio n. 9
0
def addReference(stage, path, fileName, targetPrim):
    '''
    Add a reference to the given USD stage at the given path.
    
    If defaultPrim is not None, the the referencee contains a default prim and 
    we can contruct the reference to use it.

    Otherwise, create the reference to point to the first found rootPrim. 
    (We are assume these files will only have one root prim)
    '''

    prim = stage.GetPrimAtPath(path)
    if not prim:
        # Create groups (xforms) for all the intermediate scopes in the namespace
        for ancestor in Sdf.Path(path).GetParentPath().GetPrefixes():
            p = UsdGeom.Xform.Define(stage, ancestor)
            Usd.ModelAPI(p).SetKind(Kind.Tokens.group)

        # Create an over to hold the actual reference. This is so that
        # the composited prim is named what we see in the referencing file.
        prim = stage.OverridePrim(path)
    else:
        prim = stage.GetPrimAtPath(path)

    refList = prim.GetReferences()
    if targetPrim:
        refList.AddReference(Sdf.Reference(fileName, targetPrim))
    else:
        refList.AddReference(Sdf.Reference(fileName))
Esempio n. 10
0
 def exportDynamicAssmblyRefUSD(self, location, destination, rangeTimeCode, motionSample):
     scenegraph_path = self.fetchNameSceneGraphPrim(dagnode_path)
     scenegraph_tree = self.fetchListUSDPrim(dagnode_path)
     scenegraph_data = self.fetchDataDynamicMayaXform(dagnode_path,rangeTimeCode,motionSample)
     # create a UsdStage
     if os.path.isfile(destination):
         stage = Usd.Stage.Open(destination)
     else:
         stage = Usd.Stage.CreateNew(destination)
     for prim_node in scenegraph_tree:
         gprim = Usd.ModelAPI(UsdGeom.Xform.Define(stage, prim_node))
     prim = stage.GetPrimAtPath( scenegraph_path )
     root_prim = stage.GetPrimAtPath( self.fetchNameUsdRoot(scenegraph_path))
     # set USD default setting
     stage.SetStartTimeCode(rangeTimeCode[0])
     stage.SetEndTimeCode(rangeTimeCode[1])
     stage.SetDefaultPrim(root_prim)
     UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
     # set visibility rotateXYZ scale translate sampleTime data into specific prim
     for frameData in sorted(scenegraph_data.keys()):
         if scenegraph_data[frameData]["visibility"]:
             UsdGeom.Imageable(prim).MakeVisible(frameData)
         else:
             UsdGeom.Imageable(prim).MakeInvisible(frameData)
         rotateXYZ = scenegraph_data[frameData]["rotateXYZ"]
         UsdGeom.XformCommonAPI(prim).SetRotate(tuple(rotateXYZ),UsdGeom.XformCommonAPI.RotationOrderXYZ,frameData)
         scale = scenegraph_data[frameData]["scale"]
         UsdGeom.XformCommonAPI(prim).SetScale(tuple(scale),frameData)
         translate = scenegraph_data[frameData]["translate"]
         UsdGeom.XformCommonAPI(prim).SetTranslate(tuple(translate), frameData)
     # save UsdStage
     stage.GetRootLayer().Save()
Esempio n. 11
0
def _CreateAsset(assetName, assetDir, assetKind, addShadingVariantLayer):
    assetFilePath = os.path.join(assetDir, '%s.usd' % assetName)

    print "Creating asset at %s" % assetFilePath
    # Make the layer ascii - good for readability, plus the file is small
    rootLayer = Sdf.Layer.CreateNew(assetFilePath, args={'format': 'usda'})
    assetStage = Usd.Stage.Open(rootLayer)

    # Define a prim for the asset and make it the default for the stage.
    assetPrim = UsdGeom.Xform.Define(assetStage, '/%s' % assetName).GetPrim()
    assetStage.SetDefaultPrim(assetPrim)
    # Lets viewing applications know how to orient a free camera properly
    UsdGeom.SetStageUpAxis(assetStage, UsdGeom.Tokens.y)

    # Usually we will "loft up" the kind authored into the exported geometry
    # layer rather than re-stamping here; we'll leave that for a later
    # tutorial, and just be explicit here.
    model = Usd.ModelAPI(assetPrim)
    if assetKind:
        model.SetKind(assetKind)

    model.SetAssetName(assetName)
    model.SetAssetIdentifier('%s/%s.usd' % (assetName, assetName))

    refs = []
    if addShadingVariantLayer:
        # if we're going to add it, then shading is stronger than geom and needs
        # to be added first
        refs.append('./%s.shadingVariants.usda' % assetName)

    refs.append('./%s.maya.usd' % assetName)

    _CreateAndReferenceLayers(assetPrim, assetDir, refs)

    assetStage.GetRootLayer().Save()
Esempio n. 12
0
    def testExportWithKindFlag(self):
        """
        Tests exporting a Maya file with no USD_kind custom attributes
        and using the usdExport -kind flag.
        """
        cmds.file(os.path.abspath('KindTest.ma'), open=True, force=True)
        cmds.loadPlugin('pxrUsd')

        usdFilePath = os.path.abspath('KindTest.usda')

        # Check the error mark; this ensures that we actually got a Tf error
        # (that was eventually converted into a Maya error, which Maya raises
        # in Python as a RuntimeError).
        mark = Tf.Error.Mark()
        mark.SetMark()
        with self.assertRaises(RuntimeError):
            cmds.usdExport(mergeTransformAndShape=True,
                           file=usdFilePath,
                           kind='assembly')
        errors = mark.GetErrors()
        self.assertEqual(len(errors), 1)
        self.assertIn(
            "</KindTest> has kind 'assembly', which is derived from 'assembly'",
            str(errors[0]))

        cmds.usdExport(mergeTransformAndShape=True,
                       file=usdFilePath,
                       kind='fakeKind')
        stage = Usd.Stage.Open(usdFilePath)
        self.assertTrue(stage)

        rootPrim = stage.GetPrimAtPath('/KindTest')
        self.assertTrue(Kind.Registry().IsA(
            Usd.ModelAPI(rootPrim).GetKind(), 'fakeKind'))
Esempio n. 13
0
    def testExportWithAssemblyAndMesh(self):
        """
        Tests exporting a Maya file with a root prim containing an assembly
        and a mesh.
        """
        cmds.file(os.path.abspath('KindTestAssemblyAndMesh.ma'),
                  open=True,
                  force=True)
        cmds.loadPlugin('pxrUsd')

        # Should fail due to the mesh.
        usdFilePath = os.path.abspath('KindTestAssemblyAndMesh.usda')
        with self.assertRaises(RuntimeError):
            cmds.usdExport(mergeTransformAndShape=True,
                           file=usdFilePath,
                           kind='assembly')

        # Should be 'component' because of the mesh
        usdFilePath = os.path.abspath('KindTestAssemblyAndMesh.usda')
        cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath)
        stage = Usd.Stage.Open(usdFilePath)
        self.assertTrue(stage)

        rootPrim = stage.GetPrimAtPath('/KindTest')
        self.assertTrue(Kind.Registry().IsA(
            Usd.ModelAPI(rootPrim).GetKind(), 'component'))
Esempio n. 14
0
    def testExportWithAssemblies(self):
        """
        Tests exporting a Maya file with a root prim containing an assembly.
        """
        cmds.file(os.path.abspath('KindTestAssembly.ma'),
                  open=True,
                  force=True)
        cmds.loadPlugin('pxrUsd')

        usdFilePath = os.path.abspath('KindTestAssembly.usda')
        cmds.usdExport(mergeTransformAndShape=True,
                       file=usdFilePath,
                       kind='assembly')
        stage = Usd.Stage.Open(usdFilePath)
        self.assertTrue(stage)

        # Default kind without setting kind=assembly should still be assembly.
        usdFilePath = os.path.abspath('KindTestAssembly2.usda')
        cmds.usdExport(mergeTransformAndShape=True, file=usdFilePath)
        stage = Usd.Stage.Open(usdFilePath)
        self.assertTrue(stage)

        rootPrim = stage.GetPrimAtPath('/KindTest')
        self.assertTrue(Kind.Registry().IsA(
            Usd.ModelAPI(rootPrim).GetKind(), 'assembly'))
Esempio n. 15
0
def main():
    """Run the main execution of the current script."""
    stage = Usd.Stage.CreateInMemory()
    UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)

    root = UsdGeom.Xform.Define(stage, "/TexModel")
    Usd.ModelAPI(root).SetKind(Kind.Tokens.component)

    billboard = attach_billboard(stage, root)
    material = UsdShade.Material.Define(
        stage,
        str(billboard.GetPath()) + "/" + "boardMat")
    shader = attach_surface_shader(stage, material,
                                   str(material.GetPath()) + "/" + "PBRShader")
    reader = attach_texture(stage, shader, str(material.GetPath()))

    st_input = material.CreateInput("frame:stPrimvarName",
                                    Sdf.ValueTypeNames.Token)
    st_input.Set("st")

    reader.CreateInput("varname",
                       Sdf.ValueTypeNames.Token).ConnectToSource(st_input)

    UsdShade.MaterialBindingAPI(billboard).Bind(material)

    print(stage.GetRootLayer().ExportToString())
Esempio n. 16
0
def _AddModel(stage, path, refPath):
    '''
    Adds a reference to refPath at the given path in the stage.  This will make
    sure the model hierarchy is maintained by ensuring that all ancestors of
    the path have "kind" set to "group".

    returns the referenced model.
    '''

    from pxr import Kind, Sdf, Usd, UsdGeom

    # convert path to an Sdf.Path which has several methods that are useful
    # when working with paths.  We use GetPrefixes() here which returns a list
    # of all the prim prefixes for a given path.
    path = Sdf.Path(path)
    for prefixPath in path.GetPrefixes()[1:-1]:
        parentPrim = stage.GetPrimAtPath(prefixPath)
        if not parentPrim:
            parentPrim = UsdGeom.Xform.Define(stage, prefixPath).GetPrim()
            Usd.ModelAPI(parentPrim).SetKind(Kind.Tokens.group)

    # typeless def here because we'll be getting the type from the prim that
    # we're referencing.
    m = stage.DefinePrim(path)
    m.GetReferences().AddReference(os.path.join(ASSET_BASE, refPath))
    return m
Esempio n. 17
0
    def refresh(self):
        # PrimPath
        cmds.textFieldGrp(self.primPath,
                          edit=True,
                          text=str(self.prim.GetPath()))

        # Kind
        model = Usd.ModelAPI(self.prim)
        primKind = model.GetKind()
        if not primKind:
            # Special case to handle the empty string (for meta data value empty).
            cmds.optionMenuGrp(self.kind, edit=True, select=1)
        else:
            cmds.optionMenuGrp(self.kind, edit=True, value=primKind)

        # Active
        cmds.checkBoxGrp(self.active, edit=True, value1=self.prim.IsActive())

        # Instanceable
        cmds.checkBoxGrp(self.instan,
                         edit=True,
                         value1=self.prim.IsInstanceable())

        # All other metadata types
        for k in self.extraMetadata:
            v = self.prim.GetMetadata(
                k) if k != 'customData' else self.prim.GetCustomData()
            cmds.textFieldGrp(self.extraMetadata[k], edit=True, text=str(v))
Esempio n. 18
0
def main():
    from pxr import Kind, Usd, UsdGeom

    setFilePath = os.path.join(ASSET_BASE, 'Room_set/Room_set.usd')

    # Create the model stage, the model prim, and also make the modelPrim the
    # default prim so that the layer can be referenced without specifying a
    # root path.
    stage = Usd.Stage.CreateNew(setFilePath)
    setModelPrim = UsdGeom.Xform.Define(stage, '/Room_set').GetPrim()
    stage.SetDefaultPrim(setModelPrim)

    # Lets viewing applications know how to orient a free camera properly
    UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)

    # Models can have a "kind" which can be used to categorize models into
    # different types.  This is useful for other applications to reason about
    # the model hierarchy.
    Usd.ModelAPI(setModelPrim).SetKind(Kind.Tokens.assembly)

    # add child models to our set.
    _AddModel(stage, '/Room_set/Furniture/Table', 'Table/Table.usd')

    ballNumber = 0

    import math
    for row in range(5):

        tableX = 10 + row * 2 * BALL_RADIUS * math.cos(math.pi / 6)
        tableRowZ = -row * BALL_RADIUS
        numBallsInRow = row + 1

        for i in range(numBallsInRow):
            ballNumber += 1

            b = _AddModel(stage, '/Room_set/Props/Ball_%d' % ballNumber,
                          'Ball/Ball.usd')

            # tableX and tableZ will arrange the balls into a triangle.
            tableZ = tableRowZ + i * 2 * BALL_RADIUS
            ballXlate = (tableX, TABLE_HEIGHT + BALL_RADIUS, tableZ)

            # Apply the UsdGeom.Xformable schema to the model, and then set the
            # transformation.
            # We are only going to translate the balls, but we still use
            # the helper XformCommonAPI schema to  instantiate a translate op.
            # XformCommonAPI helps ensure transform ops are interchangeable
            # between applications, when you can make do with SRT + pivot
            UsdGeom.XformCommonAPI(b).SetTranslate(ballXlate)

            # we conveniently named the shadingVariant the same as the name of
            # the ball.
            shadingVariantName = b.GetName()

            # get the variantSet "shadingVariant" and then set it accordingly.
            vs = b.GetVariantSets().GetVariantSet('shadingVariant')
            vs.SetVariantSelection(shadingVariantName)

    stage.GetRootLayer().Save()
Esempio n. 19
0
def createPrims(stage, variants):
    '''Create a testing asset prim and populate its variants.'''
    for path, pathVariants in variants.iteritems():
        prim = stage.DefinePrim(path)
        model = Usd.ModelAPI(prim)
        model.SetAssetName('test_asset')  # needs a name or it will be skipped
        createVariants(prim, pathVariants)
    stage.GetRootLayer().Save()
Esempio n. 20
0
def _SetupBilliards(stage):
    from pxr import Kind, Sdf, Usd, UsdGeom

    # Make sure the model-parents we need are well-specified
    Usd.ModelAPI(UsdGeom.Xform.Define(stage,
                                      '/World')).SetKind(Kind.Tokens.group)
    Usd.ModelAPI(UsdGeom.Xform.Define(stage, '/World/anim')).SetKind(
        Kind.Tokens.group)
    # in previous examples, we've been using GetReferences().Add(...).  The
    # following uses .SetItems() instead which lets us explicitly set (replace)
    # the references at once instead of adding.
    cueBall = stage.DefinePrim('/World/anim/CueBall')
    cueBall.GetReferences().SetItems(
        [Sdf.Reference(os.path.join(ASSET_BASE, 'Ball/Ball.usd'))])

    # deactivate everything that isn't 8, 9, 1, 4.  We accumulate the prims we
    # want to deactivate so that we don't delete while iterating.
    roomProps = stage.GetPrimAtPath('/World/sets/Room_set/Props')
    keepers = set(['Ball_%d' % i for i in [1, 9, 8, 4]])
    toDeactivate = []
    for child in roomProps.GetChildren():
        if child.GetName() not in keepers:
            toDeactivate.append(child)
    for prim in toDeactivate:
        prim.SetActive(False)

    # the offset values are relative to the radius of the ball
    def _MoveBall(ballPrim, offset):
        translation = (offset[0] * BALL_RADIUS, TABLE_HEIGHT + BALL_RADIUS,
                       offset[1] * BALL_RADIUS)

        # Apply the UsdGeom.Xformable schema to the model, and then set the
        # transformation.  Note we can use ordinary python tuples
        from pxr import UsdGeom
        UsdGeom.XformCommonAPI(ballPrim).SetTranslate(translation)

    # all these values are just eye-balled and are relative to Ball_1.
    _MoveBall(cueBall, (1.831, 4.331))
    _MoveBall(stage.GetPrimAtPath('/World/sets/Room_set/Props/Ball_2'),
              (0.000, 0.000))
    _MoveBall(stage.GetPrimAtPath('/World/sets/Room_set/Props/Ball_10'),
              (2.221, 1.119))
    _MoveBall(stage.GetPrimAtPath('/World/sets/Room_set/Props/Ball_1'),
              (3.776, 0.089))
    _MoveBall(stage.GetPrimAtPath('/World/sets/Room_set/Props/Ball_4'),
              (5.453, -0.543))
Esempio n. 21
0
 def make_defalt_prim(self, location, stage, kind):
     default_path = Sdf.Path('/{}'.format(location))
     print 'default_path', default_path
     default_prim = stage.DefinePrim(default_path)
     stage.SetDefaultPrim(default_prim)
     UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
     UsdGeom.SetStageMetersPerUnit(stage, UsdGeom.LinearUnits.centimeters)
     Usd.ModelAPI(default_prim).SetKind(kind)
Esempio n. 22
0
def make_default_prim(stage):
    default_path = Sdf.Path(DEFAULT_PATH)
    default_prim = stage.DefinePrim(default_path)
    stage.SetDefaultPrim(default_prim)
    UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
    UsdGeom.SetStageMetersPerUnit(stage, UsdGeom.LinearUnits.centimeters)
    Usd.ModelAPI(default_prim).SetKind(Kind.Tokens.component)
    return default_prim
Esempio n. 23
0
 def __defineUSDXformPrimByLoops__(self, dagnode_path):
     '''
     Create the UsdPrim that type as Xform,
     and have a loop to create every prim one by one.
     '''
     scenegraph_path = self.fetchNameSceneGraphPrim(dagnode_path)
     scenegraph_tree = self.fetchListUSDPrim(dagnode_path)
     for prim_node in scenegraph_tree:
         Usd.ModelAPI(UsdGeom.Xform.Define(self.__stage__, prim_node))
def generate_ticker_cube(index, stage, stock_name):
    stage.SetStartTimeCode(0)
    stage.SetEndTimeCode(192)
    TextureRoot = UsdGeom.Xform.Define(stage, '/TexModel' + stock_name)
    Usd.ModelAPI(TextureRoot).SetKind(Kind.Tokens.component)

    billboard = UsdGeom.Mesh.Define(
        stage, "/TexModel" + stock_name + "/card" + stock_name)
    billboard.CreatePointsAttr([(-5, -5, 5), (5, -5, 5), (5, 5, 5),
                                (-5, 5, 5)])
    billboard.CreateFaceVertexCountsAttr([4])
    billboard.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
    billboard.CreateExtentAttr([(-5, -5, 5), (5, 5, 5)])
    texCoords = billboard.CreatePrimvar("st",
                                        Sdf.ValueTypeNames.TexCoord2fArray,
                                        UsdGeom.Tokens.varying)
    texCoords.Set([(0, 0), (1, 0), (1, 1), (0, 1)])

    material = UsdShade.Material.Define(
        stage, '/TexModel' + stock_name + '/boardMat' + stock_name)
    stInput = material.CreateInput('frame:stPrimvarName',
                                   Sdf.ValueTypeNames.Token)
    stInput.Set('st')
    pbrShader = UsdShade.Shader.Define(
        stage, '/TexModel' + stock_name + '/boardMat/PBRShader' + stock_name)
    pbrShader.CreateIdAttr("UsdPreviewSurface")
    pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
    pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)

    material.CreateSurfaceOutput().ConnectToSource(pbrShader, "surface")
    stReader = UsdShade.Shader.Define(
        stage, '/TexModel' + stock_name + '/boardMat/stReader' + stock_name)
    stReader.CreateIdAttr('UsdPrimvarReader_float2')

    stReader.CreateInput('varname',
                         Sdf.ValueTypeNames.Token).ConnectToSource(stInput)
    print(stock_name)
    diffuseTextureSampler = UsdShade.Shader.Define(
        stage,
        '/TexModel' + stock_name + '/boardMat/diffuseTexture' + stock_name)
    diffuseTextureSampler.CreateIdAttr('UsdUVTexture')
    diffuseTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(
        '/Users/Abhinav/Documents/USDZ/CNBC/textures/' + stock_name + '.png')
    diffuseTextureSampler.CreateInput(
        "st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader, 'result')
    diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
    pbrShader.CreateInput("diffuseColor",
                          Sdf.ValueTypeNames.Color3f).ConnectToSource(
                              diffuseTextureSampler, 'rgb')
    UsdShade.MaterialBindingAPI(billboard.GetPrim()).Bind(material)
    UsdGeom.XformCommonAPI(billboard).SetTranslate(
        (-20, 20 * index, -index * 20))
    spin = billboard.AddRotateYOp(opSuffix='spin')
    spin.Set(time=0, value=0)
    spin.Set(time=192, value=1440)
    return stage
Esempio n. 25
0
    def testExport(self):
        """
        Tests that the adaptor mechanism can export
        USD_hidden, USD_instanceable, and USD_kind attributes by setting
        the correct metadata in the output USD file.
        """
        cmds.file(new=True, force=True)
        cmds.usdImport(file=self.inputUsdFile,
                       shadingMode=[
                           ["none", "default"],
                       ])

        newUsdFilePath = os.path.abspath('UsdAttrsNew.usda')
        cmds.usdExport(file=newUsdFilePath, shadingMode='none')
        newUsdStage = Usd.Stage.Open(newUsdFilePath)

        # pCube1 and pCube2 have USD_kind.
        prim1 = newUsdStage.GetPrimAtPath('/World/pCube1')
        self.assertEqual(Usd.ModelAPI(prim1).GetKind(), 'potato')
        prim2 = newUsdStage.GetPrimAtPath('/World/pCube2')
        self.assertEqual(Usd.ModelAPI(prim2).GetKind(), 'bakedpotato')

        # pCube2, pCube4, and pCube5 have USD_hidden. pCube1 and pCube3 do not.
        self.assertTrue(
            newUsdStage.GetPrimAtPath('/World/pCube2').HasAuthoredHidden())
        self.assertTrue(
            newUsdStage.GetPrimAtPath('/World/pCube4').HasAuthoredHidden())
        self.assertTrue(
            newUsdStage.GetPrimAtPath('/World/pCube5').HasAuthoredHidden())
        self.assertFalse(
            newUsdStage.GetPrimAtPath('/World/pCube1').HasAuthoredHidden())
        self.assertFalse(
            newUsdStage.GetPrimAtPath('/World/pCube3').HasAuthoredHidden())

        self.assertTrue(newUsdStage.GetPrimAtPath('/World/pCube2').IsHidden())
        self.assertTrue(newUsdStage.GetPrimAtPath('/World/pCube4').IsHidden())
        self.assertFalse(newUsdStage.GetPrimAtPath('/World/pCube5').IsHidden())

        # pCube3 and pCube4 have USD_instanceable.
        self.assertTrue(
            newUsdStage.GetPrimAtPath('/World/pCube3').IsInstanceable())
        self.assertTrue(
            newUsdStage.GetPrimAtPath('/World/pCube4').IsInstanceable())
def _set_assembly(prim_path):

    model = Usd.ModelAPI(prim_path)
    model.SetKind(Kind.Tokens.assembly)
    parent = prim_path.GetParent()

    if parent:
        _set_assembly(parent)

    return
Esempio n. 27
0
def main():
    """Run the main execution of the current script."""
    stage = Usd.Stage.CreateInMemory()
    stage.GetRootLayer().documentation = (
        "This is an example of setting a Model Prim kind")

    sphere1 = UsdGeom.Sphere.Define(stage, "/SomeSphere")
    Usd.ModelAPI(sphere1).SetKind(Kind.Tokens.component)
    sphere2 = UsdGeom.Sphere.Define(stage, "/SomeSphere/SphereChild")
    Usd.ModelAPI(sphere2).SetKind(Kind.Tokens.subcomponent)
    sphere3 = UsdGeom.Sphere.Define(stage, "/SomeSphere/Foo")
    Usd.ModelAPI(sphere3).SetKind("does_not_exist")
    sphere3.GetPrim().SetMetadata(
        "comment",
        "XXX: This kind is made up. But it could be real if we added to the KindRegistry\n"
        "https://graphics.pixar.com/usd/docs/api/class_kind_registry.html",
    )

    print(stage.GetRootLayer().ExportToString())
def generate_price_cube(price, stock_name, stage, position, index):
    path = create_image(price, stock_name, position)
    TextureRoot = UsdGeom.Xform.Define(
        stage, '/priceModel' + stock_name + str(position))
    Usd.ModelAPI(TextureRoot).SetKind(Kind.Tokens.component)

    billboard = UsdGeom.Mesh.Define(
        stage, "/priceModel" + stock_name + str(position) + "/card" +
        stock_name + str(position))
    billboard.CreatePointsAttr([(-5, -5, 5), (5, -5, 5), (5, 5, 5),
                                (-5, 5, 5)])
    billboard.CreateFaceVertexCountsAttr([4])
    billboard.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
    billboard.CreateExtentAttr([(-5, -5, 5), (5, 5, 5)])
    texCoords = billboard.CreatePrimvar("st",
                                        Sdf.ValueTypeNames.TexCoord2fArray,
                                        UsdGeom.Tokens.varying)
    texCoords.Set([(0, 0), (1, 0), (1, 1), (0, 1)])

    material = UsdShade.Material.Define(
        stage, '/priceModel' + stock_name + str(position) + '/boardMat' +
        stock_name + str(position))
    stInput = material.CreateInput('frame:stPrimvarName',
                                   Sdf.ValueTypeNames.Token)
    stInput.Set('st')
    pbrShader = UsdShade.Shader.Define(
        stage, '/priceModel' + stock_name + str(position) +
        '/boardMat/PBRShader' + stock_name + str(position))
    pbrShader.CreateIdAttr("UsdPreviewSurface")
    pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
    pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)

    material.CreateSurfaceOutput().ConnectToSource(pbrShader, "surface")
    stReader = UsdShade.Shader.Define(
        stage, '/priceModel' + stock_name + str(position) +
        '/boardMat/stReader' + stock_name + str(position))
    stReader.CreateIdAttr('UsdPrimvarReader_float2')

    stReader.CreateInput('varname',
                         Sdf.ValueTypeNames.Token).ConnectToSource(stInput)
    diffuseTextureSampler = UsdShade.Shader.Define(
        stage, '/priceModel' + stock_name + str(position) +
        '/boardMat/diffuseTexture' + stock_name + str(position))
    diffuseTextureSampler.CreateIdAttr('UsdUVTexture')
    diffuseTextureSampler.CreateInput('file',
                                      Sdf.ValueTypeNames.Asset).Set(path)
    diffuseTextureSampler.CreateInput(
        "st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader, 'result')
    diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
    pbrShader.CreateInput("diffuseColor",
                          Sdf.ValueTypeNames.Color3f).ConnectToSource(
                              diffuseTextureSampler, 'rgb')
    UsdShade.MaterialBindingAPI(billboard.GetPrim()).Bind(material)
    UsdGeom.XformCommonAPI(billboard).SetTranslate(
        (10 * position, (20 * index) + (price + 5), -index * 20))
Esempio n. 29
0
    def test_ModelHierarchy(self):
        for fmt in allFormats:
            s = Usd.Stage.CreateInMemory('TestModelHierarchy.' + fmt)
            x = s.DefinePrim('/X', 'Scope')
            y = s.DefinePrim('/X/Y', 'Scope')
            z = s.DefinePrim('/X/Y/Z', 'Scope')

            self.assertFalse(x.IsModel())
            self.assertFalse(y.IsModel())
            self.assertFalse(z.IsModel())

            xm = Usd.ModelAPI(x)
            ym = Usd.ModelAPI(y)
            zm = Usd.ModelAPI(z)

            # X is not a model. Hence, Y can't be a model, even if it has kind set
            # to 'component'.
            ym.SetKind(Kind.Tokens.component)
            self.assertFalse(ym.IsModel())

            # Setting X's kind to component, causes it to be a model, but Y still
            # remains a non-model as component below another component violates the
            # model hierarchy.
            xm.SetKind(Kind.Tokens.component)
            self.assertTrue(xm.IsModel())
            self.assertFalse(ym.IsModel())

            # Setting X's kind to assembly fixes the model hierarchy and causes
            # X to be a model group and Y to be a model.
            xm.SetKind(Kind.Tokens.assembly)
            self.assertTrue(xm.IsModel())
            self.assertTrue(xm.IsGroup())
            self.assertTrue(ym.IsModel())
            self.assertFalse(ym.IsGroup())

            # A component below a component violates model hierarchy.
            zm.SetKind(Kind.Tokens.component)
            self.assertFalse(zm.IsModel())

            # A subcomponent also isn't considered to be a model.
            zm.SetKind(Kind.Tokens.subcomponent)
            self.assertFalse(zm.IsModel())
def main():
    # Make the stage
    stage = Usd.Stage.CreateNew(STAGENAME)
    UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)

    modelRoot = UsdGeom.Xform.Define(stage, '/TexModel')
    Usd.ModelAPI(modelRoot).SetKind(Kind.Tokens.component)

    # A simple card with same proportions as the texture we will map
    billboard = UsdGeom.Mesh.Define(stage, '/TexModel/card')
    billboard.CreatePointsAttr([(-430, -145, 0), (430, -145, 0), (430, 145, 0),
                                (-430, 145, 0)])
    billboard.CreateFaceVertexCountsAttr([4])
    billboard.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
    billboard.CreateExtentAttr([(-430, -145, 0), (430, 145, 0)])
    texCoords = billboard.CreatePrimvar('st',
                                        Sdf.ValueTypeNames.TexCoord2fArray,
                                        UsdGeom.Tokens.varying)
    texCoords.Set([(0, 0), (1, 0), (1, 1), (0, 1)])

    # Create material
    material = UsdShade.Material.Define(stage, '/TexModel/material')
    stInput = material.CreateInput('frame:stPrimvarName',
                                   Sdf.ValueTypeNames.Token)
    stInput.Set('st')

    pbrShader = UsdShade.Shader.Define(stage, '/TexModel/material/PBRShader')
    pbrShader.CreateIdAttr('UsdPreviewSurface')
    pbrShader.CreateInput('roughness', Sdf.ValueTypeNames.Float).Set(0.4)
    pbrShader.CreateInput('metallic', Sdf.ValueTypeNames.Float).Set(0.0)

    material.CreateSurfaceOutput().ConnectToSource(pbrShader, 'surface')

    stReader = UsdShade.Shader.Define(stage, '/TexModel/material/stReader')
    stReader.CreateIdAttr('UsdPrimvarReader_float2')
    stReader.CreateInput('varname',
                         Sdf.ValueTypeNames.Token).ConnectToSource(stInput)

    diffuseTextureSampler = UsdShade.Shader.Define(
        stage, '/TexModel/material/diffuseTexture')
    diffuseTextureSampler.CreateIdAttr('UsdUVTexture')
    diffuseTextureSampler.CreateInput(
        'file', Sdf.ValueTypeNames.Asset).Set(TEXTURE_FILE)
    diffuseTextureSampler.CreateInput(
        'st', Sdf.ValueTypeNames.Float2).ConnectToSource(stReader, 'result')
    diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
    pbrShader.CreateInput('diffuseColor',
                          Sdf.ValueTypeNames.Color3f).ConnectToSource(
                              diffuseTextureSampler, 'rgb')

    UsdShade.MaterialBindingAPI(billboard).Bind(material)

    # Save stage
    stage.Save()