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