示例#1
0
def main():
    """Run the main execution of the current script."""
    inner_stage = _make_target()
    main_stage = Usd.Stage.CreateInMemory()

    # XXX : In order to use `inner_stage` in an EditContext, it must be
    # in `main_stage`'s local LayerStack (e.g. it must be a sublayer)
    #
    main_stage.GetRootLayer().subLayerPaths.append(
        inner_stage.GetRootLayer().identifier)

    print(main_stage.GetRootLayer().ExportToString())
    print('Inner stage before context')
    print(inner_stage.GetRootLayer().ExportToString())

    with Usd.EditContext(main_stage, inner_stage.GetRootLayer()):
        sphere = UsdGeom.Sphere(main_stage.GetPrimAtPath("/root/sphere"))
        sphere.GetRadiusAttr().Set(10)

    print('Inner stage after context')
    print(inner_stage.GetRootLayer().ExportToString())

    main_stage.SetEditTarget(Usd.EditTarget(inner_stage.GetRootLayer()))
    sphere = UsdGeom.Sphere(main_stage.GetPrimAtPath("/root/sphere"))
    sphere.GetRadiusAttr().Set(5)

    print('Inner stage after setting')
    print(inner_stage.GetRootLayer().ExportToString())
示例#2
0
def main():
    print("Simple Stage:")
    stage = _create_basic_scene()
    sphere = UsdGeom.Sphere(stage.GetPrimAtPath("/Some/Prim"))

    radius = sphere.GetRadiusAttr()
    print("Testing Get(), normally")
    timeit(radius.Get, REPEATS)

    query = Usd.AttributeQuery(radius)
    print(query.Get())
    radius.Set(100)
    print(query.Get())
    print("Testing Get(), using UsdAttributeQuery")
    timeit(query.Get, REPEATS)
    print()

    print("Testing GetTimeSamples(), normally")
    timeit(radius.GetTimeSamples, REPEATS)

    function = functools.partial(query.GetUnionedTimeSamples, [query])
    function.__name__ = "GetUnionedTimeSamples"
    print("Testing GetTimeSamples(), using a union")
    timeit(function, REPEATS)
    print()

    visibility = sphere.GetVisibilityAttr()

    function = functools.partial(_get_time_samples, (radius, visibility))
    function.__name__ = "_get_time_samples - with radius and visibility"
    print("Testing GetTimeSamples() for multiple attributes, normally")
    timeit(function, REPEATS)

    function = functools.partial(query.GetUnionedTimeSamples,
                                 [query, Usd.AttributeQuery(visibility)])
    function.__name__ = "GetUnionedTimeSamples - with radius and visibility"
    print("Testing GetTimeSamples() for multiple attributes, using a union")
    timeit(function, REPEATS)
    print()

    print("Heavy Stage:")
    heavier_stage = _create_basic_scene_with_more_values()
    sphere = UsdGeom.Sphere(heavier_stage.GetPrimAtPath("/Some/Prim"))
    radius = sphere.GetRadiusAttr()
    visibility = sphere.GetVisibilityAttr()
    query = Usd.AttributeQuery(radius)
    function = functools.partial(_get_time_samples, (radius, visibility))
    function.__name__ = "_get_time_samples - with radius and visibility"
    print("Testing GetTimeSamples() for multiple attributes, normally")
    timeit(function, REPEATS)

    function = functools.partial(query.GetUnionedTimeSamples,
                                 [query, Usd.AttributeQuery(visibility)])
    function.__name__ = "GetUnionedTimeSamples - with radius and visibility"
    print("Testing GetTimeSamples() for multiple attributes, using a union")
    timeit(function, REPEATS)
