Beispiel #1
0
    def testInstancedGeom(self):
        """Tests that different shader bindings are correctly authored on
        instanced geometry."""
        worldPath = "/World" # Where collections are authored
        redMat = "/World/Looks/blinn1SG"
        redPaths = ["/World/redCube", "/World/redSphere"]
        blueMat = "/World/Looks/phong1SG"
        bluePaths = [
                "/World/blueCube", "/World/blueSphere", "/World/blueSphere2"]
        instanceMasters = [
                "/InstanceSources/World_redSphere_blueSphereMultiAssignShape",
                "/InstanceSources/World_blueCube_blueCubeShape"]

        for path in redPaths:
            prim = self._simpleStage.GetPrimAtPath(path)
            self.assertTrue(prim.IsInstance())
            bindingAPI = UsdShade.MaterialBindingAPI(prim)
            mat, rel = bindingAPI.ComputeBoundMaterial()
            self.assertEqual(mat.GetPath(), redMat)
            self.assertEqual(rel.GetPrim().GetPath(), worldPath)

        for path in bluePaths:
            prim = self._simpleStage.GetPrimAtPath(path)
            self.assertTrue(prim.IsInstance())
            bindingAPI = UsdShade.MaterialBindingAPI(prim)
            mat, rel = bindingAPI.ComputeBoundMaterial()
            self.assertEqual(mat.GetPath(), blueMat)
            self.assertEqual(rel.GetPrim().GetPath(), worldPath)

        for path in instanceMasters:
            prim = self._simpleStage.GetPrimAtPath(path)
            self.assertTrue(prim)
            self.assertFalse(
                    prim.HasRelationship(UsdShade.Tokens.materialBinding))
Beispiel #2
0
    def test_BlockingOnOver(self):
        stage = Usd.Stage.CreateInMemory()
        over = stage.OverridePrim('/World/over')
        look = UsdShade.Material.Define(stage, "/World/Material")
        self.assertTrue(look)
        gprim = stage.DefinePrim("/World/gprim")

        UsdShade.MaterialBindingAPI(over).UnbindDirectBinding()
        UsdShade.MaterialBindingAPI.Apply(gprim).Bind(look)
        # This will compose in gprim's binding, but should still be blocked
        over.GetInherits().AddInherit("/World/gprim")
        self.assertFalse(UsdShade.MaterialBindingAPI(over).ComputeBoundMaterial()[0])
Beispiel #3
0
    def testNestedInstancedGeom(self):
        """Tests that different shader bindings are correctly authored on
        instanced geometry within nested instances."""
        worldPath = "/World"  # Where collections are authored
        greenMat = "/World/Materials/blinn1SG"
        greenPaths = [
            "/World/SimpleInstance1/Shape",
            "/World/ComplexA/NestedA/Base1/BaseShape1",
            "/World/ComplexA/NestedB/Base1/BaseShape1",
            "/World/Extra/Base3/Shape",
            "/World/ComplexB/NestedA/Base1/BaseShape1",
            "/World/ComplexB/NestedB/Base1/BaseShape1"
        ]
        blueMat = "/World/Materials/blinn2SG"
        bluePaths = [
            "/World/SimpleInstance2/Shape",
            "/World/ComplexA/NestedA/Base2/BaseShape1",
            "/World/ComplexA/NestedB/Base2/BaseShape1",
            "/World/ComplexB/NestedA/Base2/BaseShape1",
            "/World/ComplexB/NestedB/Base2/BaseShape1"
        ]
        instanceMasters = [
            "/InstanceSources/World_ComplexA_NestedA_Base1_BaseShape1" +
            "/Shape",
            "/InstanceSources/World_SimpleInstance1_SimpleInstanceShape1" +
            "/Shape"
        ]

        for path in greenPaths:
            prim = self._nestedStage.GetPrimAtPath(path)
            self.assertTrue(prim, msg=path)
            self.assertTrue(prim.IsInstanceProxy())
            bindingAPI = UsdShade.MaterialBindingAPI(prim)
            mat, rel = bindingAPI.ComputeBoundMaterial()
            self.assertEqual(mat.GetPath(), greenMat)
            self.assertEqual(rel.GetPrim().GetPath(), worldPath)

        for path in bluePaths:
            prim = self._nestedStage.GetPrimAtPath(path)
            self.assertTrue(prim, msg=path)
            self.assertTrue(prim.IsInstanceProxy())
            bindingAPI = UsdShade.MaterialBindingAPI(prim)
            mat, rel = bindingAPI.ComputeBoundMaterial()
            self.assertEqual(mat.GetPath(), blueMat)
            self.assertEqual(rel.GetPrim().GetPath(), worldPath)

        for path in instanceMasters:
            prim = self._nestedStage.GetPrimAtPath(path)
            self.assertTrue(prim)
            self.assertFalse(
                prim.HasRelationship(UsdShade.Tokens.materialBinding))
