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