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()
Exemplo n.º 2
0
def TestUnloadedExtentsHints():
    stage = Usd.Stage.Open(
        "unloadedCubeModel.usda",
        load = Usd.Stage.LoadNone)
    bboxCacheNo = UsdGeom.BBoxCache(Usd.TimeCode(0.0), 
        includedPurposes=[UsdGeom.Tokens.default_], useExtentsHint=False)
    bboxCacheYes = UsdGeom.BBoxCache(Usd.TimeCode(0.0), 
        includedPurposes=[UsdGeom.Tokens.default_], useExtentsHint=True)

    print "-"*80
    print "Testing aggregate bounds with unloaded child prims"
    print "-"*80
    print 

    prim = stage.GetPseudoRoot()
    bboxNo  = bboxCacheNo.ComputeWorldBound(prim)
    bboxYes = bboxCacheYes.ComputeWorldBound(prim)
    
    assert bboxNo.GetRange().IsEmpty()
    assert not bboxYes.GetRange().IsEmpty()
Exemplo n.º 3
0
    def sync_from_prim(self, root_obj, prim):
        prim_obj = self.id_data

        self.sdf_path = str(prim.GetPath())
        self.cached_stage.assign(prim.GetStage())

        prim_obj.name = prim.GetName()
        prim_obj.parent = root_obj
        prim_obj.matrix_local = usd_utils.get_xform_transform(
            UsdGeom.Xform(prim))
        prim_obj.hide_viewport = prim.GetTypeName() not in GEOM_TYPES
Exemplo n.º 4
0
    def draw_item(self, context, layout, data, item, icon, active_data,
                  active_propname, index):
        if self.layout_type not in {'DEFAULT', 'COMPACT'}:
            return

        for i in range(item.indent):
            layout.split(factor=0.1)

        items = data.items
        prim = data.get_prim(item)
        if not prim:
            return

        visible = UsdGeom.Imageable(prim).ComputeVisibility() != 'invisible'

        col = layout.column()
        if not prim.GetChildren():
            icon = 'DOT'
            col.enabled = False
        elif len(items) > index + 1 and items[index + 1].indent > item.indent:
            icon = 'TRIA_DOWN'
        else:
            icon = 'TRIA_RIGHT'

        expand_op = col.operator(HDUSD_OP_usd_list_item_expand.bl_idname,
                                 text="",
                                 icon=icon,
                                 emboss=False,
                                 depress=False)
        expand_op.index = index

        col = layout.column()
        col.label(text=prim.GetName())
        col.enabled = visible

        col = layout.column()
        col.alignment = 'RIGHT'
        col.label(text=prim.GetTypeName())
        col.enabled = visible

        col = layout.column()
        col.alignment = 'RIGHT'
        if prim.GetTypeName() == 'Xform':
            icon = 'HIDE_OFF' if visible else 'HIDE_ON'
        else:
            col.enabled = False
            icon = 'NONE'

        visible_op = col.operator(HDUSD_OP_usd_list_item_show_hide.bl_idname,
                                  text="",
                                  icon=icon,
                                  emboss=False,
                                  depress=False)
        visible_op.index = index
Exemplo n.º 5
0
def _MoveCamera(stage):
    from pxr import UsdGeom, Gf
    cam = UsdGeom.Camera.Get(stage, '/World/main_cam')

    # the camera derives from UsdGeom.Xformable so we can
    # use the XformCommonAPI on it, too, and see how rotations are handled
    xformAPI = UsdGeom.XformCommonAPI(cam)
    xformAPI.SetTranslate((8, 120, 8))
    # -86 degree rotation around X axis.  Can specify rotation order as
    # optional parameter
    xformAPI.SetRotate((-86, 0, 0))