Beispiel #4
0
    def test_Basic(self):
        s = Usd.Stage.CreateInMemory()
        rl = s.GetRootLayer()

        # set up so the weaker subtree binds gprim to look1, and
        # stronger subtree to look2
        lw1 = UsdShade.Material.Define(s, "/weaker/look1")
        lw2 = UsdShade.Material.Define(s, "/weaker/look2")
        gpw = s.OverridePrim("/weaker/gprim")
        lw1.Bind(gpw)
        self.assertEqual(
            UsdShade.MaterialBindingAPI(
                gpw).GetDirectBindingRel().GetTargets(),
            [Sdf.Path("/weaker/look1")])

        ls1 = UsdShade.Material.Define(s, "/stronger/look1")
        ls2 = UsdShade.Material.Define(s, "/stronger/look2")
        gps = s.OverridePrim("/stronger/gprim")
        ls2.Bind(gps)
        self.assertEqual(
            UsdShade.MaterialBindingAPI(
                gps).GetDirectBindingRel().GetTargets(),
            [Sdf.Path("/stronger/look2")])

        cr = s.OverridePrim("/composed")

        cr.GetReferences().AddReference(rl.identifier, "/stronger")
        cr.GetReferences().AddReference(rl.identifier, "/weaker")

        gpc = s.GetPrimAtPath("/composed/gprim")
        lb = UsdShade.MaterialBindingAPI(gpc).GetDirectBindingRel()

        # validate we get look2, the stronger binding
        self.assertEqual(lb.GetTargets(), [Sdf.Path("/composed/look2")])

        # upon unbinding *in* the stronger site (i.e. "/stronger/gprim"),
        # we should still be unbound in the fully composed view
        UsdShade.MaterialBindingAPI(gps).UnbindAllBindings()
        self.assertEqual(lb.GetTargets(), [])

        # but *clearing* the target on the referenced prim should allow
        # the weaker binding to shine through
        UsdShade.MaterialBindingAPI(gps).GetDirectBindingRel().ClearTargets(
            True)

        print rl.ExportToString()

        self.assertEqual(lb.GetTargets(), [Sdf.Path("/composed/look1")])
def bindMaterial(stage, geopath, matpath):
    geo = stage.GetPrimAtPath(geopath)
    if not geo: # if prim is not valid, let's create a new over prim
        geo = stage.OverridePrim(geopath)
    
    material = UsdShade.Material.Get(stage, matpath)
    UsdShade.MaterialBindingAPI(geo).Bind(material)
Beispiel #6
0
 def _GetBoundMaterial(self, prim, materialPurpose=UsdShade.Tokens.allPurpose):
     (material, bindingRel) = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
             materialPurpose)
     # Whenever we get a valid material, there must be a valid bindingRel.
     if material:
         self.assertTrue(bindingRel)
     return material
Beispiel #7
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())
Beispiel #8
0
def _assign_materials(obj_prim, obj, usd_mesh):
    usd_mat = None
    if obj.material_slots and obj.material_slots[0].material:
        usd_mat = material.sync(obj_prim, obj.material_slots[0].material, obj)

    if usd_mat:
        UsdShade.MaterialBindingAPI(usd_mesh).Bind(usd_mat)
