Skip to content

plugin

Shared functionality for pipeline plugins for Blender.

BlenderCreator

Bases: Creator

Base class for Blender Creator plug-ins.

Source code in client/ayon_blender/api/plugin.py
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
class BlenderCreator(Creator):
    """Base class for Blender Creator plug-ins."""
    defaults = ['Main']

    settings_category = "blender"
    create_as_asset_group = False

    @staticmethod
    def cache_instance_data(shared_data):
        """Cache instances for Creators shared data.

        Create `blender_cached_instances` key when needed in shared data and
        fill it with all collected instances from the scene under its
        respective creator identifiers.

        If legacy instances are detected in the scene, create
        `blender_cached_legacy_instances` key and fill it with
        all legacy products from this family as a value.  # key or value?

        Args:
            shared_data(Dict[str, Any]): Shared data.

        """
        if not shared_data.get('blender_cached_instances'):
            cache = {}
            cache_legacy = {}
            convert_avalon_instances()
            ayon_instances = bpy.data.collections.get(AYON_INSTANCES)
            ayon_instance_objs = (
                ayon_instances.objects if ayon_instances else []
            )

            # Consider any node tree objects as well
            node_tree_objects = []
            if bpy.context.scene.node_tree:
                node_tree_objects = bpy.context.scene.node_tree.nodes

            for obj_or_col in itertools.chain(
                    ayon_instance_objs,
                    bpy.data.collections,
                    node_tree_objects
            ):
                ayon_prop = get_ayon_property(obj_or_col)
                if not ayon_prop:
                    continue

                if ayon_prop.get('id') not in {
                    AYON_INSTANCE_ID, AVALON_INSTANCE_ID
                }:
                    continue

                creator_id = ayon_prop.get("creator_identifier")
                if "openpype" in creator_id:
                    creator_id = creator_id.replace("openpype", "ayon")
                    ayon_prop["creator_identifier"] = creator_id

                if creator_id:
                    # Creator instance
                    cache.setdefault(creator_id, []).append(obj_or_col)
                else:
                    # Legacy creator instance
                    family = ayon_prop.get('family')
                    cache_legacy.setdefault(family, []).append(obj_or_col)

            shared_data["blender_cached_instances"] = cache
            shared_data["blender_cached_legacy_instances"] = cache_legacy
        return shared_data

    def create(
        self, product_name: str, instance_data: dict, pre_create_data: dict
    ):
        """Override abstract method from Creator.
        Create new instance and store it.

        Args:
            product_name (str): Product name of created instance.
            instance_data (dict): Instance base data.
            pre_create_data (dict): Data based on pre creation attributes.
                Those may affect how creator works.
        """
        # Get Instance Container or create it if it does not exist
        ayon_instances = self._ensure_ayon_instances_collection()

        # Create asset group
        folder_name = instance_data["folderPath"].split("/")[-1]

        name = prepare_scene_name(folder_name, product_name)
        if self.create_as_asset_group:
            # Create instance as empty
            instance_node = bpy.data.objects.new(name=name, object_data=None)
            instance_node.empty_display_type = 'SINGLE_ARROW'
            ayon_instances.objects.link(instance_node)
        else:
            # Create instance collection
            instance_node = bpy.data.collections.new(name=name)
            ayon_instances.children.link(instance_node)

        self.set_instance_data(product_name, instance_data)

        instance = CreatedInstance(
            self.product_type, product_name, instance_data, self,
            transient_data={"instance_node": instance_node}
        )
        self._add_instance_to_context(instance)

        self.imprint(instance_node, instance_data)

        return instance_node

    def collect_instances(self):
        """Override abstract method from BlenderCreator.
        Collect existing instances related to this creator plugin."""

        # Cache instances in shared data
        self.cache_instance_data(self.collection_shared_data)

        # Get cached instances
        cached_instances = self.collection_shared_data.get(
            "blender_cached_instances"
        )
        if not cached_instances:
            return

        # Process only instances that were created by this creator
        for instance_node in cached_instances.get(self.identifier, []):
            instance_data = self.read(instance_node)

            # Create instance object from existing data
            instance = CreatedInstance.from_existing(
                instance_data=instance_data,
                creator=self,
                transient_data={"instance_node": instance_node}
            )

            # Add instance to create context
            self._add_instance_to_context(instance)

    def update_instances(self, update_list):
        """Override abstract method from BlenderCreator.
        Store changes of existing instances so they can be recollected.

        Args:
            update_list(List[UpdateData]): Changed instances
                and their changes, as a list of tuples.
        """

        for created_instance, changes in update_list:
            data = created_instance.data_to_store()
            node = created_instance.transient_data["instance_node"]
            if not node:
                # We can't update if we don't know the node
                self.log.error(
                    f"Unable to update instance {created_instance} "
                    f"without instance node."
                )
                return

            # Rename the instance node in the scene if product
            #   or folder changed.
            # Do not rename the instance if the family is workfile, as the
            # workfile instance is included in the AYON_CONTAINER collection.
            if (
                "productName" in changes.changed_keys
                or "folderPath" in changes.changed_keys
            ) and created_instance.product_type != "workfile":
                folder_name = data["folderPath"].split("/")[-1]
                name = prepare_scene_name(
                    folder_name, data["productName"]
                )
                node.name = name

            self.imprint(node, data)

    def remove_instances(self, instances: List[CreatedInstance]):
        for instance in instances:
            node = instance.transient_data["instance_node"]

            # Remove collection node and its children
            if isinstance(node, bpy.types.Collection):
                # Remove recursively linked child collections and objects
                for child in node.children_recursive:
                    if isinstance(child, bpy.types.Collection):
                        # If only linked to this collection, relink to scene before removal
                        if len(child.users_collection) == 1:
                            if child.name not in bpy.context.scene.collection:
                                bpy.context.scene.collection.children.link(child)

                    elif isinstance(child, bpy.types.Object):
                        if len(child.users_collection) == 1:
                            if child.name not in bpy.context.scene.collection:
                                bpy.context.scene.collection.objects.link(child)
                # Remove directly linked objects
                for obj in node.objects:
                    if len(obj.users_collection) == 1:
                        if obj.name not in bpy.context.scene.collection.objects:
                            bpy.context.scene.collection.objects.link(obj)

                bpy.data.collections.remove(node)

            # Remove object node
            elif isinstance(node, bpy.types.Object):
                bpy.data.objects.remove(node)

            # Remove compositor node
            elif isinstance(node, bpy.types.CompositorNode):
                bpy.context.scene.node_tree.nodes.remove(node)

            self._remove_instance_from_context(instance)

    def set_instance_data(
        self,
        product_name: str,
        instance_data: dict
    ):
        """Fill instance data with required items.

        Args:
            product_name (str): Product name of created instance.
            instance_data (dict): Instance base data.
            instance_node (bpy.types.ID): Instance node in blender scene.
        """
        if not instance_data:
            instance_data = {}

        instance_data.update(
            {
                "id": AYON_INSTANCE_ID,
                "creator_identifier": self.identifier,
                "productName": product_name,
            }
        )

    def _ensure_ayon_instances_collection(self) -> bpy.types.Collection:
        """Create AYON Instances collections that contains created instances.

        Returns:
            bpy.types.Collection: AYON Instances collection
        """
        node = bpy.data.collections.get(AYON_INSTANCES)
        if node:
            # Already exists, return it
            return node

        node = bpy.data.collections.new(AYON_INSTANCES)
        node.color_tag = "COLOR_04"
        node.use_fake_user = True
        bpy.context.scene.collection.children.link(node)
        return node

    def get_pre_create_attr_defs(self):
        return [
            BoolDef("use_selection",
                    label="Use selection",
                    default=True)
        ]

    def imprint(self, node, data: dict):
        """Imprint data to the instance node.

        This can be overridden by a sub-class to store certain data of the
        instance in a different way, e.g. in a custom property or the 'mute'
        state of a node.
        """
        imprint(node, data)

    def read(self, node) -> dict:
        """Read data from the instance node.

        The `data` dictionary is the readily stored
        """
        ayon_property = node.get(AYON_PROPERTY)
        if not ayon_property:
            return {}

        return ayon_property.to_dict()

