Skip to content

load_layout

LayoutLoader

Bases: HoudiniLoader

Layout Loader (json)

Source code in client/ayon_houdini/plugins/load/load_layout.py
 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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
class LayoutLoader(plugin.HoudiniLoader):
    """Layout Loader (json)"""

    product_base_types = {"layout"}
    product_types = product_base_types
    representations = {"json"}

    label = "Load Layout"
    order = -10
    icon = "code-fork"
    color = "orange"

    # For JSON elements where we don't know what representation
    # to use, prefer to load the representation in this order.
    repre_order_by_name: dict[str, int] = {
        key: i for i, key in enumerate([
            "fbx", "abc", "usd", "vdb", "bgeo"
        ])
    }
    # Settings
    remove_layout_container_members = False

    def _get_repre_contexts_by_version_id(
        self,
        data: dict,
        context: dict
    ) -> dict[str, list[dict[str, dict]]]:
        """Fetch all representation contexts for all version ids in data
        at once - as optimal query."""
        version_ids = {
            element.get("version")
            for element in data
        }
        version_ids.discard(None)
        if not version_ids:
            return {}

        output = collections.defaultdict(list)
        project_name: str = context["project"]["name"]
        repre_entities = ayon_api.get_representations(
            project_name,
            version_ids=version_ids
        )
        repre_contexts = get_representation_contexts(
            project_name,
            repre_entities
        )
        for repre_context in repre_contexts.values():
            version_id = repre_context["version"]["id"]
            output[version_id].append(repre_context)
        return dict(output)

    def _get_loader_name(self, element: dict[str, Any]) -> Optional[str]:
        """Return the name of the loader plugin to use for the given element
        data.

        Args:
            element (dict[str, Any]): element data from layout json

        Raises:
            LoadError: If the product type or extension is not supported.

        Returns:
            Optional[str]: The name of the loader plugin, or None if not found.
        """

        # Find exact loader if layout was generated from same host
        # hosts: list[str] = element.get("host", [])
        # element_loader: str = element.get("loader")
        # same_host = ...implement same host check...
        # if same_host and element_loader:
        #     # TODO: Check if it exists
        #     return element_loader

        # Otherwise use a dedicated loader based on product type and extension
        product_base_type: str = (
            element.get("product_base_type")
            # Backwards compatibility
            or element.get("product_type")
            or element.get("family")
        )
        extension = element.get("extension", "")

        if product_base_type in {
            "model", "animation", "pointcache", "gpuCache"
        }:
            if extension == "abc":
                return "AbcLoader"
            elif extension == "fbx":
                return "FbxLoader"
            else:
                raise LoadError(
                    f"Unsupported extension '{extension}' "
                    f"for product type '{product_base_type}'"
                )
        elif product_base_type == "vdbcache":
            return "VdbLoader"

        return None

    def _process_element(
        self,
        element: dict[str, Any],
        repre_contexts_by_version_id: dict[str, list[dict]]
    ) -> list[str]:
        """Load one of the elements from a layout JSON file.

        Each element will specify a version for which we will load
        the first representation.
        """
        version_id = element.get("version")
        if not version_id:
            self.log.warning(
                f"No version id found in element: {element}")
            return []

        repre_contexts: list[dict] = repre_contexts_by_version_id.get(
            version_id, []
        )
        if not repre_contexts:
            self.log.error(
                "No representations found for version id:"
                f" {version_id}")
            return []

        def _sort_by_preferred_order(_repre_context: dict) -> int:
            _repre_name: str = _repre_context["representation"]["name"]
            return self.repre_order_by_name.get(
                _repre_name,
                len(self.repre_order_by_name) + 1
            )

        repre_contexts.sort(key=_sort_by_preferred_order)

        loader_name = self._get_loader_name(element)
        # Find loader plugin
        # TODO: Cache the loaders by name once
        loader = get_loaders_by_name().get(loader_name, None)
        if not loader:
            self.log.error(
                f"No valid loader '{loader_name}' found for: {element}"
            )
            return []

        # Find a matching representation for the loader among
        # the ordered representations of the version
        # TODO: We should actually figure out from the published data what
        #   representation is actually preferred instead of guessing
        #   a first entry that is compatible with the loader
        supported_repre_context: Optional[dict[str, dict[str, Any]]] = None
        for repre_context in repre_contexts:
            if loader.is_compatible_loader(repre_context):
                supported_repre_context = repre_context

        if not supported_repre_context:
            self.log.error(
                f"Loader '{loader_name}' does not support"
                f" representation contexts: {repre_contexts}"
            )
            return []

        # Load the representation
        # TODO: Currently load API does not enforce a return data structure
        #  from the `Loader.load` call. In Maya ReferenceLoader may return
        #  a list of container nodes (objectSet names) but others may return a
        #  single container node.
        instance_name: str = element['instance_name']
        result = load_with_repre_context(
            loader,
            repre_context=supported_repre_context,
            namespace=instance_name
        )
        self.log.info(f"Loaded element with loader '{loader_name}': {result}")
        if isinstance(result, hou.Node):
            containers: list[hou.node] = [result]
        else:
            self.log.warning(
                f"Loader {loader} returned invalid container data: {result}"
            )
            return []

        # Move the container root node
        for container in containers:
            self.set_transformation(container, element)
        return containers

    def set_transformation(
            self, container: hou.Node, element: dict[str, Any]) -> None:
        """Set the transformation of the container root node based on the
        element data.

        Args:
            container (hou.Node): container node name.
            element (dict[str, Any]): element data from layout json
        """
        hou_transform_matrix = element["transform_matrix"]
        self._set_transformation_by_matrix(container,
                                           hou_transform_matrix)

    def _set_transformation_by_matrix(
            self, node: hou.Node, matrix: list[float]) -> None:
        """Set the transformation of a node based on a 4x4
        transformation matrix.

        Args:
            node (hou.Node): node name.
            matrix (list): 4x4 transformation matrix as a flat
                list of 16 floats.
        """
        hou_matrix = unreal_matrix_to_houdini(matrix)
        node.setParmTransform(hou_matrix)

    def load(self, context, name=None, namespace=None, data=None):
        obj = hou.node("/obj")
        namespace = namespace if namespace else context["folder"]["name"]
        node_name = "{}_{}".format(namespace, name) if namespace else name

        subset_node = obj.createNode("subnet", node_name=node_name)
        subset_node.moveToGoodPosition()

        path = self.filepath_from_context(context)
        self.log.info(f">>> loading json [ {path} ]")
        with open(path, "r") as fp:
            data = json.load(fp)

        # get the list of representations by using version id
        repre_contexts_by_version_id = self._get_repre_contexts_by_version_id(
            data, context
        )
        container_members: list[hou.Node] = []
        for element in data:
            loaded_containers = self._process_element(
                element,
                repre_contexts_by_version_id
            )
            container_members.extend(loaded_containers)

        self[:] = [subset_node]

        container = pipeline.containerise(
            node_name,
            namespace,
            [subset_node],
            context,
            self.__class__.__name__,
            suffix=""
        )
        self._set_members(container, container_members)

        return container

    def update(self, container, context):
        repre_entity = context["representation"]
        path = self.filepath_from_context(context)
        self.log.info(f">>> loading json [ {path} ]")
        with open(path, "r") as fp:
            data = json.load(fp)

        # get the list of representations by using version id
        repre_contexts_by_version_id = self._get_repre_contexts_by_version_id(
            data, context
        )
        member_containers = self._get_members(container["node"])
        updated_containers: list[hou.Node] = []
        for element in data:
            # Find a matching container node among the members
            # TODO: Make this lookup more reliable than just
            #  checking the container node name.
            instance_name: str = element.get("instance_name")
            update_containers: list[hou.Node] = [
                node for node in member_containers
                if instance_name in node.name()
            ]
            if update_containers:
                # Update existing elements
                for update_container in update_containers:
                    self.set_transformation(update_container, element)
            else:
                # Load new elements and add them to container
                loaded_containers: list[hou.Node] = self._process_element(
                    element, repre_contexts_by_version_id
                )
                updated_containers.extend(loaded_containers)

        container_node = container["node"]
        self._set_members(container_node, updated_containers)
        container_node.setParms({
            "representation": str(repre_entity["id"])
        })

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

    def remove(self, container) -> None:
        node = container["node"]
        if self.remove_layout_container_members:
            members = self._get_members(node)
            for member in members:
                member.destroy()
        node.destroy()

    def _get_members(self, node: hou.OpNode) -> List[hou.OpNode]:
        """Get the member nodes of the layout container.

        Args:
            node (hou.OpNode): The node representing the layout container.

        Returns:
            List[hou.OpNode]: The list of member nodes of the layout container.
        """
        return node.parm(MEMBER_ATTR_NAME).evalAsNodes()

    def _set_members(
            self, node: hou.OpNode, members: List[hou.OpNode]) -> None:
        """Set the member nodes of the layout container.

        Args:
            node (hou.OpNode): The node representing the layout container.
            members (List[hou.OpNode]): The list of member nodes to set.
        """
        # Add/set a parm of type node operator list
        parm = node.parm(MEMBER_ATTR_NAME)
        if not parm:
            # Add parm
            parm_template = hou.StringParmTemplate(
                name=MEMBER_ATTR_NAME ,
                label="Layout Members",
                num_components=1,
                string_type=hou.stringParmType.NodeReferenceList,
                # only OBJ nodes
                # tags={"opfilter": "!!OBJ!!", "oprelative": "."}
            )
            parm_template_group = node.parmTemplateGroup()
            parm_template_group.append(parm_template)
            node.setParmTemplateGroup(parm_template_group)
            parm = node.parm(MEMBER_ATTR_NAME)

        # Set value
        nodes_str = " ".join(node.path() for node in members)
        parm.set(nodes_str)