Beispiel #9
0
def add_light(app, params, path_for_objects, stage, xsi_light, root_path):  # here me add only basic parameters, all other will be defined in the material
    imp.reload(materials)
    # basic transform
    usd_xform, ref_stage, ref_stage_asset = add_xform(app, params, path_for_objects, True, stage, xsi_light, root_path)
    # get the type of the light
    xsi_light_type = xsi_light.Parameters("Type").Value
    usd_light = None
    xsi_geom_type = -1
    if xsi_light_type == 0:  # point (also area light)
        xsi_is_area = xsi_light.Parameters("LightArea").Value
        xsi_geom_type = xsi_light.Parameters("LightAreaGeom").Value
        if xsi_is_area:
            if xsi_geom_type == 1:  # rectangular
                usd_light = UsdLux.RectLight.Define(ref_stage, str(usd_xform.GetPath()) + "/" + xsi_light.Name)
            elif xsi_geom_type == 2:  # disc
                usd_light = UsdLux.DiskLight.Define(ref_stage, str(usd_xform.GetPath()) + "/" + xsi_light.Name)
            elif xsi_geom_type == 3:  # sphere
                usd_light = UsdLux.SphereLight.Define(ref_stage, str(usd_xform.GetPath()) + "/" + xsi_light.Name)
            elif xsi_geom_type == 4:  # cylinder
                usd_light = UsdLux.CylinderLight.Define(ref_stage, str(usd_xform.GetPath()) + "/" + xsi_light.Name)
    elif xsi_light_type == 1:  # infinite
        usd_light = UsdLux.DistantLight.Define(ref_stage, str(usd_xform.GetPath()) + "/" + xsi_light.Name)
    elif xsi_light_type == 2:  # spot
        usd_light = UsdLux.DistantLight.Define(ref_stage, str(usd_xform.GetPath()) + "/" + xsi_light.Name)

    # export light shader to material
    materials_opt = params.get("materials", None)
    if materials_opt is not None:
        is_materials = materials_opt.get("is_materials", True)
        if is_materials:
            usd_material = UsdShade.Material.Define(ref_stage, str(usd_xform.GetPath()) + "/Shader")
            xsi_root_shader = xsi_light.Parameters("LightShader")
            if xsi_root_shader is not None:
                materials.set_material_complete(xsi_root_shader, ref_stage, usd_material)
            # bind shader to the light
            UsdShade.MaterialBindingAPI(usd_light).Bind(usd_material)

    if usd_light is not None:
        # set neutral color
        usd_light.CreateColorAttr().Set((1.0, 1.0, 1.0))

        # diffuse and specular coefficients
        xsi_is_diffuse = xsi_light.Parameters("DiffuseContribution").Value
        xsi_is_specular = xsi_light.Parameters("SpecularContribution").Value
        usd_light.CreateDiffuseAttr().Set(1.0 if xsi_is_diffuse else 0.0)
        usd_light.CreateSpecularAttr().Set(1.0 if xsi_is_specular else 0.0)

        # default intensity = 1.0
        usd_light.CreateIntensityAttr().Set(1.0)

        # set animated parameters
        opt_animation = params["animation"]
        if opt_animation is None:
            set_light_at_frame(xsi_light, xsi_light_type, xsi_geom_type, usd_light)
        if opt_animation is not None:
            for frame in range(opt_animation[0], opt_animation[1] + 1):
                set_light_at_frame(xsi_light, xsi_light_type, xsi_geom_type, usd_light, frame)
    ref_stage.Save()

    return stage.GetPrimAtPath(root_path + str(usd_xform.GetPath()))
def _updateMeshBinding(path, appController):
    s = appController._dataModel.stage
    l = s.GetSessionLayer()
    s.SetEditTarget(l)

    mesh = s.GetPrimAtPath('/Scene/Geom/Plane')
    material = UsdShade.Material(s.GetPrimAtPath(path))
    UsdShade.MaterialBindingAPI(mesh).Bind(material)