cache_instance_data(shared_data) staticmethod

Cache instances for Creators shared data.

Create blender_cached_instances key when needed in shared data and fill it with all collected instances from the scene under its respective creator identifiers.

If legacy instances are detected in the scene, create blender_cached_legacy_instances key and fill it with all legacy products from this family as a value. # key or value?

Parameters:

Name Type Description Default
shared_data Dict[str, Any]

Shared data.

required
Source code in client/ayon_blender/api/plugin.py
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
@staticmethod
def cache_instance_data(shared_data):
    """Cache instances for Creators shared data.

    Create `blender_cached_instances` key when needed in shared data and
    fill it with all collected instances from the scene under its
    respective creator identifiers.

    If legacy instances are detected in the scene, create
    `blender_cached_legacy_instances` key and fill it with
    all legacy products from this family as a value.  # key or value?

    Args:
        shared_data(Dict[str, Any]): Shared data.

    """
    if not shared_data.get('blender_cached_instances'):
        cache = {}
        cache_legacy = {}
        convert_avalon_instances()
        ayon_instances = bpy.data.collections.get(AYON_INSTANCES)
        ayon_instance_objs = (
            ayon_instances.objects if ayon_instances else []
        )

        # Consider any node tree objects as well
        node_tree_objects = []
        if bpy.context.scene.node_tree:
            node_tree_objects = bpy.context.scene.node_tree.nodes

        for obj_or_col in itertools.chain(
                ayon_instance_objs,
                bpy.data.collections,
                node_tree_objects
        ):
            ayon_prop = get_ayon_property(obj_or_col)
            if not ayon_prop:
                continue

            if ayon_prop.get('id') not in {
                AYON_INSTANCE_ID, AVALON_INSTANCE_ID
            }:
                continue

            creator_id = ayon_prop.get("creator_identifier")
            if "openpype" in creator_id:
                creator_id = creator_id.replace("openpype", "ayon")
                ayon_prop["creator_identifier"] = creator_id

            if creator_id:
                # Creator instance
                cache.setdefault(creator_id, []).append(obj_or_col)
            else:
                # Legacy creator instance
                family = ayon_prop.get('family')
                cache_legacy.setdefault(family, []).append(obj_or_col)

        shared_data["blender_cached_instances"] = cache
        shared_data["blender_cached_legacy_instances"] = cache_legacy
    return shared_data