示例#3
0
def main():
    """Run the main execution of the current script."""
    stage = Usd.Stage.CreateInMemory()
    stage.GetRootLayer().ImportFromString("""\
        #usda 1.0

        def Scope "root" (
            variantSets = ["foo"]
        )
        {
            variantSet "foo" = {
                "base" {
                    def Scope "prim1"
                    {
                        def Sphere "a_sphere"
                        {
                            double radius = 3
                        }
                    }
                }
                "another" {
                    def Scope "prim2" (
                        variantSets = ["bar"]
                    )
                    {
                        variantSet "bar" = {
                            "one" {
                                def Sphere "sphere"
                                {
                                    double radius = 2
                                }
                            }
                        }
                    }
                }
            }
        }
        """)

    variant_sphere = UsdGeom.Sphere(
        get_prim_at_path(stage, Sdf.Path("/root{foo=base}prim1/a_sphere")))
    print('This value should be 3.0: "{}"'.format(
        variant_sphere.GetRadiusAttr().Get()))

    nested_variant_sphere = UsdGeom.Sphere(
        get_prim_at_path(stage,
                         Sdf.Path("/root{foo=another}prim2{bar=one}sphere")))
    print('This value should be 2.0: "{}"'.format(
        nested_variant_sphere.GetRadiusAttr().Get()))
示例#4
0
 def test_Revert_Bug111239(self):
     # This used to test a change for Bug111239, but now tests that this
     # fix has been reverted. We no longer allow the C++ typename be used as
     # a prim's typename.
     s = Usd.Stage.CreateInMemory()
     sphere = s.DefinePrim('/sphere', typeName='Sphere')
     tfTypeName = UsdGeom.Sphere._GetStaticTfType().typeName
     self.assertEqual(tfTypeName, 'UsdGeomSphere')
     usdGeomSphere = s.DefinePrim('/usdGeomSphere', typeName='tfTypeName')
     self.assertTrue(UsdGeom.Sphere(sphere))
     self.assertTrue(
         'radius' in [a.GetName() for a in sphere.GetAttributes()])
     self.assertFalse(UsdGeom.Sphere(usdGeomSphere))
     self.assertFalse(
         'radius' in [a.GetName() for a in usdGeomSphere.GetAttributes()])
示例#5
0
def _testReloadReopen(appController):
    from pxr import Usd, UsdGeom

    #
    # Frame the front sphere, and color it red
    #
    appController._dataModel.selection.setPrimPath("/frontSphere")
    stage = appController._dataModel.stage
    sphere = UsdGeom.Sphere(stage.GetPrimAtPath("/frontSphere"))
    with Usd.EditContext(stage, stage.GetRootLayer()):
        sphere.CreateDisplayColorAttr([(1, 0, 0)])
    _emitFrameAction(appController)
    # Finally, clear selection so the red really shows
    appController._dataModel.selection.clear()

    _takeShot(appController, "coloredAndFramed.png")

    #
    # Reloading should set the sphere back to gray (because we authored into
    # its root layer), but otherwise not change the view
    #
    _emitReload_All_LayersAction(appController)
    _takeShot(appController, "reloaded.png")

    #
    # Reopening the stage should completely reset the view
    #
    _emitReopen_StageAction(appController)
    _takeShot(appController, "reopened.png")
示例#6
0
 def Read(self, context):
     usdPrim = self._GetArgs().GetUsdPrim()
     sphere = UsdGeom.Sphere(usdPrim)
     cmds.polySphere(r=sphere.GetRadiusAttr().Get(), name=usdPrim.GetName())
     MayaNode = context.GetMayaNode(usdPrim.GetPath().GetParentPath(), True)
     print("primReaderTest.Read Ok")
     return True
示例#7
0
def create_shot(sequence):
    """Get the settings from some `sequence` and modify its assets."""
    stage = Usd.Stage.CreateInMemory()
    stage.GetRootLayer().subLayerPaths.append(sequence)
    prim = stage.OverridePrim("/SomeSphere")
    variants = prim.GetVariantSets().GetVariantSet("some_variant_set")
    variants.AddVariant("variant_name_2")

    prim.SetMetadata(
        "comment",
        textwrap.dedent("""\
        SetVariantSelection sets the default variant.

        Also note that our new variant set, "variant_name_2" adds, not
        overrides, the "some_variant_set". So we have "variant_name_2"
        and "variant_name_1" now.

        """),
    )
    variants.SetVariantSelection("variant_name_2")
    with variants.GetVariantEditContext():
        sphere = UsdGeom.Sphere(prim)
        sphere.GetDisplayColorAttr().Set([(0, 1, 0)])

    stage.Save()
    return stage
