Skip to content

load_image

FileNodeLoader

Bases: Loader

File node loader.

Source code in client/ayon_maya/plugins/load/load_image.py
 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
class FileNodeLoader(plugin.Loader):
    """File node loader."""

    product_types = {"image", "plate", "render"}
    label = "Load file node"
    representations = {"exr", "tif", "png", "jpg"}
    icon = "image"
    color = "orange"
    order = 2

    options = [
        EnumDef(
            "mode",
            items={
                "texture": "Texture",
                "projection": "Projection",
                "stencil": "Stencil"
            },
            default="texture",
            label="Texture Mode"
        )
    ]

    def load(self, context, name, namespace, data):
        folder_name = context["folder"]["name"]
        namespace = namespace or unique_namespace(
            folder_name + "_",
            prefix="_" if folder_name[0].isdigit() else "",
            suffix="_",
        )

        with namespaced(namespace, new=True) as namespace:
            # Create the nodes within the namespace
            nodes = {
                "texture": create_texture,
                "projection": create_projection,
                "stencil": create_stencil
            }[data.get("mode", "texture")]()

        file_node = cmds.ls(nodes, type="file")[0]

        self._apply_representation_context(context, file_node)

        # For ease of access for the user select all the nodes and select
        # the file node last so that UI shows its attributes by default
        cmds.select(list(nodes) + [file_node], replace=True)

        return containerise(
            name=name,
            namespace=namespace,
            nodes=nodes,
            context=context,
            loader=self.__class__.__name__
        )

    def update(self, container, context):
        repre_entity = context["representation"]

        members = cmds.sets(container['objectName'], query=True)
        file_node = cmds.ls(members, type="file")[0]

        self._apply_representation_context(context, file_node)

        # Update representation
        cmds.setAttr(
            container["objectName"] + ".representation",
            repre_entity["id"],
            type="string"
        )

    def switch(self, container, context):
        self.update(container, context)

    def remove(self, container):
        members = cmds.sets(container['objectName'], query=True)
        cmds.lockNode(members, lock=False)
        cmds.delete([container['objectName']] + members)

        # Clean up the namespace
        try:
            cmds.namespace(removeNamespace=container['namespace'],
                           deleteNamespaceContent=True)
        except RuntimeError:
            pass

    def _apply_representation_context(self, context, file_node):
        """Update the file node to match the context.

        This sets the file node's attributes for:
            - file path
            - udim tiling mode (if it is an udim tile)
            - use frame extension (if it is a sequence)
            - colorspace

        """

        repre_context = context["representation"]["context"]
        has_frames = repre_context.get("frame") is not None
        has_udim = repre_context.get("udim") is not None

        # Set UV tiling mode if UDIM tiles
        if has_udim:
            cmds.setAttr(file_node + ".uvTilingMode", 3)    # UDIM-tiles
        else:
            cmds.setAttr(file_node + ".uvTilingMode", 0)    # off

        # Enable sequence if publish has `startFrame` and `endFrame` and
        # `startFrame != endFrame`
        if has_frames and self._is_sequence(context):
            # When enabling useFrameExtension maya automatically
            # connects an expression to <file>.frameExtension to set
            # the current frame. However, this expression  is generated
            # with some delay and thus it'll show a warning if frame 0
            # doesn't exist because we're explicitly setting the <f>
            # token.
            cmds.setAttr(file_node + ".useFrameExtension", True)
        else:
            cmds.setAttr(file_node + ".useFrameExtension", False)

        # Set the file node path attribute
        path = self._format_path(context)
        cmds.setAttr(file_node + ".fileTextureName", path, type="string")

        # Set colorspace
        colorspace = self._get_colorspace(context)
        if colorspace:
            cmds.setAttr(file_node + ".colorSpace", colorspace, type="string")
        else:
            self.log.debug("Unknown colorspace - setting colorspace skipped.")

    def _is_sequence(self, context):
        """Check whether frameStart and frameEnd are not the same."""
        version = context["version"]
        representation = context["representation"]

        # TODO this is invalid logic, it should be based only on
        #   representation entity
        for entity in [representation, version]:
            # Frame range can be set on version or representation.
            # When set on representation it overrides version data.
            attributes = entity["attrib"]
            data = entity["data"]
            start = data.get("frameStartHandle", attributes.get("frameStart"))
            end = data.get("frameEndHandle", attributes.get("frameEnd"))

            if start is None or end is None:
                continue

            if start != end:
                return True
            else:
                return False

        return False

    def _get_colorspace(self, context):
        """Return colorspace of the file to load.

        Retrieves the explicit colorspace from the publish. If no colorspace
        data is stored with published content then project imageio settings
        are used to make an assumption of the colorspace based on the file
        rules. If no file rules match then None is returned.

        Returns:
            str or None: The colorspace of the file or None if not detected.

        """

        # We can't apply color spaces if management is not enabled
        if not cmds.colorManagementPrefs(query=True, cmEnabled=True):
            return

        representation = context["representation"]
        colorspace_data = representation.get("data", {}).get("colorspaceData")
        if colorspace_data:
            return colorspace_data["colorspace"]

        # Assume colorspace from filepath based on project settings
        project_name = context["project"]["name"]
        host_name = get_current_host_name()
        project_settings = get_project_settings(project_name)

        config_data = get_current_context_imageio_config_preset(
            project_settings=project_settings
        )

        # ignore if host imageio is not enabled
        if not config_data:
            return

        file_rules = get_imageio_file_rules(
            project_name, host_name,
            project_settings=project_settings
        )

        path = get_representation_path_from_context(context)
        colorspace = get_imageio_file_rules_colorspace_from_filepath(
            path,
            host_name,
            project_name,
            config_data=config_data,
            file_rules=file_rules,
            project_settings=project_settings
        )

        return colorspace

    def _format_path(self, context):
        """Format the path with correct tokens for frames and udim tiles."""

        context = copy.deepcopy(context)
        representation = context["representation"]
        template = representation.get("attrib", {}).get("template")
        if not template:
            # No template to find token locations for
            return get_representation_path_from_context(context)

        def _placeholder(key):
            # Substitute with a long placeholder value so that potential
            # custom formatting with padding doesn't find its way into
            # our formatting, so that <f> wouldn't be padded as 0<f>
            return "___{}___".format(key)

        # We format UDIM and Frame numbers with their specific tokens. To do so
        # we in-place change the representation context data to format the path
        # with our own data
        tokens = {
            "frame": "<f>",
            # We do not enforce the UDIM token in the filepath because it
            # generates the issue that Maya does not detect the file correctly
            # in e.g. the File Path Editor. Instead, we set the regular
            # filepath and allow Maya to 'compute' the UDIM token.
            # "udim": "<UDIM>"
        }
        has_tokens = False
        repre_context = representation["context"]
        for key, _token in tokens.items():
            if key in repre_context:
                repre_context[key] = _placeholder(key)
                has_tokens = True

        # Replace with our custom template that has the tokens set
        representation["attrib"]["template"] = template
        path = get_representation_path_from_context(context)

        if has_tokens:
            for key, token in tokens.items():
                if key in repre_context:
                    path = path.replace(_placeholder(key), token)

        return path