collect_instances()

Override abstract method from BlenderCreator. Collect existing instances related to this creator plugin.

Source code in client/ayon_blender/api/plugin.py
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
def collect_instances(self):
    """Override abstract method from BlenderCreator.
    Collect existing instances related to this creator plugin."""

    # Cache instances in shared data
    self.cache_instance_data(self.collection_shared_data)

    # Get cached instances
    cached_instances = self.collection_shared_data.get(
        "blender_cached_instances"
    )
    if not cached_instances:
        return

    # Process only instances that were created by this creator
    for instance_node in cached_instances.get(self.identifier, []):
        instance_data = self.read(instance_node)

        # Create instance object from existing data
        instance = CreatedInstance.from_existing(
            instance_data=instance_data,
            creator=self,
            transient_data={"instance_node": instance_node}
        )

        # Add instance to create context
        self._add_instance_to_context(instance)

create(product_name, instance_data, pre_create_data)

Override abstract method from Creator. Create new instance and store it.

Parameters:

Name Type Description Default
product_name str

Product name of created instance.

required
instance_data dict

Instance base data.

required
pre_create_data dict

Data based on pre creation attributes. Those may affect how creator works.

required
Source code in client/ayon_blender/api/plugin.py
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
def create(
    self, product_name: str, instance_data: dict, pre_create_data: dict
):
    """Override abstract method from Creator.
    Create new instance and store it.

    Args:
        product_name (str): Product name of created instance.
        instance_data (dict): Instance base data.
        pre_create_data (dict): Data based on pre creation attributes.
            Those may affect how creator works.
    """
    # Get Instance Container or create it if it does not exist
    ayon_instances = self._ensure_ayon_instances_collection()

    # Create asset group
    folder_name = instance_data["folderPath"].split("/")[-1]

    name = prepare_scene_name(folder_name, product_name)
    if self.create_as_asset_group:
        # Create instance as empty
        instance_node = bpy.data.objects.new(name=name, object_data=None)
        instance_node.empty_display_type = 'SINGLE_ARROW'
        ayon_instances.objects.link(instance_node)
    else:
        # Create instance collection
        instance_node = bpy.data.collections.new(name=name)
        ayon_instances.children.link(instance_node)

    self.set_instance_data(product_name, instance_data)

    instance = CreatedInstance(
        self.product_type, product_name, instance_data, self,
        transient_data={"instance_node": instance_node}
    )
    self._add_instance_to_context(instance)

    self.imprint(instance_node, instance_data)

    return instance_node

