Sort materials by typeΒΆ

This script example sorts database's materials into material groups according to their type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from p3dsdk import *

with CurrentP3DSession(fallback_port=33900) as p3d:
    # First create the groups by material type
    material_type_groups = {
        StandardMaterial.__name__:   p3d.data.create_material_group("Standard"),
        MultiLayerMaterial.__name__: p3d.data.create_material_group("Multi Layer"),
        MirrorMaterial.__name__:     p3d.data.create_material_group("Mirror"),
        MatteMaterial.__name__:      p3d.data.create_material_group("Matte"),
        EnvMaterial.__name__:        p3d.data.create_material_group("Environment"),
        AxfCPA2Material.__name__:    p3d.data.create_material_group("AxF CPA2"),
        SeamMaterial.__name__:       p3d.data.create_material_group("Seam"),
        Material.__name__:           p3d.data.create_material_group("Other"),
    }

    # Sort materials
    has_materials = False
    groups = p3d.data.list_material_groups()
    for group in groups:
        materials = group.list_materials()
        has_materials = has_materials or len(materials) > 0
        for material in materials:
            material.group = material_type_groups[material.__class__.__name__]

    # Clean empty groups
    if has_materials:
        groups = p3d.data.list_material_groups()
        for group in groups:
            if len(group.list_materials()) == 0:
                group.remove()

Download example

This example uses some advanced Python features.

The __name__ attribute gets the name of the class as string, that is StandardMaterial.__name__ is equivalent to "StandardMaterial". This is made so the script will throw an error if the SDK API changes (for example if StandardMaterial does not exist anymore or is renamed).

The __class__ attribute gets the type of the object. In this case it is used to get the type of the material.

The script is composed of 3 parts.

Create the new material groups

A Python dictionary is created to associate a material type name to its corresponding group.

The create_material_group() method is used to create new material groups. The method returns the new MaterialGroup.

Sort the materials according to their type

First we loop through all material groups. For each group, we get the list of materials it contains.

For each material, we assign a new group (by using its group attribute) by querying material_type_groups for the group corresponding to the material type.

The has_materials variable will be used in the cleanup part.

Clean empty groups

The cleanup is done only if has_material is True. Otherwise, it would delete all the groups, which is forbidden as at least one group must exist.

We loop through the groups and if its list of materials is empty, we delete it.