include cleanup, no functional changes
[blender-staging.git] / source / blender / blenkernel / intern / library.c
1 /** 
2  * $Id$
3  * 
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /*
31  *  Contains management of ID's and libraries
32  *  allocate and free of all library data
33  * 
34  */
35
36
37 #include <stdio.h>
38 #include <ctype.h>
39 #include <string.h>
40 #include <stdlib.h>
41 #include <stddef.h>
42
43 #include "MEM_guardedalloc.h"
44
45 /* all types are needed here, in order to do memory operations */
46 #include "DNA_anim_types.h"
47 #include "DNA_armature_types.h"
48 #include "DNA_brush_types.h"
49 #include "DNA_camera_types.h"
50 #include "DNA_group_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_material_types.h"
56 #include "DNA_mesh_types.h"
57 #include "DNA_meta_types.h"
58 #include "DNA_nla_types.h"
59 #include "DNA_node_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_screen_types.h"
62 #include "DNA_sound_types.h"
63 #include "DNA_text_types.h"
64 #include "DNA_vfont_types.h"
65 #include "DNA_windowmanager_types.h"
66 #include "DNA_world_types.h"
67 #include "DNA_gpencil_types.h"
68
69
70 #include "BLI_blenlib.h"
71 #include "BLI_dynstr.h"
72
73 #include "BKE_animsys.h"
74 #include "BKE_context.h"
75 #include "BKE_library.h"
76 #include "BKE_main.h"
77 #include "BKE_global.h"
78 #include "BKE_sound.h"
79 #include "BKE_object.h"
80 #include "BKE_screen.h"
81 #include "BKE_mesh.h"
82 #include "BKE_material.h"
83 #include "BKE_curve.h"
84 #include "BKE_mball.h"
85 #include "BKE_text.h"
86 #include "BKE_texture.h"
87 #include "BKE_scene.h"
88 #include "BKE_icons.h"
89 #include "BKE_image.h"
90 #include "BKE_ipo.h"
91 #include "BKE_key.h"
92 #include "BKE_world.h"
93 #include "BKE_font.h"
94 #include "BKE_group.h"
95 #include "BKE_lattice.h"
96 #include "BKE_armature.h"
97 #include "BKE_action.h"
98 #include "BKE_node.h"
99 #include "BKE_brush.h"
100 #include "BKE_idprop.h"
101 #include "BKE_particle.h"
102 #include "BKE_gpencil.h"
103 #include "BKE_fcurve.h"
104
105 #define MAX_IDPUP               60      /* was 24 */
106
107 /* GS reads the memory pointed at in a specific ordering. 
108    only use this definition, makes little and big endian systems
109    work fine, in conjunction with MAKE_ID */
110
111 /* from blendef: */
112 #define GS(a)   (*((short *)(a)))
113
114 /* ************* general ************************ */
115
116 void id_lib_extern(ID *id)
117 {
118         if(id) {
119                 if(id->flag & LIB_INDIRECT) {
120                         id->flag -= LIB_INDIRECT;
121                         id->flag |= LIB_EXTERN;
122                 }
123         }
124 }
125
126 void id_us_plus(ID *id)
127 {
128         if(id) {
129                 id->us++;
130                 if(id->flag & LIB_INDIRECT) {
131                         id->flag -= LIB_INDIRECT;
132                         id->flag |= LIB_EXTERN;
133                 }
134         }
135 }
136
137 void id_us_min(ID *id)
138 {
139         if(id)
140                 id->us--;
141 }
142
143 int id_make_local(ID *id, int test)
144 {
145         if(id->flag & LIB_INDIRECT)
146                 return 0;
147
148         switch(GS(id->name)) {
149                 case ID_SCE:
150                         return 0; /* not implemented */
151                 case ID_LI:
152                         return 0; /* can't be linked */
153                 case ID_OB:
154                         if(!test) make_local_object((Object*)id);
155                         return 1;
156                 case ID_ME:
157                         if(!test) {
158                                 make_local_mesh((Mesh*)id);
159                                 make_local_key(((Mesh*)id)->key);
160                         }
161                         return 1;
162                 case ID_CU:
163                         if(!test) {
164                                 make_local_curve((Curve*)id);
165                                 make_local_key(((Curve*)id)->key);
166                         }
167                         return 1;
168                 case ID_MB:
169                         if(!test) make_local_mball((MetaBall*)id);
170                         return 1;
171                 case ID_MA:
172                         if(!test) make_local_material((Material*)id);
173                         return 1;
174                 case ID_TE:
175                         if(!test) make_local_texture((Tex*)id);
176                         return 1;
177                 case ID_IM:
178                         return 0; /* not implemented */
179                 case ID_LT:
180                         if(!test) {
181                                 make_local_lattice((Lattice*)id);
182                                 make_local_key(((Lattice*)id)->key);
183                         }
184                         return 1;
185                 case ID_LA:
186                         if(!test) make_local_lamp((Lamp*)id);
187                         return 1;
188                 case ID_CA:
189                         if(!test) make_local_camera((Camera*)id);
190                         return 1;
191                 case ID_IP:
192                         return 0; /* deprecated */
193                 case ID_KE:
194                         if(!test) make_local_key((Key*)id);
195                         return 1;
196                 case ID_WO:
197                         if(!test) make_local_world((World*)id);
198                         return 1;
199                 case ID_SCR:
200                         return 0; /* can't be linked */
201                 case ID_VF:
202                         return 0; /* not implemented */
203                 case ID_TXT:
204                         return 0; /* not implemented */
205                 case ID_SCRIPT:
206                         return 0; /* deprecated */
207                 case ID_SO:
208                         return 0; /* not implemented */
209                 case ID_GR:
210                         return 0; /* not implemented */
211                 case ID_AR:
212                         if(!test) make_local_armature((bArmature*)id);
213                         return 1;
214                 case ID_AC:
215                         if(!test) make_local_action((bAction*)id);
216                         return 1;
217                 case ID_NT:
218                         return 0; /* not implemented */
219                 case ID_BR:
220                         if(!test) make_local_brush((Brush*)id);
221                         return 1;
222                 case ID_PA:
223                         if(!test) make_local_particlesettings((ParticleSettings*)id);
224                         return 1;
225                 case ID_WM:
226                         return 0; /* can't be linked */
227                 case ID_GD:
228                         return 0; /* not implemented */
229         }
230
231         return 0;
232 }
233
234 int id_copy(ID *id, ID **newid, int test)
235 {
236         if(!test) *newid= NULL;
237
238         /* conventions:
239          * - make shallow copy, only this ID block
240          * - id.us of the new ID is set to 1 */
241         switch(GS(id->name)) {
242                 case ID_SCE:
243                         return 0; /* can't be copied from here */
244                 case ID_LI:
245                         return 0; /* can't be copied from here */
246                 case ID_OB:
247                         if(!test) *newid= (ID*)copy_object((Object*)id);
248                         return 1;
249                 case ID_ME:
250                         if(!test) *newid= (ID*)copy_mesh((Mesh*)id);
251                         return 1;
252                 case ID_CU:
253                         if(!test) *newid= (ID*)copy_curve((Curve*)id);
254                         return 1;
255                 case ID_MB:
256                         if(!test) *newid= (ID*)copy_mball((MetaBall*)id);
257                         return 1;
258                 case ID_MA:
259                         if(!test) *newid= (ID*)copy_material((Material*)id);
260                         return 1;
261                 case ID_TE:
262                         if(!test) *newid= (ID*)copy_texture((Tex*)id);
263                         return 1;
264                 case ID_IM:
265                         if(!test) *newid= (ID*)copy_image((Image*)id);
266                         return 1;
267                 case ID_LT:
268                         if(!test) *newid= (ID*)copy_lattice((Lattice*)id);
269                         return 1;
270                 case ID_LA:
271                         if(!test) *newid= (ID*)copy_lamp((Lamp*)id);
272                         return 1;
273                 case ID_CA:
274                         if(!test) *newid= (ID*)copy_camera((Camera*)id);
275                         return 1;
276                 case ID_IP:
277                         return 0; /* deprecated */
278                 case ID_KE:
279                         if(!test) *newid= (ID*)copy_key((Key*)id);
280                         return 1;
281                 case ID_WO:
282                         if(!test) *newid= (ID*)copy_world((World*)id);
283                         return 1;
284                 case ID_SCR:
285                         return 0; /* can't be copied from here */
286                 case ID_VF:
287                         return 0; /* not implemented */
288                 case ID_TXT:
289                         if(!test) *newid= (ID*)copy_text((Text*)id);
290                         return 1;
291                 case ID_SCRIPT:
292                         return 0; /* deprecated */
293                 case ID_SO:
294                         return 0; /* not implemented */
295                 case ID_GR:
296                         if(!test) *newid= (ID*)copy_group((Group*)id);
297                         return 1;
298                 case ID_AR:
299                         if(!test) *newid= (ID*)copy_armature((bArmature*)id);
300                         return 1;
301                 case ID_AC:
302                         if(!test) *newid= (ID*)copy_action((bAction*)id);
303                         return 1;
304                 case ID_NT:
305                         if(!test) *newid= (ID*)ntreeCopyTree((bNodeTree*)id, 0);
306                         return 1;
307                 case ID_BR:
308                         if(!test) *newid= (ID*)copy_brush((Brush*)id);
309                         return 1;
310                 case ID_PA:
311                         if(!test) *newid= (ID*)psys_copy_settings((ParticleSettings*)id);
312                         return 1;
313                 case ID_WM:
314                         return 0; /* can't be copied from here */
315                 case ID_GD:
316                         return 0; /* not implemented */
317         }
318         
319         return 0;
320 }
321
322 int id_unlink(ID *id, int test)
323 {
324         Main *mainlib= G.main;
325         ListBase *lb;
326
327         switch(GS(id->name)) {
328                 case ID_TXT:
329                         if(test) return 1;
330                         unlink_text(mainlib, (Text*)id);
331                         break;
332                 case ID_GR:
333                         if(test) return 1;
334                         unlink_group((Group*)id);
335                         break;
336                 case ID_OB:
337                         if(test) return 1;
338                         unlink_object(NULL, (Object*)id);
339                         break;
340         }
341
342         if(id->us == 0) {
343                 if(test) return 1;
344
345                 lb= which_libbase(mainlib, GS(id->name));
346                 free_libblock(lb, id);
347
348                 return 1;
349         }
350
351         return 0;
352 }
353
354 ListBase *which_libbase(Main *mainlib, short type)
355 {
356         switch( type ) {
357                 case ID_SCE:
358                         return &(mainlib->scene);
359                 case ID_LI:
360                         return &(mainlib->library);
361                 case ID_OB:
362                         return &(mainlib->object);
363                 case ID_ME:
364                         return &(mainlib->mesh);
365                 case ID_CU:
366                         return &(mainlib->curve);
367                 case ID_MB:
368                         return &(mainlib->mball);
369                 case ID_MA:
370                         return &(mainlib->mat);
371                 case ID_TE:
372                         return &(mainlib->tex);
373                 case ID_IM:
374                         return &(mainlib->image);
375                 case ID_LT:
376                         return &(mainlib->latt);
377                 case ID_LA:
378                         return &(mainlib->lamp);
379                 case ID_CA:
380                         return &(mainlib->camera);
381                 case ID_IP:
382                         return &(mainlib->ipo);
383                 case ID_KE:
384                         return &(mainlib->key);
385                 case ID_WO:
386                         return &(mainlib->world);
387                 case ID_SCR:
388                         return &(mainlib->screen);
389                 case ID_VF:
390                         return &(mainlib->vfont);
391                 case ID_TXT:
392                         return &(mainlib->text);
393                 case ID_SCRIPT:
394                         return &(mainlib->script);
395                 case ID_SO:
396                         return &(mainlib->sound);
397                 case ID_GR:
398                         return &(mainlib->group);
399                 case ID_AR:
400                         return &(mainlib->armature);
401                 case ID_AC:
402                         return &(mainlib->action);
403                 case ID_NT:
404                         return &(mainlib->nodetree);
405                 case ID_BR:
406                         return &(mainlib->brush);
407                 case ID_PA:
408                         return &(mainlib->particle);
409                 case ID_WM:
410                         return &(mainlib->wm);
411                 case ID_GD:
412                         return &(mainlib->gpencil);
413         }
414         return 0;
415 }
416
417 /* Flag all ids in listbase */
418 void flag_listbase_ids(ListBase *lb, short flag, short value)
419 {
420         ID *id;
421         if (value) {
422                 for(id= lb->first; id; id= id->next) id->flag |= flag;
423         } else {
424                 flag = ~flag;
425                 for(id= lb->first; id; id= id->next) id->flag &= flag;
426         }
427 }
428
429 /* Flag all ids in listbase */
430 void flag_all_listbases_ids(short flag, short value)
431 {
432         ListBase *lbarray[MAX_LIBARRAY];
433         int a;
434         a= set_listbasepointers(G.main, lbarray);
435         while(a--)      flag_listbase_ids(lbarray[a], flag, value);
436 }
437
438 void recalc_all_library_objects(Main *main)
439 {
440         Object *ob;
441
442         /* flag for full recalc */
443         for(ob=main->object.first; ob; ob=ob->id.next)
444                 if(ob->id.lib)
445                         ob->recalc |= OB_RECALC_ALL;
446 }
447
448 /* note: MAX_LIBARRAY define should match this code */
449 int set_listbasepointers(Main *main, ListBase **lb)
450 {
451         int a = 0;
452
453         /* BACKWARDS! also watch order of free-ing! (mesh<->mat) */
454
455         lb[a++]= &(main->ipo);
456         lb[a++]= &(main->action); // xxx moved here to avoid problems when freeing with animato (aligorith)
457         lb[a++]= &(main->key);
458         lb[a++]= &(main->nodetree);
459         lb[a++]= &(main->image);
460         lb[a++]= &(main->tex);
461         lb[a++]= &(main->mat);
462         lb[a++]= &(main->vfont);
463         
464         /* Important!: When adding a new object type,
465          * the specific data should be inserted here 
466          */
467
468         lb[a++]= &(main->armature);
469
470         lb[a++]= &(main->mesh);
471         lb[a++]= &(main->curve);
472         lb[a++]= &(main->mball);
473
474         lb[a++]= &(main->latt);
475         lb[a++]= &(main->lamp);
476         lb[a++]= &(main->camera);
477         
478         lb[a++]= &(main->text);
479         lb[a++]= &(main->sound);
480         lb[a++]= &(main->group);
481         lb[a++]= &(main->brush);
482         lb[a++]= &(main->script);
483         lb[a++]= &(main->particle);
484         
485         lb[a++]= &(main->world);
486         lb[a++]= &(main->screen);
487         lb[a++]= &(main->object);
488         lb[a++]= &(main->scene);
489         lb[a++]= &(main->library);
490         lb[a++]= &(main->wm);
491         lb[a++]= &(main->gpencil);
492         
493         lb[a]= NULL;
494
495         return a;
496 }
497
498 /* *********** ALLOC AND FREE *****************
499   
500 free_libblock(ListBase *lb, ID *id )
501         provide a list-basis and datablock, but only ID is read
502
503 void *alloc_libblock(ListBase *lb, type, name)
504         inserts in list and returns a new ID
505
506  ***************************** */
507
508 static ID *alloc_libblock_notest(short type)
509 {
510         ID *id= NULL;
511         
512         switch( type ) {
513                 case ID_SCE:
514                         id= MEM_callocN(sizeof(Scene), "scene");
515                         break;
516                 case ID_LI:
517                         id= MEM_callocN(sizeof(Library), "library");
518                         break;
519                 case ID_OB:
520                         id= MEM_callocN(sizeof(Object), "object");
521                         break;
522                 case ID_ME:
523                         id= MEM_callocN(sizeof(Mesh), "mesh");
524                         break;
525                 case ID_CU:
526                         id= MEM_callocN(sizeof(Curve), "curve");
527                         break;
528                 case ID_MB:
529                         id= MEM_callocN(sizeof(MetaBall), "mball");
530                         break;
531                 case ID_MA:
532                         id= MEM_callocN(sizeof(Material), "mat");
533                         break;
534                 case ID_TE:
535                         id= MEM_callocN(sizeof(Tex), "tex");
536                         break;
537                 case ID_IM:
538                         id= MEM_callocN(sizeof(Image), "image");
539                         break;
540                 case ID_LT:
541                         id= MEM_callocN(sizeof(Lattice), "latt");
542                         break;
543                 case ID_LA:
544                         id= MEM_callocN(sizeof(Lamp), "lamp");
545                         break;
546                 case ID_CA:
547                         id= MEM_callocN(sizeof(Camera), "camera");
548                         break;
549                 case ID_IP:
550                         id= MEM_callocN(sizeof(Ipo), "ipo");
551                         break;
552                 case ID_KE:
553                         id= MEM_callocN(sizeof(Key), "key");
554                         break;
555                 case ID_WO:
556                         id= MEM_callocN(sizeof(World), "world");
557                         break;
558                 case ID_SCR:
559                         id= MEM_callocN(sizeof(bScreen), "screen");
560                         break;
561                 case ID_VF:
562                         id= MEM_callocN(sizeof(VFont), "vfont");
563                         break;
564                 case ID_TXT:
565                         id= MEM_callocN(sizeof(Text), "text");
566                         break;
567                 case ID_SCRIPT:
568                         //XXX id= MEM_callocN(sizeof(Script), "script");
569                         break;
570                 case ID_SO:
571                         id= MEM_callocN(sizeof(bSound), "sound");
572                         break;
573                 case ID_GR:
574                         id= MEM_callocN(sizeof(Group), "group");
575                         break;
576                 case ID_AR:
577                         id = MEM_callocN(sizeof(bArmature), "armature");
578                         break;
579                 case ID_AC:
580                         id = MEM_callocN(sizeof(bAction), "action");
581                         break;
582                 case ID_NT:
583                         id = MEM_callocN(sizeof(bNodeTree), "nodetree");
584                         break;
585                 case ID_BR:
586                         id = MEM_callocN(sizeof(Brush), "brush");
587                         break;
588                 case ID_PA:
589                         id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
590                           break;
591                 case ID_WM:
592                         id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
593                           break;
594                 case ID_GD:
595                         id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
596                         break;
597         }
598         return id;
599 }
600
601 /* used everywhere in blenkernel and text.c */
602 void *alloc_libblock(ListBase *lb, short type, const char *name)
603 {
604         ID *id= NULL;
605         
606         id= alloc_libblock_notest(type);
607         if(id) {
608                 BLI_addtail(lb, id);
609                 id->us= 1;
610                 id->icon_id = 0;
611                 *( (short *)id->name )= type;
612                 new_id(lb, id, name);
613                 /* alphabetic insterion: is in new_id */
614         }
615         return id;
616 }
617
618 /* by spec, animdata is first item after ID */
619 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
620 static void id_copy_animdata(ID *id)
621 {
622         AnimData *adt= BKE_animdata_from_id(id);
623         
624         if (adt) {
625                 IdAdtTemplate *iat = (IdAdtTemplate *)id;
626                 iat->adt= BKE_copy_animdata(iat->adt);
627         }
628 }
629
630 /* material nodes use this since they are not treated as libdata */
631 void copy_libblock_data(ID *id, const ID *id_from)
632 {
633         if (id_from->properties)
634                 id->properties = IDP_CopyProperty(id_from->properties);
635
636         /* the duplicate should get a copy of the animdata */
637         id_copy_animdata(id);
638 }
639
640 /* used everywhere in blenkernel */
641 void *copy_libblock(void *rt)
642 {
643         ID *idn, *id;
644         ListBase *lb;
645         char *cp, *cpn;
646         size_t idn_len;
647         
648         id= rt;
649
650         lb= which_libbase(G.main, GS(id->name));
651         idn= alloc_libblock(lb, GS(id->name), id->name+2);
652         
653         if(idn==NULL) {
654                 printf("ERROR: Illegal ID name for %s (Crashing now)\n", id->name);
655         }
656         
657         idn_len= MEM_allocN_len(idn);
658         if(idn_len - sizeof(ID) > 0) {
659                 cp= (char *)id;
660                 cpn= (char *)idn;
661                 memcpy(cpn+sizeof(ID), cp+sizeof(ID), idn_len - sizeof(ID));
662         }
663         
664         id->newid= idn;
665         idn->flag |= LIB_NEW;
666
667         copy_libblock_data(idn, id);
668         
669         return idn;
670 }
671
672 static void free_library(Library *lib)
673 {
674         /* no freeing needed for libraries yet */
675 }
676
677 static void (*free_windowmanager_cb)(bContext *, wmWindowManager *)= NULL;
678
679 void set_free_windowmanager_cb(void (*func)(bContext *C, wmWindowManager *) )
680 {
681         free_windowmanager_cb= func;
682 }
683
684 void animdata_dtar_clear_cb(ID *id, AnimData *adt, void *userdata)
685 {
686         ChannelDriver *driver;
687         FCurve *fcu;
688
689         /* find the driver this belongs to and update it */
690         for (fcu=adt->drivers.first; fcu; fcu=fcu->next) {
691                 driver= fcu->driver;
692                 
693                 if (driver) {
694                         DriverVar *dvar;
695                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
696                                 DRIVER_TARGETS_USED_LOOPER(dvar) 
697                                 {
698                                         if (dtar->id == userdata)
699                                                 dtar->id= NULL;
700                                 }
701                                 DRIVER_TARGETS_LOOPER_END
702                         }
703                 }
704         }
705 }
706
707
708 /* used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c */
709 void free_libblock(ListBase *lb, void *idv)
710 {
711         ID *id= idv;
712         
713         switch( GS(id->name) ) {        /* GetShort from util.h */
714                 case ID_SCE:
715                         free_scene((Scene *)id);
716                         break;
717                 case ID_LI:
718                         free_library((Library *)id);
719                         break;
720                 case ID_OB:
721                         free_object((Object *)id);
722                         break;
723                 case ID_ME:
724                         free_mesh((Mesh *)id);
725                         break;
726                 case ID_CU:
727                         free_curve((Curve *)id);
728                         break;
729                 case ID_MB:
730                         free_mball((MetaBall *)id);
731                         break;
732                 case ID_MA:
733                         free_material((Material *)id);
734                         break;
735                 case ID_TE:
736                         free_texture((Tex *)id);
737                         break;
738                 case ID_IM:
739                         free_image((Image *)id);
740                         break;
741                 case ID_LT:
742                         free_lattice((Lattice *)id);
743                         break;
744                 case ID_LA:
745                         free_lamp((Lamp *)id);
746                         break;
747                 case ID_CA:
748                         free_camera((Camera*) id);
749                         break;
750                 case ID_IP:
751                         free_ipo((Ipo *)id);
752                         break;
753                 case ID_KE:
754                         free_key((Key *)id);
755                         break;
756                 case ID_WO:
757                         free_world((World *)id);
758                         break;
759                 case ID_SCR:
760                         free_screen((bScreen *)id);
761                         break;
762                 case ID_VF:
763                         free_vfont((VFont *)id);
764                         break;
765                 case ID_TXT:
766                         free_text((Text *)id);
767                         break;
768                 case ID_SCRIPT:
769                         //XXX free_script((Script *)id);
770                         break;
771                 case ID_SO:
772                         sound_free((bSound*)id);
773                         break;
774                 case ID_GR:
775                         free_group_objects((Group *)id);
776                         break;
777                 case ID_AR:
778                         free_armature((bArmature *)id);
779                         break;
780                 case ID_AC:
781                         free_action((bAction *)id);
782                         break;
783                 case ID_NT:
784                         ntreeFreeTree((bNodeTree *)id);
785                         break;
786                 case ID_BR:
787                         free_brush((Brush *)id);
788                         break;
789                 case ID_PA:
790                         psys_free_settings((ParticleSettings *)id);
791                         break;
792                 case ID_WM:
793                         if(free_windowmanager_cb)
794                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
795                         break;
796                 case ID_GD:
797                         free_gpencil_data((bGPdata *)id);
798                         break;
799         }
800
801         if (id->properties) {
802                 IDP_FreeProperty(id->properties);
803                 MEM_freeN(id->properties);
804         }
805
806         BLI_remlink(lb, id);
807
808         /* this ID may be a driver target! */
809         BKE_animdata_main_cb(G.main, animdata_dtar_clear_cb, (void *)id);
810
811         MEM_freeN(id);
812 }
813
814 void free_libblock_us(ListBase *lb, void *idv)          /* test users */
815 {
816         ID *id= idv;
817         
818         id->us--;
819
820         if(id->us<0) {
821                 if(id->lib) printf("ERROR block %s %s users %d\n", id->lib->name, id->name, id->us);
822                 else printf("ERROR block %s users %d\n", id->name, id->us);
823         }
824         if(id->us==0) {
825                 if( GS(id->name)==ID_OB ) unlink_object(NULL, (Object *)id);
826                 
827                 free_libblock(lb, id);
828         }
829 }
830
831
832 void free_main(Main *mainvar)
833 {
834         /* also call when reading a file, erase all, etc */
835         ListBase *lbarray[MAX_LIBARRAY];
836         int a;
837
838         a= set_listbasepointers(mainvar, lbarray);
839         while(a--) {
840                 ListBase *lb= lbarray[a];
841                 ID *id;
842                 
843                 while ( (id= lb->first) ) {
844                         free_libblock(lb, id);
845                 }
846         }
847
848         MEM_freeN(mainvar);
849 }
850
851 /* ***************** ID ************************ */
852
853
854 ID *find_id(char *type, char *name)             /* type: "OB" or "MA" etc */
855 {
856         ListBase *lb= which_libbase(G.main, GS(type));
857         return BLI_findstring(lb, name, offsetof(ID, name) + 2);
858 }
859
860 static void get_flags_for_id(ID *id, char *buf) 
861 {
862         int isfake= id->flag & LIB_FAKEUSER;
863         int isnode=0;
864                 /* Writeout the flags for the entry, note there
865                  * is a small hack that writes 5 spaces instead
866                  * of 4 if no flags are displayed... this makes
867                  * things usually line up ok - better would be
868                  * to have that explicit, oh well - zr
869                  */
870
871         if(GS(id->name)==ID_MA)
872                 isnode= ((Material *)id)->use_nodes;
873         if(GS(id->name)==ID_TE)
874                 isnode= ((Tex *)id)->use_nodes;
875         
876         if (id->us<0)
877                 sprintf(buf, "-1W ");
878         else if (!id->lib && !isfake && id->us && !isnode)
879                 sprintf(buf, "     ");
880         else if(isnode)
881                 sprintf(buf, "%c%cN%c ", id->lib?'L':' ', isfake?'F':' ', (id->us==0)?'O':' ');
882         else
883                 sprintf(buf, "%c%c%c ", id->lib?'L':' ', isfake?'F':' ', (id->us==0)?'O':' ');
884 }
885
886 #define IDPUP_NO_VIEWER 1
887
888 static void IDnames_to_dyn_pupstring(DynStr *pupds, ListBase *lb, ID *link, short *nr, int hideflag)
889 {
890         int i, nids= BLI_countlist(lb);
891                 
892         if (nr) *nr= -1;
893         
894         if (nr && nids>MAX_IDPUP) {
895                 BLI_dynstr_append(pupds, "DataBrowse %x-2");
896                 *nr= -2;
897         } else {
898                 ID *id;
899                 
900                 for (i=0, id= lb->first; id; id= id->next, i++) {
901                         char buf[32];
902                         
903                         if (nr && id==link) *nr= i+1;
904
905                         if (U.uiflag & USER_HIDE_DOT && id->name[2]=='.')
906                                 continue;
907                         if (hideflag & IDPUP_NO_VIEWER)
908                                 if (GS(id->name)==ID_IM)
909                                         if ( ((Image *)id)->source==IMA_SRC_VIEWER )
910                                                 continue;
911                         
912                         get_flags_for_id(id, buf);
913                                 
914                         BLI_dynstr_append(pupds, buf);
915                         BLI_dynstr_append(pupds, id->name+2);
916                         sprintf(buf, "%%x%d", i+1);
917                         BLI_dynstr_append(pupds, buf);
918                         
919                         /* icon */
920                         switch(GS(id->name))
921                         {
922                         case ID_MA: /* fall through */
923                         case ID_TE: /* fall through */
924                         case ID_IM: /* fall through */
925                         case ID_WO: /* fall through */
926                         case ID_LA: /* fall through */
927                                 sprintf(buf, "%%i%d", BKE_icon_getid(id) );
928                                 BLI_dynstr_append(pupds, buf);
929                                 break;
930                         default:
931                                 break;
932                         }
933                         
934                         if(id->next)
935                                 BLI_dynstr_append(pupds, "|");
936                 }
937         }
938 }
939
940
941 /* used by headerbuttons.c buttons.c editobject.c editseq.c */
942 /* if nr==NULL no MAX_IDPUP, this for non-header browsing */
943 void IDnames_to_pupstring(char **str, char *title, char *extraops, ListBase *lb, ID *link, short *nr)
944 {
945         DynStr *pupds= BLI_dynstr_new();
946
947         if (title) {
948                 BLI_dynstr_append(pupds, title);
949                 BLI_dynstr_append(pupds, "%t|");
950         }
951         
952         if (extraops) {
953                 BLI_dynstr_append(pupds, extraops);
954                 if (BLI_dynstr_get_len(pupds))
955                         BLI_dynstr_append(pupds, "|");
956         }
957
958         IDnames_to_dyn_pupstring(pupds, lb, link, nr, 0);
959         
960         *str= BLI_dynstr_get_cstring(pupds);
961         BLI_dynstr_free(pupds);
962 }
963
964 /* skips viewer images */
965 void IMAnames_to_pupstring(char **str, char *title, char *extraops, ListBase *lb, ID *link, short *nr)
966 {
967         DynStr *pupds= BLI_dynstr_new();
968         
969         if (title) {
970                 BLI_dynstr_append(pupds, title);
971                 BLI_dynstr_append(pupds, "%t|");
972         }
973         
974         if (extraops) {
975                 BLI_dynstr_append(pupds, extraops);
976                 if (BLI_dynstr_get_len(pupds))
977                         BLI_dynstr_append(pupds, "|");
978         }
979         
980         IDnames_to_dyn_pupstring(pupds, lb, link, nr, IDPUP_NO_VIEWER);
981         
982         *str= BLI_dynstr_get_cstring(pupds);
983         BLI_dynstr_free(pupds);
984 }
985
986
987 /* used by buttons.c library.c mball.c */
988 int splitIDname(char *name, char *left, int *nr)
989 {
990         int a;
991         
992         *nr= 0;
993         strncpy(left, name, 21);
994         
995         a= strlen(name);
996         if(a>1 && name[a-1]=='.') return a;
997         
998         while(a--) {
999                 if( name[a]=='.' ) {
1000                         left[a]= 0;
1001                         *nr= atol(name+a+1);
1002                         return a;
1003                 }
1004                 if( isdigit(name[a])==0 ) break;
1005                 
1006                 left[a]= 0;
1007         }
1008
1009         for(a= 0; name[a]; a++)
1010                 left[a]= name[a];
1011
1012         return a;
1013 }
1014
1015 static void sort_alpha_id(ListBase *lb, ID *id)
1016 {
1017         ID *idtest;
1018         
1019         /* insert alphabetically */
1020         if(lb->first!=lb->last) {
1021                 BLI_remlink(lb, id);
1022                 
1023                 idtest= lb->first;
1024                 while(idtest) {
1025                         if(BLI_strcasecmp(idtest->name, id->name)>0 || idtest->lib) {
1026                                 BLI_insertlinkbefore(lb, idtest, id);
1027                                 break;
1028                         }
1029                         idtest= idtest->next;
1030                 }
1031                 /* as last */
1032                 if(idtest==0) {
1033                         BLI_addtail(lb, id);
1034                 }
1035         }
1036         
1037 }
1038
1039 /*
1040  * Check to see if there is an ID with the same name as 'name'.
1041  * Returns the ID if so, if not, returns NULL
1042  */
1043 static ID *is_dupid(ListBase *lb, ID *id, char *name)
1044 {
1045         ID *idtest=NULL;
1046         
1047         for( idtest = lb->first; idtest; idtest = idtest->next ) {
1048                 /* if idtest is not a lib */ 
1049                 if( id != idtest && idtest->lib == NULL ) {
1050                         /* do not test alphabetic! */
1051                         /* optimized */
1052                         if( idtest->name[2] == name[0] ) {
1053                                 if(strcmp(name, idtest->name+2)==0) break;
1054                         }
1055                 }
1056         }
1057         
1058         return idtest;
1059 }
1060
1061 /* 
1062  * Check to see if an ID name is already used, and find a new one if so.
1063  * Return 1 if created a new name (returned in name).
1064  *
1065  * Normally the ID that's being check is already in the ListBase, so ID *id
1066  * points at the new entry.  The Python Library module needs to know what
1067  * the name of a datablock will be before it is appended; in this case ID *id
1068  * id is NULL;
1069  */
1070
1071 static int check_for_dupid(ListBase *lb, ID *id, char *name)
1072 {
1073         ID *idtest;
1074         int nr= 0, nrtest, a, left_len;
1075         char left[32], leftest[32], in_use[32];
1076
1077         /* make sure input name is terminated properly */
1078         /* if( strlen(name) > 21 ) name[21]= 0; */
1079         /* removed since this is only ever called from one place - campbell */
1080
1081         while (1) {
1082
1083                 /* phase 1: id already exists? */
1084                 idtest = is_dupid(lb, id, name);
1085
1086                 /* if there is no double, done */
1087                 if( idtest == NULL ) return 0;
1088
1089                 /* we have a dup; need to make a new name */
1090                 /* quick check so we can reuse one of first 32 ids if vacant */
1091                 memset(in_use, 0, sizeof(in_use));
1092
1093                 /* get name portion, number portion ("name.number") */
1094                 left_len= splitIDname(name, left, &nr);
1095
1096                 /* if new name will be too long, truncate it */
1097                 if(nr>999 && strlen(left)>16) left[16]= 0;
1098                 else if(strlen(left)>17) left[17]= 0;
1099
1100                 for(idtest= lb->first; idtest; idtest= idtest->next) {
1101                         if(             (id != idtest) &&
1102                                         (idtest->lib == NULL) &&
1103                                         (*name == *(idtest->name+2)) &&
1104                                         (strncmp(name, idtest->name+2, left_len)==0) &&
1105                                         (splitIDname(idtest->name+2, leftest, &nrtest) == left_len)
1106                         ) {
1107                                 if(nrtest < sizeof(in_use))
1108                                         in_use[nrtest]= 1;      /* mark as used */
1109                                 if(nr <= nrtest)
1110                                         nr= nrtest+1;           /* track largest unused */
1111                         }
1112                 }
1113
1114                 /* decide which value of nr to use */
1115                 for(a=0; a < sizeof(in_use); a++) {
1116                         if(a>=nr) break;        /* stop when we've check up to biggest */
1117                         if( in_use[a]==0 ) { /* found an unused value */
1118                                 nr = a;
1119                                 break;
1120                         }
1121                 }
1122
1123                 /* If the original name has no numeric suffix, 
1124                  * rather than just chopping and adding numbers, 
1125                  * shave off the end chars until we have a unique name.
1126                  * Check the null terminators match as well so we dont get Cube.000 -> Cube.00 */
1127                 if (nr==0 && name[left_len]== left[left_len]) {
1128                         int len = strlen(name)-1;
1129                         idtest= is_dupid(lb, id, name);
1130                         
1131                         while (idtest && len> 1) {
1132                                 name[len--] = '\0';
1133                                 idtest= is_dupid(lb, id, name);
1134                         }
1135                         if (idtest == NULL) return 1;
1136                         /* otherwise just continue and use a number suffix */
1137                 }
1138                 
1139                 if(nr > 999 && strlen(left) > 16) {
1140                         /* this would overflow name buffer */
1141                         left[16] = 0;
1142                         strcpy( name, left );
1143                         continue;
1144                 }
1145                 /* this format specifier is from hell... */
1146                 sprintf(name, "%s.%.3d", left, nr);
1147
1148                 return 1;
1149         }
1150 }
1151
1152 /*
1153  * Only for local blocks: external en indirect blocks already have a
1154  * unique ID.
1155  *
1156  * return 1: created a new name
1157  */
1158
1159 int new_id(ListBase *lb, ID *id, const char *tname)
1160 {
1161         int result;
1162         char name[22];
1163
1164         /* if library, don't rename */
1165         if(id->lib) return 0;
1166
1167         /* if no libdata given, look up based on ID */
1168         if(lb==NULL) lb= which_libbase(G.main, GS(id->name));
1169
1170         /* if no name given, use name of current ID
1171          * else make a copy (tname args can be const) */
1172         if(tname==NULL)
1173                 tname= id->name+2;
1174
1175         strncpy(name, tname, sizeof(name)-1);
1176
1177         /* if result > 21, strncpy don't put the final '\0' to name.
1178          * easier to assign each time then to check if its needed */
1179         name[sizeof(name)-1]= 0;
1180
1181         if(name[0] == '\0')
1182                 strcpy(name, ID_FALLBACK_NAME);
1183
1184         result = check_for_dupid(lb, id, name);
1185         strcpy(id->name+2, name);
1186
1187         /* This was in 2.43 and previous releases
1188          * however all data in blender should be sorted, not just duplicate names
1189          * sorting should not hurt, but noting just incause it alters the way other
1190          * functions work, so sort every time */
1191         /* if( result )
1192                 sort_alpha_id(lb, id);*/
1193         
1194         sort_alpha_id(lb, id);
1195         
1196         return result;
1197 }
1198
1199 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1200 void clear_id_newpoins()
1201 {
1202         ListBase *lbarray[MAX_LIBARRAY];
1203         ID *id;
1204         int a;
1205
1206         a= set_listbasepointers(G.main, lbarray);
1207         while(a--) {
1208                 id= lbarray[a]->first;
1209                 while(id) {
1210                         id->newid= 0;
1211                         id->flag &= ~LIB_NEW;
1212                         id= id->next;
1213                 }
1214         }
1215 }
1216
1217 /* only for library fixes */
1218 static void image_fix_relative_path(Image *ima)
1219 {
1220         if(ima->id.lib==NULL) return;
1221         if(strncmp(ima->name, "//", 2)==0) {
1222                 BLI_path_abs(ima->name, ima->id.lib->filepath);
1223                 BLI_path_rel(ima->name, G.sce);
1224         }
1225 }
1226
1227 #define LIBTAG(a)       if(a && a->id.lib) {a->id.flag &=~LIB_INDIRECT; a->id.flag |= LIB_EXTERN;}
1228
1229 static void lib_indirect_test_id(ID *id, Library *lib)
1230 {
1231         
1232         if(id->lib) {
1233                 /* datablocks that were indirectly related are now direct links
1234                  * without this, appending data that has a link to other data will fail to write */
1235                 if(lib && id->lib->parent == lib) {
1236                         id_lib_extern(id);
1237                 }
1238                 return;
1239         }
1240         
1241         if(GS(id->name)==ID_OB) {               
1242                 Object *ob= (Object *)id;
1243                 bActionStrip *strip;
1244                 Mesh *me;
1245
1246                 int a;
1247         
1248                 // XXX old animation system! --------------------------------------
1249                 for (strip=ob->nlastrips.first; strip; strip=strip->next){
1250                         LIBTAG(strip->object); 
1251                         LIBTAG(strip->act);
1252                         LIBTAG(strip->ipo);
1253                 }
1254                 // XXX: new animation system needs something like this?
1255         
1256                 for(a=0; a<ob->totcol; a++) {
1257                         LIBTAG(ob->mat[a]);
1258                 }
1259         
1260                 LIBTAG(ob->dup_group);
1261                 LIBTAG(ob->proxy);
1262                 
1263                 me= ob->data;
1264                 LIBTAG(me);
1265         }
1266 }
1267
1268 void tag_main(struct Main *mainvar, int tag)
1269 {
1270         ListBase *lbarray[MAX_LIBARRAY];
1271         ID *id;
1272         int a;
1273
1274         a= set_listbasepointers(mainvar, lbarray);
1275         while(a--) {
1276                 for(id= lbarray[a]->first; id; id= id->next) {
1277                         if(tag) id->flag |= LIB_DOIT;
1278                         else    id->flag &= ~LIB_DOIT;
1279                 }
1280         }
1281 }
1282
1283 /* if lib!=NULL, only all from lib local */
1284 void all_local(Library *lib, int untagged_only)
1285 {
1286         ListBase *lbarray[MAX_LIBARRAY], tempbase={0, 0};
1287         ID *id, *idn;
1288         int a;
1289
1290         a= set_listbasepointers(G.main, lbarray);
1291         while(a--) {
1292                 id= lbarray[a]->first;
1293                 
1294                 while(id) {
1295                         id->newid= NULL;
1296                         idn= id->next;          /* id is possibly being inserted again */
1297                         
1298                         /* The check on the second line (LIB_PRE_EXISTING) is done so its
1299                          * possible to tag data you dont want to be made local, used for
1300                          * appending data, so any libdata already linked wont become local
1301                          * (very nasty to discover all your links are lost after appending)  
1302                          * */
1303                         if(id->flag & (LIB_EXTERN|LIB_INDIRECT|LIB_NEW) &&
1304                           (untagged_only==0 || !(id->flag & LIB_PRE_EXISTING)))
1305                         {
1306                                 if(lib==NULL || id->lib==lib) {
1307                                         id->flag &= ~(LIB_EXTERN|LIB_INDIRECT|LIB_NEW);
1308
1309                                         if(id->lib) {
1310                                                 /* relative file patch */
1311                                                 if(GS(id->name)==ID_IM)
1312                                                         image_fix_relative_path((Image *)id);
1313                                                 
1314                                                 id->lib= NULL;
1315                                                 new_id(lbarray[a], id, 0);      /* new_id only does it with double names */
1316                                                 sort_alpha_id(lbarray[a], id);
1317                                         }
1318                                 }
1319                         }
1320                         id= idn;
1321                 }
1322                 
1323                 /* patch2: make it aphabetically */
1324                 while( (id=tempbase.first) ) {
1325                         BLI_remlink(&tempbase, id);
1326                         BLI_addtail(lbarray[a], id);
1327                         new_id(lbarray[a], id, 0);
1328                 }
1329         }
1330
1331         /* patch 3: make sure library data isn't indirect falsely... */
1332         a= set_listbasepointers(G.main, lbarray);
1333         while(a--) {
1334                 for(id= lbarray[a]->first; id; id=id->next)
1335                         lib_indirect_test_id(id, lib);
1336         }
1337 }
1338
1339
1340 void test_idbutton(char *name)
1341 {
1342         /* called from buttons: when name already exists: call new_id */
1343         ListBase *lb;
1344         ID *idtest;
1345         
1346
1347         lb= which_libbase(G.main, GS(name-2) );
1348         if(lb==0) return;
1349         
1350         /* search for id */
1351         idtest= BLI_findstring(lb, name, offsetof(ID, name) + 2);
1352
1353         if(idtest) if( new_id(lb, idtest, name)==0 ) sort_alpha_id(lb, idtest);
1354 }
1355
1356 void text_idbutton(struct ID *id, char *text)
1357 {
1358         if(id) {
1359                 if(GS(id->name)==ID_SCE)
1360                         strcpy(text, "SCE: ");
1361                 else if(GS(id->name)==ID_SCE)
1362                         strcpy(text, "SCR: ");
1363                 else if(GS(id->name)==ID_MA && ((Material*)id)->use_nodes)
1364                         strcpy(text, "NT: ");
1365                 else {
1366                         text[0]= id->name[0];
1367                         text[1]= id->name[1];
1368                         text[2]= ':';
1369                         text[3]= ' ';
1370                         text[4]= 0;
1371                 }
1372         }
1373         else
1374                 strcpy(text, "");
1375 }
1376
1377 void rename_id(ID *id, char *name)
1378 {
1379         ListBase *lb;
1380
1381         strncpy(id->name+2, name, 21);
1382         lb= which_libbase(G.main, GS(id->name) );
1383         
1384         new_id(lb, id, name);                           
1385 }
1386
1387 void name_uiprefix_id(char *name, ID *id)
1388 {
1389         name[0] = id->lib ? 'L':' ';
1390         name[1] = id->flag & LIB_FAKEUSER ? 'F':' ';
1391         name[2] = ' ';
1392
1393         strcpy(name+3, id->name+2);
1394 }