imprint(node, data)

Imprint data to the instance node.

This can be overridden by a sub-class to store certain data of the instance in a different way, e.g. in a custom property or the 'mute' state of a node.

Source code in client/ayon_blender/api/plugin.py
437
438
439
440
441
442
443
444
def imprint(self, node, data: dict):
    """Imprint data to the instance node.

    This can be overridden by a sub-class to store certain data of the
    instance in a different way, e.g. in a custom property or the 'mute'
    state of a node.
    """
    imprint(node, data)

read(node)

Read data from the instance node.

The data dictionary is the readily stored

Source code in client/ayon_blender/api/plugin.py
446
447
448
449
450
451
452
453
454
455
def read(self, node) -> dict:
    """Read data from the instance node.

    The `data` dictionary is the readily stored
    """
    ayon_property = node.get(AYON_PROPERTY)
    if not ayon_property:
        return {}

    return ayon_property.to_dict()

set_instance_data(product_name, instance_data)

Fill instance data with required items.

Parameters:

Name Type Description Default
product_name str

Product name of created instance.

required
instance_data dict

Instance base data.

required
instance_node ID

Instance node in blender scene.

required
Source code in client/ayon_blender/api/plugin.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
def set_instance_data(
    self,
    product_name: str,
    instance_data: dict
):
    """Fill instance data with required items.

    Args:
        product_name (str): Product name of created instance.
        instance_data (dict): Instance base data.
        instance_node (bpy.types.ID): Instance node in blender scene.
    """
    if not instance_data:
        instance_data = {}

    instance_data.update(
        {
            "id": AYON_INSTANCE_ID,
            "creator_identifier": self.identifier,
            "productName": product_name,
        }
    )

update_instances(update_list)

Override abstract method from BlenderCreator. Store changes of existing instances so they can be recollected.

Parameters:

Name Type Description Default
update_list List[UpdateData]

Changed instances and their changes, as a list of tuples.

required
Source code in client/ayon_blender/api/plugin.py
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
def update_instances(self, update_list):
    """Override abstract method from BlenderCreator.
    Store changes of existing instances so they can be recollected.

    Args:
        update_list(List[UpdateData]): Changed instances
            and their changes, as a list of tuples.
    """

    for created_instance, changes in update_list:
        data = created_instance.data_to_store()
        node = created_instance.transient_data["instance_node"]
        if not node:
            # We can't update if we don't know the node
            self.log.error(
                f"Unable to update instance {created_instance} "
                f"without instance node."
            )
            return

        # Rename the instance node in the scene if product
        #   or folder changed.
        # Do not rename the instance if the family is workfile, as the
        # workfile instance is included in the AYON_CONTAINER collection.
        if (
            "productName" in changes.changed_keys
            or "folderPath" in changes.changed_keys
        ) and created_instance.product_type != "workfile":
            folder_name = data["folderPath"].split("/")[-1]
            name = prepare_scene_name(
                folder_name, data["productName"]
            )
            node.name = name

        self.imprint(node, data)

