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