Beispiel #11
0
def _addModel(model, prototypesPrimPath, stage):
    # the name must be a full path without the . so just strip .usd from name
    name = model[0:model.find('.')]
    primPath = prototypesPrimPath.AppendChild(name)
    treeRefPrim = stage.DefinePrim(primPath)
    refs = treeRefPrim.GetReferences()
    refs.AddReference(model)

    path = treeRefPrim.GetPath()

    leaves = '/World/TreePointInstance/prototypes/{}/Leaves'.format(name)
    tree = UsdGeom.Mesh(stage.GetPrimAtPath(leaves))
    tree.CreateDisplayColorAttr([(0.0, 0.8, 0.0)])

    material = UsdShade.Material.Define(stage,
                                        '/World/Leaf{}Material'.format(name))
    pbrShader = UsdShade.Shader.Define(
        stage, '/World/Leaf{}Material/LeafShader'.format(name))
    pbrShader.CreateIdAttr("UsdPreviewSurface")
    pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(
        (0.0, 0.8, 0.0))

    pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.2)
    pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.1)
    material.CreateSurfaceOutput().ConnectToSource(pbrShader, "surface")
    UsdShade.MaterialBindingAPI(tree).Bind(material)

    trunk = '/World/TreePointInstance/prototypes/{}/Trunk'.format(name)
    tree = UsdGeom.Mesh(stage.GetPrimAtPath(trunk))
    tree.CreateDisplayColorAttr([(0.5, 0.2, 0.0)])

    material = UsdShade.Material.Define(stage,
                                        '/World/Trunk{}Material'.format(name))
    pbrShader = UsdShade.Shader.Define(
        stage, '/World/Trunk{}Material/TrunkShader'.format(name))
    pbrShader.CreateIdAttr("UsdPreviewSurface")
    pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(
        (0.5, 0.2, 0.0))
    pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.2)
    pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.1)
    material.CreateSurfaceOutput().ConnectToSource(pbrShader, "surface")
    UsdShade.MaterialBindingAPI(tree).Bind(material)

    # return the actual path to the model which will be added to the instancer
    return path
Beispiel #12
0
 def computeBoundMaterial(self, prim, purpose):
     """Compute the material that the prim is bound to, for the given value
        of material purpose. 
     """
     if not isinstance(prim, Usd.Prim):
         raise ValueError("Expected Usd.Prim object, got: {}".format(
             repr(prim)))
     # We don't use the binding cache yet since it isn't exposed to python.
     return UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(purpose)
Beispiel #13
0
def GetMtlxBoundPrims(usdStage, originalMtlxMaterialPath):
    prims = []
    for prim in usdStage.Traverse():
        for purpose in UsdShade.MaterialBindingAPI.GetMaterialPurposes():
            (material, bindingRel) = UsdShade.MaterialBindingAPI(prim).\
                                        ComputeBoundMaterial(purpose)
            if originalMtlxMaterialPath == material.GetPath():
                prims.append((prim, bindingRel))
    return prims
    def testExportUVSetMappings(self):
        '''
        Tests that exporting multiple Maya planes with varying UV mappings
        setups results in USD data with material specializations:
        '''
        expected = [
            ("/pPlane1", "/blinn1SG_map1_map1_map1", "map1", "map1", "map1"),
            ("/pPlane2", "/blinn1SG", "st1", "st1", "st1"),
            ("/pPlane3", "/blinn1SG", "st1", "st1", "st1"),
            ("/pPlane4", "/blinn1SG_st2_st2_st2", "st2", "st2", "st2"),
            ("/pPlane5", "/blinn1SG_p5a_p5b_p5c", "p5a", "p5b", "p5c"),
            ("/pPlane6", "/blinn1SG_p62_p63_p61", "p62", "p63", "p61"),
            ("/pPlane7", "/blinn1SG_p7r_p7p_p7q", "p7r", "p7p", "p7q"),
        ]

        if mayaUsdLib.WriteUtil.WriteMap1AsST():
            # map1 renaming has almost no impact here. Getting better results
            # for that test would require something more radical, possibly
            #    uvSet[0] is always renamed to "st"
            # Which would reuse a single material for the first four planes.
            #
            # As currently implemented, the renaming affects only one material:
            expected[0] = ("/pPlane1", "/blinn1SG_st_st_st", "st", "st", "st")

        for mesh_name, mat_name, f1_name, f2_name, f3_name in expected:
            plane_prim = self._stage.GetPrimAtPath(mesh_name)
            binding_api = UsdShade.MaterialBindingAPI(plane_prim)
            mat = binding_api.ComputeBoundMaterial()[0]
            self.assertEqual(mat.GetPath(), mat_name)

            self.assertEqual(
                mat.GetInput("file1:varname").GetAttr().Get(), f1_name)
            self.assertEqual(
                mat.GetInput("file2:varname").GetAttr().Get(), f2_name)
            self.assertEqual(
                mat.GetInput("file3:varname").GetAttr().Get(), f3_name)

        # Initial code had a bug where a material with no UV mappings would
        # specialize itself. Make sure it stays fixed:
        plane_prim = self._stage.GetPrimAtPath("/pPlane8")
        binding_api = UsdShade.MaterialBindingAPI(plane_prim)
        mat = binding_api.ComputeBoundMaterial()[0]
        self.assertEqual(mat.GetPath(), "/pPlane8/Materials/blinn2SG")
        self.assertFalse(mat.GetPrim().HasAuthoredSpecializes())
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
Beispiel #16
0
    def testInstancedGeom_Subsets(self):
        """Tests that instanced geom with materials assigned to subsets are
        automatically de-instanced."""
        multiAssignPrim = self._simpleStage.GetPrimAtPath(
            "/World/blueSphereMultiAssign")
        self.assertFalse(multiAssignPrim.IsInstanceable())

        shape = multiAssignPrim.GetChild("Shape")
        self.assertFalse(shape.IsInstance())

        subset1 = shape.GetChild("initialShadingGroup")
        self.assertTrue(subset1)
        mat, _ = UsdShade.MaterialBindingAPI(subset1).ComputeBoundMaterial()
        self.assertEqual(mat.GetPath(), "/World/Materials/initialShadingGroup")

        subset2 = shape.GetChild("blinn1SG")
        self.assertTrue(subset2)
        mat, _ = UsdShade.MaterialBindingAPI(subset2).ComputeBoundMaterial()
        self.assertEqual(mat.GetPath(), "/World/Materials/blinn1SG")
