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