示例#8
0
def _create_basic_scene_with_more_values():
    stage = _create_basic_scene()
    override = UsdGeom.Sphere(stage.OverridePrim("/Some/Prim"))

    for sample in range(10000):
        override.GetRadiusAttr().Set(sample + 30, sample)

    return stage
示例#9
0
def _run_resolution_test():
    referencee = Usd.Stage.CreateInMemory()
    referencee.GetRootLayer().ImportFromString("""\
        #usda 1.0
        (
            defaultPrim = "root"
        )

        def Scope "root"
        {
            def Sphere "sphere"
            {
                double radius = 2
                double radius.timeSamples = {
                    10: 10,
                    40: 40,
                }
            }
        }
        """)

    referencer = Usd.Stage.CreateInMemory()
    root = referencer.DefinePrim("/root")
    root.GetReferences().AddReference(
        Sdf.Reference(
            referencee.GetRootLayer().identifier,
            layerOffset=Sdf.LayerOffset(offset=5, scale=2),
        ))

    sphere = UsdGeom.Sphere(referencer.GetPrimAtPath("/root/sphere"))
    radius = sphere.GetRadiusAttr()

    times = [
        (10, 10.0, Usd.ResolveInfoSourceTimeSamples),
        (20, 10.0, Usd.ResolveInfoSourceTimeSamples),
        (25, 10.0, Usd.ResolveInfoSourceTimeSamples),
        (30, 12.5, Usd.ResolveInfoSourceTimeSamples),
        (55, 25.0, Usd.ResolveInfoSourceTimeSamples),
        (85, 40.0, Usd.ResolveInfoSourceTimeSamples),
    ]

    template = textwrap.dedent("""\
        Expected Value: "{expected_value}"
        Actual Value: "{actual_value}"
        Expected Resolve: "{expected_resolve}",
        Actual Resolve: "{actual_resolve}",\
        """)

    for time_code, expected_value, expected_resolve in times:
        print('Time Start: "{time_code}"'.format(time_code=time_code))
        print(
            template.format(
                expected_value=expected_value,
                actual_value=radius.Get(time_code),
                expected_resolve=expected_resolve,
                actual_resolve=radius.GetResolveInfo(time_code).GetSource(),
            ))
        print('Time End: "{time_code}"'.format(time_code=time_code))
示例#10
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
示例#11
0
def create_override_stage(identifier):
    stage = Usd.Stage.CreateInMemory()
    stage.GetPrimAtPath("/SomeSphere")
    root = stage.GetRootLayer()
    root.subLayerPaths.append(identifier)
    sphere = UsdGeom.Sphere(stage.GetPrimAtPath("/SomeSphere"))

    # Here's an example of adding a completely new variant set
    sphere.GetPrim().GetVariantSets().AddVariantSet("another")

    variants = sphere.GetPrim().GetVariantSets().GetVariantSet("some_variant_set")
    variants.AddVariant("foo")

    variants.SetVariantSelection("foo")
    with variants.GetVariantEditContext():
        sphere.GetRadiusAttr().Set(100)

    return stage
示例#12
0
def create_sequence(asset):
    """Create a collection that shots will include and add some character to it."""
    stage = Usd.Stage.CreateInMemory()
    root = stage.GetRootLayer()
    root.documentation = "A common set of data for an entire sequence."
    root.subLayerPaths.append(asset)
    stage.SetMetadata(
        "comment",
        "We override the character to make it bigger and add some viewing option.",
    )
    prim = stage.OverridePrim("/SomeSphere")
    variants = prim.GetVariantSets().AddVariantSet("some_variant_set")
    variants.AddVariant("variant_name_1")

    variants.SetVariantSelection("variant_name_1")

    with variants.GetVariantEditContext():
        sphere = UsdGeom.Sphere(prim)
        sphere.GetDisplayColorAttr().Set([(1, 0, 0)])

    return stage