Beispiel #17
0
def add_material(materials_opt, xsi_mat, stage, stage_asset_path, usd_xform, usd_prim, is_bind=True):  # do the same in prim_mesh
    material_asset_path = materials_opt.get("asset_path", None)
    if material_asset_path is not None:
        rel_material_path = utils.transform_path_to_relative(stage_asset_path, material_asset_path)
        mat_name = utils.buil_material_name(xsi_mat)
        mat_ref = stage.DefinePrim(str(usd_xform.GetPath()) + "/" + mat_name)
        mat_ref.GetReferences().AddReference(rel_material_path, "/" + xsi_mat.Library.Name + "/" + xsi_mat.Name)
        # bind the main material
        if is_bind:
            UsdShade.MaterialBindingAPI(usd_prim).Bind(UsdShade.Material(stage.GetPrimAtPath(mat_ref.GetPath())))
Beispiel #18
0
def sync(objects_prim, obj_data: ObjectData, **kwargs):
    """ sync the object and any data attached """
    log("sync", obj_data.object, obj_data.instance_id)

    stage = objects_prim.GetStage()
    xform = UsdGeom.Xform.Define(
        stage,
        objects_prim.GetPath().AppendChild(obj_data.sdf_name))
    obj_prim = xform.GetPrim()

    # setting transform
    xform.MakeMatrixXform().Set(Gf.Matrix4d(obj_data.transform))

    obj = obj_data.object

    if obj_data.is_particle:
        orig_obj_path = objects_prim.GetPath().AppendChild(
            sdf_name(obj.original))
        usd_mesh = UsdGeom.Mesh.Define(
            stage,
            obj_prim.GetPath().AppendChild(sdf_name(obj.original)))
        mesh_prim = stage.DefinePrim(
            orig_obj_path.AppendChild(sdf_name(obj.data)), 'Mesh')
        usd_mesh.GetPrim().GetReferences().AddInternalReference(
            mesh_prim.GetPath())

        if obj.active_material:
            material_prim = stage.DefinePrim(
                orig_obj_path.AppendChild(
                    material.sdf_name(obj.active_material)), 'Material')

            usd_material = UsdShade.Material.Get(stage,
                                                 material_prim.GetPath())
            UsdShade.MaterialBindingAPI(usd_mesh).Bind(usd_material)

        return

    if obj.type == 'MESH':
        if obj.mode == 'OBJECT':
            # if in edit mode use to_mesh
            mesh.sync(obj_prim, obj, **kwargs)
        else:
            to_mesh.sync(obj_prim, obj, **kwargs)

    elif obj.type == 'LIGHT':
        light.sync(obj_prim, obj, **kwargs)

    elif obj.type == 'CAMERA':
        camera.sync(obj_prim, obj, **kwargs)

    elif obj.type in ('EMPTY', 'ARMATURE'):
        pass

    else:
        to_mesh.sync(obj_prim, obj, **kwargs)
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))
Beispiel #20
0
    def testUninstancedGeom(self):
        """Tests a basic case of non-instanced geometry with bindings."""
        worldPath = "/World" # Where collections are authored
        redMat = self._simpleStage.GetPrimAtPath("/World/Looks/blinn1SG")
        uninstancedPrim = self._simpleStage.GetPrimAtPath("/World/notInstanced")

        self.assertFalse(uninstancedPrim.IsInstance())
        bindingAPI = UsdShade.MaterialBindingAPI(uninstancedPrim)
        mat, rel = bindingAPI.ComputeBoundMaterial()
        self.assertEqual(mat.GetPrim(), redMat)
        self.assertEqual(rel.GetPrim().GetPath(), worldPath)
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()
Beispiel #22
0
    def __init__(self, appController, item):
        PrimContextMenuItem.__init__(self, appController, item)
        from pxr import UsdShade 

        self._boundFullMaterial = None
        self._bindingRel = None
        for p in self._selectionDataModel.getPrims():
            (self._boundFullMaterial, self._bindingRel) = \
                UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial(
                    UsdShade.Tokens.full)
            if self._boundFullMaterial:
                break