BlenderLoader

Bases: LoaderPlugin

A basic AssetLoader for Blender

This will implement the basic logic for linking/appending assets into another Blender scene.

The update method should be implemented by a subclass, because it's different for different types (e.g. model, rig, animation, etc.).

Source code in client/ayon_blender/api/plugin.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
class BlenderLoader(LoaderPlugin):
    """A basic AssetLoader for Blender

    This will implement the basic logic for linking/appending assets
    into another Blender scene.

    The `update` method should be implemented by a subclass, because
    it's different for different types (e.g. model, rig, animation,
    etc.).
    """
    settings_category = "blender"

    @staticmethod
    def _get_instance_empty(instance_name: str, nodes: List) -> Optional[bpy.types.Object]:
        """Get the 'instance empty' that holds the collection instance."""
        for node in nodes:
            if not isinstance(node, bpy.types.Object):
                continue
            if (node.type == 'EMPTY' and node.instance_type == 'COLLECTION'
                    and node.instance_collection and node.name == instance_name):
                return node
        return None

    @staticmethod
    def _get_instance_collection(instance_name: str, nodes: List) -> Optional[bpy.types.Collection]:
        """Get the 'instance collection' (container) for this asset."""
        for node in nodes:
            if not isinstance(node, bpy.types.Collection):
                continue
            if node.name == instance_name:
                return node
        return None

    @staticmethod
    def _get_library_from_container(container: bpy.types.Collection) -> bpy.types.Library:
        """Find the library file from the container.

        It traverses the objects from this collection, checks if there is only
        1 library from which the objects come from and returns the library.

        Warning:
            No nested collections are supported at the moment!
        """
        assert not container.children, "Nested collections are not supported."
        assert container.objects, "The collection doesn't contain any objects."
        libraries = set()
        for obj in container.objects:
            assert obj.library, f"'{obj.name}' is not linked."
            libraries.add(obj.library)

        assert len(
            libraries) == 1, "'{container.name}' contains objects from more then 1 library."

        return list(libraries)[0]

    def process_asset(self,
                      context: dict,
                      name: str,
                      namespace: Optional[str] = None,
                      options: Optional[Dict] = None):
        """Must be implemented by a subclass"""
        raise NotImplementedError("Must be implemented by a subclass")

    def load(self,
             context: dict,
             name: Optional[str] = None,
             namespace: Optional[str] = None,
             options: Optional[Dict] = None) -> Optional[bpy.types.Collection]:
        """ Run the loader on Blender main thread"""
        mti = MainThreadItem(self._load, context, name, namespace, options)
        execute_in_main_thread(mti)

    def _load(self,
              context: dict,
              name: Optional[str] = None,
              namespace: Optional[str] = None,
              options: Optional[Dict] = None
    ) -> Optional[bpy.types.Collection]:
        """Load asset via database

        Arguments:
            context: Full parenthood of representation to load
            name: Use pre-defined name
            namespace: Use pre-defined namespace
            options: Additional settings dictionary
        """
        # TODO: make it possible to add the asset several times by
        # just re-using the collection
        filepath = self.filepath_from_context(context)
        assert Path(filepath).exists(), f"{filepath} doesn't exist."

        folder_name = context["folder"]["name"]
        product_name = context["product"]["name"]
        unique_number = get_unique_number(
            folder_name, product_name
        )
        namespace = namespace or f"{folder_name}_{unique_number}"
        name = name or prepare_scene_name(
            folder_name, product_name, unique_number
        )

        nodes = self.process_asset(
            context=context,
            name=name,
            namespace=namespace,
            options=options,
        )

        # Only containerise if anything was loaded by the Loader.
        if not nodes:
            return None

        # Only containerise if it's not already a collection from a .blend file.
        # representation = context["representation"]["name"]
        # if representation != "blend":
        #     from ayon_blender.api.pipeline import containerise
        #     return containerise(
        #         name=name,
        #         namespace=namespace,
        #         nodes=nodes,
        #         context=context,
        #         loader=self.__class__.__name__,
        #     )

        # folder_name = context["folder"]["name"]
        # product_name = context["product"]["name"]
        # instance_name = prepare_scene_name(
        #     folder_name, product_name, unique_number
        # ) + '_CON'

        # return self._get_instance_collection(instance_name, nodes)

    def exec_update(self, container: Dict, context: Dict):
        """Must be implemented by a subclass"""
        raise NotImplementedError("Must be implemented by a subclass")

    def update(self, container: Dict, context: Dict):
        """ Run the update on Blender main thread"""
        mti = MainThreadItem(self.exec_update, container, context)
        execute_in_main_thread(mti)

    def exec_remove(self, container: Dict) -> bool:
        """Must be implemented by a subclass"""
        raise NotImplementedError("Must be implemented by a subclass")

    def remove(self, container: Dict) -> bool:
        """ Run the remove on Blender main thread"""
        mti = MainThreadItem(self.exec_remove, container)
        execute_in_main_thread(mti)

    def switch(self, container, context):
        # Support switch in scene inventory
        self.update(container, context)