示例#13
0
def animate(stage):
  """The output from Tilt Brush is strokes with a growth velocity.
  This could be authored per vertex later (e.g. for easing).
  """
  # The current animation time, this will increase monotonicly to generate frames of animation.
  time = 1

  # The maximum number of animated strokes, for performance constraints.
  maxActive = 30

  # Filters dictate when a stroke becomes active, i.e. predicates for activation.
  activeFilter = isInRadius 
  activeFilterVert = isHigherVert
  
  # The target length of the animation.
  lengthInSeconds = 30 
  # The playback framerate.
  framesPerSecond = 30 
  # The number of frames we will generate based on target time and rate.
  numFrames = lengthInSeconds * framesPerSecond

  # Boundaries for activation.
  minHeight = 0 
  maxHeight = 20 
  radius = 17.0 
  maxRadius = 100.
  height = minHeight
 
  # Compute the actual radius of the world bounds.
  worldBounds = UsdGeom.Xform(stage.GetPrimAtPath("/")).ComputeWorldBound(0, "default")
  maxRadius = (worldBounds.GetRange().max - worldBounds.GetRange().min).GetLength()

  # Compute the centroid of the world.
  global worldCenter
  worldCenter = Gf.Vec3f(worldBounds.ComputeCentroid())
  # Just for newIntroSketch.tilt
  if "NewIntroSketch" in stage.GetRootLayer().identifier:
    worldCenter = Gf.Vec3f(0.73135, 19.92212, 33.2210311)
  worldCenter[1] = worldBounds.GetRange().min[1]

  print("World Center:", worldCenter)
  print("Max Radius:", maxRadius)

  # Visualize the radius.
  debugSphere = UsdGeom.Sphere(stage.DefinePrim("/debug", "Sphere"))
  debugSphere.CreateRadiusAttr(radius)
  debugSphere.GetPrim().GetAttribute("purpose").Set("guide")
  attr = debugSphere.GetPrim().GetAttribute("primvars:displayOpacity")
  attr.Set([0.125])
  attr.SetMetadata("interpolation", "constant")
  UsdGeom.Xform(attr.GetPrim()).AddTranslateOp().Set(worldCenter)
 

  # Initialize data structures.
  #   - strokes are Unity meshes (or Tilt Brush batches).
  #   - substrokes are the individual brush strokes within a single mesh.
  #   - activeSubstrokes are sub-strokes currently in-flight.
  #   - completeSubstrokes are sub-strokes that are done animating.
  strokes = MakeStrokes(stage)
  substrokes = MakeSubstrokes(strokes)
  activeStrokes = set()
  activeSubstrokes = set()
  completeSubstrokes = set() 

  # Compute step sizes based on target animation length.
  dRadius = (maxRadius - radius) / float(numFrames) / 1.5 
  dHeight = (maxHeight - minHeight) / float(numFrames)

  # Set USD animation start/end times.
  stage.SetStartTimeCode(time)
  stage.SetEndTimeCode(numFrames)

  # Zero out stroke opacities
  for s in strokes:
    s.Save(time)

  # Main animation loop.
  for time in range(0, numFrames):
    print()
    print("Time:", time, height, radius, smoothstep(1.0, float(numFrames), time))
    curActive = 0
    
    if len(activeStrokes) < maxActive:
      # On the final frame, increase activation volumes to "infinity" (and beyond ;)
      if time == numFrames - 1:
        height = 10000000
        radius = 10000000
      
      # Search for strokes to be activated.
      didAddStroke = 0
      for ss in substrokes:
        # Already animating, skip.
        if ss in activeSubstrokes:
          continue
        # Done animating, skip.
        if ss in completeSubstrokes:
          continue
        # Overloaded.
        if len(activeStrokes) >= maxActive:
          break
        # If this sub-stroke passes the filter, add it to the animating list.
        if activeFilter(ss.minPoint, radius):
          didAddStroke = 1
          activeSubstrokes.add(ss)
          activeStrokes.add(ss.stroke)        
          # Mark the stroke as dirty to save its initial state.
          ss.stroke.dirty = True
          ss.SetRadius(radius, time)
          print("+", end=' ')
      if not didAddStroke:
        # We didn't add any strokes, which means the radius needs to increase.
        # Grow the activation volumes (increase sphere size, raise floor plane height).
        height += dHeight 
        radius += dRadius * smoothstep(1.0, float(numFrames), time)



    # Update debug vis.
    debugSphere.GetRadiusAttr().Set(radius, time)

    # Call save on everything, but only dirty strokes will actually write data.
    # Save a key at the previous frame here so that when a stroke starts animating, when linearly
    # interpolated, it will not start animating from frame zero to the first key frame.
    #for s in strokes:
    #  s.Save(time - 1)

    # Update stroke animation.
    remove = []
    for ss in activeSubstrokes:
      print(".", end=' ')
      if not ss.Update(dRadius, smoothstep(1.0, float(numFrames), time)):
        if ss.indicesWritten != ss.indexCount:
          raise "Fail"
        remove.append(ss)
    
    # Remove all the completed strokes.
    for ss in remove:
      activeSubstrokes.remove(ss)
      completeSubstrokes.add(ss)

    # Save keyframes for the current time.
    for s in strokes:
      s.Save(time)

    # Rebuild the activeStrokes set.
    activeStrokes = set()
    for ss in activeSubstrokes:
      activeStrokes.add(ss.stroke)

  # Drainstop: we have leftover strokes that didn't finish animating within the target time, rather
  # than popping them, we let them finish animating and run over the target time.
  while len(activeSubstrokes) > 0:
    remove = []
    time += 1
    # Since we blew past the initial frame estimate, we also need to update the USD end time.
    stage.SetEndTimeCode(time)
    # Loop: update, remove, save, rinse, repeat.
    for ss in activeSubstrokes:
      if not ss.Update(dRadius, 2.0):
        if ss.indicesWritten != ss.indexCount:
          raise "Fail"
        remove.append(ss)
    for ss in remove:
      activeSubstrokes.remove(ss)
      completeSubstrokes.add(ss)
    for s in strokes:
      s.Save(time)