Beispiel #23
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()
    def testExportPxrRisShading(self):
        """
        Tests that exporting a Maya mesh with a simple Maya shading setup
        results in the correct shading on the USD mesh.
        """
        cubePrim = self._stage.GetPrimAtPath('/MarbleCube/Geom/Cube')
        self.assertTrue(cubePrim)

        # Validate the Material prim bound to the Mesh prim.
        materialBindingAPI = UsdShade.MaterialBindingAPI(cubePrim)
        material = materialBindingAPI.ComputeBoundMaterial()[0]
        self.assertTrue(material)
        materialPath = material.GetPath().pathString
        self.assertEqual(materialPath, '/MarbleCube/Materials/MarbleCubeSG')

        if Usd.GetVersion() >= (0, 21, 5):
            # For USD 21.05 and later, GetInputs() and GetOutputs() take an
            # "onlyAuthored" argument that is True by default, so in that case
            # we expect only one output on the material for the "surface"
            # terminal in the "ri" renderContext that the export should have
            # authored.
            expectedNumOutputs = 1
        else:
            # Otherwise prior to USD 21.05, GetInputs() and GetOutputs() did
            # not take any arguments and always included the built-in
            # terminals for the universal renderContext as well as any other
            # authored terminals.
            expectedNumOutputs = 4

        # Validate the surface shader that is connected to the material.
        materialOutputs = material.GetOutputs()
        self.assertEqual(len(materialOutputs), expectedNumOutputs)
        print(self._stage.ExportToString())
        materialOutput = material.GetOutput('ri:surface')
        (connectableAPI, outputName, outputType) = materialOutput.GetConnectedSource()
        self.assertEqual(outputName, 'out')
        shader = UsdShade.Shader(connectableAPI)
        self.assertTrue(shader)

        shaderId = shader.GetIdAttr().Get()
        self.assertEqual(shaderId, 'PxrMayaMarble')

        # Validate the connected input on the surface shader.
        shaderInput = shader.GetInput('placementMatrix')
        self.assertTrue(shaderInput)

        (connectableAPI, outputName, outputType) = shaderInput.GetConnectedSource()
        self.assertEqual(outputName, 'worldInverseMatrix')
        shader = UsdShade.Shader(connectableAPI)
        self.assertTrue(shader)

        shaderId = shader.GetIdAttr().Get()
        self.assertEqual(shaderId, 'PxrMayaPlacement3d')
