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