Skip to content

load_image_shader

LoadImageShaderEditor

Bases: BlenderLoader

Load a product to the Shader Editor for selected mesh in Blender.

Source code in client/ayon_blender/plugins/load/load_image_shader.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
class LoadImageShaderEditor(plugin.BlenderLoader):
    """Load a product to the Shader Editor for selected mesh in Blender."""

    product_types = {"render", "image", "plate"}
    representations = {"*"}

    label = "Load to Shader Editor"
    icon = "code-fork"
    color = "orange"

    CREATE_NEW = "create_new"

    @classmethod
    def get_options(cls, contexts):

        selected_object = cls.get_selected_object()
        if not selected_object:
            return []

        slot_materials = [
            (i, material) for i, material
            in enumerate(selected_object.data.materials)
            # Ignore empty material slots
            if material is not None
        ]
        items = [
            {"value": i, "label": material.name}
            for i, material in slot_materials
        ]
        items.append(
            {"value": cls.CREATE_NEW, "label": "New Material"}
        )
        return [
            EnumDef(
                "material_slot",
                label="Material Slot",
                items=items,
                default=items[0]["value"]
            )
        ]

    @staticmethod
    def get_selected_object():
        selected_objects = lib.get_selection()
        for obj in selected_objects:
            if obj.type in {'MESH', 'SURFACE'}:
                return obj

    def process_asset(
            self, context: dict, name: str, namespace: Optional[str] = None,
            options: Optional[Dict] = None
    ) -> Optional[List]:
        """
        Arguments:
            name: Use pre-defined name
            namespace: Use pre-defined namespace
            context: Full parenthood of representation to load
            options: Additional settings dictionary
        """

        # In the current objects selection, I get the first one that is a
        # MESH or a SURFACE.
        # TODO: We tend to avoid acting on 'user selection' so that the loaders
        #  can run completely automatically, without user interaction or popups
        #  So we may want to investigate different approaches to this.
        cur_obj = self.get_selected_object()
        if cur_obj is None:
            self.log.info(
                "Load in Shader Editor: The process (image load) was "
                "cancelled, because no object (mesh or surface) was selected "
                "in Blender.")
            self.display_warning(
                "You did not select any object in Blender.\n"
                "So this process is cancelled.")
            return []

        # If the currently selected object has one or more materials, let's use
        # the first one. If it has no material, let's create a new one.
        material_slot = options.get("material_slot")
        if material_slot is None:
            # Get first slot with a material
            material_slot = next(
                (
                    i for i, material in enumerate(cur_obj.data.materials)
                    # Ignore empty material slots
                    if material is not None
                ), None
            )
        if material_slot is None or material_slot == self.CREATE_NEW:
            # Create a new material
            current_material = bpy.data.materials.new(name="material")
            current_material.use_nodes = True
            cur_obj.data.materials.append(current_material)
        else:
            current_material = cur_obj.data.materials[material_slot]
            current_material.use_nodes = True

        nodes = current_material.node_tree.nodes

        # Create an "Image Texture" node. It will appear in the Shader Editor
        # (which appears when you are in the "Shading" workspace tab), when you
        # select the "Object" filter (among this choice: Object, World,
        # Line Style).
        image_texture_node = nodes.new(type='ShaderNodeTexImage')

        # Load the image in data
        path = self.filepath_from_context(context)
        image = bpy.data.images.load(path)
        image_texture_node.image = image

        self.set_colorspace(context, image_texture_node)

        data = {
            "schema": "openpype:container-2.0",
            "id": AVALON_CONTAINER_ID,
            "name": name,
            "namespace": namespace or '',
            "loader": str(self.__class__.__name__),
            "representation": context["representation"]["id"],
        }
        lib.imprint(image_texture_node, data)

        return [image_texture_node]

    def exec_remove(self, container: Dict) -> bool:
        """Remove the Image Texture node."""

        image_texture_node: bpy.types.ShaderNodeTexImage = container["node"]
        image: Optional[bpy.types.Image] = image_texture_node.image

        # Delete the node
        image_texture_node.id_data.nodes.remove(image_texture_node)

        # Delete the image if it remains unused
        self.remove_image_if_unused(image)

        return True

    def exec_update(self, container: Dict, context: Dict):
        """Update the Image Texture node to new context version."""

        path = self.filepath_from_context(context)
        image_texture_node: bpy.types.ShaderNodeTexImage = container["node"]

        old_image: Optional[bpy.types.Image] = image_texture_node.image

        new_image = bpy.data.images.load(path)
        image_texture_node.image = new_image

        self.set_colorspace(context, image_texture_node)
        self.remove_image_if_unused(old_image)

        # Update representation id
        lib.imprint(image_texture_node, {
            "representation": context["representation"]["id"]
        })

    def set_colorspace(
            self,
            context: dict,
            image_texture_node: bpy.types.ShaderNodeTexImage
    ):
        """
        Set colorspace if representation has colorspace data.
        """

        image = image_texture_node.image
        representation: dict = context["representation"]

        colorspace_data = representation.get("data", {}).get(
            "colorspaceData", {})
        if colorspace_data:
            colorspace: str = colorspace_data["colorspace"]
            if colorspace:
                image.colorspace_settings.name = colorspace

    def remove_image_if_unused(self, image: bpy.types.Image):
        if image and not image.users:
            self.log.debug("Removing unused image: %s", image.name)
            bpy.data.images.remove(image)

    def display_warning(self, message):
        loader_gui_window = host_tools.get_tool_by_name("loader")

        QtWidgets.QMessageBox.warning(
            loader_gui_window,
            "Warning",
            message,
            buttons=QtWidgets.QMessageBox.Ok,
            defaultButton=QtWidgets.QMessageBox.Ok)

