Skip to content

load_camera_abc

Load an asset in Blender from an Alembic file.

AbcCameraLoader

Bases: BlenderLoader

Load a camera from Alembic file.

Stores the imported asset in an empty named after the asset.

Source code in client/ayon_blender/plugins/load/load_camera_abc.py
 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
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
class AbcCameraLoader(plugin.BlenderLoader):
    """Load a camera from Alembic file.

    Stores the imported asset in an empty named after the asset.
    """

    product_types = {"camera"}
    representations = {"*"}
    extensions = {"abc"}

    label = "Load Camera (ABC)"
    icon = "code-fork"
    color = "orange"

    always_add_cache_reader = True
    add_namespace = True

    @classmethod
    def get_options(cls, contexts):
        return [
            BoolDef("always_add_cache_reader",
                    default=cls.always_add_cache_reader,
                    label="Always Add Cache Reader"),
            BoolDef("add_namespace",
                    default=cls.add_namespace,
                    label="Add namespace to objects"),
        ]

    def _remove(self, asset_group):
        objects = list(asset_group.children)

        for obj in objects:
            if obj.type == "CAMERA":
                bpy.data.cameras.remove(obj.data)
            elif obj.type == "EMPTY":
                objects.extend(obj.children)
                bpy.data.objects.remove(obj)

    def _process(self, libpath, asset_group, group_name, options=None):
        if options is None:
            options = {}

        plugin.deselect_all()

        # Force the creation of the transform cache even if the camera
        # doesn't have an animation. We use the cache to update the camera.
        always_add_cache_reader = options.get(
            "always_add_cache_reader", self.always_add_cache_reader
        )
        bpy.ops.wm.alembic_import(
            filepath=libpath,
            always_add_cache_reader=always_add_cache_reader
        )

        objects = lib.get_selection()

        for obj in objects:
            obj.parent = asset_group

        # Add namespace
        if options.get("add_namespace", self.add_namespace):
            for obj in objects:
                name = obj.name
                obj.name = f"{group_name}:{name}"
                if obj.type != "EMPTY":
                    name_data = obj.data.name
                    obj.data.name = f"{group_name}:{name_data}"

        # Add AYON metadata
        for obj in objects:
            if not obj.get(AYON_PROPERTY):
                obj[AYON_PROPERTY] = dict()

            ayon_info = obj[AYON_PROPERTY]
            ayon_info.update({"container_name": group_name})

        plugin.deselect_all()

        return objects

    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
        """

        libpath = self.filepath_from_context(context)

        folder_name = context["folder"]["name"]
        product_name = context["product"]["name"]

        asset_name = plugin.prepare_scene_name(folder_name, product_name)
        unique_number = plugin.get_unique_number(folder_name, product_name)
        group_name = plugin.prepare_scene_name(
            folder_name, product_name, unique_number
        )
        namespace = namespace or f"{folder_name}_{unique_number}"

        asset_group = bpy.data.objects.new(group_name, object_data=None)
        add_to_ayon_container(asset_group)
        self._process(libpath, asset_group, group_name, options)

        objects = []
        nodes = list(asset_group.children)

        for obj in nodes:
            objects.append(obj)
            nodes.extend(list(obj.children))

        bpy.context.scene.collection.objects.link(asset_group)

        asset_group[AYON_PROPERTY] = {
            "schema": "ayon:container-3.0",
            "id": AYON_CONTAINER_ID,
            "name": name,
            "namespace": namespace or "",
            "loader": str(self.__class__.__name__),
            "representation": context["representation"]["id"],
            "libpath": libpath,
            "asset_name": asset_name,
            "parent": context["representation"]["versionId"],
            "productType": context["product"]["productType"],
            "objectName": group_name,
            "project_name": context["project"]["name"],
            "options": options or {}
        }

        self[:] = objects
        return objects

    def exec_update(self, container: Dict, context: Dict):
        """Update the loaded asset.

        This will remove all objects of the current collection, load the new
        ones and add them to the collection.
        If the objects of the collection are used in another collection they
        will not be removed, only unlinked. Normally this should not be the
        case though.

        Warning:
            No nested collections are supported at the moment!
        """
        repre_entity = context["representation"]
        object_name = container["objectName"]
        asset_group = bpy.data.objects.get(object_name)
        libpath = Path(self.filepath_from_context(context))
        extension = libpath.suffix.lower()

        assert asset_group, (
            f"The asset is not loaded: {container['objectName']}")
        assert libpath, (
            f"No existing library file found for {container['objectName']}")
        assert libpath.is_file(), f"The file doesn't exist: {libpath}"
        assert extension in VALID_EXTENSIONS, (
            f"Unsupported file: {libpath}")

        metadata = asset_group.get(AYON_PROPERTY)
        group_libpath = metadata["libpath"]

        normalized_group_libpath = str(
            Path(bpy.path.abspath(group_libpath)).resolve())
        normalized_libpath = str(
            Path(bpy.path.abspath(str(libpath))).resolve())
        self.log.debug(
            "normalized_group_libpath:\n  %s\nnormalized_libpath:\n  %s",
            normalized_group_libpath,
            normalized_libpath,
        )
        if normalized_group_libpath == normalized_libpath:
            self.log.info("Library already loaded, not updating...")
            return

        new_cachefile = lib.add_cache_file(libpath.as_posix())
        new_cachefile.scale = 1.0

        remove_unused_caches = set()

        # Update transform cache constraints
        for obj in asset_group.children_recursive:
            for constraint in obj.constraints:
                if constraint.type != "TRANSFORM_CACHE":
                    continue

                if not constraint.cache_file:
                    continue

                remove_unused_caches.add(constraint.cache_file)
                constraint.cache_file = new_cachefile

                # Update the object path if object not found in cache file
                if constraint.object_path not in new_cachefile.object_paths:
                    self.log.warning(
                        f"Object path '{constraint.object_path}' not found in new "
                        "cache file, trying to update it."
                    )
                    self.log.info("new_cache object paths '%s'", new_cachefile.object_paths)

        remove_unused_caches = {
            cache for cache in remove_unused_caches if
            not lib.has_users(cache)
        }
        if remove_unused_caches:
            bpy.data.batch_remove(remove_unused_caches)

        metadata["libpath"] = str(libpath)
        metadata["representation"] = repre_entity["id"]
        metadata["project_name"] = context["project"]["name"]

    def exec_remove(self, container: Dict) -> bool:
        """Remove an existing container from a Blender scene.

        Arguments:
            container (ayon:container-1.0): Container to remove,
                from `host.ls()`.

        Returns:
            bool: Whether the container was deleted.

        Warning:
            No nested collections are supported at the moment!
        """
        object_name = container["objectName"]
        asset_group = bpy.data.objects.get(object_name)

        if not asset_group:
            return False

        self._remove(asset_group)

        bpy.data.objects.remove(asset_group)

        return True

exec_remove(container)

Remove an existing container from a Blender scene.

Parameters:

Name Type Description Default
container (ayon

container-1.0): Container to remove, from host.ls().

required

Returns:

Name Type Description
bool bool

Whether the container was deleted.

Warning

No nested collections are supported at the moment!

Source code in client/ayon_blender/plugins/load/load_camera_abc.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def exec_remove(self, container: Dict) -> bool:
    """Remove an existing container from a Blender scene.

    Arguments:
        container (ayon:container-1.0): Container to remove,
            from `host.ls()`.

    Returns:
        bool: Whether the container was deleted.

    Warning:
        No nested collections are supported at the moment!
    """
    object_name = container["objectName"]
    asset_group = bpy.data.objects.get(object_name)

    if not asset_group:
        return False

    self._remove(asset_group)

    bpy.data.objects.remove(asset_group)

    return True

exec_update(container, context)

Update the loaded asset.

This will remove all objects of the current collection, load the new ones and add them to the collection. If the objects of the collection are used in another collection they will not be removed, only unlinked. Normally this should not be the case though.

Warning

No nested collections are supported at the moment!

Source code in client/ayon_blender/plugins/load/load_camera_abc.py
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
def exec_update(self, container: Dict, context: Dict):
    """Update the loaded asset.

    This will remove all objects of the current collection, load the new
    ones and add them to the collection.
    If the objects of the collection are used in another collection they
    will not be removed, only unlinked. Normally this should not be the
    case though.

    Warning:
        No nested collections are supported at the moment!
    """
    repre_entity = context["representation"]
    object_name = container["objectName"]
    asset_group = bpy.data.objects.get(object_name)
    libpath = Path(self.filepath_from_context(context))
    extension = libpath.suffix.lower()

    assert asset_group, (
        f"The asset is not loaded: {container['objectName']}")
    assert libpath, (
        f"No existing library file found for {container['objectName']}")
    assert libpath.is_file(), f"The file doesn't exist: {libpath}"
    assert extension in VALID_EXTENSIONS, (
        f"Unsupported file: {libpath}")

    metadata = asset_group.get(AYON_PROPERTY)
    group_libpath = metadata["libpath"]

    normalized_group_libpath = str(
        Path(bpy.path.abspath(group_libpath)).resolve())
    normalized_libpath = str(
        Path(bpy.path.abspath(str(libpath))).resolve())
    self.log.debug(
        "normalized_group_libpath:\n  %s\nnormalized_libpath:\n  %s",
        normalized_group_libpath,
        normalized_libpath,
    )
    if normalized_group_libpath == normalized_libpath:
        self.log.info("Library already loaded, not updating...")
        return

    new_cachefile = lib.add_cache_file(libpath.as_posix())
    new_cachefile.scale = 1.0

    remove_unused_caches = set()

    # Update transform cache constraints
    for obj in asset_group.children_recursive:
        for constraint in obj.constraints:
            if constraint.type != "TRANSFORM_CACHE":
                continue

            if not constraint.cache_file:
                continue

            remove_unused_caches.add(constraint.cache_file)
            constraint.cache_file = new_cachefile

            # Update the object path if object not found in cache file
            if constraint.object_path not in new_cachefile.object_paths:
                self.log.warning(
                    f"Object path '{constraint.object_path}' not found in new "
                    "cache file, trying to update it."
                )
                self.log.info("new_cache object paths '%s'", new_cachefile.object_paths)

    remove_unused_caches = {
        cache for cache in remove_unused_caches if
        not lib.has_users(cache)
    }
    if remove_unused_caches:
        bpy.data.batch_remove(remove_unused_caches)

    metadata["libpath"] = str(libpath)
    metadata["representation"] = repre_entity["id"]
    metadata["project_name"] = context["project"]["name"]

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_camera_abc.py
 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
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
    """

    libpath = self.filepath_from_context(context)

    folder_name = context["folder"]["name"]
    product_name = context["product"]["name"]

    asset_name = plugin.prepare_scene_name(folder_name, product_name)
    unique_number = plugin.get_unique_number(folder_name, product_name)
    group_name = plugin.prepare_scene_name(
        folder_name, product_name, unique_number
    )
    namespace = namespace or f"{folder_name}_{unique_number}"

    asset_group = bpy.data.objects.new(group_name, object_data=None)
    add_to_ayon_container(asset_group)
    self._process(libpath, asset_group, group_name, options)

    objects = []
    nodes = list(asset_group.children)

    for obj in nodes:
        objects.append(obj)
        nodes.extend(list(obj.children))

    bpy.context.scene.collection.objects.link(asset_group)

    asset_group[AYON_PROPERTY] = {
        "schema": "ayon:container-3.0",
        "id": AYON_CONTAINER_ID,
        "name": name,
        "namespace": namespace or "",
        "loader": str(self.__class__.__name__),
        "representation": context["representation"]["id"],
        "libpath": libpath,
        "asset_name": asset_name,
        "parent": context["representation"]["versionId"],
        "productType": context["product"]["productType"],
        "objectName": group_name,
        "project_name": context["project"]["name"],
        "options": options or {}
    }

    self[:] = objects
    return objects