Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenkernel / intern / library.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/library.c
29  *  \ingroup bke
30  *
31  * Contains management of ID's and libraries
32  * allocate and free of all library data
33  */
34
35 #include <stdio.h>
36 #include <ctype.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <stddef.h>
40 #include <assert.h>
41
42 #include "MEM_guardedalloc.h"
43
44 /* all types are needed here, in order to do memory operations */
45 #include "DNA_anim_types.h"
46 #include "DNA_armature_types.h"
47 #include "DNA_brush_types.h"
48 #include "DNA_camera_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_gpencil_types.h"
51 #include "DNA_ipo_types.h"
52 #include "DNA_key_types.h"
53 #include "DNA_lamp_types.h"
54 #include "DNA_lattice_types.h"
55 #include "DNA_linestyle_types.h"
56 #include "DNA_material_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_meta_types.h"
59 #include "DNA_movieclip_types.h"
60 #include "DNA_mask_types.h"
61 #include "DNA_node_types.h"
62 #include "DNA_object_types.h"
63 #include "DNA_scene_types.h"
64 #include "DNA_screen_types.h"
65 #include "DNA_speaker_types.h"
66 #include "DNA_sound_types.h"
67 #include "DNA_text_types.h"
68 #include "DNA_vfont_types.h"
69 #include "DNA_windowmanager_types.h"
70 #include "DNA_world_types.h"
71
72 #include "BLI_blenlib.h"
73 #include "BLI_utildefines.h"
74
75 #include "BLI_threads.h"
76 #include "BLT_translation.h"
77
78 #include "BKE_action.h"
79 #include "BKE_animsys.h"
80 #include "BKE_armature.h"
81 #include "BKE_bpath.h"
82 #include "BKE_brush.h"
83 #include "BKE_camera.h"
84 #include "BKE_context.h"
85 #include "BKE_curve.h"
86 #include "BKE_depsgraph.h"
87 #include "BKE_fcurve.h"
88 #include "BKE_font.h"
89 #include "BKE_global.h"
90 #include "BKE_group.h"
91 #include "BKE_gpencil.h"
92 #include "BKE_idcode.h"
93 #include "BKE_idprop.h"
94 #include "BKE_image.h"
95 #include "BKE_ipo.h"
96 #include "BKE_key.h"
97 #include "BKE_lamp.h"
98 #include "BKE_lattice.h"
99 #include "BKE_library.h"
100 #include "BKE_library_query.h"
101 #include "BKE_linestyle.h"
102 #include "BKE_mesh.h"
103 #include "BKE_material.h"
104 #include "BKE_main.h"
105 #include "BKE_mball.h"
106 #include "BKE_movieclip.h"
107 #include "BKE_mask.h"
108 #include "BKE_node.h"
109 #include "BKE_object.h"
110 #include "BKE_paint.h"
111 #include "BKE_packedFile.h"
112 #include "BKE_speaker.h"
113 #include "BKE_sound.h"
114 #include "BKE_screen.h"
115 #include "BKE_scene.h"
116 #include "BKE_text.h"
117 #include "BKE_texture.h"
118 #include "BKE_world.h"
119
120 #include "DEG_depsgraph.h"
121
122 #include "RNA_access.h"
123
124 #include "IMB_imbuf.h"
125 #include "IMB_imbuf_types.h"
126
127 #ifdef WITH_PYTHON
128 #include "BPY_extern.h"
129 #endif
130
131 /* GS reads the memory pointed at in a specific ordering. 
132  * only use this definition, makes little and big endian systems
133  * work fine, in conjunction with MAKE_ID */
134
135 /* ************* general ************************ */
136
137
138 /* this has to be called from each make_local_* func, we could call
139  * from id_make_local() but then the make local functions would not be self
140  * contained.
141  * also note that the id _must_ have a library - campbell */
142 void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
143 {
144         const char *bpath_user_data[2] = {bmain->name, lib->filepath};
145
146         BKE_bpath_traverse_id(bmain, id,
147                               BKE_bpath_relocate_visitor,
148                               BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
149                               (void *)bpath_user_data);
150 }
151
152 void id_lib_extern(ID *id)
153 {
154         if (id) {
155                 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
156                 if (id->tag & LIB_TAG_INDIRECT) {
157                         id->tag -= LIB_TAG_INDIRECT;
158                         id->tag |= LIB_TAG_EXTERN;
159                 }
160         }
161 }
162
163 /* ensure we have a real user */
164 /* Note: Now that we have flags, we could get rid of the 'fake_user' special case, flags are enough to ensure
165  *       we always have a real user.
166  *       However, ID_REAL_USERS is used in several places outside of core library.c, so think we can wait later
167  *       to make this change... */
168 void id_us_ensure_real(ID *id)
169 {
170         if (id) {
171                 const int limit = ID_FAKE_USERS(id);
172                 id->tag |= LIB_TAG_EXTRAUSER;
173                 if (id->us <= limit) {
174                         if (id->us < limit || ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER_SET))) {
175                                 printf("ID user count error: %s (from '%s')\n", id->name, id->lib ? id->lib->filepath : "[Main]");
176                                 BLI_assert(0);
177                         }
178                         id->us = limit + 1;
179                         id->tag |= LIB_TAG_EXTRAUSER_SET;
180                 }
181         }
182 }
183
184 /* Unused currently... */
185 void id_us_clear_real(ID *id)
186 {
187         if (id && (id->tag & LIB_TAG_EXTRAUSER)) {
188                 if (id->tag & LIB_TAG_EXTRAUSER_SET) {
189                         id->us--;
190                         BLI_assert(id->us >= ID_FAKE_USERS(id));
191                 }
192                 id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
193         }
194 }
195
196 /**
197  * Same as \a id_us_plus, but does not handle lib indirect -> extern.
198  * Only used by readfile.c so far, but simpler/safer to keep it here nonetheless.
199  */
200 void id_us_plus_no_lib(ID *id)
201 {
202         if (id) {
203                 if ((id->tag & LIB_TAG_EXTRAUSER) && (id->tag & LIB_TAG_EXTRAUSER_SET)) {
204                         BLI_assert(id->us >= 1);
205                         /* No need to increase count, just tag extra user as no more set.
206                          * Avoids annoying & inconsistent +1 in user count. */
207                         id->tag &= ~LIB_TAG_EXTRAUSER_SET;
208                 }
209                 else {
210                         BLI_assert(id->us >= 0);
211                         id->us++;
212                 }
213         }
214 }
215
216
217 void id_us_plus(ID *id)
218 {
219         if (id) {
220                 id_us_plus_no_lib(id);
221                 id_lib_extern(id);
222         }
223 }
224
225 /* decrements the user count for *id. */
226 void id_us_min(ID *id)
227 {
228         if (id) {
229                 const int limit = ID_FAKE_USERS(id);
230
231                 if (id->us <= limit) {
232                         printf("ID user decrement error: %s (from '%s'): %d <= %d\n",
233                                id->name, id->lib ? id->lib->filepath : "[Main]", id->us, limit);
234                         /* We cannot assert here, because of how we 'delete' datablocks currently (setting their usercount to zero),
235                          * this is weak but it's how it works for now. */
236                         /* BLI_assert(0); */
237                         id->us = limit;
238                 }
239                 else {
240                         id->us--;
241                 }
242
243                 if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) {
244                         /* We need an extra user here, but never actually incremented user count for it so far, do it now. */
245                         id_us_ensure_real(id);
246                 }
247         }
248 }
249
250 void id_fake_user_set(ID *id)
251 {
252         if (id && !(id->flag & LIB_FAKEUSER)) {
253                 id->flag |= LIB_FAKEUSER;
254                 id_us_plus(id);
255         }
256 }
257
258 void id_fake_user_clear(ID *id)
259 {
260         if (id && (id->flag & LIB_FAKEUSER)) {
261                 id->flag &= ~LIB_FAKEUSER;
262                 id_us_min(id);
263         }
264 }
265
266 /* calls the appropriate make_local method for the block, unless test. Returns true
267  * if the block can be made local. */
268 bool id_make_local(ID *id, bool test)
269 {
270         if (id->tag & LIB_TAG_INDIRECT)
271                 return false;
272
273         switch (GS(id->name)) {
274                 case ID_SCE:
275                         return false; /* not implemented */
276                 case ID_LI:
277                         return false; /* can't be linked */
278                 case ID_OB:
279                         if (!test) BKE_object_make_local((Object *)id);
280                         return true;
281                 case ID_ME:
282                         if (!test) {
283                                 BKE_mesh_make_local((Mesh *)id);
284                                 BKE_key_make_local(((Mesh *)id)->key);
285                         }
286                         return true;
287                 case ID_CU:
288                         if (!test) {
289                                 BKE_curve_make_local((Curve *)id);
290                                 BKE_key_make_local(((Curve *)id)->key);
291                         }
292                         return true;
293                 case ID_MB:
294                         if (!test) BKE_mball_make_local((MetaBall *)id);
295                         return true;
296                 case ID_MA:
297                         if (!test) BKE_material_make_local((Material *)id);
298                         return true;
299                 case ID_TE:
300                         if (!test) BKE_texture_make_local((Tex *)id);
301                         return true;
302                 case ID_IM:
303                         if (!test) BKE_image_make_local((Image *)id);
304                         return true;
305                 case ID_LT:
306                         if (!test) {
307                                 BKE_lattice_make_local((Lattice *)id);
308                                 BKE_key_make_local(((Lattice *)id)->key);
309                         }
310                         return true;
311                 case ID_LA:
312                         if (!test) BKE_lamp_make_local((Lamp *)id);
313                         return true;
314                 case ID_CA:
315                         if (!test) BKE_camera_make_local((Camera *)id);
316                         return true;
317                 case ID_SPK:
318                         if (!test) BKE_speaker_make_local((Speaker *)id);
319                         return true;
320                 case ID_IP:
321                         return false; /* deprecated */
322                 case ID_KE:
323                         if (!test) BKE_key_make_local((Key *)id);
324                         return true;
325                 case ID_WO:
326                         if (!test) BKE_world_make_local((World *)id);
327                         return true;
328                 case ID_SCR:
329                         return false; /* can't be linked */
330                 case ID_VF:
331                         return false; /* not implemented */
332                 case ID_TXT:
333                         return false; /* not implemented */
334                 case ID_SO:
335                         return false; /* not implemented */
336                 case ID_GR:
337                         return false; /* not implemented */
338                 case ID_AR:
339                         if (!test) BKE_armature_make_local((bArmature *)id);
340                         return true;
341                 case ID_AC:
342                         if (!test) BKE_action_make_local((bAction *)id);
343                         return true;
344                 case ID_NT:
345                         if (!test) ntreeMakeLocal((bNodeTree *)id, true);
346                         return true;
347                 case ID_BR:
348                         if (!test) BKE_brush_make_local((Brush *)id);
349                         return true;
350                 case ID_WM:
351                         return false; /* can't be linked */
352                 case ID_GD:
353                         return false; /* not implemented */
354                 case ID_LS:
355                         return false; /* not implemented */
356         }
357
358         return false;
359 }
360
361 /**
362  * Invokes the appropriate copy method for the block and returns the result in
363  * newid, unless test. Returns true if the block can be copied.
364  */
365 bool id_copy(ID *id, ID **newid, bool test)
366 {
367         if (!test) *newid = NULL;
368
369         /* conventions:
370          * - make shallow copy, only this ID block
371          * - id.us of the new ID is set to 1 */
372         switch (GS(id->name)) {
373                 case ID_SCE:
374                         return false;  /* can't be copied from here */
375                 case ID_LI:
376                         return false;  /* can't be copied from here */
377                 case ID_OB:
378                         if (!test) *newid = (ID *)BKE_object_copy((Object *)id);
379                         return true;
380                 case ID_ME:
381                         if (!test) *newid = (ID *)BKE_mesh_copy((Mesh *)id);
382                         return true;
383                 case ID_CU:
384                         if (!test) *newid = (ID *)BKE_curve_copy((Curve *)id);
385                         return true;
386                 case ID_MB:
387                         if (!test) *newid = (ID *)BKE_mball_copy((MetaBall *)id);
388                         return true;
389                 case ID_MA:
390                         if (!test) *newid = (ID *)BKE_material_copy((Material *)id);
391                         return true;
392                 case ID_TE:
393                         if (!test) *newid = (ID *)BKE_texture_copy((Tex *)id);
394                         return true;
395                 case ID_IM:
396                         if (!test) *newid = (ID *)BKE_image_copy(G.main, (Image *)id);
397                         return true;
398                 case ID_LT:
399                         if (!test) *newid = (ID *)BKE_lattice_copy((Lattice *)id);
400                         return true;
401                 case ID_LA:
402                         if (!test) *newid = (ID *)BKE_lamp_copy((Lamp *)id);
403                         return true;
404                 case ID_SPK:
405                         if (!test) *newid = (ID *)BKE_speaker_copy((Speaker *)id);
406                         return true;
407                 case ID_CA:
408                         if (!test) *newid = (ID *)BKE_camera_copy((Camera *)id);
409                         return true;
410                 case ID_IP:
411                         return false;  /* deprecated */
412                 case ID_KE:
413                         if (!test) *newid = (ID *)BKE_key_copy((Key *)id);
414                         return true;
415                 case ID_WO:
416                         if (!test) *newid = (ID *)BKE_world_copy((World *)id);
417                         return true;
418                 case ID_SCR:
419                         return false;  /* can't be copied from here */
420                 case ID_VF:
421                         return false;  /* not implemented */
422                 case ID_TXT:
423                         if (!test) *newid = (ID *)BKE_text_copy(G.main, (Text *)id);
424                         return true;
425                 case ID_SO:
426                         return false;  /* not implemented */
427                 case ID_GR:
428                         if (!test) *newid = (ID *)BKE_group_copy((Group *)id);
429                         return true;
430                 case ID_AR:
431                         if (!test) *newid = (ID *)BKE_armature_copy((bArmature *)id);
432                         return true;
433                 case ID_AC:
434                         if (!test) *newid = (ID *)BKE_action_copy((bAction *)id);
435                         return true;
436                 case ID_NT:
437                         if (!test) *newid = (ID *)ntreeCopyTree((bNodeTree *)id);
438                         return true;
439                 case ID_BR:
440                         if (!test) *newid = (ID *)BKE_brush_copy((Brush *)id);
441                         return true;
442                 case ID_WM:
443                         return false;  /* can't be copied from here */
444                 case ID_GD:
445                         if (!test) *newid = (ID *)gpencil_data_duplicate((bGPdata *)id, false);
446                         return true;
447                 case ID_MSK:
448                         if (!test) *newid = (ID *)BKE_mask_copy((Mask *)id);
449                         return true;
450                 case ID_LS:
451                         if (!test) *newid = (ID *)BKE_linestyle_copy(G.main, (FreestyleLineStyle *)id);
452                         return true;
453         }
454         
455         return false;
456 }
457
458 bool id_unlink(ID *id, int test)
459 {
460         Main *mainlib = G.main;
461         short type = GS(id->name);
462
463         switch (type) {
464                 case ID_TXT:
465                         if (test) return true;
466                         BKE_text_unlink(mainlib, (Text *)id);
467                         break;
468                 case ID_GR:
469                         if (test) return true;
470                         BKE_group_unlink(mainlib, (Group *)id);
471                         break;
472                 case ID_OB:
473                         if (test) return true;
474                         BKE_object_unlink(mainlib, (Object *)id);
475                         break;
476         }
477
478         if (id->us == 0) {
479                 if (test) return true;
480
481                 BKE_libblock_free(mainlib, id);
482
483                 return true;
484         }
485
486         return false;
487 }
488
489 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
490 {
491         ID *newid = NULL;
492         PointerRNA idptr;
493         
494         if (id) {
495                 /* if property isn't editable, we're going to have an extra block hanging around until we save */
496                 if (RNA_property_editable(ptr, prop)) {
497                         if (id_copy(id, &newid, false) && newid) {
498                                 /* copy animation actions too */
499                                 BKE_animdata_copy_id_action(id);
500                                 /* us is 1 by convention, but RNA_property_pointer_set
501                                  * will also increment it, so set it to zero */
502                                 newid->us = 0;
503                                 
504                                 /* assign copy */
505                                 RNA_id_pointer_create(newid, &idptr);
506                                 RNA_property_pointer_set(ptr, prop, idptr);
507                                 RNA_property_update(C, ptr, prop);
508                                 
509                                 return true;
510                         }
511                 }
512         }
513         
514         return false;
515 }
516
517 ListBase *which_libbase(Main *mainlib, short type)
518 {
519         switch (type) {
520                 case ID_SCE:
521                         return &(mainlib->scene);
522                 case ID_LI:
523                         return &(mainlib->library);
524                 case ID_OB:
525                         return &(mainlib->object);
526                 case ID_ME:
527                         return &(mainlib->mesh);
528                 case ID_CU:
529                         return &(mainlib->curve);
530                 case ID_MB:
531                         return &(mainlib->mball);
532                 case ID_MA:
533                         return &(mainlib->mat);
534                 case ID_TE:
535                         return &(mainlib->tex);
536                 case ID_IM:
537                         return &(mainlib->image);
538                 case ID_LT:
539                         return &(mainlib->latt);
540                 case ID_LA:
541                         return &(mainlib->lamp);
542                 case ID_CA:
543                         return &(mainlib->camera);
544                 case ID_IP:
545                         return &(mainlib->ipo);
546                 case ID_KE:
547                         return &(mainlib->key);
548                 case ID_WO:
549                         return &(mainlib->world);
550                 case ID_SCR:
551                         return &(mainlib->screen);
552                 case ID_VF:
553                         return &(mainlib->vfont);
554                 case ID_TXT:
555                         return &(mainlib->text);
556                 case ID_SPK:
557                         return &(mainlib->speaker);
558                 case ID_SO:
559                         return &(mainlib->sound);
560                 case ID_GR:
561                         return &(mainlib->group);
562                 case ID_AR:
563                         return &(mainlib->armature);
564                 case ID_AC:
565                         return &(mainlib->action);
566                 case ID_NT:
567                         return &(mainlib->nodetree);
568                 case ID_BR:
569                         return &(mainlib->brush);
570                 case ID_WM:
571                         return &(mainlib->wm);
572                 case ID_GD:
573                         return &(mainlib->gpencil);
574                 case ID_MC:
575                         return &(mainlib->movieclip);
576                 case ID_MSK:
577                         return &(mainlib->mask);
578                 case ID_LS:
579                         return &(mainlib->linestyle);
580                 case ID_PAL:
581                         return &(mainlib->palettes);
582                 case ID_PC:
583                         return &(mainlib->paintcurves);
584         }
585         return NULL;
586 }
587
588 /**
589  * Clear or set given tags for all ids in listbase (runtime tags).
590  */
591 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
592 {
593         ID *id;
594         if (value) {
595                 for (id = lb->first; id; id = id->next) {
596                         id->tag |= tag;
597                 }
598         }
599         else {
600                 const int ntag = ~tag;
601                 for (id = lb->first; id; id = id->next) {
602                         id->tag &= ntag;
603                 }
604         }
605 }
606
607 /**
608  * Clear or set given tags for all ids of given type in bmain (runtime tags).
609  */
610 void BKE_main_id_tag_idcode(struct Main *mainvar, const short type, const int tag, const bool value)
611 {
612         ListBase *lb = which_libbase(mainvar, type);
613
614         BKE_main_id_tag_listbase(lb, tag, value);
615 }
616
617 /**
618  * Clear or set given tags for all ids in bmain (runtime tags).
619  */
620 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
621 {
622         ListBase *lbarray[MAX_LIBARRAY];
623         int a;
624
625         a = set_listbasepointers(mainvar, lbarray);
626         while (a--) {
627                 BKE_main_id_tag_listbase(lbarray[a], tag, value);
628         }
629 }
630
631
632 /**
633  * Clear or set given flags for all ids in listbase (persistent flags).
634  */
635 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
636 {
637         ID *id;
638         if (value) {
639                 for (id = lb->first; id; id = id->next)
640                         id->tag |= flag;
641         }
642         else {
643                 const int nflag = ~flag;
644                 for (id = lb->first; id; id = id->next)
645                         id->tag &= nflag;
646         }
647 }
648
649 /**
650  * Clear or set given flags for all ids in bmain (persistent flags).
651  */
652 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
653 {
654         ListBase *lbarray[MAX_LIBARRAY];
655         int a;
656         a = set_listbasepointers(bmain, lbarray);
657         while (a--) {
658                 BKE_main_id_flag_listbase(lbarray[a], flag, value);
659         }
660 }
661
662 void BKE_main_lib_objects_recalc_all(Main *bmain)
663 {
664         Object *ob;
665
666         /* flag for full recalc */
667         for (ob = bmain->object.first; ob; ob = ob->id.next) {
668                 if (ob->id.lib) {
669                         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
670                 }
671         }
672
673         DAG_id_type_tag(bmain, ID_OB);
674 }
675
676 /**
677  * puts into array *lb pointers to all the ListBase structs in main,
678  * and returns the number of them as the function result. This is useful for
679  * generic traversal of all the blocks in a Main (by traversing all the
680  * lists in turn), without worrying about block types.
681  *
682  * \note MAX_LIBARRAY define should match this code */
683 int set_listbasepointers(Main *main, ListBase **lb)
684 {
685         int a = 0;
686
687         /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
688          * This is important because freeing data decreases usercounts of other datablocks,
689          * if this data is its self freed it can crash. */
690         lb[a++] = &(main->library);  /* Libraries may be accessed from pretty much any other ID... */
691         lb[a++] = &(main->ipo);
692         lb[a++] = &(main->action); /* moved here to avoid problems when freeing with animato (aligorith) */
693         lb[a++] = &(main->key);
694         lb[a++] = &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
695         lb[a++] = &(main->nodetree);
696         lb[a++] = &(main->image);
697         lb[a++] = &(main->tex);
698         lb[a++] = &(main->mat);
699         lb[a++] = &(main->vfont);
700         
701         /* Important!: When adding a new object type,
702          * the specific data should be inserted here 
703          */
704
705         lb[a++] = &(main->armature);
706
707         lb[a++] = &(main->mesh);
708         lb[a++] = &(main->curve);
709         lb[a++] = &(main->mball);
710
711         lb[a++] = &(main->latt);
712         lb[a++] = &(main->lamp);
713         lb[a++] = &(main->camera);
714
715         lb[a++] = &(main->text);
716         lb[a++] = &(main->sound);
717         lb[a++] = &(main->group);
718         lb[a++] = &(main->palettes);
719         lb[a++] = &(main->paintcurves);
720         lb[a++] = &(main->brush);
721         lb[a++] = &(main->speaker);
722
723         lb[a++] = &(main->world);
724         lb[a++] = &(main->movieclip);
725         lb[a++] = &(main->screen);
726         lb[a++] = &(main->object);
727         lb[a++] = &(main->linestyle); /* referenced by scenes */
728         lb[a++] = &(main->scene);
729         lb[a++] = &(main->wm);
730         lb[a++] = &(main->mask);
731         
732         lb[a] = NULL;
733
734         BLI_assert(a + 1 == MAX_LIBARRAY);
735
736         return a;
737 }
738
739 /* *********** ALLOC AND FREE *****************
740  *
741  * BKE_libblock_free(ListBase *lb, ID *id )
742  * provide a list-basis and datablock, but only ID is read
743  *
744  * void *BKE_libblock_alloc(ListBase *lb, type, name)
745  * inserts in list and returns a new ID
746  *
747  * **************************** */
748
749 /**
750  * Allocates and returns memory of the right size for the specified block type,
751  * initialized to zero.
752  */
753 void *BKE_libblock_alloc_notest(short type)
754 {
755         ID *id = NULL;
756         
757         switch (type) {
758                 case ID_SCE:
759                         id = MEM_callocN(sizeof(Scene), "scene");
760                         break;
761                 case ID_LI:
762                         id = MEM_callocN(sizeof(Library), "library");
763                         break;
764                 case ID_OB:
765                         id = MEM_callocN(sizeof(Object), "object");
766                         break;
767                 case ID_ME:
768                         id = MEM_callocN(sizeof(Mesh), "mesh");
769                         break;
770                 case ID_CU:
771                         id = MEM_callocN(sizeof(Curve), "curve");
772                         break;
773                 case ID_MB:
774                         id = MEM_callocN(sizeof(MetaBall), "mball");
775                         break;
776                 case ID_MA:
777                         id = MEM_callocN(sizeof(Material), "mat");
778                         break;
779                 case ID_TE:
780                         id = MEM_callocN(sizeof(Tex), "tex");
781                         break;
782                 case ID_IM:
783                         id = MEM_callocN(sizeof(Image), "image");
784                         break;
785                 case ID_LT:
786                         id = MEM_callocN(sizeof(Lattice), "latt");
787                         break;
788                 case ID_LA:
789                         id = MEM_callocN(sizeof(Lamp), "lamp");
790                         break;
791                 case ID_CA:
792                         id = MEM_callocN(sizeof(Camera), "camera");
793                         break;
794                 case ID_IP:
795                         id = MEM_callocN(sizeof(Ipo), "ipo");
796                         break;
797                 case ID_KE:
798                         id = MEM_callocN(sizeof(Key), "key");
799                         break;
800                 case ID_WO:
801                         id = MEM_callocN(sizeof(World), "world");
802                         break;
803                 case ID_SCR:
804                         id = MEM_callocN(sizeof(bScreen), "screen");
805                         break;
806                 case ID_VF:
807                         id = MEM_callocN(sizeof(VFont), "vfont");
808                         break;
809                 case ID_TXT:
810                         id = MEM_callocN(sizeof(Text), "text");
811                         break;
812                 case ID_SPK:
813                         id = MEM_callocN(sizeof(Speaker), "speaker");
814                         break;
815                 case ID_SO:
816                         id = MEM_callocN(sizeof(bSound), "sound");
817                         break;
818                 case ID_GR:
819                         id = MEM_callocN(sizeof(Group), "group");
820                         break;
821                 case ID_AR:
822                         id = MEM_callocN(sizeof(bArmature), "armature");
823                         break;
824                 case ID_AC:
825                         id = MEM_callocN(sizeof(bAction), "action");
826                         break;
827                 case ID_NT:
828                         id = MEM_callocN(sizeof(bNodeTree), "nodetree");
829                         break;
830                 case ID_BR:
831                         id = MEM_callocN(sizeof(Brush), "brush");
832                         break;
833                 case ID_WM:
834                         id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
835                         break;
836                 case ID_GD:
837                         id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
838                         break;
839                 case ID_MC:
840                         id = MEM_callocN(sizeof(MovieClip), "Movie Clip");
841                         break;
842                 case ID_MSK:
843                         id = MEM_callocN(sizeof(Mask), "Mask");
844                         break;
845                 case ID_LS:
846                         id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
847                         break;
848                 case ID_PAL:
849                         id = MEM_callocN(sizeof(Palette), "Palette");
850                         break;
851                 case ID_PC:
852                         id = MEM_callocN(sizeof(PaintCurve), "Paint Curve");
853                         break;
854         }
855         return id;
856 }
857
858 /**
859  * Allocates and returns a block of the specified type, with the specified name
860  * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
861  * The user count is set to 1, all other content (apart from name and links) being
862  * initialized to zero.
863  */
864 void *BKE_libblock_alloc(Main *bmain, short type, const char *name)
865 {
866         ID *id = NULL;
867         ListBase *lb = which_libbase(bmain, type);
868         
869         id = BKE_libblock_alloc_notest(type);
870         if (id) {
871                 BKE_main_lock(bmain);
872                 BLI_addtail(lb, id);
873                 id->us = 1;
874                 id->icon_id = 0;
875                 *( (short *)id->name) = type;
876                 new_id(lb, id, name);
877                 /* alphabetic insertion: is in new_id */
878                 BKE_main_unlock(bmain);
879         }
880         DAG_id_type_tag(bmain, type);
881         return id;
882 }
883
884 /**
885  * Initialize an ID of given type, such that it has valid 'empty' data.
886  * ID is assumed to be just calloc'ed.
887  */
888 void BKE_libblock_init_empty(ID *id)
889 {
890         /* Note that only ID types that are not valid when filled of zero should have a callback here. */
891         switch (GS(id->name)) {
892                 case ID_SCE:
893                         BKE_scene_init((Scene *)id);
894                         break;
895                 case ID_LI:
896                         /* Nothing to do. */
897                         break;
898                 case ID_OB:
899                 {
900                         Object *ob = (Object *)id;
901                         ob->type = OB_EMPTY;
902                         BKE_object_init(ob);
903                         break;
904                 }
905                 case ID_ME:
906                         BKE_mesh_init((Mesh *)id);
907                         break;
908                 case ID_CU:
909                         BKE_curve_init((Curve *)id);
910                         break;
911                 case ID_MB:
912                         BKE_mball_init((MetaBall *)id);
913                         break;
914                 case ID_MA:
915                         BKE_material_init((Material *)id);
916                         break;
917                 case ID_TE:
918                         BKE_texture_default((Tex *)id);
919                         break;
920                 case ID_IM:
921                         BKE_image_init((Image *)id);
922                         break;
923                 case ID_LT:
924                         BKE_lattice_init((Lattice *)id);
925                         break;
926                 case ID_LA:
927                         BKE_lamp_init((Lamp *)id);
928                         break;
929                 case ID_SPK:
930                         BKE_speaker_init((Speaker *)id);
931                         break;
932                 case ID_CA:
933                         BKE_camera_init((Camera *)id);
934                         break;
935                 case ID_IP:
936                         /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
937                         BLI_assert(0);
938                         break;
939                 case ID_KE:
940                         /* Shapekeys are a complex topic too - they depend on their 'user' data type...
941                          * They are not linkable, though, so it should never reach here anyway. */
942                         BLI_assert(0);
943                         break;
944                 case ID_WO:
945                         BKE_world_init((World *)id);
946                         break;
947                 case ID_SCR:
948                         /* Nothing to do. */
949                         break;
950                 case ID_VF:
951                         BKE_vfont_init((VFont *)id);
952                         break;
953                 case ID_TXT:
954                         BKE_text_init((Text *)id);
955                         break;
956                 case ID_SO:
957                         /* Another fuzzy case, think NULLified content is OK here... */
958                         break;
959                 case ID_GR:
960                         /* Nothing to do. */
961                         break;
962                 case ID_AR:
963                         /* Nothing to do. */
964                         break;
965                 case ID_AC:
966                         /* Nothing to do. */
967                         break;
968                 case ID_NT:
969                         ntreeInitDefault((bNodeTree *)id);
970                         break;
971                 case ID_BR:
972                         BKE_brush_init((Brush *)id);
973                         break;
974                 case ID_PC:
975                         /* Nothing to do. */
976                         break;
977                 case ID_WM:
978                         /* We should never reach this. */
979                         BLI_assert(0);
980                         break;
981                 case ID_GD:
982                         /* Nothing to do. */
983                         break;
984                 case ID_MSK:
985                         /* Nothing to do. */
986                         break;
987                 case ID_LS:
988                         BKE_linestyle_init((FreestyleLineStyle *)id);
989                         break;
990         }
991 }
992
993 /* by spec, animdata is first item after ID */
994 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
995 static void id_copy_animdata(ID *id, const bool do_action)
996 {
997         AnimData *adt = BKE_animdata_from_id(id);
998         
999         if (adt) {
1000                 IdAdtTemplate *iat = (IdAdtTemplate *)id;
1001                 iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */
1002         }
1003 }
1004
1005 /* material nodes use this since they are not treated as libdata */
1006 void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action)
1007 {
1008         if (id_from->properties)
1009                 id->properties = IDP_CopyProperty(id_from->properties);
1010
1011         /* the duplicate should get a copy of the animdata */
1012         id_copy_animdata(id, do_action);
1013 }
1014
1015 /* used everywhere in blenkernel */
1016 void *BKE_libblock_copy_ex(Main *bmain, ID *id)
1017 {
1018         ID *idn;
1019         size_t idn_len;
1020
1021         idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2);
1022
1023         assert(idn != NULL);
1024
1025         idn_len = MEM_allocN_len(idn);
1026         if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1027                 const char *cp = (const char *)id;
1028                 char *cpn = (char *)idn;
1029
1030                 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1031         }
1032         
1033         id->newid = idn;
1034         idn->tag |= LIB_TAG_NEW;
1035
1036         BKE_libblock_copy_data(idn, id, false);
1037         
1038         return idn;
1039 }
1040
1041 void *BKE_libblock_copy_nolib(ID *id, const bool do_action)
1042 {
1043         ID *idn;
1044         size_t idn_len;
1045
1046         idn = BKE_libblock_alloc_notest(GS(id->name));
1047         assert(idn != NULL);
1048
1049         BLI_strncpy(idn->name, id->name, sizeof(idn->name));
1050
1051         idn_len = MEM_allocN_len(idn);
1052         if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1053                 const char *cp = (const char *)id;
1054                 char *cpn = (char *)idn;
1055
1056                 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1057         }
1058
1059         id->newid = idn;
1060         idn->tag |= LIB_TAG_NEW;
1061         idn->us = 1;
1062
1063         BKE_libblock_copy_data(idn, id, do_action);
1064
1065         return idn;
1066 }
1067
1068 void *BKE_libblock_copy(ID *id)
1069 {
1070         return BKE_libblock_copy_ex(G.main, id);
1071 }
1072
1073 static int id_relink_looper(void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int cd_flag)
1074 {
1075         ID *id = *id_pointer;
1076         if (id) {
1077                 /* See: NEW_ID macro */
1078                 if (id->newid) {
1079                         BKE_library_update_ID_link_user(id->newid, id, cd_flag);
1080                         *id_pointer = id->newid;
1081                 }
1082                 else if (id->tag & LIB_TAG_NEW) {
1083                         id->tag &= ~LIB_TAG_NEW;
1084                         BKE_libblock_relink(id);
1085                 }
1086         }
1087         return IDWALK_RET_NOP;
1088 }
1089
1090 void BKE_libblock_relink(ID *id)
1091 {
1092         if (id->lib)
1093                 return;
1094
1095         BKE_library_foreach_ID_link(id, id_relink_looper, NULL, 0);
1096 }
1097
1098 static void BKE_library_free(Library *lib)
1099 {
1100         if (lib->packedfile)
1101                 freePackedFile(lib->packedfile);
1102 }
1103
1104 static BKE_library_free_window_manager_cb free_windowmanager_cb = NULL;
1105
1106 void BKE_library_callback_free_window_manager_set(BKE_library_free_window_manager_cb func)
1107 {
1108         free_windowmanager_cb = func;
1109 }
1110
1111 static BKE_library_free_notifier_reference_cb free_notifier_reference_cb = NULL;
1112
1113 void BKE_library_callback_free_notifier_reference_set(BKE_library_free_notifier_reference_cb func)
1114 {
1115         free_notifier_reference_cb = func;
1116 }
1117
1118 static BKE_library_free_editor_id_reference_cb free_editor_id_reference_cb = NULL;
1119
1120 void BKE_library_callback_free_editor_id_reference_set(BKE_library_free_editor_id_reference_cb func)
1121 {
1122         free_editor_id_reference_cb = func;
1123 }
1124
1125 static void animdata_dtar_clear_cb(ID *UNUSED(id), AnimData *adt, void *userdata)
1126 {
1127         ChannelDriver *driver;
1128         FCurve *fcu;
1129
1130         /* find the driver this belongs to and update it */
1131         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
1132                 driver = fcu->driver;
1133                 
1134                 if (driver) {
1135                         DriverVar *dvar;
1136                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1137                                 DRIVER_TARGETS_USED_LOOPER(dvar) 
1138                                 {
1139                                         if (dtar->id == userdata)
1140                                                 dtar->id = NULL;
1141                                 }
1142                                 DRIVER_TARGETS_LOOPER_END
1143                         }
1144                 }
1145         }
1146 }
1147
1148 void BKE_libblock_free_data(Main *bmain, ID *id)
1149 {
1150         if (id->properties) {
1151                 IDP_FreeProperty(id->properties);
1152                 MEM_freeN(id->properties);
1153         }
1154         
1155         /* this ID may be a driver target! */
1156         BKE_animdata_main_cb(bmain, animdata_dtar_clear_cb, (void *)id);
1157 }
1158
1159 /* used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c */
1160 void BKE_libblock_free_ex(Main *bmain, void *idv, bool do_id_user)
1161 {
1162         ID *id = idv;
1163         short type = GS(id->name);
1164         ListBase *lb = which_libbase(bmain, type);
1165
1166         DAG_id_type_tag(bmain, type);
1167
1168 #ifdef WITH_PYTHON
1169         BPY_id_release(id);
1170 #endif
1171
1172         switch (type) {    /* GetShort from util.h */
1173                 case ID_SCE:
1174                         BKE_scene_free((Scene *)id);
1175                         break;
1176                 case ID_LI:
1177                         BKE_library_free((Library *)id);
1178                         break;
1179                 case ID_OB:
1180                         BKE_object_free_ex((Object *)id, do_id_user);
1181                         break;
1182                 case ID_ME:
1183                         BKE_mesh_free((Mesh *)id, 1);
1184                         break;
1185                 case ID_CU:
1186                         BKE_curve_free((Curve *)id);
1187                         break;
1188                 case ID_MB:
1189                         BKE_mball_free((MetaBall *)id);
1190                         break;
1191                 case ID_MA:
1192                         BKE_material_free((Material *)id);
1193                         break;
1194                 case ID_TE:
1195                         BKE_texture_free((Tex *)id);
1196                         break;
1197                 case ID_IM:
1198                         BKE_image_free((Image *)id);
1199                         break;
1200                 case ID_LT:
1201                         BKE_lattice_free((Lattice *)id);
1202                         break;
1203                 case ID_LA:
1204                         BKE_lamp_free((Lamp *)id);
1205                         break;
1206                 case ID_CA:
1207                         BKE_camera_free((Camera *) id);
1208                         break;
1209                 case ID_IP:
1210                         BKE_ipo_free((Ipo *)id);
1211                         break;
1212                 case ID_KE:
1213                         BKE_key_free((Key *)id);
1214                         break;
1215                 case ID_WO:
1216                         BKE_world_free((World *)id);
1217                         break;
1218                 case ID_SCR:
1219                         BKE_screen_free((bScreen *)id);
1220                         break;
1221                 case ID_VF:
1222                         BKE_vfont_free((VFont *)id);
1223                         break;
1224                 case ID_TXT:
1225                         BKE_text_free((Text *)id);
1226                         break;
1227                 case ID_SPK:
1228                         BKE_speaker_free((Speaker *)id);
1229                         break;
1230                 case ID_SO:
1231                         BKE_sound_free((bSound *)id);
1232                         break;
1233                 case ID_GR:
1234                         BKE_group_free((Group *)id);
1235                         break;
1236                 case ID_AR:
1237                         BKE_armature_free((bArmature *)id);
1238                         break;
1239                 case ID_AC:
1240                         BKE_action_free((bAction *)id);
1241                         break;
1242                 case ID_NT:
1243                         ntreeFreeTree_ex((bNodeTree *)id, do_id_user);
1244                         break;
1245                 case ID_BR:
1246                         BKE_brush_free((Brush *)id);
1247                         break;
1248                 case ID_WM:
1249                         if (free_windowmanager_cb)
1250                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
1251                         break;
1252                 case ID_GD:
1253                         BKE_gpencil_free((bGPdata *)id);
1254                         break;
1255                 case ID_MC:
1256                         BKE_movieclip_free((MovieClip *)id);
1257                         break;
1258                 case ID_MSK:
1259                         BKE_mask_free(bmain, (Mask *)id);
1260                         break;
1261                 case ID_LS:
1262                         BKE_linestyle_free((FreestyleLineStyle *)id);
1263                         break;
1264                 case ID_PAL:
1265                         BKE_palette_free((Palette *)id);
1266                         break;
1267                 case ID_PC:
1268                         BKE_paint_curve_free((PaintCurve *)id);
1269                         break;
1270         }
1271
1272         /* avoid notifying on removed data */
1273         BKE_main_lock(bmain);
1274
1275         if (free_notifier_reference_cb) {
1276                 free_notifier_reference_cb(id);
1277         }
1278
1279         if (free_editor_id_reference_cb) {
1280                 free_editor_id_reference_cb(id);
1281         }
1282
1283         BLI_remlink(lb, id);
1284
1285         BKE_libblock_free_data(bmain, id);
1286         BKE_main_unlock(bmain);
1287
1288         MEM_freeN(id);
1289 }
1290
1291 void BKE_libblock_free(Main *bmain, void *idv)
1292 {
1293         BKE_libblock_free_ex(bmain, idv, true);
1294 }
1295
1296 void BKE_libblock_free_us(Main *bmain, void *idv)      /* test users */
1297 {
1298         ID *id = idv;
1299         
1300         id_us_min(id);
1301
1302         /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding groups when deleting an object.
1303          *     Since only 'user_one' usage of objects is groups, and only 'real user' usage of objects is scenes,
1304          *     removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets
1305          *     fully unlinked.
1306          *     Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO.
1307          */
1308         if ((GS(id->name) == ID_OB) && (id->us == 1)) {
1309                 id_us_clear_real(id);
1310         }
1311
1312         if (id->us == 0) {
1313                 switch (GS(id->name)) {
1314                         case ID_OB:
1315                                 BKE_object_unlink(bmain, (Object *)id);
1316                                 break;
1317                 }
1318                 
1319                 BKE_libblock_free(bmain, id);
1320         }
1321 }
1322
1323 Main *BKE_main_new(void)
1324 {
1325         Main *bmain = MEM_callocN(sizeof(Main), "new main");
1326         bmain->eval_ctx = DEG_evaluation_context_new(DAG_EVAL_VIEWPORT);
1327         bmain->lock = MEM_mallocN(sizeof(SpinLock), "main lock");
1328         BLI_spin_init((SpinLock *)bmain->lock);
1329         return bmain;
1330 }
1331
1332 void BKE_main_free(Main *mainvar)
1333 {
1334         /* also call when reading a file, erase all, etc */
1335         ListBase *lbarray[MAX_LIBARRAY];
1336         int a;
1337
1338         MEM_SAFE_FREE(mainvar->blen_thumb);
1339
1340         a = set_listbasepointers(mainvar, lbarray);
1341         while (a--) {
1342                 ListBase *lb = lbarray[a];
1343                 ID *id;
1344                 
1345                 while ( (id = lb->first) ) {
1346 #if 1
1347                         BKE_libblock_free_ex(mainvar, id, false);
1348 #else
1349                         /* errors freeing ID's can be hard to track down,
1350                          * enable this so valgrind will give the line number in its error log */
1351                         switch (a) {
1352                                 case   0: BKE_libblock_free_ex(mainvar, id, false); break;
1353                                 case   1: BKE_libblock_free_ex(mainvar, id, false); break;
1354                                 case   2: BKE_libblock_free_ex(mainvar, id, false); break;
1355                                 case   3: BKE_libblock_free_ex(mainvar, id, false); break;
1356                                 case   4: BKE_libblock_free_ex(mainvar, id, false); break;
1357                                 case   5: BKE_libblock_free_ex(mainvar, id, false); break;
1358                                 case   6: BKE_libblock_free_ex(mainvar, id, false); break;
1359                                 case   7: BKE_libblock_free_ex(mainvar, id, false); break;
1360                                 case   8: BKE_libblock_free_ex(mainvar, id, false); break;
1361                                 case   9: BKE_libblock_free_ex(mainvar, id, false); break;
1362                                 case  10: BKE_libblock_free_ex(mainvar, id, false); break;
1363                                 case  11: BKE_libblock_free_ex(mainvar, id, false); break;
1364                                 case  12: BKE_libblock_free_ex(mainvar, id, false); break;
1365                                 case  13: BKE_libblock_free_ex(mainvar, id, false); break;
1366                                 case  14: BKE_libblock_free_ex(mainvar, id, false); break;
1367                                 case  15: BKE_libblock_free_ex(mainvar, id, false); break;
1368                                 case  16: BKE_libblock_free_ex(mainvar, id, false); break;
1369                                 case  17: BKE_libblock_free_ex(mainvar, id, false); break;
1370                                 case  18: BKE_libblock_free_ex(mainvar, id, false); break;
1371                                 case  19: BKE_libblock_free_ex(mainvar, id, false); break;
1372                                 case  20: BKE_libblock_free_ex(mainvar, id, false); break;
1373                                 case  21: BKE_libblock_free_ex(mainvar, id, false); break;
1374                                 case  22: BKE_libblock_free_ex(mainvar, id, false); break;
1375                                 case  23: BKE_libblock_free_ex(mainvar, id, false); break;
1376                                 case  24: BKE_libblock_free_ex(mainvar, id, false); break;
1377                                 case  25: BKE_libblock_free_ex(mainvar, id, false); break;
1378                                 case  26: BKE_libblock_free_ex(mainvar, id, false); break;
1379                                 case  27: BKE_libblock_free_ex(mainvar, id, false); break;
1380                                 case  28: BKE_libblock_free_ex(mainvar, id, false); break;
1381                                 case  29: BKE_libblock_free_ex(mainvar, id, false); break;
1382                                 case  30: BKE_libblock_free_ex(mainvar, id, false); break;
1383                                 case  31: BKE_libblock_free_ex(mainvar, id, false); break;
1384                                 case  32: BKE_libblock_free_ex(mainvar, id, false); break;
1385                                 case  33: BKE_libblock_free_ex(mainvar, id, false); break;
1386                                 default:
1387                                         BLI_assert(0);
1388                                         break;
1389                         }
1390 #endif
1391                 }
1392         }
1393
1394         BLI_spin_end((SpinLock *)mainvar->lock);
1395         MEM_freeN(mainvar->lock);
1396         DEG_evaluation_context_free(mainvar->eval_ctx);
1397         MEM_freeN(mainvar);
1398 }
1399
1400 void BKE_main_lock(struct Main *bmain)
1401 {
1402         BLI_spin_lock((SpinLock *) bmain->lock);
1403 }
1404
1405 void BKE_main_unlock(struct Main *bmain)
1406 {
1407         BLI_spin_unlock((SpinLock *) bmain->lock);
1408 }
1409
1410 /**
1411  * Generates a raw .blend file thumbnail data from given image.
1412  *
1413  * \param bmain If not NULL, also store generated data in this Main.
1414  * \param img ImBuf image to generate thumbnail data from.
1415  * \return The generated .blend file raw thumbnail data.
1416  */
1417 BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img)
1418 {
1419         BlendThumbnail *data = NULL;
1420
1421         if (bmain) {
1422                 MEM_SAFE_FREE(bmain->blen_thumb);
1423         }
1424
1425         if (img) {
1426                 const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y);
1427                 data = MEM_mallocN(sz, __func__);
1428
1429                 IMB_rect_from_float(img);  /* Just in case... */
1430                 data->width = img->x;
1431                 data->height = img->y;
1432                 memcpy(data->rect, img->rect, sz - sizeof(*data));
1433         }
1434
1435         if (bmain) {
1436                 bmain->blen_thumb = data;
1437         }
1438         return data;
1439 }
1440
1441 /**
1442  * Generates an image from raw .blend file thumbnail \a data.
1443  *
1444  * \param bmain Use this bmain->blen_thumb data if given \a data is NULL.
1445  * \param data Raw .blend file thumbnail data.
1446  * \return An ImBuf from given data, or NULL if invalid.
1447  */
1448 ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data)
1449 {
1450         ImBuf *img = NULL;
1451
1452         if (!data && bmain) {
1453                 data = bmain->blen_thumb;
1454         }
1455
1456         if (data) {
1457                 /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail
1458                  *       here (we do not want to pass the first two ints!). */
1459                 img = IMB_allocImBuf((unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata);
1460                 memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data));
1461         }
1462
1463         return img;
1464 }
1465
1466 /**
1467  * Generates an empty (black) thumbnail for given Main.
1468  */
1469 void BKE_main_thumbnail_create(struct Main *bmain)
1470 {
1471         MEM_SAFE_FREE(bmain->blen_thumb);
1472
1473         bmain->blen_thumb = MEM_callocN(BLEN_THUMB_MEMSIZE(BLEN_THUMB_SIZE, BLEN_THUMB_SIZE), __func__);
1474         bmain->blen_thumb->width = BLEN_THUMB_SIZE;
1475         bmain->blen_thumb->height = BLEN_THUMB_SIZE;
1476 }
1477
1478 /* ***************** ID ************************ */
1479 ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const char *name)
1480 {
1481         ListBase *lb = which_libbase(bmain, type);
1482         BLI_assert(lb != NULL);
1483         return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1484 }
1485 ID *BKE_libblock_find_name(const short type, const char *name)
1486 {
1487         return BKE_libblock_find_name_ex(G.main, type, name);
1488 }
1489
1490
1491 void id_sort_by_name(ListBase *lb, ID *id)
1492 {
1493         ID *idtest;
1494         
1495         /* insert alphabetically */
1496         if (lb->first != lb->last) {
1497                 BLI_remlink(lb, id);
1498                 
1499                 idtest = lb->first;
1500                 while (idtest) {
1501                         if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) {
1502                                 BLI_insertlinkbefore(lb, idtest, id);
1503                                 break;
1504                         }
1505                         idtest = idtest->next;
1506                 }
1507                 /* as last */
1508                 if (idtest == NULL) {
1509                         BLI_addtail(lb, id);
1510                 }
1511         }
1512         
1513 }
1514
1515 /**
1516  * Check to see if there is an ID with the same name as 'name'.
1517  * Returns the ID if so, if not, returns NULL
1518  */
1519 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1520 {
1521         ID *idtest = NULL;
1522         
1523         for (idtest = lb->first; idtest; idtest = idtest->next) {
1524                 /* if idtest is not a lib */ 
1525                 if (id != idtest && idtest->lib == NULL) {
1526                         /* do not test alphabetic! */
1527                         /* optimized */
1528                         if (idtest->name[2] == name[0]) {
1529                                 if (STREQ(name, idtest->name + 2)) break;
1530                         }
1531                 }
1532         }
1533         
1534         return idtest;
1535 }
1536
1537 /**
1538  * Check to see if an ID name is already used, and find a new one if so.
1539  * Return true if created a new name (returned in name).
1540  *
1541  * Normally the ID that's being check is already in the ListBase, so ID *id
1542  * points at the new entry.  The Python Library module needs to know what
1543  * the name of a datablock will be before it is appended; in this case ID *id
1544  * id is NULL
1545  */
1546
1547 static bool check_for_dupid(ListBase *lb, ID *id, char *name)
1548 {
1549         ID *idtest;
1550         int nr = 0, a, left_len;
1551 #define MAX_IN_USE 64
1552         bool in_use[MAX_IN_USE];
1553         /* to speed up finding unused numbers within [1 .. MAX_IN_USE - 1] */
1554
1555         char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
1556
1557         while (true) {
1558
1559                 /* phase 1: id already exists? */
1560                 idtest = is_dupid(lb, id, name);
1561
1562                 /* if there is no double, done */
1563                 if (idtest == NULL) return false;
1564
1565                 /* we have a dup; need to make a new name */
1566                 /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */
1567                 memset(in_use, false, sizeof(in_use));
1568
1569                 /* get name portion, number portion ("name.number") */
1570                 left_len = BLI_split_name_num(left, &nr, name, '.');
1571
1572                 /* if new name will be too long, truncate it */
1573                 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {  /* assumption: won't go beyond 9999 */
1574                         left[MAX_ID_NAME - 8] = 0;
1575                         left_len = MAX_ID_NAME - 8;
1576                 }
1577                 else if (left_len > (MAX_ID_NAME - 7)) {
1578                         left[MAX_ID_NAME - 7] = 0;
1579                         left_len = MAX_ID_NAME - 7;
1580                 }
1581
1582                 for (idtest = lb->first; idtest; idtest = idtest->next) {
1583                         int nrtest;
1584                         if ( (id != idtest) &&
1585                              (idtest->lib == NULL) &&
1586                              (*name == *(idtest->name + 2)) &&
1587                              STREQLEN(name, idtest->name + 2, left_len) &&
1588                              (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
1589                              )
1590                         {
1591                                 /* will get here at least once, otherwise is_dupid call above would have returned NULL */
1592                                 if (nrtest < MAX_IN_USE)
1593                                         in_use[nrtest] = true;  /* mark as used */
1594                                 if (nr <= nrtest)
1595                                         nr = nrtest + 1;    /* track largest unused */
1596                         }
1597                 }
1598                 /* At this point, 'nr' will typically be at least 1. (but not always) */
1599                 // BLI_assert(nr >= 1);
1600
1601                 /* decide which value of nr to use */
1602                 for (a = 0; a < MAX_IN_USE; a++) {
1603                         if (a >= nr) break;  /* stop when we've checked up to biggest */  /* redundant check */
1604                         if (!in_use[a]) { /* found an unused value */
1605                                 nr = a;
1606                                 /* can only be zero if all potential duplicate names had
1607                                  * nonzero numeric suffixes, which means name itself has
1608                                  * nonzero numeric suffix (else no name conflict and wouldn't
1609                                  * have got here), which means name[left_len] is not a null */
1610                                 break;
1611                         }
1612                 }
1613                 /* At this point, nr is either the lowest unused number within [0 .. MAX_IN_USE - 1],
1614                  * or 1 greater than the largest used number if all those low ones are taken.
1615                  * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */
1616
1617                 /* If the original name has no numeric suffix, 
1618                  * rather than just chopping and adding numbers, 
1619                  * shave off the end chars until we have a unique name.
1620                  * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */
1621                 if (nr == 0 && name[left_len] == '\0') {
1622                         int len;
1623                         /* FIXME: this code will never be executed, because either nr will be
1624                          * at least 1, or name will not end at left_len! */
1625                         BLI_assert(0);
1626
1627                         len = left_len - 1;
1628                         idtest = is_dupid(lb, id, name);
1629                         
1630                         while (idtest && len > 1) {
1631                                 name[len--] = '\0';
1632                                 idtest = is_dupid(lb, id, name);
1633                         }
1634                         if (idtest == NULL) return true;
1635                         /* otherwise just continue and use a number suffix */
1636                 }
1637                 
1638                 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {
1639                         /* this would overflow name buffer */
1640                         left[MAX_ID_NAME - 8] = 0;
1641                         /* left_len = MAX_ID_NAME - 8; */ /* for now this isn't used again */
1642                         memcpy(name, left, sizeof(char) * (MAX_ID_NAME - 7));
1643                         continue;
1644                 }
1645                 /* this format specifier is from hell... */
1646                 BLI_snprintf(name, sizeof(id->name) - 2, "%s.%.3d", left, nr);
1647
1648                 return true;
1649         }
1650
1651 #undef MAX_IN_USE
1652 }
1653
1654 /*
1655  * Only for local blocks: external en indirect blocks already have a
1656  * unique ID.
1657  *
1658  * return true: created a new name
1659  */
1660
1661 bool new_id(ListBase *lb, ID *id, const char *tname)
1662 {
1663         bool result;
1664         char name[MAX_ID_NAME - 2];
1665
1666         /* if library, don't rename */
1667         if (id->lib)
1668                 return false;
1669
1670         /* if no libdata given, look up based on ID */
1671         if (lb == NULL)
1672                 lb = which_libbase(G.main, GS(id->name));
1673
1674         /* if no name given, use name of current ID
1675          * else make a copy (tname args can be const) */
1676         if (tname == NULL)
1677                 tname = id->name + 2;
1678
1679         BLI_strncpy(name, tname, sizeof(name));
1680
1681         if (name[0] == '\0') {
1682                 /* disallow empty names */
1683                 BLI_strncpy(name, DATA_(ID_FALLBACK_NAME), sizeof(name));
1684         }
1685         else {
1686                 /* disallow non utf8 chars,
1687                  * the interface checks for this but new ID's based on file names don't */
1688                 BLI_utf8_invalid_strip(name, strlen(name));
1689         }
1690
1691         result = check_for_dupid(lb, id, name);
1692         strcpy(id->name + 2, name);
1693
1694         /* This was in 2.43 and previous releases
1695          * however all data in blender should be sorted, not just duplicate names
1696          * sorting should not hurt, but noting just incase it alters the way other
1697          * functions work, so sort every time */
1698 #if 0
1699         if (result)
1700                 id_sort_by_name(lb, id);
1701 #endif
1702
1703         id_sort_by_name(lb, id);
1704         
1705         return result;
1706 }
1707
1708 /**
1709  * Pull an ID out of a library (make it local). Only call this for IDs that
1710  * don't have other library users.
1711  */
1712 void id_clear_lib_data_ex(Main *bmain, ID *id, bool id_in_mainlist)
1713 {
1714         bNodeTree *ntree = NULL;
1715
1716         BKE_id_lib_local_paths(bmain, id->lib, id);
1717
1718         id_fake_user_clear(id);
1719
1720         id->lib = NULL;
1721         id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
1722         if (id_in_mainlist)
1723                 new_id(which_libbase(bmain, GS(id->name)), id, NULL);
1724
1725         /* internal bNodeTree blocks inside ID types below
1726          * also stores id->lib, make sure this stays in sync.
1727          */
1728         ntree = ntreeFromID(id);
1729
1730         if (ntree) {
1731                 ntreeMakeLocal(ntree, false);
1732         }
1733
1734         if (GS(id->name) == ID_OB) {
1735                 Object *object = (Object *)id;
1736                 if (object->proxy_from != NULL) {
1737                         object->proxy_from->proxy = NULL;
1738                         object->proxy_from->proxy_group = NULL;
1739                 }
1740                 object->proxy = object->proxy_from = object->proxy_group = NULL;
1741         }
1742 }
1743
1744 void id_clear_lib_data(Main *bmain, ID *id)
1745 {
1746         id_clear_lib_data_ex(bmain, id, true);
1747 }
1748
1749 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1750 void BKE_main_id_clear_newpoins(Main *bmain)
1751 {
1752         ListBase *lbarray[MAX_LIBARRAY];
1753         ID *id;
1754         int a;
1755
1756         a = set_listbasepointers(bmain, lbarray);
1757         while (a--) {
1758                 id = lbarray[a]->first;
1759                 while (id) {
1760                         id->newid = NULL;
1761                         id->tag &= ~LIB_TAG_NEW;
1762                         id = id->next;
1763                 }
1764         }
1765 }
1766
1767 static void lib_indirect_test_id(ID *id, const Library *lib)
1768 {
1769 #define LIBTAG(a) \
1770         if (a && a->id.lib) { a->id.tag &= ~LIB_TAG_INDIRECT; a->id.tag |= LIB_TAG_EXTERN; } (void)0
1771         
1772         if (id->lib) {
1773                 /* datablocks that were indirectly related are now direct links
1774                  * without this, appending data that has a link to other data will fail to write */
1775                 if (lib && id->lib->parent == lib) {
1776                         id_lib_extern(id);
1777                 }
1778                 return;
1779         }
1780         
1781         if (GS(id->name) == ID_OB) {
1782                 Object *ob = (Object *)id;
1783                 Mesh *me;
1784
1785                 int a;
1786
1787 #if 0   /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
1788                 /* XXX old animation system! -------------------------------------- */
1789                 {
1790                         bActionStrip *strip;
1791                         for (strip = ob->nlastrips.first; strip; strip = strip->next) {
1792                                 LIBTAG(strip->object);
1793                                 LIBTAG(strip->act);
1794                                 LIBTAG(strip->ipo);
1795                         }
1796                 }
1797                 /* XXX: new animation system needs something like this? */
1798 #endif
1799
1800                 for (a = 0; a < ob->totcol; a++) {
1801                         LIBTAG(ob->mat[a]);
1802                 }
1803         
1804                 LIBTAG(ob->dup_group);
1805                 LIBTAG(ob->proxy);
1806                 
1807                 me = ob->data;
1808                 LIBTAG(me);
1809         }
1810
1811 #undef LIBTAG
1812 }
1813
1814 /** Make linked datablocks local.
1815  *
1816  * \param bmain Almost certainly G.main.
1817  * \param lib If not NULL, only make local datablocks from this library.
1818  * \param untagged_only If true, only make local datablocks not tagged with LIB_TAG_PRE_EXISTING.
1819  * \param set_fake If true, set fake user on all localized datablocks (except group and objects ones).
1820  */
1821 void BKE_library_make_local(Main *bmain, const Library *lib, const bool untagged_only, const bool set_fake)
1822 {
1823         ListBase *lbarray[MAX_LIBARRAY];
1824         ID *id, *idn;
1825         int a;
1826
1827         a = set_listbasepointers(bmain, lbarray);
1828         while (a--) {
1829                 id = lbarray[a]->first;
1830                 
1831                 while (id) {
1832                         id->newid = NULL;
1833                         idn = id->next;      /* id is possibly being inserted again */
1834                         
1835                         /* The check on the second line (LIB_TAG_PRE_EXISTING) is done so its
1836                          * possible to tag data you don't want to be made local, used for
1837                          * appending data, so any libdata already linked wont become local
1838                          * (very nasty to discover all your links are lost after appending)  
1839                          * */
1840                         if (id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
1841                             ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING)))
1842                         {
1843                                 if (lib == NULL || id->lib == lib) {
1844                                         if (id->lib) {
1845                                                 /* for Make Local > All we should be calling id_make_local,
1846                                                  * but doing that breaks append (see #36003 and #36006), we
1847                                                  * we should make it work with all datablocks and id.us==0 */
1848                                                 id_clear_lib_data(bmain, id); /* sets 'id->tag' */
1849
1850                                                 /* why sort alphabetically here but not in
1851                                                  * id_clear_lib_data() ? - campbell */
1852                                                 id_sort_by_name(lbarray[a], id);
1853                                         }
1854                                         else {
1855                                                 id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
1856                                         }
1857                                 }
1858
1859                                 if (set_fake) {
1860                                         if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
1861                                                 /* do not set fake user on objects, groups (instancing) */
1862                                                 id_fake_user_set(id);
1863                                         }
1864                                 }
1865                         }
1866
1867                         id = idn;
1868                 }
1869         }
1870
1871         a = set_listbasepointers(bmain, lbarray);
1872         while (a--) {
1873                 for (id = lbarray[a]->first; id; id = id->next)
1874                         lib_indirect_test_id(id, lib);
1875         }
1876 }
1877
1878 /**
1879  * Use after setting the ID's name
1880  * When name exists: call 'new_id'
1881  */
1882 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
1883 {
1884         ListBase *lb;
1885         ID *idtest;
1886
1887
1888         lb = which_libbase(bmain, GS(name));
1889         if (lb == NULL) return;
1890         
1891         /* search for id */
1892         idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
1893
1894         if (idtest && !new_id(lb, idtest, idtest->name + 2)) {
1895                 id_sort_by_name(lb, idtest);
1896         }
1897 }
1898
1899 /**
1900  * Sets the name of a block to name, suitably adjusted for uniqueness.
1901  */
1902 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
1903 {
1904         ListBase *lb = which_libbase(bmain, GS(id->name));
1905         new_id(lb, id, name);
1906 }
1907
1908 /**
1909  * Returns in name the name of the block, with a 3-character prefix prepended
1910  * indicating whether it comes from a library, has a fake user, or no users.
1911  */
1912 void BKE_id_ui_prefix(char name[MAX_ID_NAME + 1], const ID *id)
1913 {
1914         name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ' ';
1915         name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
1916         name[2] = ' ';
1917
1918         strcpy(name + 3, id->name + 2);
1919 }
1920
1921 void BKE_library_filepath_set(Library *lib, const char *filepath)
1922 {
1923         /* in some cases this is used to update the absolute path from the
1924          * relative */
1925         if (lib->name != filepath) {
1926                 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
1927         }
1928
1929         BLI_strncpy(lib->filepath, filepath, sizeof(lib->filepath));
1930
1931         /* not essential but set filepath is an absolute copy of value which
1932          * is more useful if its kept in sync */
1933         if (BLI_path_is_rel(lib->filepath)) {
1934                 /* note that the file may be unsaved, in this case, setting the
1935                  * filepath on an indirectly linked path is not allowed from the
1936                  * outliner, and its not really supported but allow from here for now
1937                  * since making local could cause this to be directly linked - campbell
1938                  */
1939                 const char *basepath = lib->parent ? lib->parent->filepath : G.main->name;
1940                 BLI_path_abs(lib->filepath, basepath);
1941         }
1942 }