示例#14
0
# section 2
expected = ['proxyPrim', 'purpose', 'visibility', 'xformOpOrder']
assert xform.GetPropertyNames() == expected

expected = [
    'doubleSided', 'extent', 'orientation', 'primvars:displayColor',
    'primvars:displayOpacity', 'proxyPrim', 'purpose', 'radius', 'visibility',
    'xformOpOrder'
]
assert sphere.GetPropertyNames() == expected

# section 3
extentAttr = sphere.GetAttribute('extent')
expected = Vt.Vec3fArray([(-1, -1, -1), (1, 1, 1)])
assert extentAttr.Get() == expected

# section 4
radiusAttr = sphere.GetAttribute('radius')
radiusAttr.Set(2)
extentAttr.Set(extentAttr.Get() * 2)
print stage.GetRootLayer().ExportToString()

# section 5
from pxr import UsdGeom
sphereSchema = UsdGeom.Sphere(sphere)
color = sphereSchema.GetDisplayColorAttr()
color.Set([(0, 0, 1)])
print stage.GetRootLayer().ExportToString()
stage.GetRootLayer().Save()
示例#15
0
# language governing permissions and limitations under the Apache License.
#

from pxr import Usd, UsdGeom

# section 1
stage = Usd.Stage.Open("RefExample.usda")
assert ([x for x in stage.Traverse()] == [
    stage.GetPrimAtPath("/refSphere"),
    stage.GetPrimAtPath("/refSphere/world"),
    stage.GetPrimAtPath("/refSphere2"),
    stage.GetPrimAtPath("/refSphere2/world")
])

# section 2
assert ([x for x in stage.Traverse() if UsdGeom.Sphere(x)] == [
    stage.GetPrimAtPath("/refSphere/world"),
    stage.GetPrimAtPath("/refSphere2/world")
])

# section 3
treeIter = Usd.TreeIterator.PreAndPostVisit(stage.GetPseudoRoot())

treeIterExpectedResults = [(stage.GetPrimAtPath("/"), False),
                           (stage.GetPrimAtPath("/refSphere"), False),
                           (stage.GetPrimAtPath("/refSphere/world"), False),
                           (stage.GetPrimAtPath("/refSphere/world"), True),
                           (stage.GetPrimAtPath("/refSphere"), True),
                           (stage.GetPrimAtPath("/refSphere2"), False),
                           (stage.GetPrimAtPath("/refSphere2/world"), False),
                           (stage.GetPrimAtPath("/refSphere2/world"), True),