Exemplo n.º 6
0
    def _ValidateXformPrim(self, stage, xformPrimPath,
            expectedTranslation=None):
        xformPrim = stage.GetPrimAtPath(xformPrimPath)
        self.assertTrue(xformPrim)

        xformSchema = UsdGeom.Xform(xformPrim)
        self.assertTrue(xformSchema)

        self._ValidateXformOps(xformPrim, expectedTranslation)

        return xformSchema
    def _AssertDisplayColorEqual(self, prim, expectedColor):
        # expectedColor should be given as a list, so turn it into the type we'd
        # expect to get out of the displayColor attribute, namely a VtVec3fArray.
        expectedColor = Vt.Vec3fArray(1, expectedColor)

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

        displayColorPrimvar = gprim.GetDisplayColorPrimvar()
        self.assertTrue(displayColorPrimvar)
        self.assertEqual(displayColorPrimvar.ComputeFlattened(), expectedColor)
Exemplo n.º 8
0
    def __init__(self, appController, item):
        PrimContextMenuItem.__init__(self, appController, item)

        self._nonActiveCameraPrim = None
        if len(self._selectionDataModel.getPrims()) is 1:
            prim = self._selectionDataModel.getPrims()[0]
            from pxr import UsdGeom
            cam = UsdGeom.Camera(prim)
            if cam:
                if prim != appController.getActiveCamera():
                    self._nonActiveCameraPrim = prim
Exemplo n.º 9
0
    def test_import_st_no_indices_uniform(self, out_dir, mesh):
        out_path = os.path.join(out_dir, 'st_no_indices_face_uniform.usda')
        uvs = torch.rand((mesh.faces.size(0), 2))
        scene_path = '/World/mesh_0'
        usd.export_mesh(out_path, scene_path=scene_path, vertices=mesh.vertices,
                        faces=mesh.faces, uvs=uvs)

        # check that interpolation was set correctly to 'uniform'
        stage = Usd.Stage.Open(out_path)
        pv = UsdGeom.Mesh(stage.GetPrimAtPath(scene_path)).GetPrimvar('st')
        assert pv.GetInterpolation() == 'uniform'
Exemplo n.º 10
0
        def createCommonAPI(testCase, sphereXformable):
            sphereXformable.AddTranslateOp(UsdGeom.XformOp.PrecisionFloat,
                                           "pivot")
            sphereXformable.AddTranslateOp(UsdGeom.XformOp.PrecisionFloat,
                                           "pivot", True)

            self.assertEqual(
                sphereXformable.GetXformOpOrderAttr().Get(),
                Vt.TokenArray(("xformOp:translate:pivot",
                               "!invert!xformOp:translate:pivot")))
            self.assertTrue(UsdGeom.XformCommonAPI(sphereXformable))
Exemplo n.º 11
0
def makeBackSq(parentPath, imgHeight, imgWidth, upAxis, frameW, materialBackSq, stage):
    meshPath = os.path.join(parentPath, "BackSq")
    meshSchema = UsdGeom.Mesh.Define(stage, meshPath)
    vertexCounts = [4]
    meshSchema.CreateFaceVertexCountsAttr().Set(vertexCounts)
    indices = [2, 3, 0, 1]
    meshSchema.GetFaceVertexIndicesAttr().Set(indices)
    meshSchema.GetSubdivisionSchemeAttr().Set("none")
    # put comment here
    offset = -0.6
    sqSide = min(imgHeight, imgWidth)
    # we want to put the origin of the card in the center 'bottom'
    # this is course depends on what the up axis is:
    if upAxis == 'y' or upAxis == 'Y':
        UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
        points = [(-sqSide /2, sqSide + frameW, offset),
                  (sqSide /2, sqSide + frameW, offset),
                  (sqSide/2, frameW, offset),
                  (-sqSide /2, frameW, offset)]
    if upAxis == 'z' or upAxis == 'Z':
        UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
        points =[(-sqSide /2, offset, sqSide + frameW),
                 (sqSide /2, offset, sqSide + frameW),
                 (sqSide/2, offset, frameW),
                 (-sqSide /2, offset, frameW)]
    meshSchema.CreatePointsAttr().Set(points)
    uvs = [(1, 1),
           (0, 1),
           (0, 0),
           (1, 0)]
    st = meshSchema.CreatePrimvar("st", Sdf.ValueTypeNames.Float2Array)
    st.Set(uvs)
    st.SetInterpolation(UsdGeom.Tokens.vertex)
    extent = meshSchema.ComputeExtent(points)
    meshSchema.CreateExtentAttr().Set(extent)
    meshSchema.GetDisplayColorAttr().Set( [(1, 1, 1)] )
    if materialBackSq != None:
        prim = meshSchema.GetPrim()
        relName = "material:binding"
        rel = prim.CreateRelationship(relName)
        rel.AddTarget(materialBackSq)