exec_remove(container)

Remove the Image Texture node.

Source code in client/ayon_blender/plugins/load/load_image_shader.py
136
137
138
139
140
141
142
143
144
145
146
147
148
def exec_remove(self, container: Dict) -> bool:
    """Remove the Image Texture node."""

    image_texture_node: bpy.types.ShaderNodeTexImage = container["node"]
    image: Optional[bpy.types.Image] = image_texture_node.image

    # Delete the node
    image_texture_node.id_data.nodes.remove(image_texture_node)

    # Delete the image if it remains unused
    self.remove_image_if_unused(image)

    return True

exec_update(container, context)

Update the Image Texture node to new context version.

Source code in client/ayon_blender/plugins/load/load_image_shader.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def exec_update(self, container: Dict, context: Dict):
    """Update the Image Texture node to new context version."""

    path = self.filepath_from_context(context)
    image_texture_node: bpy.types.ShaderNodeTexImage = container["node"]

    old_image: Optional[bpy.types.Image] = image_texture_node.image

    new_image = bpy.data.images.load(path)
    image_texture_node.image = new_image

    self.set_colorspace(context, image_texture_node)
    self.remove_image_if_unused(old_image)

    # Update representation id
    lib.imprint(image_texture_node, {
        "representation": context["representation"]["id"]
    })

process_asset(context, name, namespace=None, options=None)

Parameters:

Name Type Description Default
name str

Use pre-defined name

required
namespace Optional[str]

Use pre-defined namespace

None
context dict

Full parenthood of representation to load

required
options Optional[Dict]

Additional settings dictionary

None
Source code in client/ayon_blender/plugins/load/load_image_shader.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def process_asset(
        self, context: dict, name: str, namespace: Optional[str] = None,
        options: Optional[Dict] = None
) -> Optional[List]:
    """
    Arguments:
        name: Use pre-defined name
        namespace: Use pre-defined namespace
        context: Full parenthood of representation to load
        options: Additional settings dictionary
    """

    # In the current objects selection, I get the first one that is a
    # MESH or a SURFACE.
    # TODO: We tend to avoid acting on 'user selection' so that the loaders
    #  can run completely automatically, without user interaction or popups
    #  So we may want to investigate different approaches to this.
    cur_obj = self.get_selected_object()
    if cur_obj is None:
        self.log.info(
            "Load in Shader Editor: The process (image load) was "
            "cancelled, because no object (mesh or surface) was selected "
            "in Blender.")
        self.display_warning(
            "You did not select any object in Blender.\n"
            "So this process is cancelled.")
        return []

    # If the currently selected object has one or more materials, let's use
    # the first one. If it has no material, let's create a new one.
    material_slot = options.get("material_slot")
    if material_slot is None:
        # Get first slot with a material
        material_slot = next(
            (
                i for i, material in enumerate(cur_obj.data.materials)
                # Ignore empty material slots
                if material is not None
            ), None
        )
    if material_slot is None or material_slot == self.CREATE_NEW:
        # Create a new material
        current_material = bpy.data.materials.new(name="material")
        current_material.use_nodes = True
        cur_obj.data.materials.append(current_material)
    else:
        current_material = cur_obj.data.materials[material_slot]
        current_material.use_nodes = True

    nodes = current_material.node_tree.nodes

    # Create an "Image Texture" node. It will appear in the Shader Editor
    # (which appears when you are in the "Shading" workspace tab), when you
    # select the "Object" filter (among this choice: Object, World,
    # Line Style).
    image_texture_node = nodes.new(type='ShaderNodeTexImage')

    # Load the image in data
    path = self.filepath_from_context(context)
    image = bpy.data.images.load(path)
    image_texture_node.image = image

    self.set_colorspace(context, image_texture_node)

    data = {
        "schema": "openpype:container-2.0",
        "id": AVALON_CONTAINER_ID,
        "name": name,
        "namespace": namespace or '',
        "loader": str(self.__class__.__name__),
        "representation": context["representation"]["id"],
    }
    lib.imprint(image_texture_node, data)

    return [image_texture_node]

set_colorspace(context, image_texture_node)

Set colorspace if representation has colorspace data.

Source code in client/ayon_blender/plugins/load/load_image_shader.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def set_colorspace(
        self,
        context: dict,
        image_texture_node: bpy.types.ShaderNodeTexImage
):
    """
    Set colorspace if representation has colorspace data.
    """

    image = image_texture_node.image
    representation: dict = context["representation"]

    colorspace_data = representation.get("data", {}).get(
        "colorspaceData", {})
    if colorspace_data:
        colorspace: str = colorspace_data["colorspace"]
        if colorspace:
            image.colorspace_settings.name = colorspace