1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16 
17 /** \file
18  * \ingroup bke
19  */
20 
21 #include <string.h>
22 
23 #include "BLI_blenlib.h"
24 #include "BLI_iterator.h"
25 #include "BLI_listbase.h"
26 #include "BLI_math_base.h"
27 #include "BLI_threads.h"
28 #include "BLT_translation.h"
29 
30 #include "BKE_anim_data.h"
31 #include "BKE_collection.h"
32 #include "BKE_icons.h"
33 #include "BKE_idprop.h"
34 #include "BKE_idtype.h"
35 #include "BKE_layer.h"
36 #include "BKE_lib_id.h"
37 #include "BKE_lib_query.h"
38 #include "BKE_lib_remap.h"
39 #include "BKE_main.h"
40 #include "BKE_object.h"
41 #include "BKE_rigidbody.h"
42 #include "BKE_scene.h"
43 
44 #include "DNA_defaults.h"
45 
46 #include "DNA_ID.h"
47 #include "DNA_collection_types.h"
48 #include "DNA_layer_types.h"
49 #include "DNA_object_types.h"
50 #include "DNA_rigidbody_types.h"
51 #include "DNA_scene_types.h"
52 
53 #include "DEG_depsgraph.h"
54 #include "DEG_depsgraph_query.h"
55 
56 #include "MEM_guardedalloc.h"
57 
58 /* -------------------------------------------------------------------- */
59 /** \name Prototypes
60  * \{ */
61 
62 static bool collection_child_add(Collection *parent,
63                                  Collection *collection,
64                                  const int flag,
65                                  const bool add_us);
66 static bool collection_child_remove(Collection *parent, Collection *collection);
67 static bool collection_object_add(
68     Main *bmain, Collection *collection, Object *ob, int flag, const bool add_us);
69 static bool collection_object_remove(Main *bmain,
70                                      Collection *collection,
71                                      Object *ob,
72                                      const bool free_us);
73 
74 static CollectionChild *collection_find_child(Collection *parent, Collection *collection);
75 static CollectionParent *collection_find_parent(Collection *child, Collection *collection);
76 
77 static bool collection_find_child_recursive(Collection *parent, Collection *collection);
78 
79 /** \} */
80 
81 /* -------------------------------------------------------------------- */
82 /** \name Collection Data-Block
83  * \{ */
84 
collection_init_data(ID * id)85 static void collection_init_data(ID *id)
86 {
87   Collection *collection = (Collection *)id;
88   BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(collection, id));
89 
90   MEMCPY_STRUCT_AFTER(collection, DNA_struct_default_get(Collection), id);
91 }
92 
93 /**
94  * Only copy internal data of Collection ID from source
95  * to already allocated/initialized destination.
96  * You probably never want to use that directly,
97  * use #BKE_id_copy or #BKE_id_copy_ex for typical needs.
98  *
99  * WARNING! This function will not handle ID user count!
100  *
101  * \param flag: Copying options (see BKE_lib_id.h's LIB_ID_COPY_... flags for more).
102  */
collection_copy_data(Main * bmain,ID * id_dst,const ID * id_src,const int flag)103 static void collection_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const int flag)
104 {
105   Collection *collection_dst = (Collection *)id_dst;
106   const Collection *collection_src = (const Collection *)id_src;
107 
108   BLI_assert(((collection_src->flag & COLLECTION_IS_MASTER) != 0) ==
109              ((collection_src->id.flag & LIB_EMBEDDED_DATA) != 0));
110 
111   /* Do not copy collection's preview (same behavior as for objects). */
112   if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO temp hack */
113     BKE_previewimg_id_copy(&collection_dst->id, &collection_src->id);
114   }
115   else {
116     collection_dst->preview = NULL;
117   }
118 
119   collection_dst->flag &= ~COLLECTION_HAS_OBJECT_CACHE;
120   BLI_listbase_clear(&collection_dst->object_cache);
121 
122   BLI_listbase_clear(&collection_dst->gobject);
123   BLI_listbase_clear(&collection_dst->children);
124   BLI_listbase_clear(&collection_dst->parents);
125 
126   LISTBASE_FOREACH (CollectionChild *, child, &collection_src->children) {
127     collection_child_add(collection_dst, child->collection, flag, false);
128   }
129   LISTBASE_FOREACH (CollectionObject *, cob, &collection_src->gobject) {
130     collection_object_add(bmain, collection_dst, cob->ob, flag, false);
131   }
132 }
133 
collection_free_data(ID * id)134 static void collection_free_data(ID *id)
135 {
136   Collection *collection = (Collection *)id;
137 
138   /* No animdata here. */
139   BKE_previewimg_free(&collection->preview);
140 
141   BLI_freelistN(&collection->gobject);
142   BLI_freelistN(&collection->children);
143   BLI_freelistN(&collection->parents);
144 
145   BKE_collection_object_cache_free(collection);
146 }
147 
collection_foreach_id(ID * id,LibraryForeachIDData * data)148 static void collection_foreach_id(ID *id, LibraryForeachIDData *data)
149 {
150   Collection *collection = (Collection *)id;
151 
152   LISTBASE_FOREACH (CollectionObject *, cob, &collection->gobject) {
153     BKE_LIB_FOREACHID_PROCESS(data, cob->ob, IDWALK_CB_USER);
154   }
155   LISTBASE_FOREACH (CollectionChild *, child, &collection->children) {
156     BKE_LIB_FOREACHID_PROCESS(data, child->collection, IDWALK_CB_NEVER_SELF | IDWALK_CB_USER);
157   }
158   LISTBASE_FOREACH (CollectionParent *, parent, &collection->parents) {
159     /* XXX This is very weak. The whole idea of keeping pointers to private IDs is very bad
160      * anyway... */
161     const int cb_flag = ((parent->collection != NULL &&
162                           (parent->collection->id.flag & LIB_EMBEDDED_DATA) != 0) ?
163                              IDWALK_CB_EMBEDDED :
164                              IDWALK_CB_NOP);
165     BKE_LIB_FOREACHID_PROCESS(
166         data, parent->collection, IDWALK_CB_NEVER_SELF | IDWALK_CB_LOOPBACK | cb_flag);
167   }
168 }
169 
170 IDTypeInfo IDType_ID_GR = {
171     .id_code = ID_GR,
172     .id_filter = FILTER_ID_GR,
173     .main_listbase_index = INDEX_ID_GR,
174     .struct_size = sizeof(Collection),
175     .name = "Collection",
176     .name_plural = "collections",
177     .translation_context = BLT_I18NCONTEXT_ID_COLLECTION,
178     .flags = IDTYPE_FLAGS_NO_ANIMDATA,
179 
180     .init_data = collection_init_data,
181     .copy_data = collection_copy_data,
182     .free_data = collection_free_data,
183     .make_local = NULL,
184     .foreach_id = collection_foreach_id,
185     .foreach_cache = NULL,
186 
187     .blend_write = NULL,
188     .blend_read_data = NULL,
189     .blend_read_lib = NULL,
190     .blend_read_expand = NULL,
191 };
192 
193 /** \} */
194 
195 /* -------------------------------------------------------------------- */
196 /** \name Add Collection
197  * \{ */
198 
199 /* Add new collection, without view layer syncing. */
collection_add(Main * bmain,Collection * collection_parent,const char * name_custom)200 static Collection *collection_add(Main *bmain,
201                                   Collection *collection_parent,
202                                   const char *name_custom)
203 {
204   /* Determine new collection name. */
205   char name[MAX_NAME];
206 
207   if (name_custom) {
208     STRNCPY(name, name_custom);
209   }
210   else {
211     BKE_collection_new_name_get(collection_parent, name);
212   }
213 
214   /* Create new collection. */
215   Collection *collection = BKE_id_new(bmain, ID_GR, name);
216 
217   /* We increase collection user count when linking to Collections. */
218   id_us_min(&collection->id);
219 
220   /* Optionally add to parent collection. */
221   if (collection_parent) {
222     collection_child_add(collection_parent, collection, 0, true);
223   }
224 
225   return collection;
226 }
227 
228 /**
229  * Add a collection to a collection ListBase and synchronize all render layers
230  * The ListBase is NULL when the collection is to be added to the master collection
231  */
BKE_collection_add(Main * bmain,Collection * collection_parent,const char * name_custom)232 Collection *BKE_collection_add(Main *bmain, Collection *collection_parent, const char *name_custom)
233 {
234   Collection *collection = collection_add(bmain, collection_parent, name_custom);
235   BKE_main_collection_sync(bmain);
236   return collection;
237 }
238 
239 /**
240  * Add \a collection_dst to all scene collections that reference object \a ob_src is in.
241  * Used to replace an instance object with a collection (library override operator).
242  *
243  * Logic is very similar to #BKE_collection_object_add_from().
244  */
BKE_collection_add_from_object(Main * bmain,Scene * scene,const Object * ob_src,Collection * collection_dst)245 void BKE_collection_add_from_object(Main *bmain,
246                                     Scene *scene,
247                                     const Object *ob_src,
248                                     Collection *collection_dst)
249 {
250   bool is_instantiated = false;
251 
252   FOREACH_SCENE_COLLECTION_BEGIN (scene, collection) {
253     if (!ID_IS_LINKED(collection) && BKE_collection_has_object(collection, ob_src)) {
254       collection_child_add(collection, collection_dst, 0, true);
255       is_instantiated = true;
256     }
257   }
258   FOREACH_SCENE_COLLECTION_END;
259 
260   if (!is_instantiated) {
261     collection_child_add(scene->master_collection, collection_dst, 0, true);
262   }
263 
264   BKE_main_collection_sync(bmain);
265 }
266 
267 /**
268  * Add \a collection_dst to all scene collections that reference collection \a collection_src is
269  * in.
270  *
271  * Logic is very similar to #BKE_collection_object_add_from().
272  */
BKE_collection_add_from_collection(Main * bmain,Scene * scene,Collection * collection_src,Collection * collection_dst)273 void BKE_collection_add_from_collection(Main *bmain,
274                                         Scene *scene,
275                                         Collection *collection_src,
276                                         Collection *collection_dst)
277 {
278   bool is_instantiated = false;
279 
280   FOREACH_SCENE_COLLECTION_BEGIN (scene, collection) {
281     if (!ID_IS_LINKED(collection) && BKE_collection_has_collection(collection, collection_src)) {
282       collection_child_add(collection, collection_dst, 0, true);
283       is_instantiated = true;
284     }
285   }
286   FOREACH_SCENE_COLLECTION_END;
287 
288   if (!is_instantiated) {
289     collection_child_add(scene->master_collection, collection_dst, 0, true);
290   }
291 
292   BKE_main_collection_sync(bmain);
293 }
294 
295 /** \} */
296 
297 /* -------------------------------------------------------------------- */
298 /** \name Free and Delete Collection
299  * \{ */
300 
301 /** Free (or release) any data used by this collection (does not free the collection itself). */
BKE_collection_free(Collection * collection)302 void BKE_collection_free(Collection *collection)
303 {
304   collection_free_data(&collection->id);
305 }
306 
307 /**
308  * Remove a collection, optionally removing its child objects or moving
309  * them to parent collections.
310  */
BKE_collection_delete(Main * bmain,Collection * collection,bool hierarchy)311 bool BKE_collection_delete(Main *bmain, Collection *collection, bool hierarchy)
312 {
313   /* Master collection is not real datablock, can't be removed. */
314   if (collection->flag & COLLECTION_IS_MASTER) {
315     BLI_assert(!"Scene master collection can't be deleted");
316     return false;
317   }
318 
319   if (hierarchy) {
320     /* Remove child objects. */
321     CollectionObject *cob = collection->gobject.first;
322     while (cob != NULL) {
323       collection_object_remove(bmain, collection, cob->ob, true);
324       cob = collection->gobject.first;
325     }
326 
327     /* Delete all child collections recursively. */
328     CollectionChild *child = collection->children.first;
329     while (child != NULL) {
330       BKE_collection_delete(bmain, child->collection, hierarchy);
331       child = collection->children.first;
332     }
333   }
334   else {
335     /* Link child collections into parent collection. */
336     LISTBASE_FOREACH (CollectionChild *, child, &collection->children) {
337       LISTBASE_FOREACH (CollectionParent *, cparent, &collection->parents) {
338         Collection *parent = cparent->collection;
339         collection_child_add(parent, child->collection, 0, true);
340       }
341     }
342 
343     CollectionObject *cob = collection->gobject.first;
344     while (cob != NULL) {
345       /* Link child object into parent collections. */
346       LISTBASE_FOREACH (CollectionParent *, cparent, &collection->parents) {
347         Collection *parent = cparent->collection;
348         collection_object_add(bmain, parent, cob->ob, 0, true);
349       }
350 
351       /* Remove child object. */
352       collection_object_remove(bmain, collection, cob->ob, true);
353       cob = collection->gobject.first;
354     }
355   }
356 
357   BKE_id_delete(bmain, collection);
358 
359   BKE_main_collection_sync(bmain);
360 
361   return true;
362 }
363 
364 /** \} */
365 
366 /* -------------------------------------------------------------------- */
367 /** \name Collection Copy
368  * \{ */
369 
collection_duplicate_recursive(Main * bmain,Collection * parent,Collection * collection_old,const eDupli_ID_Flags duplicate_flags,const eLibIDDuplicateFlags duplicate_options)370 static Collection *collection_duplicate_recursive(Main *bmain,
371                                                   Collection *parent,
372                                                   Collection *collection_old,
373                                                   const eDupli_ID_Flags duplicate_flags,
374                                                   const eLibIDDuplicateFlags duplicate_options)
375 {
376   Collection *collection_new;
377   bool do_full_process = false;
378   const bool is_collection_master = (collection_old->flag & COLLECTION_IS_MASTER) != 0;
379 
380   const bool do_objects = (duplicate_flags & USER_DUP_OBJECT) != 0;
381 
382   if (is_collection_master) {
383     /* We never duplicate master collections here, but we can still deep-copy their objects and
384      * collections. */
385     BLI_assert(parent == NULL);
386     collection_new = collection_old;
387     do_full_process = true;
388   }
389   else if (collection_old->id.newid == NULL) {
390     collection_new = (Collection *)BKE_id_copy_for_duplicate(
391         bmain, (ID *)collection_old, duplicate_flags);
392 
393     if (collection_new == collection_old) {
394       return collection_new;
395     }
396 
397     do_full_process = true;
398   }
399   else {
400     collection_new = (Collection *)collection_old->id.newid;
401   }
402 
403   /* Optionally add to parent (we always want to do that,
404    * even if collection_old had already been duplicated). */
405   if (parent != NULL) {
406     if (collection_child_add(parent, collection_new, 0, true)) {
407       /* Put collection right after existing one. */
408       CollectionChild *child = collection_find_child(parent, collection_old);
409       CollectionChild *child_new = collection_find_child(parent, collection_new);
410 
411       if (child && child_new) {
412         BLI_remlink(&parent->children, child_new);
413         BLI_insertlinkafter(&parent->children, child, child_new);
414       }
415     }
416   }
417 
418   /* If we are not doing any kind of deep-copy, we can return immediately.
419    * False do_full_process means collection_old had already been duplicated,
420    * no need to redo some deep-copy on it. */
421   if (!do_full_process) {
422     return collection_new;
423   }
424 
425   if (do_objects) {
426     /* We need to first duplicate the objects in a separate loop, to support the master collection
427      * case, where both old and new collections are the same.
428      * Otherwise, depending on naming scheme and sorting, we may end up duplicating the new objects
429      * we just added, in some infinite loop. */
430     LISTBASE_FOREACH (CollectionObject *, cob, &collection_old->gobject) {
431       Object *ob_old = cob->ob;
432 
433       if (ob_old->id.newid == NULL) {
434         BKE_object_duplicate(
435             bmain, ob_old, duplicate_flags, duplicate_options | LIB_ID_DUPLICATE_IS_SUBPROCESS);
436       }
437     }
438 
439     /* We can loop on collection_old's objects, but have to consider it mutable because with master
440      * collections collection_old and collection_new are the same data here. */
441     LISTBASE_FOREACH_MUTABLE (CollectionObject *, cob, &collection_old->gobject) {
442       Object *ob_old = cob->ob;
443       Object *ob_new = (Object *)ob_old->id.newid;
444 
445       /* New object can be NULL in master collection case, since new and old objects are in same
446        * collection. */
447       if (ELEM(ob_new, ob_old, NULL)) {
448         continue;
449       }
450 
451       collection_object_add(bmain, collection_new, ob_new, 0, true);
452       collection_object_remove(bmain, collection_new, ob_old, false);
453     }
454   }
455 
456   /* We can loop on collection_old's children,
457    * that list is currently identical the collection_new' children, and won't be changed here. */
458   LISTBASE_FOREACH_MUTABLE (CollectionChild *, child, &collection_old->children) {
459     Collection *child_collection_old = child->collection;
460 
461     Collection *child_collection_new = collection_duplicate_recursive(
462         bmain, collection_new, child_collection_old, duplicate_flags, duplicate_options);
463     if (child_collection_new != child_collection_old) {
464       collection_child_remove(collection_new, child_collection_old);
465     }
466   }
467 
468   return collection_new;
469 }
470 
471 /**
472  * Make a deep copy (aka duplicate) of the given collection and all of its children, recursively.
473  *
474  * \warning This functions will clear all \a bmain #ID.idnew pointers, unless \a
475  * #LIB_ID_DUPLICATE_IS_SUBPROCESS duplicate option is passed on, in which case caller is
476  * responsible to reconstruct collection dependencies information's
477  * (i.e. call #BKE_main_collection_sync).
478  */
BKE_collection_duplicate(Main * bmain,Collection * parent,Collection * collection,eDupli_ID_Flags duplicate_flags,eLibIDDuplicateFlags duplicate_options)479 Collection *BKE_collection_duplicate(Main *bmain,
480                                      Collection *parent,
481                                      Collection *collection,
482                                      eDupli_ID_Flags duplicate_flags,
483                                      eLibIDDuplicateFlags duplicate_options)
484 {
485   const bool is_subprocess = (duplicate_options & LIB_ID_DUPLICATE_IS_SUBPROCESS) != 0;
486 
487   if (!is_subprocess) {
488     BKE_main_id_tag_all(bmain, LIB_TAG_NEW, false);
489     BKE_main_id_clear_newpoins(bmain);
490     /* In case root duplicated ID is linked, assume we want to get a local copy of it and duplicate
491      * all expected linked data. */
492     if (ID_IS_LINKED(collection)) {
493       duplicate_flags |= USER_DUP_LINKED_ID;
494     }
495   }
496 
497   Collection *collection_new = collection_duplicate_recursive(
498       bmain, parent, collection, duplicate_flags, duplicate_options);
499 
500   if (!is_subprocess) {
501     /* `collection_duplicate_recursive` will also tag our 'root' collection, which is not required
502      * unless its duplication is a sub-process of another one. */
503     collection_new->id.tag &= ~LIB_TAG_NEW;
504 
505     /* This code will follow into all ID links using an ID tagged with LIB_TAG_NEW.*/
506     BKE_libblock_relink_to_newid(&collection_new->id);
507 
508 #ifndef NDEBUG
509     /* Call to `BKE_libblock_relink_to_newid` above is supposed to have cleared all those flags. */
510     ID *id_iter;
511     FOREACH_MAIN_ID_BEGIN (bmain, id_iter) {
512       if (id_iter->tag & LIB_TAG_NEW) {
513         BLI_assert((id_iter->tag & LIB_TAG_NEW) == 0);
514       }
515     }
516     FOREACH_MAIN_ID_END;
517 #endif
518 
519     /* Cleanup. */
520     BKE_main_id_tag_all(bmain, LIB_TAG_NEW, false);
521     BKE_main_id_clear_newpoins(bmain);
522 
523     BKE_main_collection_sync(bmain);
524   }
525 
526   return collection_new;
527 }
528 
529 /** \} */
530 
531 /* -------------------------------------------------------------------- */
532 /** \name Collection Naming
533  * \{ */
534 
535 /**
536  * The automatic/fallback name of a new collection.
537  */
BKE_collection_new_name_get(Collection * collection_parent,char * rname)538 void BKE_collection_new_name_get(Collection *collection_parent, char *rname)
539 {
540   char *name;
541 
542   if (!collection_parent) {
543     name = BLI_strdup("Collection");
544   }
545   else if (collection_parent->flag & COLLECTION_IS_MASTER) {
546     name = BLI_sprintfN("Collection %d", BLI_listbase_count(&collection_parent->children) + 1);
547   }
548   else {
549     const int number = BLI_listbase_count(&collection_parent->children) + 1;
550     const int digits = integer_digits_i(number);
551     const int max_len = sizeof(collection_parent->id.name) - 1 /* NULL terminator */ -
552                         (1 + digits) /* " %d" */ - 2 /* ID */;
553     name = BLI_sprintfN("%.*s %d", max_len, collection_parent->id.name + 2, number);
554   }
555 
556   BLI_strncpy(rname, name, MAX_NAME);
557   MEM_freeN(name);
558 }
559 
560 /**
561  * The name to show in the interface.
562  */
BKE_collection_ui_name_get(struct Collection * collection)563 const char *BKE_collection_ui_name_get(struct Collection *collection)
564 {
565   if (collection->flag & COLLECTION_IS_MASTER) {
566     return IFACE_("Scene Collection");
567   }
568 
569   return collection->id.name + 2;
570 }
571 
572 /** \} */
573 
574 /* -------------------------------------------------------------------- */
575 /** \name Object List Cache
576  * \{ */
577 
collection_object_cache_fill(ListBase * lb,Collection * collection,int parent_restrict)578 static void collection_object_cache_fill(ListBase *lb, Collection *collection, int parent_restrict)
579 {
580   int child_restrict = collection->flag | parent_restrict;
581 
582   LISTBASE_FOREACH (CollectionObject *, cob, &collection->gobject) {
583     Base *base = BLI_findptr(lb, cob->ob, offsetof(Base, object));
584 
585     if (base == NULL) {
586       base = MEM_callocN(sizeof(Base), "Object Base");
587       base->object = cob->ob;
588       BLI_addtail(lb, base);
589     }
590 
591     /* Only collection flags are checked here currently, object restrict flag is checked
592      * in FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN since it can be animated
593      * without updating the cache. */
594     if (((child_restrict & COLLECTION_RESTRICT_VIEWPORT) == 0)) {
595       base->flag |= BASE_ENABLED_VIEWPORT;
596     }
597     if (((child_restrict & COLLECTION_RESTRICT_RENDER) == 0)) {
598       base->flag |= BASE_ENABLED_RENDER;
599     }
600   }
601 
602   LISTBASE_FOREACH (CollectionChild *, child, &collection->children) {
603     collection_object_cache_fill(lb, child->collection, child_restrict);
604   }
605 }
606 
BKE_collection_object_cache_get(Collection * collection)607 ListBase BKE_collection_object_cache_get(Collection *collection)
608 {
609   if (!(collection->flag & COLLECTION_HAS_OBJECT_CACHE)) {
610     static ThreadMutex cache_lock = BLI_MUTEX_INITIALIZER;
611 
612     BLI_mutex_lock(&cache_lock);
613     if (!(collection->flag & COLLECTION_HAS_OBJECT_CACHE)) {
614       collection_object_cache_fill(&collection->object_cache, collection, 0);
615       collection->flag |= COLLECTION_HAS_OBJECT_CACHE;
616     }
617     BLI_mutex_unlock(&cache_lock);
618   }
619 
620   return collection->object_cache;
621 }
622 
collection_object_cache_free(Collection * collection)623 static void collection_object_cache_free(Collection *collection)
624 {
625   /* Clear own cache an for all parents, since those are affected by changes as well. */
626   collection->flag &= ~COLLECTION_HAS_OBJECT_CACHE;
627   BLI_freelistN(&collection->object_cache);
628 
629   LISTBASE_FOREACH (CollectionParent *, parent, &collection->parents) {
630     collection_object_cache_free(parent->collection);
631   }
632 }
633 
BKE_collection_object_cache_free(Collection * collection)634 void BKE_collection_object_cache_free(Collection *collection)
635 {
636   collection_object_cache_free(collection);
637 }
638 
BKE_collection_or_layer_objects(const ViewLayer * view_layer,Collection * collection)639 Base *BKE_collection_or_layer_objects(const ViewLayer *view_layer, Collection *collection)
640 {
641   if (collection) {
642     return BKE_collection_object_cache_get(collection).first;
643   }
644 
645   return FIRSTBASE(view_layer);
646 }
647 
648 /** \} */
649 
650 /* -------------------------------------------------------------------- */
651 /** \name Scene Master Collection
652  * \{ */
653 
BKE_collection_master_add()654 Collection *BKE_collection_master_add()
655 {
656   /* Not an actual datablock, but owned by scene. */
657   Collection *master_collection = MEM_callocN(sizeof(Collection), "Master Collection");
658   STRNCPY(master_collection->id.name, "GRMaster Collection");
659   master_collection->id.flag |= LIB_EMBEDDED_DATA;
660   master_collection->flag |= COLLECTION_IS_MASTER;
661   master_collection->color_tag = COLLECTION_COLOR_NONE;
662   return master_collection;
663 }
664 
BKE_collection_master_scene_search(const Main * bmain,const Collection * master_collection)665 Scene *BKE_collection_master_scene_search(const Main *bmain, const Collection *master_collection)
666 {
667   BLI_assert((master_collection->flag & COLLECTION_IS_MASTER) != 0);
668 
669   for (Scene *scene = bmain->scenes.first; scene != NULL; scene = scene->id.next) {
670     if (scene->master_collection == master_collection) {
671       return scene;
672     }
673   }
674 
675   return NULL;
676 }
677 
678 /** \} */
679 
680 /* -------------------------------------------------------------------- */
681 /** \name Cyclic Checks
682  * \{ */
683 
collection_object_cyclic_check_internal(Object * object,Collection * collection)684 static bool collection_object_cyclic_check_internal(Object *object, Collection *collection)
685 {
686   if (object->instance_collection) {
687     Collection *dup_collection = object->instance_collection;
688     if ((dup_collection->id.tag & LIB_TAG_DOIT) == 0) {
689       /* Cycle already exists in collections, let's prevent further crappyness */
690       return true;
691     }
692     /* flag the object to identify cyclic dependencies in further dupli collections */
693     dup_collection->id.tag &= ~LIB_TAG_DOIT;
694 
695     if (dup_collection == collection) {
696       return true;
697     }
698 
699     FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (dup_collection, collection_object) {
700       if (collection_object_cyclic_check_internal(collection_object, dup_collection)) {
701         return true;
702       }
703     }
704     FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
705 
706     /* un-flag the object, it's allowed to have the same collection multiple times in parallel */
707     dup_collection->id.tag |= LIB_TAG_DOIT;
708   }
709 
710   return false;
711 }
712 
BKE_collection_object_cyclic_check(Main * bmain,Object * object,Collection * collection)713 bool BKE_collection_object_cyclic_check(Main *bmain, Object *object, Collection *collection)
714 {
715   /* first flag all collections */
716   BKE_main_id_tag_listbase(&bmain->collections, LIB_TAG_DOIT, true);
717 
718   return collection_object_cyclic_check_internal(object, collection);
719 }
720 
721 /** \} */
722 
723 /* -------------------------------------------------------------------- */
724 /** \name Collection Object Membership
725  * \{ */
726 
BKE_collection_has_object(Collection * collection,const Object * ob)727 bool BKE_collection_has_object(Collection *collection, const Object *ob)
728 {
729   if (ELEM(NULL, collection, ob)) {
730     return false;
731   }
732 
733   return (BLI_findptr(&collection->gobject, ob, offsetof(CollectionObject, ob)));
734 }
735 
BKE_collection_has_object_recursive(Collection * collection,Object * ob)736 bool BKE_collection_has_object_recursive(Collection *collection, Object *ob)
737 {
738   if (ELEM(NULL, collection, ob)) {
739     return false;
740   }
741 
742   const ListBase objects = BKE_collection_object_cache_get(collection);
743   return (BLI_findptr(&objects, ob, offsetof(Base, object)));
744 }
745 
collection_next_find(Main * bmain,Scene * scene,Collection * collection)746 static Collection *collection_next_find(Main *bmain, Scene *scene, Collection *collection)
747 {
748   if (scene && collection == scene->master_collection) {
749     return bmain->collections.first;
750   }
751 
752   return collection->id.next;
753 }
754 
BKE_collection_object_find(Main * bmain,Scene * scene,Collection * collection,Object * ob)755 Collection *BKE_collection_object_find(Main *bmain,
756                                        Scene *scene,
757                                        Collection *collection,
758                                        Object *ob)
759 {
760   if (collection) {
761     collection = collection_next_find(bmain, scene, collection);
762   }
763   else if (scene) {
764     collection = scene->master_collection;
765   }
766   else {
767     collection = bmain->collections.first;
768   }
769 
770   while (collection) {
771     if (BKE_collection_has_object(collection, ob)) {
772       return collection;
773     }
774     collection = collection_next_find(bmain, scene, collection);
775   }
776   return NULL;
777 }
778 
BKE_collection_is_empty(Collection * collection)779 bool BKE_collection_is_empty(Collection *collection)
780 {
781   return BLI_listbase_is_empty(&collection->gobject) &&
782          BLI_listbase_is_empty(&collection->children);
783 }
784 
785 /** \} */
786 
787 /* -------------------------------------------------------------------- */
788 /** \name Collection Objects
789  * \{ */
790 
collection_tag_update_parent_recursive(Main * bmain,Collection * collection,const int flag)791 static void collection_tag_update_parent_recursive(Main *bmain,
792                                                    Collection *collection,
793                                                    const int flag)
794 {
795   if (collection->flag & COLLECTION_IS_MASTER) {
796     return;
797   }
798 
799   DEG_id_tag_update_ex(bmain, &collection->id, flag);
800 
801   LISTBASE_FOREACH (CollectionParent *, collection_parent, &collection->parents) {
802     if (collection_parent->collection->flag & COLLECTION_IS_MASTER) {
803       /* We don't care about scene/master collection here. */
804       continue;
805     }
806     collection_tag_update_parent_recursive(bmain, collection_parent->collection, flag);
807   }
808 }
809 
collection_parent_editable_find_recursive(Collection * collection)810 static Collection *collection_parent_editable_find_recursive(Collection *collection)
811 {
812   if (!ID_IS_LINKED(collection) && !ID_IS_OVERRIDE_LIBRARY(collection)) {
813     return collection;
814   }
815 
816   if (collection->flag & COLLECTION_IS_MASTER) {
817     return NULL;
818   }
819 
820   LISTBASE_FOREACH (CollectionParent *, collection_parent, &collection->parents) {
821     if (!ID_IS_LINKED(collection_parent->collection) &&
822         !ID_IS_OVERRIDE_LIBRARY(collection_parent->collection)) {
823       return collection_parent->collection;
824     }
825     Collection *editable_collection = collection_parent_editable_find_recursive(
826         collection_parent->collection);
827     if (editable_collection != NULL) {
828       return editable_collection;
829     }
830   }
831 
832   return NULL;
833 }
834 
collection_object_add(Main * bmain,Collection * collection,Object * ob,int flag,const bool add_us)835 static bool collection_object_add(
836     Main *bmain, Collection *collection, Object *ob, int flag, const bool add_us)
837 {
838   if (ob->instance_collection) {
839     /* Cyclic dependency check. */
840     if (collection_find_child_recursive(ob->instance_collection, collection) ||
841         ob->instance_collection == collection) {
842       return false;
843     }
844   }
845 
846   CollectionObject *cob = BLI_findptr(&collection->gobject, ob, offsetof(CollectionObject, ob));
847   if (cob) {
848     return false;
849   }
850 
851   cob = MEM_callocN(sizeof(CollectionObject), __func__);
852   cob->ob = ob;
853   BLI_addtail(&collection->gobject, cob);
854   BKE_collection_object_cache_free(collection);
855 
856   if (add_us && (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
857     id_us_plus(&ob->id);
858   }
859 
860   if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
861     collection_tag_update_parent_recursive(bmain, collection, ID_RECALC_COPY_ON_WRITE);
862   }
863 
864   if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
865     BKE_rigidbody_main_collection_object_add(bmain, collection, ob);
866   }
867 
868   return true;
869 }
870 
collection_object_remove(Main * bmain,Collection * collection,Object * ob,const bool free_us)871 static bool collection_object_remove(Main *bmain,
872                                      Collection *collection,
873                                      Object *ob,
874                                      const bool free_us)
875 {
876   CollectionObject *cob = BLI_findptr(&collection->gobject, ob, offsetof(CollectionObject, ob));
877   if (cob == NULL) {
878     return false;
879   }
880 
881   BLI_freelinkN(&collection->gobject, cob);
882   BKE_collection_object_cache_free(collection);
883 
884   if (free_us) {
885     BKE_id_free_us(bmain, ob);
886   }
887   else {
888     id_us_min(&ob->id);
889   }
890 
891   collection_tag_update_parent_recursive(bmain, collection, ID_RECALC_COPY_ON_WRITE);
892 
893   return true;
894 }
895 
896 /**
897  * Add object to collection
898  */
BKE_collection_object_add(Main * bmain,Collection * collection,Object * ob)899 bool BKE_collection_object_add(Main *bmain, Collection *collection, Object *ob)
900 {
901   if (ELEM(NULL, collection, ob)) {
902     return false;
903   }
904 
905   collection = collection_parent_editable_find_recursive(collection);
906 
907   /* Only case where this pointer can be NULL is when scene itself is linked, this case should
908    * never be reached. */
909   BLI_assert(collection != NULL);
910   if (collection == NULL) {
911     return false;
912   }
913 
914   if (!collection_object_add(bmain, collection, ob, 0, true)) {
915     return false;
916   }
917 
918   if (BKE_collection_is_in_scene(collection)) {
919     BKE_main_collection_sync(bmain);
920   }
921 
922   return true;
923 }
924 
925 /**
926  * Add \a ob_dst to all scene collections that reference object \a ob_src is in.
927  * Used for copying objects.
928  *
929  * Logic is very similar to #BKE_collection_add_from_object()
930  */
BKE_collection_object_add_from(Main * bmain,Scene * scene,Object * ob_src,Object * ob_dst)931 void BKE_collection_object_add_from(Main *bmain, Scene *scene, Object *ob_src, Object *ob_dst)
932 {
933   bool is_instantiated = false;
934 
935   FOREACH_SCENE_COLLECTION_BEGIN (scene, collection) {
936     if (!ID_IS_LINKED(collection) && !ID_IS_OVERRIDE_LIBRARY(collection) &&
937         BKE_collection_has_object(collection, ob_src)) {
938       collection_object_add(bmain, collection, ob_dst, 0, true);
939       is_instantiated = true;
940     }
941   }
942   FOREACH_SCENE_COLLECTION_END;
943 
944   if (!is_instantiated) {
945     /* In case we could not find any non-linked collections in which instantiate our ob_dst,
946      * fallback to scene's master collection... */
947     collection_object_add(bmain, scene->master_collection, ob_dst, 0, true);
948   }
949 
950   BKE_main_collection_sync(bmain);
951 }
952 
953 /**
954  * Remove object from collection.
955  */
BKE_collection_object_remove(Main * bmain,Collection * collection,Object * ob,const bool free_us)956 bool BKE_collection_object_remove(Main *bmain,
957                                   Collection *collection,
958                                   Object *ob,
959                                   const bool free_us)
960 {
961   if (ELEM(NULL, collection, ob)) {
962     return false;
963   }
964 
965   if (!collection_object_remove(bmain, collection, ob, free_us)) {
966     return false;
967   }
968 
969   if (BKE_collection_is_in_scene(collection)) {
970     BKE_main_collection_sync(bmain);
971   }
972 
973   return true;
974 }
975 
976 /**
977  * Remove object from all collections of scene
978  * \param collection_skip: Don't remove base from this collection.
979  */
scene_collections_object_remove(Main * bmain,Scene * scene,Object * ob,const bool free_us,Collection * collection_skip)980 static bool scene_collections_object_remove(
981     Main *bmain, Scene *scene, Object *ob, const bool free_us, Collection *collection_skip)
982 {
983   bool removed = false;
984 
985   if (collection_skip == NULL) {
986     BKE_scene_remove_rigidbody_object(bmain, scene, ob, free_us);
987   }
988 
989   FOREACH_SCENE_COLLECTION_BEGIN (scene, collection) {
990     if (collection != collection_skip) {
991       removed |= collection_object_remove(bmain, collection, ob, free_us);
992     }
993   }
994   FOREACH_SCENE_COLLECTION_END;
995 
996   BKE_main_collection_sync(bmain);
997 
998   return removed;
999 }
1000 
1001 /**
1002  * Remove object from all collections of scene
1003  */
BKE_scene_collections_object_remove(Main * bmain,Scene * scene,Object * ob,const bool free_us)1004 bool BKE_scene_collections_object_remove(Main *bmain, Scene *scene, Object *ob, const bool free_us)
1005 {
1006   return scene_collections_object_remove(bmain, scene, ob, free_us, NULL);
1007 }
1008 
1009 /*
1010  * Remove all NULL objects from collections.
1011  * This is used for library remapping, where these pointers have been set to NULL.
1012  * Otherwise this should never happen.
1013  */
collection_object_remove_nulls(Collection * collection)1014 static void collection_object_remove_nulls(Collection *collection)
1015 {
1016   bool changed = false;
1017 
1018   for (CollectionObject *cob = collection->gobject.first, *cob_next = NULL; cob; cob = cob_next) {
1019     cob_next = cob->next;
1020 
1021     if (cob->ob == NULL) {
1022       BLI_freelinkN(&collection->gobject, cob);
1023       changed = true;
1024     }
1025   }
1026 
1027   if (changed) {
1028     BKE_collection_object_cache_free(collection);
1029   }
1030 }
1031 
BKE_collections_object_remove_nulls(Main * bmain)1032 void BKE_collections_object_remove_nulls(Main *bmain)
1033 {
1034   for (Scene *scene = bmain->scenes.first; scene; scene = scene->id.next) {
1035     collection_object_remove_nulls(scene->master_collection);
1036   }
1037 
1038   for (Collection *collection = bmain->collections.first; collection;
1039        collection = collection->id.next) {
1040     collection_object_remove_nulls(collection);
1041   }
1042 }
1043 
collection_null_children_remove(Collection * collection)1044 static void collection_null_children_remove(Collection *collection)
1045 {
1046   for (CollectionChild *child = collection->children.first, *child_next = NULL; child;
1047        child = child_next) {
1048     child_next = child->next;
1049 
1050     if (child->collection == NULL) {
1051       BLI_freelinkN(&collection->children, child);
1052     }
1053   }
1054 }
1055 
collection_missing_parents_remove(Collection * collection)1056 static void collection_missing_parents_remove(Collection *collection)
1057 {
1058   for (CollectionParent *parent = collection->parents.first, *parent_next; parent != NULL;
1059        parent = parent_next) {
1060     parent_next = parent->next;
1061     if ((parent->collection == NULL) || !collection_find_child(parent->collection, collection)) {
1062       BLI_freelinkN(&collection->parents, parent);
1063     }
1064   }
1065 }
1066 
1067 /**
1068  * Remove all NULL children from parent collections of changed \a collection.
1069  * This is used for library remapping, where these pointers have been set to NULL.
1070  * Otherwise this should never happen.
1071  *
1072  * \note caller must ensure #BKE_main_collection_sync_remap() is called afterwards!
1073  *
1074  * \param collection: may be \a NULL,
1075  * in which case whole \a bmain database of collections is checked.
1076  */
BKE_collections_child_remove_nulls(Main * bmain,Collection * collection)1077 void BKE_collections_child_remove_nulls(Main *bmain, Collection *collection)
1078 {
1079   if (collection == NULL) {
1080     /* We need to do the checks in two steps when more than one collection may be involved,
1081      * otherwise we can miss some cases...
1082      * Also, master collections are not in bmain, so we also need to loop over scenes.
1083      */
1084     for (collection = bmain->collections.first; collection != NULL;
1085          collection = collection->id.next) {
1086       collection_null_children_remove(collection);
1087     }
1088     for (Scene *scene = bmain->scenes.first; scene != NULL; scene = scene->id.next) {
1089       collection_null_children_remove(scene->master_collection);
1090     }
1091 
1092     for (collection = bmain->collections.first; collection != NULL;
1093          collection = collection->id.next) {
1094       collection_missing_parents_remove(collection);
1095     }
1096     for (Scene *scene = bmain->scenes.first; scene != NULL; scene = scene->id.next) {
1097       collection_missing_parents_remove(scene->master_collection);
1098     }
1099   }
1100   else {
1101     for (CollectionParent *parent = collection->parents.first, *parent_next; parent;
1102          parent = parent_next) {
1103       parent_next = parent->next;
1104 
1105       collection_null_children_remove(parent->collection);
1106 
1107       if (!collection_find_child(parent->collection, collection)) {
1108         BLI_freelinkN(&collection->parents, parent);
1109       }
1110     }
1111   }
1112 }
1113 
1114 /**
1115  * Move object from a collection into another
1116  *
1117  * If source collection is NULL move it from all the existing collections.
1118  */
BKE_collection_object_move(Main * bmain,Scene * scene,Collection * collection_dst,Collection * collection_src,Object * ob)1119 void BKE_collection_object_move(
1120     Main *bmain, Scene *scene, Collection *collection_dst, Collection *collection_src, Object *ob)
1121 {
1122   /* In both cases we first add the object, then remove it from the other collections.
1123    * Otherwise we lose the original base and whether it was active and selected. */
1124   if (collection_src != NULL) {
1125     if (BKE_collection_object_add(bmain, collection_dst, ob)) {
1126       BKE_collection_object_remove(bmain, collection_src, ob, false);
1127     }
1128   }
1129   else {
1130     /* Adding will fail if object is already in collection.
1131      * However we still need to remove it from the other collections. */
1132     BKE_collection_object_add(bmain, collection_dst, ob);
1133     scene_collections_object_remove(bmain, scene, ob, false, collection_dst);
1134   }
1135 }
1136 
1137 /** \} */
1138 
1139 /* -------------------------------------------------------------------- */
1140 /** \name Collection Scene Membership
1141  * \{ */
1142 
BKE_collection_is_in_scene(Collection * collection)1143 bool BKE_collection_is_in_scene(Collection *collection)
1144 {
1145   if (collection->flag & COLLECTION_IS_MASTER) {
1146     return true;
1147   }
1148 
1149   LISTBASE_FOREACH (CollectionParent *, cparent, &collection->parents) {
1150     if (BKE_collection_is_in_scene(cparent->collection)) {
1151       return true;
1152     }
1153   }
1154 
1155   return false;
1156 }
1157 
BKE_collections_after_lib_link(Main * bmain)1158 void BKE_collections_after_lib_link(Main *bmain)
1159 {
1160   /* Need to update layer collections because objects might have changed
1161    * in linked files, and because undo push does not include updated base
1162    * flags since those are refreshed after the operator completes. */
1163   BKE_main_collection_sync(bmain);
1164 }
1165 
1166 /** \} */
1167 
1168 /* -------------------------------------------------------------------- */
1169 /** \name Collection Children
1170  * \{ */
1171 
collection_instance_find_recursive(Collection * collection,Collection * instance_collection)1172 static bool collection_instance_find_recursive(Collection *collection,
1173                                                Collection *instance_collection)
1174 {
1175   LISTBASE_FOREACH (CollectionObject *, collection_object, &collection->gobject) {
1176     if (collection_object->ob != NULL &&
1177         /* Object from a given collection should never instantiate that collection either. */
1178         ELEM(collection_object->ob->instance_collection, instance_collection, collection)) {
1179       return true;
1180     }
1181   }
1182 
1183   LISTBASE_FOREACH (CollectionChild *, collection_child, &collection->children) {
1184     if (collection_instance_find_recursive(collection_child->collection, instance_collection)) {
1185       return true;
1186     }
1187   }
1188 
1189   return false;
1190 }
1191 
1192 /**
1193  * Find potential cycles in collections.
1194  *
1195  * \param new_ancestor: the potential new owner of given \a collection,
1196  * or the collection to check if the later is NULL.
1197  * \param collection: the collection we want to add to \a new_ancestor,
1198  * may be NULL if we just want to ensure \a new_ancestor does not already have cycles.
1199  * \return true if a cycle is found.
1200  */
BKE_collection_cycle_find(Collection * new_ancestor,Collection * collection)1201 bool BKE_collection_cycle_find(Collection *new_ancestor, Collection *collection)
1202 {
1203   if (collection == new_ancestor) {
1204     return true;
1205   }
1206 
1207   if (collection == NULL) {
1208     collection = new_ancestor;
1209   }
1210 
1211   LISTBASE_FOREACH (CollectionParent *, parent, &new_ancestor->parents) {
1212     if (BKE_collection_cycle_find(parent->collection, collection)) {
1213       return true;
1214     }
1215   }
1216 
1217   /* Find possible objects in collection or its children, that would instantiate the given ancestor
1218    * collection (that would also make a fully invalid cycle of dependencies) .*/
1219   return collection_instance_find_recursive(collection, new_ancestor);
1220 }
1221 
collection_instance_fix_recursive(Collection * parent_collection,Collection * collection)1222 static bool collection_instance_fix_recursive(Collection *parent_collection,
1223                                               Collection *collection)
1224 {
1225   bool cycles_found = false;
1226 
1227   LISTBASE_FOREACH (CollectionObject *, collection_object, &parent_collection->gobject) {
1228     if (collection_object->ob != NULL &&
1229         collection_object->ob->instance_collection == collection) {
1230       id_us_min(&collection->id);
1231       collection_object->ob->instance_collection = NULL;
1232       cycles_found = true;
1233     }
1234   }
1235 
1236   LISTBASE_FOREACH (CollectionChild *, collection_child, &parent_collection->children) {
1237     if (collection_instance_fix_recursive(collection_child->collection, collection)) {
1238       cycles_found = true;
1239     }
1240   }
1241 
1242   return cycles_found;
1243 }
1244 
collection_cycle_fix_recursive(Main * bmain,Collection * parent_collection,Collection * collection)1245 static bool collection_cycle_fix_recursive(Main *bmain,
1246                                            Collection *parent_collection,
1247                                            Collection *collection)
1248 {
1249   bool cycles_found = false;
1250 
1251   LISTBASE_FOREACH_MUTABLE (CollectionParent *, parent, &parent_collection->parents) {
1252     if (BKE_collection_cycle_find(parent->collection, collection)) {
1253       BKE_collection_child_remove(bmain, parent->collection, parent_collection);
1254       cycles_found = true;
1255     }
1256     else if (collection_cycle_fix_recursive(bmain, parent->collection, collection)) {
1257       cycles_found = true;
1258     }
1259   }
1260 
1261   return cycles_found;
1262 }
1263 
1264 /**
1265  * Find and fix potential cycles in collections.
1266  *
1267  * \param collection: The collection to check for existing cycles.
1268  * \return true if cycles are found and fixed.
1269  */
BKE_collection_cycles_fix(Main * bmain,Collection * collection)1270 bool BKE_collection_cycles_fix(Main *bmain, Collection *collection)
1271 {
1272   return collection_cycle_fix_recursive(bmain, collection, collection) ||
1273          collection_instance_fix_recursive(collection, collection);
1274 }
1275 
collection_find_child(Collection * parent,Collection * collection)1276 static CollectionChild *collection_find_child(Collection *parent, Collection *collection)
1277 {
1278   return BLI_findptr(&parent->children, collection, offsetof(CollectionChild, collection));
1279 }
1280 
collection_find_child_recursive(Collection * parent,Collection * collection)1281 static bool collection_find_child_recursive(Collection *parent, Collection *collection)
1282 {
1283   LISTBASE_FOREACH (CollectionChild *, child, &parent->children) {
1284     if (child->collection == collection) {
1285       return true;
1286     }
1287 
1288     if (collection_find_child_recursive(child->collection, collection)) {
1289       return true;
1290     }
1291   }
1292 
1293   return false;
1294 }
1295 
BKE_collection_has_collection(Collection * parent,Collection * collection)1296 bool BKE_collection_has_collection(Collection *parent, Collection *collection)
1297 {
1298   return collection_find_child_recursive(parent, collection);
1299 }
1300 
collection_find_parent(Collection * child,Collection * collection)1301 static CollectionParent *collection_find_parent(Collection *child, Collection *collection)
1302 {
1303   return BLI_findptr(&child->parents, collection, offsetof(CollectionParent, collection));
1304 }
1305 
collection_child_add(Collection * parent,Collection * collection,const int flag,const bool add_us)1306 static bool collection_child_add(Collection *parent,
1307                                  Collection *collection,
1308                                  const int flag,
1309                                  const bool add_us)
1310 {
1311   CollectionChild *child = collection_find_child(parent, collection);
1312   if (child) {
1313     return false;
1314   }
1315   if (BKE_collection_cycle_find(parent, collection)) {
1316     return false;
1317   }
1318 
1319   child = MEM_callocN(sizeof(CollectionChild), "CollectionChild");
1320   child->collection = collection;
1321   BLI_addtail(&parent->children, child);
1322 
1323   /* Don't add parent links for depsgraph datablocks, these are not kept in sync. */
1324   if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
1325     CollectionParent *cparent = MEM_callocN(sizeof(CollectionParent), "CollectionParent");
1326     cparent->collection = parent;
1327     BLI_addtail(&collection->parents, cparent);
1328   }
1329 
1330   if (add_us) {
1331     id_us_plus(&collection->id);
1332   }
1333 
1334   BKE_collection_object_cache_free(parent);
1335 
1336   return true;
1337 }
1338 
collection_child_remove(Collection * parent,Collection * collection)1339 static bool collection_child_remove(Collection *parent, Collection *collection)
1340 {
1341   CollectionChild *child = collection_find_child(parent, collection);
1342   if (child == NULL) {
1343     return false;
1344   }
1345 
1346   CollectionParent *cparent = collection_find_parent(collection, parent);
1347   BLI_freelinkN(&collection->parents, cparent);
1348   BLI_freelinkN(&parent->children, child);
1349 
1350   id_us_min(&collection->id);
1351 
1352   BKE_collection_object_cache_free(parent);
1353 
1354   return true;
1355 }
1356 
BKE_collection_child_add(Main * bmain,Collection * parent,Collection * child)1357 bool BKE_collection_child_add(Main *bmain, Collection *parent, Collection *child)
1358 {
1359   if (!collection_child_add(parent, child, 0, true)) {
1360     return false;
1361   }
1362 
1363   BKE_main_collection_sync(bmain);
1364   return true;
1365 }
1366 
BKE_collection_child_add_no_sync(Collection * parent,Collection * child)1367 bool BKE_collection_child_add_no_sync(Collection *parent, Collection *child)
1368 {
1369   return collection_child_add(parent, child, 0, true);
1370 }
1371 
BKE_collection_child_remove(Main * bmain,Collection * parent,Collection * child)1372 bool BKE_collection_child_remove(Main *bmain, Collection *parent, Collection *child)
1373 {
1374   if (!collection_child_remove(parent, child)) {
1375     return false;
1376   }
1377 
1378   BKE_main_collection_sync(bmain);
1379   return true;
1380 }
1381 
1382 /**
1383  * Rebuild parent relationships from child ones, for all children of given \a collection.
1384  *
1385  * \note Given collection is assumed to already have valid parents.
1386  */
BKE_collection_parent_relations_rebuild(Collection * collection)1387 void BKE_collection_parent_relations_rebuild(Collection *collection)
1388 {
1389   for (CollectionChild *child = collection->children.first, *child_next = NULL; child;
1390        child = child_next) {
1391     child_next = child->next;
1392 
1393     if (child->collection == NULL || BKE_collection_cycle_find(collection, child->collection)) {
1394       BLI_freelinkN(&collection->children, child);
1395     }
1396     else {
1397       CollectionParent *cparent = MEM_callocN(sizeof(CollectionParent), __func__);
1398       cparent->collection = collection;
1399       BLI_addtail(&child->collection->parents, cparent);
1400     }
1401   }
1402 }
1403 
collection_parents_rebuild_recursive(Collection * collection)1404 static void collection_parents_rebuild_recursive(Collection *collection)
1405 {
1406   BKE_collection_parent_relations_rebuild(collection);
1407   collection->tag &= ~COLLECTION_TAG_RELATION_REBUILD;
1408 
1409   for (CollectionChild *child = collection->children.first; child != NULL; child = child->next) {
1410     collection_parents_rebuild_recursive(child->collection);
1411   }
1412 }
1413 
1414 /**
1415  * Rebuild parent relationships from child ones, for all collections in given \a bmain.
1416  */
BKE_main_collections_parent_relations_rebuild(Main * bmain)1417 void BKE_main_collections_parent_relations_rebuild(Main *bmain)
1418 {
1419   /* Only collections not in bmain (master ones in scenes) have no parent... */
1420   for (Collection *collection = bmain->collections.first; collection != NULL;
1421        collection = collection->id.next) {
1422     BLI_freelistN(&collection->parents);
1423 
1424     collection->tag |= COLLECTION_TAG_RELATION_REBUILD;
1425   }
1426 
1427   /* Scene's master collections will be 'root' parent of most of our collections, so start with
1428    * them. */
1429   for (Scene *scene = bmain->scenes.first; scene != NULL; scene = scene->id.next) {
1430     /* This function can be called from readfile.c, when this pointer is not guaranteed to be NULL.
1431      */
1432     if (scene->master_collection != NULL) {
1433       collection_parents_rebuild_recursive(scene->master_collection);
1434     }
1435   }
1436 
1437   /* We may have parent chains outside of scene's master_collection context? At least, readfile's
1438    * lib_link_collection_data() seems to assume that, so do the same here. */
1439   for (Collection *collection = bmain->collections.first; collection != NULL;
1440        collection = collection->id.next) {
1441     if (collection->tag & COLLECTION_TAG_RELATION_REBUILD) {
1442       /* Note: we do not have easy access to 'which collections is root' info in that case, which
1443        * means test for cycles in collection relationships may fail here. I don't think that is an
1444        * issue in practice here, but worth keeping in mind... */
1445       collection_parents_rebuild_recursive(collection);
1446     }
1447   }
1448 }
1449 
1450 /** \} */
1451 
1452 /* -------------------------------------------------------------------- */
1453 /** \name Collection Index
1454  * \{ */
1455 
collection_from_index_recursive(Collection * collection,const int index,int * index_current)1456 static Collection *collection_from_index_recursive(Collection *collection,
1457                                                    const int index,
1458                                                    int *index_current)
1459 {
1460   if (index == (*index_current)) {
1461     return collection;
1462   }
1463 
1464   (*index_current)++;
1465 
1466   LISTBASE_FOREACH (CollectionChild *, child, &collection->children) {
1467     Collection *nested = collection_from_index_recursive(child->collection, index, index_current);
1468     if (nested != NULL) {
1469       return nested;
1470     }
1471   }
1472   return NULL;
1473 }
1474 
1475 /**
1476  * Return Scene Collection for a given index.
1477  *
1478  * The index is calculated from top to bottom counting the children before the siblings.
1479  */
BKE_collection_from_index(Scene * scene,const int index)1480 Collection *BKE_collection_from_index(Scene *scene, const int index)
1481 {
1482   int index_current = 0;
1483   Collection *master_collection = scene->master_collection;
1484   return collection_from_index_recursive(master_collection, index, &index_current);
1485 }
1486 
collection_objects_select(ViewLayer * view_layer,Collection * collection,bool deselect)1487 static bool collection_objects_select(ViewLayer *view_layer, Collection *collection, bool deselect)
1488 {
1489   bool changed = false;
1490 
1491   if (collection->flag & COLLECTION_RESTRICT_SELECT) {
1492     return false;
1493   }
1494 
1495   LISTBASE_FOREACH (CollectionObject *, cob, &collection->gobject) {
1496     Base *base = BKE_view_layer_base_find(view_layer, cob->ob);
1497 
1498     if (base) {
1499       if (deselect) {
1500         if (base->flag & BASE_SELECTED) {
1501           base->flag &= ~BASE_SELECTED;
1502           changed = true;
1503         }
1504       }
1505       else {
1506         if ((base->flag & BASE_SELECTABLE) && !(base->flag & BASE_SELECTED)) {
1507           base->flag |= BASE_SELECTED;
1508           changed = true;
1509         }
1510       }
1511     }
1512   }
1513 
1514   LISTBASE_FOREACH (CollectionChild *, child, &collection->children) {
1515     if (collection_objects_select(view_layer, collection, deselect)) {
1516       changed = true;
1517     }
1518   }
1519 
1520   return changed;
1521 }
1522 
1523 /**
1524  * Select all the objects in this Collection (and its nested collections) for this ViewLayer.
1525  * Return true if any object was selected.
1526  */
BKE_collection_objects_select(ViewLayer * view_layer,Collection * collection,bool deselect)1527 bool BKE_collection_objects_select(ViewLayer *view_layer, Collection *collection, bool deselect)
1528 {
1529   LayerCollection *layer_collection = BKE_layer_collection_first_from_scene_collection(view_layer,
1530                                                                                        collection);
1531 
1532   if (layer_collection != NULL) {
1533     return BKE_layer_collection_objects_select(view_layer, layer_collection, deselect);
1534   }
1535 
1536   return collection_objects_select(view_layer, collection, deselect);
1537 }
1538 
1539 /** \} */
1540 
1541 /* -------------------------------------------------------------------- */
1542 /** \name Collection move (outliner drag & drop)
1543  * \{ */
1544 
1545 /* Local temporary storage for layer collection flags. */
1546 typedef struct LayerCollectionFlag {
1547   struct LayerCollectionFlag *next, *prev;
1548   /** The view layer for the collections being moved, NULL for their children. */
1549   ViewLayer *view_layer;
1550   /** The original #LayerCollection's collection field. */
1551   Collection *collection;
1552   /** The original #LayerCollection's flag. */
1553   int flag;
1554   /** Corresponds to #LayerCollection->layer_collections. */
1555   ListBase children;
1556 } LayerCollectionFlag;
1557 
layer_collection_flags_store_recursive(const LayerCollection * layer_collection,LayerCollectionFlag * flag)1558 static void layer_collection_flags_store_recursive(const LayerCollection *layer_collection,
1559                                                    LayerCollectionFlag *flag)
1560 {
1561   flag->collection = layer_collection->collection;
1562   flag->flag = layer_collection->flag;
1563 
1564   LISTBASE_FOREACH (const LayerCollection *, child, &layer_collection->layer_collections) {
1565     LayerCollectionFlag *child_flag = MEM_callocN(sizeof(LayerCollectionFlag), __func__);
1566     BLI_addtail(&flag->children, child_flag);
1567     layer_collection_flags_store_recursive(child, child_flag);
1568   }
1569 }
1570 
1571 /**
1572  * For every view layer, find the \a collection and save flags
1573  * for it and its children in a temporary tree structure.
1574  */
layer_collection_flags_store(Main * bmain,const Collection * collection,ListBase * r_layer_level_list)1575 static void layer_collection_flags_store(Main *bmain,
1576                                          const Collection *collection,
1577                                          ListBase *r_layer_level_list)
1578 {
1579   BLI_listbase_clear(r_layer_level_list);
1580   LISTBASE_FOREACH (Scene *, scene, &bmain->scenes) {
1581     LISTBASE_FOREACH (ViewLayer *, view_layer, &scene->view_layers) {
1582       LayerCollection *layer_collection = BKE_layer_collection_first_from_scene_collection(
1583           view_layer, collection);
1584       /* Skip this view layer if the collection isn't found for some reason. */
1585       if (layer_collection == NULL) {
1586         continue;
1587       }
1588 
1589       /* Store the flags for the collection and all of its children. */
1590       LayerCollectionFlag *flag = MEM_callocN(sizeof(LayerCollectionFlag), __func__);
1591       flag->view_layer = view_layer;
1592 
1593       /* Recursively save flags from collection children. */
1594       layer_collection_flags_store_recursive(layer_collection, flag);
1595 
1596       BLI_addtail(r_layer_level_list, flag);
1597     }
1598   }
1599 }
1600 
layer_collection_flags_restore_recursive(LayerCollection * layer_collection,LayerCollectionFlag * flag)1601 static void layer_collection_flags_restore_recursive(LayerCollection *layer_collection,
1602                                                      LayerCollectionFlag *flag)
1603 {
1604   /* There should be a flag struct for every layer collection. */
1605   BLI_assert(BLI_listbase_count(&layer_collection->layer_collections) ==
1606              BLI_listbase_count(&flag->children));
1607   /* The flag and the the layer collection should actually correspond. */
1608   BLI_assert(flag->collection == layer_collection->collection);
1609 
1610   LayerCollectionFlag *child_flag = flag->children.first;
1611   LISTBASE_FOREACH (LayerCollection *, child, &layer_collection->layer_collections) {
1612     layer_collection_flags_restore_recursive(child, child_flag);
1613 
1614     child_flag = child_flag->next;
1615   }
1616   BLI_freelistN(&flag->children);
1617 
1618   /* We treat exclude as a special case.
1619    *
1620    * If in a different view layer the parent collection was disabled (e.g., background)
1621    * and now we moved a new collection to be part of the background this collection should
1622    * probably be disabled.
1623    *
1624    * Note: If we were to also keep the exclude flag we would need to re-sync the collections.
1625    */
1626   layer_collection->flag = flag->flag | (layer_collection->flag & LAYER_COLLECTION_EXCLUDE);
1627 }
1628 
1629 /**
1630  * Restore a collection's (and its children's) flags for each view layer
1631  * from the structure built in #layer_collection_flags_store.
1632  */
layer_collection_flags_restore(ListBase * flags,const Collection * collection)1633 static void layer_collection_flags_restore(ListBase *flags, const Collection *collection)
1634 {
1635   LISTBASE_FOREACH (LayerCollectionFlag *, flag, flags) {
1636     ViewLayer *view_layer = flag->view_layer;
1637     /* The top level of flag structs must have this set. */
1638     BLI_assert(view_layer != NULL);
1639 
1640     LayerCollection *layer_collection = BKE_layer_collection_first_from_scene_collection(
1641         view_layer, collection);
1642     /* The flags should only be added if the collection is in the view layer. */
1643     BLI_assert(layer_collection != NULL);
1644 
1645     layer_collection_flags_restore_recursive(layer_collection, flag);
1646   }
1647 
1648   BLI_freelistN(flags);
1649 }
1650 
BKE_collection_move(Main * bmain,Collection * to_parent,Collection * from_parent,Collection * relative,bool relative_after,Collection * collection)1651 bool BKE_collection_move(Main *bmain,
1652                          Collection *to_parent,
1653                          Collection *from_parent,
1654                          Collection *relative,
1655                          bool relative_after,
1656                          Collection *collection)
1657 {
1658   if (collection->flag & COLLECTION_IS_MASTER) {
1659     return false;
1660   }
1661   if (BKE_collection_cycle_find(to_parent, collection)) {
1662     return false;
1663   }
1664 
1665   /* Move to new parent collection */
1666   if (from_parent) {
1667     collection_child_remove(from_parent, collection);
1668   }
1669 
1670   collection_child_add(to_parent, collection, 0, true);
1671 
1672   /* Move to specified location under parent. */
1673   if (relative) {
1674     CollectionChild *child = collection_find_child(to_parent, collection);
1675     CollectionChild *relative_child = collection_find_child(to_parent, relative);
1676 
1677     if (relative_child) {
1678       BLI_remlink(&to_parent->children, child);
1679 
1680       if (relative_after) {
1681         BLI_insertlinkafter(&to_parent->children, relative_child, child);
1682       }
1683       else {
1684         BLI_insertlinkbefore(&to_parent->children, relative_child, child);
1685       }
1686 
1687       BKE_collection_object_cache_free(to_parent);
1688     }
1689   }
1690 
1691   /* Make sure we store the flag of the layer collections before we remove and re-create them.
1692    * Otherwise they will get lost and everything will be copied from the new parent collection.
1693    * Don't use flag syncing when moving a collection to a different scene, as it no longer exists
1694    * in the same view layers anyway. */
1695   const bool do_flag_sync = BKE_scene_find_from_collection(bmain, to_parent) ==
1696                             BKE_scene_find_from_collection(bmain, collection);
1697   ListBase layer_flags;
1698   if (do_flag_sync) {
1699     layer_collection_flags_store(bmain, collection, &layer_flags);
1700   }
1701 
1702   /* Create and remove layer collections. */
1703   BKE_main_collection_sync(bmain);
1704 
1705   /* Restore the original layer collection flags. */
1706   if (do_flag_sync) {
1707     layer_collection_flags_restore(&layer_flags, collection);
1708   }
1709 
1710   /* We need to sync it again to pass the correct flags to the collections objects. */
1711   BKE_main_collection_sync(bmain);
1712 
1713   return true;
1714 }
1715 
1716 /** \} */
1717 
1718 /* -------------------------------------------------------------------- */
1719 /** \name Iterators
1720  * \{ */
1721 
1722 /* scene collection iteractor */
1723 
1724 typedef struct CollectionsIteratorData {
1725   Scene *scene;
1726   void **array;
1727   int tot, cur;
1728 } CollectionsIteratorData;
1729 
scene_collection_callback(Collection * collection,BKE_scene_collections_Cb callback,void * data)1730 static void scene_collection_callback(Collection *collection,
1731                                       BKE_scene_collections_Cb callback,
1732                                       void *data)
1733 {
1734   callback(collection, data);
1735 
1736   LISTBASE_FOREACH (CollectionChild *, child, &collection->children) {
1737     scene_collection_callback(child->collection, callback, data);
1738   }
1739 }
1740 
scene_collections_count(Collection * UNUSED (collection),void * data)1741 static void scene_collections_count(Collection *UNUSED(collection), void *data)
1742 {
1743   int *tot = data;
1744   (*tot)++;
1745 }
1746 
scene_collections_build_array(Collection * collection,void * data)1747 static void scene_collections_build_array(Collection *collection, void *data)
1748 {
1749   Collection ***array = data;
1750   **array = collection;
1751   (*array)++;
1752 }
1753 
scene_collections_array(Scene * scene,Collection *** collections_array,int * tot)1754 static void scene_collections_array(Scene *scene, Collection ***collections_array, int *tot)
1755 {
1756   Collection *collection;
1757   Collection **array;
1758 
1759   *collections_array = NULL;
1760   *tot = 0;
1761 
1762   if (scene == NULL) {
1763     return;
1764   }
1765 
1766   collection = scene->master_collection;
1767   BLI_assert(collection != NULL);
1768   scene_collection_callback(collection, scene_collections_count, tot);
1769 
1770   if (*tot == 0) {
1771     return;
1772   }
1773 
1774   *collections_array = array = MEM_mallocN(sizeof(Collection *) * (*tot), "CollectionArray");
1775   scene_collection_callback(collection, scene_collections_build_array, &array);
1776 }
1777 
1778 /**
1779  * Only use this in non-performance critical situations
1780  * (it iterates over all scene collections twice)
1781  */
BKE_scene_collections_iterator_begin(BLI_Iterator * iter,void * data_in)1782 void BKE_scene_collections_iterator_begin(BLI_Iterator *iter, void *data_in)
1783 {
1784   Scene *scene = data_in;
1785   CollectionsIteratorData *data = MEM_callocN(sizeof(CollectionsIteratorData), __func__);
1786 
1787   data->scene = scene;
1788   iter->data = data;
1789   iter->valid = true;
1790 
1791   scene_collections_array(scene, (Collection ***)&data->array, &data->tot);
1792   BLI_assert(data->tot != 0);
1793 
1794   data->cur = 0;
1795   iter->current = data->array[data->cur];
1796 }
1797 
BKE_scene_collections_iterator_next(struct BLI_Iterator * iter)1798 void BKE_scene_collections_iterator_next(struct BLI_Iterator *iter)
1799 {
1800   CollectionsIteratorData *data = iter->data;
1801 
1802   if (++data->cur < data->tot) {
1803     iter->current = data->array[data->cur];
1804   }
1805   else {
1806     iter->valid = false;
1807   }
1808 }
1809 
BKE_scene_collections_iterator_end(struct BLI_Iterator * iter)1810 void BKE_scene_collections_iterator_end(struct BLI_Iterator *iter)
1811 {
1812   CollectionsIteratorData *data = iter->data;
1813 
1814   if (data) {
1815     if (data->array) {
1816       MEM_freeN(data->array);
1817     }
1818     MEM_freeN(data);
1819   }
1820   iter->valid = false;
1821 }
1822 
1823 /* scene objects iterator */
1824 
1825 typedef struct SceneObjectsIteratorData {
1826   GSet *visited;
1827   CollectionObject *cob_next;
1828   BLI_Iterator scene_collection_iter;
1829 } SceneObjectsIteratorData;
1830 
BKE_scene_objects_iterator_begin(BLI_Iterator * iter,void * data_in)1831 void BKE_scene_objects_iterator_begin(BLI_Iterator *iter, void *data_in)
1832 {
1833   Scene *scene = data_in;
1834   SceneObjectsIteratorData *data = MEM_callocN(sizeof(SceneObjectsIteratorData), __func__);
1835   iter->data = data;
1836 
1837   /* lookup list ot make sure each object is object called once */
1838   data->visited = BLI_gset_ptr_new(__func__);
1839 
1840   /* we wrap the scenecollection iterator here to go over the scene collections */
1841   BKE_scene_collections_iterator_begin(&data->scene_collection_iter, scene);
1842 
1843   Collection *collection = data->scene_collection_iter.current;
1844   data->cob_next = collection->gobject.first;
1845 
1846   BKE_scene_objects_iterator_next(iter);
1847 }
1848 
1849 /**
1850  * Ensures we only get each object once, even when included in several collections.
1851  */
object_base_unique(GSet * gs,CollectionObject * cob)1852 static CollectionObject *object_base_unique(GSet *gs, CollectionObject *cob)
1853 {
1854   for (; cob != NULL; cob = cob->next) {
1855     Object *ob = cob->ob;
1856     void **ob_key_p;
1857     if (!BLI_gset_ensure_p_ex(gs, ob, &ob_key_p)) {
1858       *ob_key_p = ob;
1859       return cob;
1860     }
1861   }
1862   return NULL;
1863 }
1864 
BKE_scene_objects_iterator_next(BLI_Iterator * iter)1865 void BKE_scene_objects_iterator_next(BLI_Iterator *iter)
1866 {
1867   SceneObjectsIteratorData *data = iter->data;
1868   CollectionObject *cob = data->cob_next ? object_base_unique(data->visited, data->cob_next) :
1869                                            NULL;
1870 
1871   if (cob) {
1872     data->cob_next = cob->next;
1873     iter->current = cob->ob;
1874   }
1875   else {
1876     /* if this is the last object of this ListBase look at the next Collection */
1877     Collection *collection;
1878     BKE_scene_collections_iterator_next(&data->scene_collection_iter);
1879     do {
1880       collection = data->scene_collection_iter.current;
1881       /* get the first unique object of this collection */
1882       CollectionObject *new_cob = object_base_unique(data->visited, collection->gobject.first);
1883       if (new_cob) {
1884         data->cob_next = new_cob->next;
1885         iter->current = new_cob->ob;
1886         return;
1887       }
1888       BKE_scene_collections_iterator_next(&data->scene_collection_iter);
1889     } while (data->scene_collection_iter.valid);
1890 
1891     if (!data->scene_collection_iter.valid) {
1892       iter->valid = false;
1893     }
1894   }
1895 }
1896 
BKE_scene_objects_iterator_end(BLI_Iterator * iter)1897 void BKE_scene_objects_iterator_end(BLI_Iterator *iter)
1898 {
1899   SceneObjectsIteratorData *data = iter->data;
1900   if (data) {
1901     BKE_scene_collections_iterator_end(&data->scene_collection_iter);
1902     BLI_gset_free(data->visited, NULL);
1903     MEM_freeN(data);
1904   }
1905 }
1906 
1907 /** \} */
1908