"""
Collection of functions to manage blender collections
"""
import bpy
import ddg
[docs]def collection(name, parent=None, children=None):
r"""Creates a new collection or uses an existing one if
a collection with given name exists.
If the collection already exists the remaining parameters are ignored.
Examples
--------
>>> import ddg
>>> ddg.blender.collection.collection(
... "parent",
... children=[
... "1",
... "2",
... ["3", "3.1", "3.2", "3.3"],
... ["4", ["4.1", "4.1.1", "4.1.2"]],
... ],
... )
bpy.data.collections['parent']
Parameters
----------
name : str
``.name`` of the collection.
parent : bpy.types.Collection (default=None)
Parent collection to link newly generated collection to.
If `None`, collections get linked to ``bpy.context.scene.collection``.
children: list of str or lists (default=None)
``.name`` of children that will be generated when generating a new collection.
If an entry is a list, the first string will be the child's ``.name``
and the others the child's children's ``.name``\s.
Returns
-------
bpy.types.Collection
Reference to the created Blender collection.
"""
if name in bpy.data.collections:
col = bpy.data.collections[name]
else:
if parent is None:
parent = bpy.context.scene.collection
col = bpy.data.collections.new(name)
parent.children.link(col)
if children:
for child in children:
if isinstance(child, str):
collection(child, parent=col)
elif len(child) > 0:
collection(child[0], parent=col, children=child[1:])
return col
[docs]def clear(collections=None, deep=False, remove_collections=False):
"""Unlink all the objects contained in the given collection.
Parameters
----------
collections : Iterable of bpy.types.Collection (default=None)
Collection(s) to clear. If the argument is not provided or ``None``,
``bpy.context.scene`` will be used.
deep : bool (default=False)
Delete the data corresponding to the objects.
remove_collections : bool (default=False)
Deletes the given collections and children.
If ``bpy.context.scene.collection`` was given it deletes all
children of this collection (``bpy.context.scene.collection`` can't be removed).
"""
if collections is None:
collections = [bpy.context.scene.collection]
for collection in collections:
ddg.blender.object.clear(objects=collection.all_objects, deep=deep)
if remove_collections:
if collection is bpy.data.scenes["Scene"].collection:
for c in bpy.data.collections:
bpy.data.collections.remove(c)
else:
if collection.children:
clear(
collections=collection.children,
remove_collections=remove_collections,
)
bpy.data.collections.remove(collection)