set_transformation(container, element)

Set the transformation of the container root node based on the element data.

Parameters:

Name Type Description Default
container Node

container node name.

required
element dict[str, Any]

element data from layout json

required
Source code in client/ayon_houdini/plugins/load/load_layout.py
233
234
235
236
237
238
239
240
241
242
243
244
def set_transformation(
        self, container: hou.Node, element: dict[str, Any]) -> None:
    """Set the transformation of the container root node based on the
    element data.

    Args:
        container (hou.Node): container node name.
        element (dict[str, Any]): element data from layout json
    """
    hou_transform_matrix = element["transform_matrix"]
    self._set_transformation_by_matrix(container,
                                       hou_transform_matrix)

unreal_matrix_to_houdini(unreal_matrix)

Convert an Unreal Engine 4x4 matrix to a Houdini hou.Matrix4.

Parameters:

Name Type Description Default
unreal_matrix list[list[float]]

list[list[float]] - A 4x4 matrix represented as a list of 4 lists, each containing 4 floats.

required

Returns:

Type Description
Matrix4

hou.Matrix4 in Houdini's right-handed, Y-up coordinate system.

Source code in client/ayon_houdini/plugins/load/load_layout.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def unreal_matrix_to_houdini(unreal_matrix: list[list[float]]) -> hou.Matrix4:
    """
    Convert an Unreal Engine 4x4 matrix to a Houdini hou.Matrix4.

    Args:
        unreal_matrix: list[list[float]] - A 4x4 matrix represented as
            a list of 4 lists, each containing 4 floats.

    Returns:
        hou.Matrix4 in Houdini's right-handed, Y-up coordinate system.
    """

    def _remap(v):
        return hou.Vector3(v[0], v[2], v[1])

    houdini_matrix = hou.Matrix4(unreal_matrix)
    trs = houdini_matrix.explode()
    trs["translate"] = _remap(trs["translate"])
    trs["rotate"] = _remap(trs["rotate"])
    trs["scale"] = _remap(trs["scale"])
    return hou.hmath.buildTransform(trs)