exec_remove(container)

Must be implemented by a subclass

Source code in client/ayon_blender/api/plugin.py
599
600
601
def exec_remove(self, container: Dict) -> bool:
    """Must be implemented by a subclass"""
    raise NotImplementedError("Must be implemented by a subclass")

exec_update(container, context)

Must be implemented by a subclass

Source code in client/ayon_blender/api/plugin.py
590
591
592
def exec_update(self, container: Dict, context: Dict):
    """Must be implemented by a subclass"""
    raise NotImplementedError("Must be implemented by a subclass")

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

Run the loader on Blender main thread

Source code in client/ayon_blender/api/plugin.py
521
522
523
524
525
526
527
528
def load(self,
         context: dict,
         name: Optional[str] = None,
         namespace: Optional[str] = None,
         options: Optional[Dict] = None) -> Optional[bpy.types.Collection]:
    """ Run the loader on Blender main thread"""
    mti = MainThreadItem(self._load, context, name, namespace, options)
    execute_in_main_thread(mti)

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

Must be implemented by a subclass

Source code in client/ayon_blender/api/plugin.py
513
514
515
516
517
518
519
def process_asset(self,
                  context: dict,
                  name: str,
                  namespace: Optional[str] = None,
                  options: Optional[Dict] = None):
    """Must be implemented by a subclass"""
    raise NotImplementedError("Must be implemented by a subclass")

remove(container)

Run the remove on Blender main thread

Source code in client/ayon_blender/api/plugin.py
603
604
605
606
def remove(self, container: Dict) -> bool:
    """ Run the remove on Blender main thread"""
    mti = MainThreadItem(self.exec_remove, container)
    execute_in_main_thread(mti)

update(container, context)

Run the update on Blender main thread

Source code in client/ayon_blender/api/plugin.py
594
595
596
597
def update(self, container: Dict, context: Dict):
    """ Run the update on Blender main thread"""
    mti = MainThreadItem(self.exec_update, container, context)
    execute_in_main_thread(mti)

create_blender_context(active=None, selected=None, window=None)

Create a new Blender context. If an object is passed as parameter, it is set as selected and active.

Source code in client/ayon_blender/api/plugin.py
 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