Exemplo n.º 12
0
    def compute(self, **kwargs):
        depsgraph = bpy.context.evaluated_depsgraph_get()

        stage = self.cached_stage.create()
        UsdGeom.SetStageMetersPerUnit(stage, 1)
        UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)

        root_prim = stage.GetPseudoRoot()

        kwargs = {'scene': depsgraph.scene,
                  'is_use_animation': self.is_use_animation,
                  'is_restrict_frames': self.is_restrict_frames,
                  'frame_start': self.frame_start,
                  'frame_end': self.frame_end}

        if self.data == 'SCENE':
            for obj_data in ObjectData.depsgraph_objects(depsgraph):
                object.sync(root_prim, obj_data, **kwargs)

            if depsgraph.scene.world is not None:
                world.sync(root_prim, depsgraph.scene.world)

        elif self.data == 'COLLECTION':
            if not self.collection:
                return

            for obj_col in self.collection.objects:
                if obj_col.hdusd.is_usd or (obj_col.type == 'CAMERA' and obj_col.name == USD_CAMERA ):
                    continue

                object.sync(root_prim, ObjectData.from_object(
                    obj_col.evaluated_get(depsgraph)), **kwargs)

        elif self.data == 'OBJECT':
            if not self.object or self.object.hdusd.is_usd:
                return

            object.sync(root_prim, ObjectData.from_object(self.object.evaluated_get(depsgraph)),
                        **kwargs)

        return stage
Exemplo n.º 13
0
 def test_XformOpOperators(self):
     s = Usd.Stage.CreateInMemory()
     rootXform = UsdGeom.Xform.Define(s, "/Root")
     translateOp = rootXform.AddTranslateOp()
     scaleOp = rootXform.AddScaleOp()
     self.assertFalse(UsdGeom.XformOp())
     self.assertTrue(translateOp)
     self.assertTrue(scaleOp)
     xformOps = rootXform.GetOrderedXformOps()
     self.assertEqual(xformOps, [translateOp, scaleOp])
     xformOps.remove(translateOp)
     self.assertEqual(xformOps, [scaleOp])
Exemplo n.º 14
0
 def test_InvalidXformable(self):
     xf = UsdGeom.Xformable()
     # This used to crash before the SchemaBase __getattribute__ method
     # was overridden to test the validity of the underlying prim.
     with self.assertRaises(RuntimeError):
         xf.ClearXformOpOrder()
     # It should still be safe to get the prim, but the prim will be invalid.
     p = xf.GetPrim()
     with self.assertRaises(RuntimeError):
         p.IsActive()
     # It should still be safe to get the path, but the path will be empty.
     self.assertEqual(xf.GetPath(), Sdf.Path())
Exemplo n.º 15
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))
Exemplo n.º 16
0
 def __init__(self, appController, item):
     PrimContextMenuItem.__init__(self, appController, item)
     from pxr import UsdGeom
     self._imageable = False
     self._isVisible = False
     for prim in self._selectionDataModel.getPrims():
         imgbl = UsdGeom.Imageable(prim)
         if imgbl:
             self._imageable = True
             self._isVisible = (imgbl.ComputeVisibility(self._currentFrame)
                                == UsdGeom.Tokens.inherited)
             break