create_projection()

Create texture with place3dTexture and projection

Mimics Maya "file [Projection]" creation.

Source code in client/ayon_maya/plugins/load/load_image.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def create_projection():
    """Create texture with place3dTexture and projection

    Mimics Maya "file [Projection]" creation.
    """

    file, place = create_texture()
    projection = cmds.shadingNode("projection", asTexture=True,
                                  name="projection")
    place3d = cmds.shadingNode("place3dTexture", asUtility=True,
                               name="place3d")

    cmds.connectAttr(place3d + '.worldInverseMatrix[0]',
                     projection + ".placementMatrix")
    cmds.connectAttr(file + '.outColor', projection + ".image")

    return file, place, projection, place3d

create_stencil()

Create texture with extra place2dTexture offset and stencil

Mimics Maya "file [Stencil]" creation.

Source code in client/ayon_maya/plugins/load/load_image.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def create_stencil():
    """Create texture with extra place2dTexture offset and stencil

    Mimics Maya "file [Stencil]" creation.
    """

    file, place = create_texture()

    place_stencil = cmds.shadingNode("place2dTexture", asUtility=True,
                                     name="place2d_stencil")
    stencil = cmds.shadingNode("stencil", asTexture=True, name="stencil")

    for src_attr, dest_attr in [
        ("outUV", "uvCoord"),
        ("outUvFilterSize", "uvFilterSize")
    ]:
        src_plug = "{}.{}".format(place_stencil, src_attr)
        cmds.connectAttr(src_plug, "{}.{}".format(place, dest_attr))
        cmds.connectAttr(src_plug, "{}.{}".format(stencil, dest_attr))

    return file, place, stencil, place_stencil

create_texture()

Create place2dTexture with file node with uv connections

Mimics Maya "file [Texture]" creation.

Source code in client/ayon_maya/plugins/load/load_image.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def create_texture():
    """Create place2dTexture with file node with uv connections

    Mimics Maya "file [Texture]" creation.
    """

    place = cmds.shadingNode("place2dTexture", asUtility=True, name="place2d")
    file = cmds.shadingNode("file", asTexture=True, name="file")

    connections = ["coverage", "translateFrame", "rotateFrame", "rotateUV",
                   "mirrorU", "mirrorV", "stagger", "wrapV", "wrapU",
                   "repeatUV", "offset", "noiseUV", "vertexUvThree",
                   "vertexUvTwo", "vertexUvOne", "vertexCameraOne"]
    for attr in connections:
        src = "{}.{}".format(place, attr)
        dest = "{}.{}".format(file, attr)
        cmds.connectAttr(src, dest)

    cmds.connectAttr(place + '.outUV', file + '.uvCoord')
    cmds.connectAttr(place + '.outUvFilterSize', file + '.uvFilterSize')

    return file, place