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