Exemplo n.º 17
0
    def _sync(self, context, depsgraph):
        super()._sync(context, depsgraph)

        stage = self.cached_stage.create()

        log("sync", depsgraph)

        UsdGeom.SetStageMetersPerUnit(stage, 1)
        UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)

        root_prim = stage.GetPseudoRoot()

        for obj_data in object.ObjectData.depsgraph_objects(
                depsgraph,
                space_data=self.space_data,
                use_scene_cameras=False,
                use_scene_lights=self.shading_data.use_scene_lights):
            object.sync(root_prim, obj_data)

        world.sync(root_prim, depsgraph.scene.world, self.shading_data)
        self.render_params.clearColor = world.get_clear_color(root_prim)
Exemplo n.º 18
0
def main():
    # Make the stage
    stage = Usd.Stage.CreateNew(STAGENAME)
    UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)

    # Set transform and create primitive
    xformPrim = UsdGeom.Xform.Define(stage, '/hello')
    Usd.ModelAPI(xformPrim).SetKind(Kind.Tokens.component)

    spherePrim = UsdGeom.Sphere.Define(stage, '/hello/world')

    # Create texture coords
    texCoords = spherePrim.CreatePrimvar('st',
                                         Sdf.ValueTypeNames.TexCoord2fArray,
                                         UsdGeom.Tokens.varying)

    # This line makes USD complain that there aren't enough texture coordinates.
    #texCoords.Set([(0, 0), (1, 0), (1,1), (0, 1)])

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

    pbrShader = UsdShade.Shader.Define(stage, '/hello/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, '/hello/material/stReader')
    stReader.CreateIdAttr('UsdPrimvarReader_float2')
    stReader.CreateInput('varname',
                         Sdf.ValueTypeNames.Token).ConnectToSource(stInput)

    diffuseTextureSampler = UsdShade.Shader.Define(
        stage, '/hello/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(spherePrim).Bind(material)

    # Save stage
    stage.Save()
Exemplo n.º 19
0
    def test_Extent(self):
        stage = Usd.Stage.Open("test.usda")
        pi = UsdGeom.PointInstancer(
            stage.GetPrimAtPath("/MultiInstanceForExtents"))

        times = [0, 1, 2]
        expectedExtents = [[(-1, -1, -1), (1, 1, 1)],
                           [(-3.7600734, 1.2399265, -1),
                            (3.7600734, 6.2600737, 3.5)],
                           [(-6.3968024, 3.6031978, -1),
                            (6.3968024, 11.396802, 6)]]
        self.compareExtents(pi, times, 0, expectedExtents)
Exemplo n.º 20
0
def _create_basic_scene():
    stage = Usd.Stage.CreateInMemory()
    sphere = UsdGeom.Sphere.Define(stage, "/Some/Prim")
    sphere.GetRadiusAttr().Set(10.0)

    another = Usd.Stage.CreateInMemory()
    another.GetRootLayer().subLayerPaths.append(
        stage.GetRootLayer().identifier)
    override = UsdGeom.Sphere(another.OverridePrim("/Some/Prim"))
    override.GetRadiusAttr().Set(20.0)

    return another
Exemplo n.º 21
0
    def testMashPrototypes_NoIdsArray(self):
        """
        MASH instancers might not have an ids array if using dynamics.
        Make sure they still export OK.
        """
        instancerPrim = self.stage.GetPrimAtPath(
            "/InstancerTest/MASH2_Instancer")
        self.assertTrue(instancerPrim)

        instancer = UsdGeom.PointInstancer(instancerPrim)
        protoIndices = instancer.GetProtoIndicesAttr().Get()
        self.assertEqual(len(protoIndices), 10)
Exemplo n.º 22
0
    def testTransforms(self):
        """
        Check that the point transforms are correct.
        """
        mayaInstancer = OMFX.MFnInstancer(self._GetDagPath("instancer1"))
        usdInstancer = UsdGeom.PointInstancer(
            self.stage.GetPrimAtPath("/InstancerTest/instancer1"))

        time = self.START_TIMECODE
        while time <= self.END_TIMECODE:
            cmds.currentTime(time, edit=True)

            # Need to do this because MFnInstancer will give instance matrices
            # as offsets from prototypes' original world space positions.
            worldPositions = [
                self._GetWorldSpacePosition("|dummyGroup|pCube1"),
                self._GetWorldSpacePosition(
                    "|InstancerTest|instancer1|prototypeUnderInstancer"),
                self._GetWorldSpacePosition("|referencePrototype")
            ]

            paths = OM.MDagPathArray()
            matrices = OM.MMatrixArray()
            particlePathStartIndices = OM.MIntArray()
            pathIndices = OM.MIntArray()
            mayaInstancer.allInstances(paths, matrices,
                                       particlePathStartIndices, pathIndices)

            usdInstanceTransforms = \
                    usdInstancer.ComputeInstanceTransformsAtTime(time, time)
            usdProtoIndices = usdInstancer.GetProtoIndicesAttr().Get(time)

            self.assertEqual(matrices.length(), len(usdInstanceTransforms))

            # Compute the instancer-space position of instances in Maya
            # (including the protos' transforms). By default, this is what
            # UsdGeomPointInstancer::ComputeInstanceTransformsAtTime already
            # gives us.
            mayaWorldPositions = [
                worldPositions[protoIndex] for protoIndex in usdProtoIndices
            ]
            mayaGfMatrices = [
                mayaWorldPositions[i] * self._MayaToGfMatrix(matrices[i])
                for i in xrange(matrices.length())
            ]
            usdGfMatrices = [
                usdInstanceTransforms[i]
                for i in xrange(len(usdInstanceTransforms))
            ]
            for i in xrange(len(usdGfMatrices)):
                self._AssertXformMatrices(mayaGfMatrices[i], usdGfMatrices[i])

            time += 1.0
Exemplo n.º 23
0
def createXformOps(ufeObject):
    selDag, selPrim = getDagAndPrimFromUfe(ufeObject)
    stage = mayaUsdLib.GetPrim(selDag).GetStage()

    primPath = Sdf.Path(selPrim)
    prim = stage.GetPrimAtPath(primPath)

    xformAPI = UsdGeom.XformCommonAPI(prim)
    xformAPI.CreateXformOps(
                UsdGeom.XformCommonAPI.OpTranslate,
                UsdGeom.XformCommonAPI.OpRotate,
                UsdGeom.XformCommonAPI.OpScale)
Exemplo n.º 24
0
 def testExportUvVersusUvIndexFromIterator(self):
     """
     Tests that UVs export properly on a mesh where the UV returned by
     MItMeshFaceVertex::getUV is known to be different from that
     returned by MItMeshFaceVertex::getUVIndex and indexed into the UV array.
     (The latter should return the desired result from the outMesh and is the
     method currently used by usdMaya.)
     """
     brokenBoxMesh = UsdGeom.Mesh(self._stage.GetPrimAtPath(
             "/UsdExportUVSetsTest/Geom/BrokenUVs/box"))
     stPrimvar = brokenBoxMesh.GetPrimvar("st").ComputeFlattened()
     self.assertEqual(stPrimvar[0], Gf.Vec2f(1.0, 1.0))
Exemplo n.º 25
0
 def relocateWorldCenter(self,in_dagnode_path="|assets", out_dagnode_path="|assets|scn"):
     '''
     Try to define static prim xform information.
     '''
     if not cmds.objExists(in_dagnode_path) or not cmds.objExists(out_dagnode_path):
         return
     if not self.isDAGNodeBeMoved(in_dagnode_path):
         return
     scenegraph_path = self.fetchNameSceneGraphPrim(out_dagnode_path)
     scenegraph_data = self.fetchDataStaticMayaXform(in_dagnode_path)
     prim = self.__stage__.GetPrimAtPath( scenegraph_path ) 
     if scenegraph_data["visibility"]:
         UsdGeom.Imageable(prim).MakeVisible()
     else:
         UsdGeom.Imageable(prim).MakeInvisible()
     rotateXYZ = scenegraph_data["rotateXYZ"]
     UsdGeom.XformCommonAPI(prim).SetRotate(tuple(rotateXYZ),UsdGeom.XformCommonAPI.RotationOrderXYZ)
     scale = scenegraph_data["scale"]
     UsdGeom.XformCommonAPI(prim).SetScale(tuple(scale))
     translate = scenegraph_data["translate"]
     UsdGeom.XformCommonAPI(prim).SetTranslate(tuple(translate))
Exemplo n.º 26
0
Arquivo: common.py Projeto: yjang/USD
def GetInstanceIndicesForIds(prim, instanceIds, time):
    '''Attempt to find the instance indices of a list of authored instance IDs
    for prim 'prim' at time 'time'. If the prim is not a PointInstancer or does
    not have authored IDs, returns None. If any ID from 'instanceIds' does not
    exist at the given time, its index is not added to the list (because it does
    not have an index).'''
    ids = UsdGeom.PointInstancer(prim).GetIdsAttr().Get(time)
    if ids:
        return [instanceIndex for instanceIndex, instanceId in enumerate(ids)
            if instanceId in instanceIds]
    else:
        return None
Exemplo n.º 27
0
 def __init__(self, mainWindow, item):
     NodeContextMenuItem.__init__(self, mainWindow, item)
     from pxr import UsdGeom
     self._imageable = False
     self._isVisible = False
     for prim in self._currentNodes:
         imgbl = UsdGeom.Imageable(prim)
         if imgbl:
             self._imageable = True
             self._isVisible = (imgbl.ComputeVisibility(
                 self._currentFrame) == UsdGeom.Tokens.inherited)
             break
Exemplo n.º 28
0
 def __defineUSDDefaultSetting__(self, dagnode_path, rangeTimeCode=None):
     '''
     Set the default of USD such as TimeCode, DefaultPrim and UpAxis.
     '''
     # set USD default setting
     if rangeTimeCode:
         self.__stage__.SetStartTimeCode(rangeTimeCode[0])
         self.__stage__.SetEndTimeCode(rangeTimeCode[1])
     scenegraph_path = self.fetchNameSceneGraphPrim(dagnode_path)
     root_prim = self.__stage__.GetPrimAtPath( self.fetchNameUsdRoot(scenegraph_path))
     self.__stage__.SetDefaultPrim(root_prim)
     UsdGeom.SetStageUpAxis(self.__stage__, UsdGeom.Tokens.y)
Exemplo n.º 29
0
def TestUsd4957():
    """ Tests the case in which a prim has an xform directly on it and its
        bounding box relative to one of its ancestors is computed using
        ComputeRelativeBound().
    """
    s = Usd.Stage.Open("testUSD4957.usda")
    b = s.GetPrimAtPath("/A/B")
    c = s.GetPrimAtPath("/A/B/C")
    bc = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ['default', 'render'])
    
    # Call the function being tested
    relativeBbox = bc.ComputeRelativeBound(c, b)
    
    # Compare the result with the bbox of C in its local space
    cExtent = UsdGeom.Boundable(c).GetExtentAttr().Get()
    cRange = Gf.Range3d(Gf.Vec3d(cExtent[0]), Gf.Vec3d(cExtent[1]))
    cLocalXform = UsdGeom.Xformable(c).GetLocalTransformation()
    cBbox = Gf.BBox3d(cRange, cLocalXform)
    
    AssertBBoxesClose(relativeBbox, cBbox,
                      "ComputeRelativeBound produced a wrong bbox.")
Exemplo n.º 30
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()