def test_CacheContextLifetime(self): # Check that python object lifetimes are preserved as expected, to ensure # that the C++ objects they refer to do not expire prematurely. import weakref # Create a cache and a weak reference to it. cache = Usd.StageCache() weakCache = weakref.ref(cache) # Create a nonpopulating wrapper around the cache, and a weakref to it. nonPop = Usd.UseButDoNotPopulateCache(cache) weakNonPop = weakref.ref(nonPop) # del our local name 'cache'. The rw object should keep it alive. del cache assert weakCache() # Create a CacheContext. ctx = Usd.StageCacheContext(nonPop) # del our local name 'rw'. The ctx object should keep it alive (and # transitively, the cache object). del nonPop assert weakNonPop() assert weakCache() # Try populating into the cache, for fun. with ctx: stage = Usd.Stage.Open(Sdf.Layer.CreateAnonymous()) assert weakNonPop() assert weakCache() assert not weakCache().Contains(stage) # nonpopulating cache usage. # Killing our ctx reference should let the objects expire. del ctx assert weakNonPop() is None assert weakCache() is None # Now try again with a context on the cache directly. cache = Usd.StageCache() weakCache = weakref.ref(cache) ctx = Usd.StageCacheContext(cache) del cache assert weakCache() with ctx: stage = Usd.Stage.Open(Sdf.Layer.CreateAnonymous()) assert weakCache() assert weakCache().Contains(stage) # this ctx will populate. # Killing ctx should let the cache expire. del ctx assert weakCache() is None
def test_ImplicitSessionLayer(self): cache = Usd.StageCache() layer1 = Sdf.Layer.CreateAnonymous() sess = Sdf.Layer.CreateAnonymous() # Opening a stage that is not already present in the cache, specifying no # session layer should actually produce a stage with no session layer. with Usd.StageCacheContext(cache): implicitSession = Usd.Stage.Open(layer1) noSession = Usd.Stage.Open(layer1, sessionLayer=None) explicitSession = Usd.Stage.Open(layer1, sessionLayer=sess) dontCareSession = Usd.Stage.Open(layer1) # The implicitSession stage should have a usd-generated session layer, and # should not match explicitSession's session layer. assert implicitSession.GetSessionLayer() assert (implicitSession.GetSessionLayer() != explicitSession.GetSessionLayer()) # The noSession stage should have no session layer, and should not be the # same stage as either explicitSession or implicitSession. assert not noSession.GetSessionLayer() assert noSession not in (explicitSession, implicitSession) # The explicitSession stage should have the session layer we specified, and # should not be the same as noSession or implicitSession. assert explicitSession.GetSessionLayer() == sess assert explicitSession not in (noSession, implicitSession) # The dontCareSession should be either noSession or explicitSession or # implicitSession, since it didn't specify a sessionLayer argument. assert dontCareSession in (noSession, explicitSession, implicitSession)
def getStage(usdFile, variantOverrides=None, loadAll=False, stageCache=None): ''' Open a stage from a USD file path, optionally populating the session layer with variant overrides. Parameters ---------- usdFile : str variantOverrides : Optional[Dict[str, Dict[str, str]]] Dict[primPath, Dict[variantSetName, selectedVariant]] as returned by `getVariantSelections()` loadAll : Optional[bool] stageCache : Optional[Usd.StageCache] Returns ------- Usd.Stage ''' # TODO: Implement PopulationMask support if stageCache is not None: assert isinstance(stageCache, Usd.StageCache) ctxArg = stageCache else: ctxArg = Usd.BlockStageCaches with Usd.StageCacheContext(ctxArg): loadSet = Usd.Stage.LoadAll if loadAll else Usd.Stage.LoadNone if variantOverrides: rootLayer = Sdf.Layer.FindOrOpen(usdFile) assert rootLayer sessionLayer = Sdf.Layer.CreateAnonymous() for primPath, variantSelections in variantOverrides.iteritems(): sdfPath = Sdf.Path(primPath) primSpec = Sdf.CreatePrimInLayer(sessionLayer, sdfPath.GetPrimPath()) # FIXME: If any of these selections no longer exists or is # invalid it could result in a prim not being found when we # populate the asset manager. Either take performance hit to # check, or add a way to clean out stale selections. primSpec.variantSelections.update(variantSelections) stage = Usd.Stage.Open(rootLayer, sessionLayer, loadSet) stage.SetEditTarget(sessionLayer) else: stage = Usd.Stage.Open(usdFile, loadSet) assert stage stage.SetEditTarget(stage.GetSessionLayer()) return stage
def main(): """Run the main execution of the current script.""" stage = Usd.Stage.CreateInMemory() cache = UsdUtils.StageCache.Get() with Usd.StageCacheContext(cache): print("This should be False", cache.Contains(stage)) auto_added_stage = Usd.Stage.CreateInMemory() print("This should be True", cache.Contains(auto_added_stage)) get_stage_from_id(cache.GetId(auto_added_stage)) print( "We will add a stage to the cache in a separate function (1)", len(cache.GetAllStages()), ) add_to_cache_from_external_function() print("Cache was added (now it should be (2))", len(cache.GetAllStages()))
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)
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()
def GetPrimSelectedIndices(self): '''Provides access to the internal selected indices''' return self.__hierarchyView.selectedIndexes() def SetSourceModel(self, model): '''Replaces the current editor's current model with the new model. The model must be a subclass of HierarchyBaseModel.''' self.__filterModel.setSourceModel(model) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) with Usd.StageCacheContext(UsdUtils.StageCache.Get()): stage = Usd.Stage.Open( '../usdQt/testenv/testUsdQtHierarchyModel/simpleHierarchy.usda') model = UsdQt.HierarchyBaseModel(stage) class Listener(QtCore.QObject): def __init__(self, parent=None): super(Listener, self).__init__(parent=parent) @QtCore.Slot() def OnPrimSelectionChanged(self, selected=None, deselected=None): for index in self.sender().selectedIndexes(): prim = index.data(role=UsdQt.roles.HierarchyPrimRole) # print(prim)
------- Usd.Stage """ return self._stageCache.GetAllStages()[index.row()] if __name__ == '__main__': """ Sample usage """ import os from pxr import Usd, UsdUtils from ._Qt import QtWidgets import sys app = QtWidgets.QApplication([]) stageCache = UsdUtils.StageCache.Get() dir = os.path.split(__file__)[0] path = os.path.join(dir, 'testenv', 'testUsdQtOpinionModel', 'simple.usda') with Usd.StageCacheContext(stageCache): stage1 = Usd.Stage.CreateInMemory() stage2 = Usd.Stage.Open(path) stage3 = Usd.Stage.CreateInMemory() comboBox = QtWidgets.QComboBox() model = StageCacheModel(stageCache) comboBox.setModel(model) comboBox.show() sys.exit(app.exec_())
def FromUsdFile(cls, usdFile, parent=None): with Usd.StageCacheContext(Usd.BlockStageCaches): stage = Usd.Stage.Open(usdFile, Usd.Stage.LoadNone) assert stage stage.SetEditTarget(stage.GetSessionLayer()) return cls(stage, parent=parent)
def test_CacheContext(self): layer1 = Sdf.Layer.CreateAnonymous() layer2 = Sdf.Layer.CreateAnonymous() cache1 = Usd.StageCache() # Populate cache1 with a stage, by binding a context and using the # Stage.Open API. with Usd.StageCacheContext(cache1): stage = Usd.Stage.Open(layer1) assert cache1.Size() == 1 assert cache1.Contains(stage) assert cache1.FindOneMatching(layer1) == stage # Read the stage from the read-only cache, assert a different opened stage # doesn't populate the cache. with Usd.StageCacheContext(Usd.UseButDoNotPopulateCache(cache1)): stageAgain = Usd.Stage.Open(layer1) newStage = Usd.Stage.Open(layer2) assert stageAgain is stage assert newStage assert not cache1.Contains(newStage) # Create a new cache, make a context for both, and check that a newly # created stage publishes to both caches. cache1.Clear() cache2 = Usd.StageCache() with Usd.StageCacheContext(cache1): with Usd.StageCacheContext(cache2): newStage = Usd.Stage.Open(layer2) assert cache1.Contains(newStage) assert cache2.Contains(newStage) # Publish a stage with a specific session layer to a cache, then check that # a call to Stage.Open() that doesn't specify a session layer finds that # layer in the cache, but that a call to Stage.Open() that demands no # session layer finds no layer in the cache. cache1.Clear() with Usd.StageCacheContext(cache1): newStage = Usd.Stage.Open(layer1, layer2) newStage2 = Usd.Stage.Open(layer1) assert newStage is newStage2 newStage3 = Usd.Stage.Open(layer1, sessionLayer=None) assert newStage3 != newStage # Verify that blocking caches works as expected. cache1.Clear() with Usd.StageCacheContext(cache1): # Populate a stage into the cache. newStage = Usd.Stage.Open(layer1) assert cache1.Contains(newStage) with Usd.StageCacheContext(Usd.BlockStageCaches): # Open() should create a new stage, since cache is blocked. newStage2 = Usd.Stage.Open(layer1) assert newStage2 != newStage assert cache1.Size() == 1 # Opening a different stage should not populate the cache. newStage3 = Usd.Stage.Open(layer2) assert not cache1.Contains(newStage3) assert cache1.Size() == 1 # Try blocking cache writes only. cache1.Clear() with Usd.StageCacheContext(cache1): # Populate a stage into the cache. newStage = Usd.Stage.Open(layer1) assert cache1.Contains(newStage) with Usd.StageCacheContext(Usd.BlockStageCachePopulation): # Open() should read the stage from the cache. newStage2 = Usd.Stage.Open(layer1) assert newStage2 == newStage # Opening a different stage should not populate the cache. newStage3 = Usd.Stage.Open(layer2) assert not cache1.Contains(newStage3) assert cache1.Size() == 1
def test_Basic(self): # Verify that the UsdUtils.StageCache singleton # does not crash upon system teardown. lyr = Sdf.Layer.CreateAnonymous() with Usd.StageCacheContext(UsdUtils.StageCache.Get()): stage = Usd.Stage.Open(lyr)