Beispiel #25
0
def sync_update_all(root_prim, mat: bpy.types.Material):
    sdf_mat_name = sdf_name(mat)
    mat_prims = []
    for obj_prim in root_prim.GetAllChildren():
        mat_prim = obj_prim.GetChild(sdf_mat_name)
        if mat_prim:
            mat_prims.append(mat_prim)

    if not mat_prims:
        return None

    doc = mat.hdusd.export(None)
    if not doc:
        # removing rpr_materialx_node in all material_prims
        return None

    surfacematerial = next(node for node in doc.getNodes()
                           if node.getCategory() == 'surfacematerial')

    stage = root_prim.GetStage()
    mx_file = utils.get_temp_file(
        ".mtlx",
        f'{mat.name}{mat.hdusd.mx_node_tree.name if mat.hdusd.mx_node_tree else ""}'
    )
    mx.writeToXmlFile(doc, str(mx_file))

    for mat_prim in mat_prims:
        mat_prim.GetReferences().ClearReferences()
        mat_prim.GetReferences().AddReference(f"./{mx_file.name}",
                                              "/MaterialX")

        # apply new bind if shader switched to MaterialX or vice versa
        mesh_prim = next((prim for prim in mat_prim.GetParent().GetChildren()
                          if prim.GetTypeName() == 'Mesh'), None)
        if not mesh_prim:
            return None

        bindings = UsdShade.MaterialBindingAPI(mesh_prim)
        rel_bind = bindings.GetDirectBindingRel()

        sdf_path = mat_prim.GetPath().AppendChild('Materials').AppendChild(
            surfacematerial.getName())
        sdf_path_old = next((target for target in rel_bind.GetTargets()), None)

        # check if bind path is changed
        if not sdf_path_old or sdf_path == sdf_path_old:
            return None

        usd_mat = UsdShade.Material.Define(stage, sdf_path)
        bindings.UnbindAllBindings()
        bindings.Bind(usd_mat)
    def testExportRfMShaders(self):
        '''
        Tests that exporting a Maya mesh with a simple Maya shading setup
        results in the correct shading on the USD mesh.
        '''
        cubePrim = self._stage.GetPrimAtPath('/MarbleCube/Geom/Cube')
        self.assertTrue(cubePrim)

        # Validate the Material prim bound to the Mesh prim.
        self.assertTrue(cubePrim.HasAPI(UsdShade.MaterialBindingAPI))
        materialBindingAPI = UsdShade.MaterialBindingAPI(cubePrim)
        material = materialBindingAPI.ComputeBoundMaterial()[0]
        self.assertTrue(material)
        materialPath = material.GetPath().pathString
        self.assertEqual(materialPath, '/MarbleCube/Materials/MarbleCubeSG')

        # We expect four outputs on the material, the three built-in terminals
        # for the universal renderContext, and a fourth for the "surface"
        # terminal in the "ri" renderContext that the export should have
        # authored.
        materialOutputs = material.GetOutputs()
        self.assertEqual(len(materialOutputs), 4)

        # Validate the lambert surface shader that is connected to the material.
        materialOutput = material.GetOutput('ri:surface')
        (connectableAPI, outputName, outputType) = materialOutput.GetConnectedSource()
        self.assertEqual(outputName, UsdShade.Tokens.surface)
        shader = UsdShade.Shader(connectableAPI)
        self.assertTrue(shader)
        shaderId = shader.GetIdAttr().Get()
        self.assertEqual(shaderId, 'PxrMayaLambert')

        # Validate the connected input on the lambert surface shader.
        shaderInput = shader.GetInput('color')
        self.assertTrue(shaderInput)
        (connectableAPI, outputName, outputType) = shaderInput.GetConnectedSource()
        self.assertEqual(outputName, 'outColor')
        shader = UsdShade.Shader(connectableAPI)
        self.assertTrue(shader)
        shaderId = shader.GetIdAttr().Get()
        self.assertEqual(shaderId, 'PxrMayaMarble')

        # Validate the connected input on the marble shader.
        shaderInput = shader.GetInput('placementMatrix')
        self.assertTrue(shaderInput)
        (connectableAPI, outputName, outputType) = shaderInput.GetConnectedSource()
        self.assertEqual(outputName, 'worldInverseMatrix')
        shader = UsdShade.Shader(connectableAPI)
        self.assertTrue(shader)
        shaderId = shader.GetIdAttr().Get()
        self.assertEqual(shaderId, 'PxrMayaPlacement3d')
    def testExportDisplacementShaders(self):
        '''
        Tests that exporting multiple Maya planes with varying displacement
        setups results in the expected USD data:
        '''

        textures = ["RGBA", "RGB", "MonoA", "Mono"]
        channels = ["r", "g", "b", "a", "a"]

        for suffix in range(1, 21):
            image = textures[int((suffix - 1) / 5)]
            channel = channels[(suffix - 1) % 5]

            mesh_prim = self._stage.GetPrimAtPath('/pPlane%i' % suffix)
            self.assertTrue(mesh_prim)

            # Validate the Material prim bound to the Mesh prim.
            self.assertTrue(mesh_prim.HasAPI(UsdShade.MaterialBindingAPI))
            mat_binding = UsdShade.MaterialBindingAPI(mesh_prim)
            material = mat_binding.ComputeBoundMaterial()[0]
            self.assertTrue(material)
            material_path = material.GetPath().pathString
            self.assertEqual(
                material_path,
                '/pPlane%i/Materials/blinn%iSG' % (suffix, suffix))

            self.assertTrue(material.ComputeSurfaceSource())
            self.assertTrue(material.ComputeDisplacementSource())

            # Validate the shader that is connected to the material.
            mat_out = material.GetOutput(UsdShade.Tokens.displacement)
            (connect_api, out_name, _) = mat_out.GetConnectedSource()
            self.assertEqual(out_name, UsdShade.Tokens.displacement)
            shader = UsdShade.Shader(connect_api)
            self.assertTrue(shader)
            shader_id = shader.GetIdAttr().Get()
            self.assertEqual(shader_id, 'UsdPreviewSurface')

            # Validate the connected input on the displacement shader.
            in_displacement = shader.GetInput('displacement')
            self.assertTrue(in_displacement)
            (connect_api, out_name, _) = in_displacement.GetConnectedSource()
            self.assertEqual(out_name, channel)
            shader = UsdShade.Shader(connect_api)
            self.assertTrue(shader)
            shader_id = shader.GetIdAttr().Get()
            self.assertEqual(shader_id, 'UsdUVTexture')
            filename = shader.GetInput("file")
            self.assertTrue(filename.Get().path.endswith("/%s.png" % image))