def create_blender_context(active: Optional[bpy.types.Object] = None,
                           selected: Optional[bpy.types.Object] = None,
                           window: Optional[bpy.types.Window] = None):
    """Create a new Blender context. If an object is passed as
    parameter, it is set as selected and active.
    """

    if not isinstance(selected, list):
        selected = [selected]

    override_context = bpy.context.copy()

    windows = [window] if window else bpy.context.window_manager.windows

    for win in windows:
        for area in win.screen.areas:
            if area.type == 'VIEW_3D':
                for region in area.regions:
                    if region.type == 'WINDOW':
                        override_context['window'] = win
                        override_context['screen'] = win.screen
                        override_context['area'] = area
                        override_context['region'] = region
                        override_context['scene'] = bpy.context.scene
                        override_context['active_object'] = active
                        override_context['selected_objects'] = selected
                        return override_context
    raise Exception("Could not create a custom Blender context.")

deselect_all()

Deselect all objects in the scene.

Blender gives context error if trying to deselect object that it isn't in object mode.

Source code in client/ayon_blender/api/plugin.py
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
def deselect_all():
    """Deselect all objects in the scene.

    Blender gives context error if trying to deselect object that it isn't
    in object mode.
    """
    modes = []
    active = bpy.context.view_layer.objects.active

    for obj in bpy.data.objects:
        if obj.mode != 'OBJECT':
            modes.append((obj, obj.mode))
            bpy.context.view_layer.objects.active = obj
            context_override = create_blender_context(active=obj)
            with bpy.context.temp_override(**context_override):
                bpy.ops.object.mode_set(mode='OBJECT')

    context_override = create_blender_context()
    with bpy.context.temp_override(**context_override):
        bpy.ops.object.select_all(action='DESELECT')

    for p in modes:
        bpy.context.view_layer.objects.active = p[0]
        context_override = create_blender_context(active=p[0])
        with bpy.context.temp_override(**context_override):
            bpy.ops.object.mode_set(mode=p[1])

    bpy.context.view_layer.objects.active = active

get_parent_collection(collection)

Get the parent of the input collection

Source code in client/ayon_blender/api/plugin.py
120
121
122
123
124
125
126
127
128
129
def get_parent_collection(collection):
    """Get the parent of the input collection"""
    check_list = [bpy.context.scene.collection]

    for c in check_list:
        if collection.name in c.children.keys():
            return c
        check_list.extend(c.children)

    return None

get_unique_number(folder_name, product_name)

Return a unique number based on the folder name.

Source code in client/ayon_blender/api/plugin.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def get_unique_number(
    folder_name: str, product_name: str
) -> str:
    """Return a unique number based on the folder name."""
    ayon_container = get_ayon_container()
    # Check the names of both object and collection containers
    obj_asset_groups = ayon_container.objects
    obj_group_names = {
        c.name for c in obj_asset_groups
        if c.type == 'EMPTY' and c.get(AYON_PROPERTY)}
    coll_asset_groups = ayon_container.children
    coll_group_names = {
        c.name for c in coll_asset_groups
        if c.get(AYON_PROPERTY)}
    container_names = obj_group_names.union(coll_group_names)
    count = 1
    name = f"{folder_name}_{count:0>2}_{product_name}"
    while name in container_names:
        count += 1
        name = f"{folder_name}_{count:0>2}_{product_name}"
    return f"{count:0>2}"

prepare_scene_name(folder_name, product_name, namespace=None)

Return a consistent name for an asset.

Source code in client/ayon_blender/api/plugin.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def prepare_scene_name(
    folder_name: str, product_name: str, namespace: Optional[str] = None
) -> str:
    """Return a consistent name for an asset."""
    name = f"{folder_name}"
    if namespace:
        name = f"{name}_{namespace}"
    name = f"{name}_{product_name}"

    # Blender name for a collection or object cannot be longer than 63
    # characters. If the name is longer, it will raise an error.
    # The truncation will only happen for blender version elder than 5.0
    if get_blender_version() < (5, 0, 0) and len(name) > 63:
        raise ValueError(f"Scene name '{name}' would be too long.")

    return name