Beispiel #28
0
def _bugStep1(s):
    # Make a Material that contains a UsdPreviewSurface
    material = UsdShade.Material.Define(s, '/Scene/Looks/NewMaterial')

    # Create the surface.
    pbrShader = UsdShade.Shader.Define(s, '/Scene/Looks/NewMaterial/PbrPreview')
    pbrShader.CreateIdAttr("UsdPreviewSurface")
    pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.0)
    pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
    pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((0.0, 0.0, 1.0))
    material.CreateSurfaceOutput().ConnectToSource(pbrShader, "surface")

    # Now bind the Material to the card
    mesh = s.GetPrimAtPath('/Scene/Geom/Plane')
    UsdShade.MaterialBindingAPI(mesh).Bind(material)
def _assign_materials(obj_prim, obj, usd_mesh):
    if not obj.material_slots:
        return

    mat = obj.material_slots[0].material
    if not mat:
        return

    stage = obj_prim.GetStage()
    root_prim = obj_prim.GetParent().GetParent()
    materials_prim = stage.DefinePrim(f"{root_prim.GetPath()}/materials")

    usd_mat = material.sync(materials_prim, mat, obj=obj)
    if usd_mat:
        UsdShade.MaterialBindingAPI(usd_mesh).Bind(usd_mat)
Beispiel #30
0
    def test_GetBoundMaterial(self):
        stage = Usd.Stage.CreateInMemory()
        look = UsdShade.Material.Define(stage, "/World/Material")
        self.assertTrue(look)
        gprim = stage.OverridePrim("/World/Gprim")
        self.assertTrue(gprim)

        gprimBindingAPI = UsdShade.MaterialBindingAPI(gprim)
        self.assertFalse(gprimBindingAPI.ComputeBoundMaterial()[0])
        gprimBindingAPI.Bind(look)
        (mat, rel) = gprimBindingAPI.ComputeBoundMaterial()
        self.assertTrue(mat and rel)

        # Now add one more target to mess things up
        rel = gprimBindingAPI.GetDirectBindingRel()
        rel.AddTarget(Sdf.Path("/World"))
        self.assertFalse(gprimBindingAPI.ComputeBoundMaterial()[0])