Merged changes in the trunk up to revision 53584.
[blender.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  *
26  */
27
28 /** \file blender/blenloader/intern/readfile.c
29  *  \ingroup blenloader
30  */
31
32
33 #include "zlib.h"
34
35 #include <limits.h>
36 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
37 #include <stdlib.h> // for getenv atoi
38 #include <stddef.h> // for offsetof
39 #include <fcntl.h> // for open
40 #include <string.h> // for strrchr strncmp strstr
41 #include <math.h> // for fabs
42 #include <stdarg.h> /* for va_start/end */
43
44 #ifndef WIN32
45 #  include <unistd.h> // for read close
46 #else
47 #  include <io.h> // for open close read
48 #  include "winsock2.h"
49 #  include "BLI_winstuff.h"
50 #endif
51
52 /* allow readfile to use deprecated functionality */
53 #define DNA_DEPRECATED_ALLOW
54
55 #include "DNA_anim_types.h"
56 #include "DNA_armature_types.h"
57 #include "DNA_actuator_types.h"
58 #include "DNA_brush_types.h"
59 #include "DNA_camera_types.h"
60 #include "DNA_cloth_types.h"
61 #include "DNA_controller_types.h"
62 #include "DNA_constraint_types.h"
63 #include "DNA_dynamicpaint_types.h"
64 #include "DNA_effect_types.h"
65 #include "DNA_fileglobal_types.h"
66 #include "DNA_genfile.h"
67 #include "DNA_group_types.h"
68 #include "DNA_gpencil_types.h"
69 #include "DNA_ipo_types.h"
70 #include "DNA_key_types.h"
71 #include "DNA_lattice_types.h"
72 #include "DNA_lamp_types.h"
73 #ifdef WITH_FREESTYLE
74 #  include "DNA_linestyle_types.h"
75 #endif
76 #include "DNA_meta_types.h"
77 #include "DNA_material_types.h"
78 #include "DNA_mesh_types.h"
79 #include "DNA_meshdata_types.h"
80 #include "DNA_nla_types.h"
81 #include "DNA_node_types.h"
82 #include "DNA_object_fluidsim.h" // NT
83 #include "DNA_object_types.h"
84 #include "DNA_packedFile_types.h"
85 #include "DNA_particle_types.h"
86 #include "DNA_property_types.h"
87 #include "DNA_text_types.h"
88 #include "DNA_view3d_types.h"
89 #include "DNA_screen_types.h"
90 #include "DNA_sensor_types.h"
91 #include "DNA_sdna_types.h"
92 #include "DNA_scene_types.h"
93 #include "DNA_sequence_types.h"
94 #include "DNA_smoke_types.h"
95 #include "DNA_speaker_types.h"
96 #include "DNA_sound_types.h"
97 #include "DNA_space_types.h"
98 #include "DNA_vfont_types.h"
99 #include "DNA_world_types.h"
100 #include "DNA_movieclip_types.h"
101 #include "DNA_mask_types.h"
102
103 #include "MEM_guardedalloc.h"
104
105 #include "BLI_utildefines.h"
106 #include "BLI_endian_switch.h"
107 #include "BLI_blenlib.h"
108 #include "BLI_math.h"
109 #include "BLI_edgehash.h"
110
111 #include "BLF_translation.h"
112
113 #include "BKE_anim.h"
114 #include "BKE_action.h"
115 #include "BKE_armature.h"
116 #include "BKE_brush.h"
117 #include "BKE_colortools.h"
118 #include "BKE_constraint.h"
119 #include "BKE_context.h"
120 #include "BKE_curve.h"
121 #include "BKE_deform.h"
122 #include "BKE_effect.h"
123 #include "BKE_fcurve.h"
124 #include "BKE_global.h" // for G
125 #include "BKE_group.h"
126 #include "BKE_image.h"
127 #include "BKE_lattice.h"
128 #include "BKE_library.h" // for which_libbase
129 #include "BKE_idcode.h"
130 #include "BKE_material.h"
131 #include "BKE_main.h" // for Main
132 #include "BKE_mesh.h" // for ME_ defines (patching)
133 #include "BKE_modifier.h"
134 #include "BKE_multires.h"
135 #include "BKE_node.h" // for tree type defines
136 #include "BKE_ocean.h"
137 #include "BKE_object.h"
138 #include "BKE_paint.h"
139 #include "BKE_particle.h"
140 #include "BKE_pointcache.h"
141 #include "BKE_property.h" // for BKE_bproperty_object_get
142 #include "BKE_report.h"
143 #include "BKE_sca.h" // for init_actuator
144 #include "BKE_scene.h"
145 #include "BKE_screen.h"
146 #include "BKE_sequencer.h"
147 #include "BKE_text.h" // for txt_extended_ascii_as_utf8
148 #include "BKE_tracking.h"
149 #include "BKE_sound.h"
150
151 #include "IMB_imbuf.h"  // for proxy / timecode versioning stuff
152
153 #include "NOD_socket.h"
154
155 #include "BLO_readfile.h"
156 #include "BLO_undofile.h"
157 #include "BLO_blend_defs.h"
158
159 #include "RE_engine.h"
160
161 #include "readfile.h"
162
163 #include "PIL_time.h"
164
165 #include <errno.h>
166
167 /*
168  * Remark: still a weak point is the newaddress() function, that doesnt solve reading from
169  * multiple files at the same time
170  *
171  * (added remark: oh, i thought that was solved? will look at that... (ton)
172  *
173  * READ
174  * - Existing Library (Main) push or free
175  * - allocate new Main
176  * - load file
177  * - read SDNA
178  * - for each LibBlock
179  *     - read LibBlock
180  *     - if a Library
181  *         - make a new Main
182  *         - attach ID's to it
183  *     - else
184  *         - read associated 'direct data'
185  *         - link direct data (internal and to LibBlock)
186  * - read FileGlobal
187  * - read USER data, only when indicated (file is ~/X.XX/startup.blend)
188  * - free file
189  * - per Library (per Main)
190  *     - read file
191  *     - read SDNA
192  *     - find LibBlocks and attach IDs to Main
193  *         - if external LibBlock
194  *             - search all Main's
195  *                 - or it's already read,
196  *                 - or not read yet
197  *                 - or make new Main
198  *     - per LibBlock
199  *         - read recursive
200  *         - read associated direct data
201  *         - link direct data (internal and to LibBlock)
202  *     - free file
203  * - per Library with unread LibBlocks
204  *     - read file
205  *     - read SDNA
206  *     - per LibBlock
207  *                - read recursive
208  *                - read associated direct data
209  *                - link direct data (internal and to LibBlock)
210  *         - free file
211  * - join all Mains
212  * - link all LibBlocks and indirect pointers to libblocks
213  * - initialize FileGlobal and copy pointers to Global
214  */
215
216 /* also occurs in library.c */
217 /* GS reads the memory pointed at in a specific ordering. There are,
218  * however two definitions for it. I have jotted them down here, both,
219  * but I think the first one is actually used. The thing is that
220  * big-endian systems might read this the wrong way round. OTOH, we
221  * constructed the IDs that are read out with this macro explicitly as
222  * well. I expect we'll sort it out soon... */
223
224 /* from blendef: */
225 #define GS(a)   (*((short *)(a)))
226
227 /* from misc_util: flip the bytes from x  */
228 /*  #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
229
230 /***/
231
232 typedef struct OldNew {
233         void *old, *newp;
234         int nr;
235 } OldNew;
236
237 typedef struct OldNewMap {
238         OldNew *entries;
239         int nentries, entriessize;
240         int sorted;
241         int lasthit;
242 } OldNewMap;
243
244
245 /* local prototypes */
246 static void *read_struct(FileData *fd, BHead *bh, const char *blockname);
247 static void direct_link_modifiers(FileData *fd, ListBase *lb);
248 static void convert_tface_mt(FileData *fd, Main *main);
249
250 /* this function ensures that reports are printed,
251  * in the case of libraray linking errors this is important!
252  *
253  * bit kludge but better then doubling up on prints,
254  * we could alternatively have a versions of a report function which forces printing - campbell
255  */
256
257 static void BKE_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...)
258 #ifdef __GNUC__
259 __attribute__ ((format(printf, 3, 4)))
260 #endif
261 ;
262 static void BKE_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...)
263 {
264         char fixed_buf[1024]; /* should be long enough */
265         
266         va_list args;
267         
268         va_start(args, format);
269         vsnprintf(fixed_buf, sizeof(fixed_buf), format, args);
270         va_end(args);
271         
272         fixed_buf[sizeof(fixed_buf) - 1] = '\0';
273         
274         BKE_report(reports, type, fixed_buf);
275         
276         if (G.background == 0) {
277                 printf("%s\n", fixed_buf);
278         }
279 }
280
281 static OldNewMap *oldnewmap_new(void) 
282 {
283         OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
284         
285         onm->entriessize = 1024;
286         onm->entries = MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
287         
288         return onm;
289 }
290
291 static int verg_oldnewmap(const void *v1, const void *v2)
292 {
293         const struct OldNew *x1=v1, *x2=v2;
294         
295         if (x1->old > x2->old) return 1;
296         else if (x1->old < x2->old) return -1;
297         return 0;
298 }
299
300
301 static void oldnewmap_sort(FileData *fd) 
302 {
303         qsort(fd->libmap->entries, fd->libmap->nentries, sizeof(OldNew), verg_oldnewmap);
304         fd->libmap->sorted = 1;
305 }
306
307 /* nr is zero for data, and ID code for libdata */
308 static void oldnewmap_insert(OldNewMap *onm, void *oldaddr, void *newaddr, int nr) 
309 {
310         OldNew *entry;
311         
312         if (oldaddr==NULL || newaddr==NULL) return;
313         
314         if (onm->nentries == onm->entriessize) {
315                 int osize = onm->entriessize;
316                 OldNew *oentries = onm->entries;
317                 
318                 onm->entriessize *= 2;
319                 onm->entries = MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
320                 
321                 memcpy(onm->entries, oentries, sizeof(*oentries)*osize);
322                 MEM_freeN(oentries);
323         }
324
325         entry = &onm->entries[onm->nentries++];
326         entry->old = oldaddr;
327         entry->newp = newaddr;
328         entry->nr = nr;
329 }
330
331 void blo_do_versions_oldnewmap_insert(OldNewMap *onm, void *oldaddr, void *newaddr, int nr)
332 {
333         oldnewmap_insert(onm, oldaddr, newaddr, nr);
334 }
335
336 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, void *addr) 
337 {
338         int i;
339         
340         if (addr == NULL) return NULL;
341         
342         if (onm->lasthit < onm->nentries-1) {
343                 OldNew *entry = &onm->entries[++onm->lasthit];
344                 
345                 if (entry->old == addr) {
346                         entry->nr++;
347                         return entry->newp;
348                 }
349         }
350         
351         for (i = 0; i < onm->nentries; i++) {
352                 OldNew *entry = &onm->entries[i];
353                 
354                 if (entry->old == addr) {
355                         onm->lasthit = i;
356                         
357                         entry->nr++;
358                         return entry->newp;
359                 }
360         }
361         
362         return NULL;
363 }
364
365 /* for libdata, nr has ID code, no increment */
366 static void *oldnewmap_liblookup(OldNewMap *onm, void *addr, void *lib)
367 {
368         if (addr == NULL) {
369                 return NULL;
370         }
371
372         /* lasthit works fine for non-libdata, linking there is done in same sequence as writing */
373         if (onm->sorted) {
374                 OldNew entry_s, *entry;
375
376                 entry_s.old = addr;
377
378                 entry = bsearch(&entry_s, onm->entries, onm->nentries, sizeof(OldNew), verg_oldnewmap);
379                 if (entry) {
380                         ID *id = entry->newp;
381
382                         if (id && (!lib || id->lib)) {
383                                 return id;
384                         }
385                 }
386         }
387         else {
388                 /* note, this can be a bottle neck when loading some files */
389                 unsigned int nentries = (unsigned int)onm->nentries;
390                 unsigned int i;
391                 OldNew *entry;
392
393                 for (i = 0, entry = onm->entries; i < nentries; i++, entry++) {
394                         if (entry->old == addr) {
395                                 ID *id = id = entry->newp;
396                                 if (id && (!lib || id->lib)) {
397                                         return id;
398                                 }
399                         }
400                 }
401         }
402
403         return NULL;
404 }
405
406 static void oldnewmap_free_unused(OldNewMap *onm) 
407 {
408         int i;
409
410         for (i = 0; i < onm->nentries; i++) {
411                 OldNew *entry = &onm->entries[i];
412                 if (entry->nr == 0) {
413                         MEM_freeN(entry->newp);
414                         entry->newp = NULL;
415                 }
416         }
417 }
418
419 static void oldnewmap_clear(OldNewMap *onm) 
420 {
421         onm->nentries = 0;
422         onm->lasthit = 0;
423 }
424
425 static void oldnewmap_free(OldNewMap *onm) 
426 {
427         MEM_freeN(onm->entries);
428         MEM_freeN(onm);
429 }
430
431 /***/
432
433 static void read_libraries(FileData *basefd, ListBase *mainlist);
434
435 /* ************ help functions ***************** */
436
437 static void add_main_to_main(Main *mainvar, Main *from)
438 {
439         ListBase *lbarray[MAX_LIBARRAY], *fromarray[MAX_LIBARRAY];
440         int a;
441         
442         set_listbasepointers(mainvar, lbarray);
443         a = set_listbasepointers(from, fromarray);
444         while (a--) {
445                 BLI_movelisttolist(lbarray[a], fromarray[a]);
446         }
447 }
448
449 void blo_join_main(ListBase *mainlist)
450 {
451         Main *tojoin, *mainl;
452         
453         mainl = mainlist->first;
454         while ((tojoin = mainl->next)) {
455                 add_main_to_main(mainl, tojoin);
456                 BLI_remlink(mainlist, tojoin);
457                 MEM_freeN(tojoin);
458         }
459 }
460
461 static void split_libdata(ListBase *lb, Main *first)
462 {
463         ListBase *lbn;
464         ID *id, *idnext;
465         Main *mainvar;
466         
467         id = lb->first;
468         while (id) {
469                 idnext = id->next;
470                 if (id->lib) {
471                         mainvar = first;
472                         while (mainvar) {
473                                 if (mainvar->curlib == id->lib) {
474                                         lbn= which_libbase(mainvar, GS(id->name));
475                                         BLI_remlink(lb, id);
476                                         BLI_addtail(lbn, id);
477                                         break;
478                                 }
479                                 mainvar = mainvar->next;
480                         }
481                         if (mainvar == NULL) printf("error split_libdata\n");
482                 }
483                 id = idnext;
484         }
485 }
486
487 void blo_split_main(ListBase *mainlist, Main *main)
488 {
489         ListBase *lbarray[MAX_LIBARRAY];
490         Library *lib;
491         int i;
492         
493         mainlist->first = mainlist->last = main;
494         main->next = NULL;
495         
496         if (main->library.first == NULL)
497                 return;
498         
499         for (lib = main->library.first; lib; lib = lib->id.next) {
500                 Main *libmain = MEM_callocN(sizeof(Main), "libmain");
501                 libmain->curlib = lib;
502                 BLI_addtail(mainlist, libmain);
503         }
504         
505         i = set_listbasepointers(main, lbarray);
506         while (i--)
507                 split_libdata(lbarray[i], main->next);
508 }
509
510 /* removes things like /blah/blah/../../blah/ etc, then writes in *name the full path */
511 static void cleanup_path(const char *relabase, char *name)
512 {
513         char filename[FILE_MAXFILE];
514         
515         BLI_splitdirstring(name, filename);
516         BLI_cleanup_dir(relabase, name);
517         strcat(name, filename);
518 }
519
520 static void read_file_version(FileData *fd, Main *main)
521 {
522         BHead *bhead;
523         
524         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
525                 if (bhead->code == GLOB) {
526                         FileGlobal *fg= read_struct(fd, bhead, "Global");
527                         if (fg) {
528                                 main->subversionfile= fg->subversion;
529                                 main->minversionfile= fg->minversion;
530                                 main->minsubversionfile= fg->minsubversion;
531                                 MEM_freeN(fg);
532                         }
533                         else if (bhead->code == ENDB)
534                                 break;
535                 }
536         }
537 }
538
539
540 static Main *blo_find_main(FileData *fd, const char *filepath, const char *relabase)
541 {
542         ListBase *mainlist = fd->mainlist;
543         Main *m;
544         Library *lib;
545         char name1[FILE_MAX];
546         
547         BLI_strncpy(name1, filepath, sizeof(name1));
548         cleanup_path(relabase, name1);
549         
550 //      printf("blo_find_main: relabase  %s\n", relabase);
551 //      printf("blo_find_main: original in  %s\n", filepath);
552 //      printf("blo_find_main: converted to %s\n", name1);
553         
554         for (m = mainlist->first; m; m = m->next) {
555                 char *libname = (m->curlib) ? m->curlib->filepath : m->name;
556                 
557                 if (BLI_path_cmp(name1, libname) == 0) {
558                         if (G.debug & G_DEBUG) printf("blo_find_main: found library %s\n", libname);
559                         return m;
560                 }
561         }
562         
563         m = MEM_callocN(sizeof(Main), "find_main");
564         BLI_addtail(mainlist, m);
565         
566         lib = BKE_libblock_alloc(&m->library, ID_LI, "lib");
567         BLI_strncpy(lib->name, filepath, sizeof(lib->name));
568         BLI_strncpy(lib->filepath, name1, sizeof(lib->filepath));
569         
570         m->curlib = lib;
571         
572         read_file_version(fd, m);
573         
574         if (G.debug & G_DEBUG) printf("blo_find_main: added new lib %s\n", filepath);
575         return m;
576 }
577
578
579 /* ************ FILE PARSING ****************** */
580
581 static void switch_endian_bh4(BHead4 *bhead)
582 {
583         /* the ID_.. codes */
584         if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
585         
586         if (bhead->code != ENDB) {
587                 BLI_endian_switch_int32(&bhead->len);
588                 BLI_endian_switch_int32(&bhead->SDNAnr);
589                 BLI_endian_switch_int32(&bhead->nr);
590         }
591 }
592
593 static void switch_endian_bh8(BHead8 *bhead)
594 {
595         /* the ID_.. codes */
596         if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
597         
598         if (bhead->code != ENDB) {
599                 BLI_endian_switch_int32(&bhead->len);
600                 BLI_endian_switch_int32(&bhead->SDNAnr);
601                 BLI_endian_switch_int32(&bhead->nr);
602         }
603 }
604
605 static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap)
606 {
607         BHead4 *bhead4 = (BHead4 *) bhead;
608         int64_t old;
609
610         bhead4->code = bhead8->code;
611         bhead4->len = bhead8->len;
612
613         if (bhead4->code != ENDB) {
614                 /* perform a endian swap on 64bit pointers, otherwise the pointer might map to zero
615                  * 0x0000000000000000000012345678 would become 0x12345678000000000000000000000000
616                  */
617                 if (do_endian_swap) {
618                         BLI_endian_switch_int64(&bhead8->old);
619                 }
620                 
621                 /* this patch is to avoid a long long being read from not-eight aligned positions
622                  * is necessary on any modern 64bit architecture) */
623                 memcpy(&old, &bhead8->old, 8);
624                 bhead4->old = (int) (old >> 3);
625                 
626                 bhead4->SDNAnr = bhead8->SDNAnr;
627                 bhead4->nr = bhead8->nr;
628         }
629 }
630
631 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
632 {
633         BHead8 *bhead8 = (BHead8 *) bhead;
634         
635         bhead8->code = bhead4->code;
636         bhead8->len = bhead4->len;
637         
638         if (bhead8->code != ENDB) {
639                 bhead8->old = bhead4->old;
640                 bhead8->SDNAnr = bhead4->SDNAnr;
641                 bhead8->nr= bhead4->nr;
642         }
643 }
644
645 static BHeadN *get_bhead(FileData *fd)
646 {
647         BHeadN *new_bhead = NULL;
648         int readsize;
649         
650         if (fd) {
651                 if (!fd->eof) {
652                         /* initializing to zero isn't strictly needed but shuts valgrind up
653                          * since uninitialized memory gets compared */
654                         BHead8 bhead8 = {0};
655                         BHead4 bhead4 = {0};
656                         BHead  bhead = {0};
657                         
658                         /* First read the bhead structure.
659                          * Depending on the platform the file was written on this can
660                          * be a big or little endian BHead4 or BHead8 structure.
661                          *
662                          * As usual 'ENDB' (the last *partial* bhead of the file)
663                          * needs some special handling. We don't want to EOF just yet.
664                          */
665                         if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
666                                 bhead4.code = DATA;
667                                 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
668                                 
669                                 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {
670                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
671                                                 switch_endian_bh4(&bhead4);
672                                         }
673                                         
674                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
675                                                 bh8_from_bh4(&bhead, &bhead4);
676                                         }
677                                         else {
678                                                 memcpy(&bhead, &bhead4, sizeof(bhead));
679                                         }
680                                 }
681                                 else {
682                                         fd->eof = 1;
683                                         bhead.len= 0;
684                                 }
685                         }
686                         else {
687                                 bhead8.code = DATA;
688                                 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
689                                 
690                                 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
691                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
692                                                 switch_endian_bh8(&bhead8);
693                                         }
694                                         
695                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
696                                                 bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
697                                         }
698                                         else {
699                                                 memcpy(&bhead, &bhead8, sizeof(bhead));
700                                         }
701                                 }
702                                 else {
703                                         fd->eof = 1;
704                                         bhead.len= 0;
705                                 }
706                         }
707                         
708                         /* make sure people are not trying to pass bad blend files */
709                         if (bhead.len < 0) fd->eof = 1;
710                         
711                         /* bhead now contains the (converted) bhead structure. Now read
712                          * the associated data and put everything in a BHeadN (creative naming !)
713                          */
714                         if (!fd->eof) {
715                                 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
716                                 if (new_bhead) {
717                                         new_bhead->next = new_bhead->prev = NULL;
718                                         new_bhead->bhead = bhead;
719                                         
720                                         readsize = fd->read(fd, new_bhead + 1, bhead.len);
721                                         
722                                         if (readsize != bhead.len) {
723                                                 fd->eof = 1;
724                                                 MEM_freeN(new_bhead);
725                                                 new_bhead = NULL;
726                                         }
727                                 }
728                                 else {
729                                         fd->eof = 1;
730                                 }
731                         }
732                 }
733         }
734
735         /* We've read a new block. Now add it to the list
736          * of blocks.
737          */
738         if (new_bhead) {
739                 BLI_addtail(&fd->listbase, new_bhead);
740         }
741         
742         return(new_bhead);
743 }
744
745 BHead *blo_firstbhead(FileData *fd)
746 {
747         BHeadN *new_bhead;
748         BHead *bhead = NULL;
749         
750         /* Rewind the file
751          * Read in a new block if necessary
752          */
753         new_bhead = fd->listbase.first;
754         if (new_bhead == NULL) {
755                 new_bhead = get_bhead(fd);
756         }
757         
758         if (new_bhead) {
759                 bhead = &new_bhead->bhead;
760         }
761         
762         return(bhead);
763 }
764
765 BHead *blo_prevbhead(FileData *UNUSED(fd), BHead *thisblock)
766 {
767         BHeadN *bheadn = (BHeadN *) (((char *) thisblock) - offsetof(BHeadN, bhead));
768         BHeadN *prev = bheadn->prev;
769         
770         return (prev) ? &prev->bhead : NULL;
771 }
772
773 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
774 {
775         BHeadN *new_bhead = NULL;
776         BHead *bhead = NULL;
777         
778         if (thisblock) {
779                 /* bhead is actually a sub part of BHeadN
780                  * We calculate the BHeadN pointer from the BHead pointer below */
781                 new_bhead = (BHeadN *) (((char *) thisblock) - offsetof(BHeadN, bhead));
782                 
783                 /* get the next BHeadN. If it doesn't exist we read in the next one */
784                 new_bhead = new_bhead->next;
785                 if (new_bhead == NULL) {
786                         new_bhead = get_bhead(fd);
787                 }
788         }
789         
790         if (new_bhead) {
791                 /* here we do the reverse:
792                  * go from the BHeadN pointer to the BHead pointer */
793                 bhead = &new_bhead->bhead;
794         }
795         
796         return(bhead);
797 }
798
799 static void decode_blender_header(FileData *fd)
800 {
801         char header[SIZEOFBLENDERHEADER], num[4];
802         int readsize;
803         
804         /* read in the header data */
805         readsize = fd->read(fd, header, sizeof(header));
806         
807         if (readsize == sizeof(header)) {
808                 if (strncmp(header, "BLENDER", 7) == 0) {
809                         int remove_this_endian_test = 1;
810                         
811                         fd->flags |= FD_FLAGS_FILE_OK;
812                         
813                         /* what size are pointers in the file ? */
814                         if (header[7]=='_') {
815                                 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
816                                 if (sizeof(void *) != 4) {
817                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
818                                 }
819                         }
820                         else {
821                                 if (sizeof(void *) != 8) {
822                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
823                                 }
824                         }
825                         
826                         /* is the file saved in a different endian
827                          * than we need ?
828                          */
829                         if (((((char *)&remove_this_endian_test)[0] == 1) ? L_ENDIAN : B_ENDIAN) != ((header[8] == 'v') ? L_ENDIAN : B_ENDIAN)) {
830                                 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
831                         }
832                         
833                         /* get the version number */
834                         memcpy(num, header + 9, 3);
835                         num[3] = 0;
836                         fd->fileversion = atoi(num);
837                 }
838         }
839 }
840
841 static int read_file_dna(FileData *fd)
842 {
843         BHead *bhead;
844         
845         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
846                 if (bhead->code == DNA1) {
847                         int do_endian_swap = (fd->flags & FD_FLAGS_SWITCH_ENDIAN) ? 1 : 0;
848                         
849                         fd->filesdna = DNA_sdna_from_data(&bhead[1], bhead->len, do_endian_swap);
850                         if (fd->filesdna) {
851                                 fd->compflags = DNA_struct_get_compareflags(fd->filesdna, fd->memsdna);
852                                 /* used to retrieve ID names from (bhead+1) */
853                                 fd->id_name_offs = DNA_elem_offset(fd->filesdna, "ID", "char", "name[]");
854                         }
855                         
856                         return 1;
857                 }
858                 else if (bhead->code == ENDB)
859                         break;
860         }
861         
862         return 0;
863 }
864
865 static int fd_read_from_file(FileData *filedata, void *buffer, unsigned int size)
866 {
867         int readsize = read(filedata->filedes, buffer, size);
868         
869         if (readsize < 0) {
870                 readsize = EOF;
871         }
872         else {
873                 filedata->seek += readsize;
874         }
875         
876         return readsize;
877 }
878
879 static int fd_read_gzip_from_file(FileData *filedata, void *buffer, unsigned int size)
880 {
881         int readsize = gzread(filedata->gzfiledes, buffer, size);
882         
883         if (readsize < 0) {
884                 readsize = EOF;
885         }
886         else {
887                 filedata->seek += readsize;
888         }
889         
890         return (readsize);
891 }
892
893 static int fd_read_from_memory(FileData *filedata, void *buffer, unsigned int size)
894 {
895         /* don't read more bytes then there are available in the buffer */
896         int readsize = (int)MIN2(size, (unsigned int)(filedata->buffersize - filedata->seek));
897         
898         memcpy(buffer, filedata->buffer + filedata->seek, readsize);
899         filedata->seek += readsize;
900         
901         return (readsize);
902 }
903
904 static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int size)
905 {
906         static unsigned int seek = (1<<30);     /* the current position */
907         static unsigned int offset = 0;         /* size of previous chunks */
908         static MemFileChunk *chunk = NULL;
909         unsigned int chunkoffset, readsize, totread;
910         
911         if (size == 0) return 0;
912         
913         if (seek != (unsigned int)filedata->seek) {
914                 chunk = filedata->memfile->chunks.first;
915                 seek = 0;
916                 
917                 while (chunk) {
918                         if (seek + chunk->size > (unsigned) filedata->seek) break;
919                         seek += chunk->size;
920                         chunk = chunk->next;
921                 }
922                 offset = seek;
923                 seek = filedata->seek;
924         }
925         
926         if (chunk) {
927                 totread = 0;
928                 
929                 do {
930                         /* first check if it's on the end if current chunk */
931                         if (seek-offset == chunk->size) {
932                                 offset += chunk->size;
933                                 chunk = chunk->next;
934                         }
935                         
936                         /* debug, should never happen */
937                         if (chunk == NULL) {
938                                 printf("illegal read, chunk zero\n");
939                                 return 0;
940                         }
941                         
942                         chunkoffset = seek-offset;
943                         readsize = size-totread;
944                         
945                         /* data can be spread over multiple chunks, so clamp size
946                          * to within this chunk, and then it will read further in
947                          * the next chunk */
948                         if (chunkoffset+readsize > chunk->size)
949                                 readsize= chunk->size-chunkoffset;
950                         
951                         memcpy((char *)buffer + totread, chunk->buf + chunkoffset, readsize);
952                         totread += readsize;
953                         filedata->seek += readsize;
954                         seek += readsize;
955                 } while (totread < size);
956                 
957                 return totread;
958         }
959         
960         return 0;
961 }
962
963 static FileData *filedata_new(void)
964 {
965         FileData *fd = MEM_callocN(sizeof(FileData), "FileData");
966         
967         fd->filedes = -1;
968         fd->gzfiledes = NULL;
969         
970                 /* XXX, this doesn't need to be done all the time,
971                  * but it keeps us re-entrant,  remove once we have
972                  * a lib that provides a nice lock. - zr
973                  */
974         fd->memsdna = DNA_sdna_from_data(DNAstr,  DNAlen,  0);
975         
976         fd->datamap = oldnewmap_new();
977         fd->globmap = oldnewmap_new();
978         fd->libmap = oldnewmap_new();
979         
980         return fd;
981 }
982
983 static FileData *blo_decode_and_check(FileData *fd, ReportList *reports)
984 {
985         decode_blender_header(fd);
986         
987         if (fd->flags & FD_FLAGS_FILE_OK) {
988                 if (!read_file_dna(fd)) {
989                         BKE_reportf(reports, RPT_ERROR, "Failed to read blend file '%s', incomplete", fd->relabase);
990                         blo_freefiledata(fd);
991                         fd = NULL;
992                 }
993         }
994         else {
995                 BKE_reportf(reports, RPT_ERROR, "Failed to read blend file '%s', not a blend file", fd->relabase);
996                 blo_freefiledata(fd);
997                 fd = NULL;
998         }
999         
1000         return fd;
1001 }
1002
1003 /* cannot be called with relative paths anymore! */
1004 /* on each new library added, it now checks for the current FileData and expands relativeness */
1005 FileData *blo_openblenderfile(const char *filepath, ReportList *reports)
1006 {
1007         gzFile gzfile;
1008         errno = 0;
1009         gzfile = BLI_gzopen(filepath, "rb");
1010         
1011         if (gzfile == (gzFile)Z_NULL) {
1012                 BKE_reportf(reports, RPT_WARNING, "Unable to open '%s': %s",
1013                             filepath, errno ? strerror(errno) : TIP_("unknown error reading file"));
1014                 return NULL;
1015         }
1016         else {
1017                 FileData *fd = filedata_new();
1018                 fd->gzfiledes = gzfile;
1019                 fd->read = fd_read_gzip_from_file;
1020                 
1021                 /* needed for library_append and read_libraries */
1022                 BLI_strncpy(fd->relabase, filepath, sizeof(fd->relabase));
1023                 
1024                 return blo_decode_and_check(fd, reports);
1025         }
1026 }
1027
1028 static int fd_read_gzip_from_memory(FileData *filedata, void *buffer, unsigned int size)
1029 {
1030         int err;
1031
1032         filedata->strm.next_out = (Bytef *) buffer;
1033         filedata->strm.avail_out = size;
1034
1035         // Inflate another chunk.
1036         err = inflate (&filedata->strm, Z_SYNC_FLUSH);
1037
1038         if (err == Z_STREAM_END) {
1039                 return 0;
1040         }
1041         else if (err != Z_OK)  {
1042                 printf("fd_read_gzip_from_memory: zlib error\n");
1043                 return 0;
1044         }
1045
1046         filedata->seek += size;
1047
1048         return (size);
1049 }
1050
1051 static int fd_read_gzip_from_memory_init(FileData *fd)
1052 {
1053
1054         fd->strm.next_in = (Bytef *) fd->buffer;
1055         fd->strm.avail_in = fd->buffersize;
1056         fd->strm.total_out = 0;
1057         fd->strm.zalloc = Z_NULL;
1058         fd->strm.zfree = Z_NULL;
1059         
1060         if (inflateInit2(&fd->strm, (16+MAX_WBITS)) != Z_OK)
1061                 return 0;
1062
1063         fd->read = fd_read_gzip_from_memory;
1064         
1065         return 1;
1066 }
1067
1068 FileData *blo_openblendermemory(void *mem, int memsize, ReportList *reports)
1069 {
1070         if (!mem || memsize<SIZEOFBLENDERHEADER) {
1071                 BKE_report(reports, RPT_WARNING, (mem) ? TIP_("Unable to read"): TIP_("Unable to open"));
1072                 return NULL;
1073         }
1074         else {
1075                 FileData *fd = filedata_new();
1076                 char *cp = mem;
1077                 
1078                 fd->buffer = mem;
1079                 fd->buffersize = memsize;
1080                 
1081                 /* test if gzip */
1082                 if (cp[0] == 0x1f && cp[1] == 0x8b) {
1083                         if (0 == fd_read_gzip_from_memory_init(fd)) {
1084                                 blo_freefiledata(fd);
1085                                 return NULL;
1086                         }
1087                 }
1088                 else
1089                 fd->read = fd_read_from_memory;
1090                         
1091                 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1092                 
1093                 return blo_decode_and_check(fd, reports);
1094         }
1095 }
1096
1097 FileData *blo_openblendermemfile(MemFile *memfile, ReportList *reports)
1098 {
1099         if (!memfile) {
1100                 BKE_report(reports, RPT_WARNING, "Unable to open blend <memory>");
1101                 return NULL;
1102         }
1103         else {
1104                 FileData *fd = filedata_new();
1105                 fd->memfile = memfile;
1106                 
1107                 fd->read = fd_read_from_memfile;
1108                 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1109                 
1110                 return blo_decode_and_check(fd, reports);
1111         }
1112 }
1113
1114
1115 void blo_freefiledata(FileData *fd)
1116 {
1117         if (fd) {
1118                 if (fd->filedes != -1) {
1119                         close(fd->filedes);
1120                 }
1121                 
1122                 if (fd->gzfiledes != NULL) {
1123                         gzclose(fd->gzfiledes);
1124                 }
1125                 
1126                 if (fd->strm.next_in) {
1127                         if (inflateEnd (&fd->strm) != Z_OK) {
1128                                 printf("close gzip stream error\n");
1129                         }
1130                 }
1131                 
1132                 if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
1133                         MEM_freeN(fd->buffer);
1134                         fd->buffer = NULL;
1135                 }
1136                 
1137                 // Free all BHeadN data blocks
1138                 BLI_freelistN(&fd->listbase);
1139                 
1140                 if (fd->memsdna)
1141                         DNA_sdna_free(fd->memsdna);
1142                 if (fd->filesdna)
1143                         DNA_sdna_free(fd->filesdna);
1144                 if (fd->compflags)
1145                         MEM_freeN(fd->compflags);
1146                 
1147                 if (fd->datamap)
1148                         oldnewmap_free(fd->datamap);
1149                 if (fd->globmap)
1150                         oldnewmap_free(fd->globmap);
1151                 if (fd->imamap)
1152                         oldnewmap_free(fd->imamap);
1153                 if (fd->movieclipmap)
1154                         oldnewmap_free(fd->movieclipmap);
1155                 if (fd->packedmap)
1156                         oldnewmap_free(fd->packedmap);
1157                 if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
1158                         oldnewmap_free(fd->libmap);
1159                 if (fd->bheadmap)
1160                         MEM_freeN(fd->bheadmap);
1161                 
1162                 MEM_freeN(fd);
1163         }
1164 }
1165
1166 /* ************ DIV ****************** */
1167
1168 int BLO_has_bfile_extension(const char *str)
1169 {
1170         return (BLI_testextensie(str, ".ble") || 
1171                 BLI_testextensie(str, ".blend") || 
1172                 BLI_testextensie(str, ".blend.gz"));
1173 }
1174
1175 int BLO_is_a_library(const char *path, char *dir, char *group)
1176 {
1177         /* return ok when a blenderfile, in dir is the filename,
1178          * in group the type of libdata
1179          */
1180         int len;
1181         char *fd;
1182         
1183         strcpy(dir, path);
1184         len = strlen(dir);
1185         if (len < 7) return 0;
1186         if ((dir[len - 1] != '/') && (dir[len - 1] != '\\')) return 0;
1187         
1188         group[0] = '\0';
1189         dir[len - 1] = '\0';
1190
1191         /* Find the last slash */
1192         fd = BLI_last_slash(dir);
1193
1194         if (fd == NULL) return 0;
1195         *fd = 0;
1196         if (BLO_has_bfile_extension(fd+1)) {
1197                 /* the last part of the dir is a .blend file, no group follows */
1198                 *fd = '/'; /* put back the removed slash separating the dir and the .blend file name */
1199         }
1200         else {
1201                 char *gp = fd + 1; // in case we have a .blend file, gp points to the group
1202                 
1203                 /* Find the last slash */
1204                 fd = BLI_last_slash(dir);
1205                 if (!fd || !BLO_has_bfile_extension(fd+1)) return 0;
1206                 
1207                 /* now we know that we are in a blend file and it is safe to 
1208                  * assume that gp actually points to a group */
1209                 if (strcmp("Screen", gp) != 0)
1210                         BLI_strncpy(group, gp, GROUP_MAX);
1211         }
1212         return 1;
1213 }
1214
1215 /* ************** OLD POINTERS ******************* */
1216
1217 static void *newdataadr(FileData *fd, void *adr)                /* only direct databocks */
1218 {
1219         return oldnewmap_lookup_and_inc(fd->datamap, adr);
1220 }
1221
1222 static void *newglobadr(FileData *fd, void *adr)                /* direct datablocks with global linking */
1223 {
1224         return oldnewmap_lookup_and_inc(fd->globmap, adr);
1225 }
1226
1227 static void *newimaadr(FileData *fd, void *adr)         /* used to restore image data after undo */
1228 {
1229         if (fd->imamap && adr)
1230                 return oldnewmap_lookup_and_inc(fd->imamap, adr);
1231         return NULL;
1232 }
1233
1234 static void *newmclipadr(FileData *fd, void *adr)              /* used to restore movie clip data after undo */
1235 {
1236         if (fd->movieclipmap && adr)
1237                 return oldnewmap_lookup_and_inc(fd->movieclipmap, adr);
1238         return NULL;
1239 }
1240
1241 static void *newpackedadr(FileData *fd, void *adr)      /* used to restore packed data after undo */
1242 {
1243         if (fd->packedmap && adr)
1244                 return oldnewmap_lookup_and_inc(fd->packedmap, adr);
1245
1246         return oldnewmap_lookup_and_inc(fd->datamap, adr);
1247 }
1248
1249
1250 static void *newlibadr(FileData *fd, void *lib, void *adr)              /* only lib data */
1251 {
1252         return oldnewmap_liblookup(fd->libmap, adr, lib);
1253 }
1254
1255 void *blo_do_versions_newlibadr(FileData *fd, void *lib, void *adr)             /* only lib data */
1256 {
1257         return newlibadr(fd, lib, adr);
1258 }
1259
1260 static void *newlibadr_us(FileData *fd, void *lib, void *adr)   /* increases user number */
1261 {
1262         ID *id = newlibadr(fd, lib, adr);
1263         
1264         if (id)
1265                 id->us++;
1266         
1267         return id;
1268 }
1269
1270 void *blo_do_versions_newlibadr_us(FileData *fd, void *lib, void *adr)  /* increases user number */
1271 {
1272         return newlibadr_us(fd, lib, adr);
1273 }
1274
1275 static void change_idid_adr_fd(FileData *fd, void *old, void *new)
1276 {
1277         int i;
1278         
1279         for (i = 0; i < fd->libmap->nentries; i++) {
1280                 OldNew *entry = &fd->libmap->entries[i];
1281                 
1282                 if (old==entry->newp && entry->nr==ID_ID) {
1283                         entry->newp = new;
1284                         if (new) entry->nr = GS( ((ID *)new)->name );
1285                 }
1286         }
1287 }
1288
1289 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
1290 {
1291         Main *mainptr;
1292         
1293         for (mainptr = mainlist->first; mainptr; mainptr = mainptr->next) {
1294                 FileData *fd;
1295                 
1296                 if (mainptr->curlib)
1297                         fd = mainptr->curlib->filedata;
1298                 else
1299                         fd = basefd;
1300                 
1301                 if (fd) {
1302                         change_idid_adr_fd(fd, old, new);
1303                 }
1304         }
1305 }
1306
1307 /* lib linked proxy objects point to our local data, we need
1308  * to clear that pointer before reading the undo memfile since
1309  * the object might be removed, it is set again in reading
1310  * if the local object still exists */
1311 void blo_clear_proxy_pointers_from_lib(Main *oldmain)
1312 {
1313         Object *ob = oldmain->object.first;
1314         
1315         for (; ob; ob= ob->id.next) {
1316                 if (ob->id.lib)
1317                         ob->proxy_from = NULL;
1318         }
1319 }
1320
1321 void blo_make_image_pointer_map(FileData *fd, Main *oldmain)
1322 {
1323         Image *ima = oldmain->image.first;
1324         Scene *sce = oldmain->scene.first;
1325         int a;
1326         
1327         fd->imamap = oldnewmap_new();
1328         
1329         for (; ima; ima = ima->id.next) {
1330                 Link *ibuf = ima->ibufs.first;
1331                 for (; ibuf; ibuf = ibuf->next)
1332                         oldnewmap_insert(fd->imamap, ibuf, ibuf, 0);
1333                 if (ima->gputexture)
1334                         oldnewmap_insert(fd->imamap, ima->gputexture, ima->gputexture, 0);
1335                 for (a=0; a < IMA_MAX_RENDER_SLOT; a++)
1336                         if (ima->renders[a])
1337                                 oldnewmap_insert(fd->imamap, ima->renders[a], ima->renders[a], 0);
1338         }
1339         for (; sce; sce = sce->id.next) {
1340                 if (sce->nodetree) {
1341                         bNode *node;
1342                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1343                                 oldnewmap_insert(fd->imamap, node->preview, node->preview, 0);
1344                 }
1345         }
1346 }
1347
1348 /* set old main image ibufs to zero if it has been restored */
1349 /* this works because freeing old main only happens after this call */
1350 void blo_end_image_pointer_map(FileData *fd, Main *oldmain)
1351 {
1352         OldNew *entry = fd->imamap->entries;
1353         Image *ima = oldmain->image.first;
1354         Scene *sce = oldmain->scene.first;
1355         int i;
1356         
1357         /* used entries were restored, so we put them to zero */
1358         for (i = 0; i < fd->imamap->nentries; i++, entry++) {
1359                 if (entry->nr > 0)
1360                         entry->newp = NULL;
1361         }
1362         
1363         for (; ima; ima = ima->id.next) {
1364                 Link *ibuf, *next;
1365                 
1366                 /* this mirrors direct_link_image */
1367                 for (ibuf = ima->ibufs.first; ibuf; ibuf = next) {
1368                         next = ibuf->next;
1369                         if (NULL == newimaadr(fd, ibuf)) {      /* so was restored */
1370                                 BLI_remlink(&ima->ibufs, ibuf);
1371                                 ima->bindcode = 0;
1372                                 ima->tpageflag &= ~IMA_GLBIND_IS_DATA;
1373                                 ima->gputexture = NULL;
1374                         }
1375                 }
1376                 for (i = 0; i < IMA_MAX_RENDER_SLOT; i++)
1377                         ima->renders[i] = newimaadr(fd, ima->renders[i]);
1378                 
1379                 ima->gputexture = newimaadr(fd, ima->gputexture);
1380         }
1381         for (; sce; sce = sce->id.next) {
1382                 if (sce->nodetree) {
1383                         bNode *node;
1384                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1385                                 node->preview = newimaadr(fd, node->preview);
1386                 }
1387         }
1388 }
1389
1390 void blo_make_movieclip_pointer_map(FileData *fd, Main *oldmain)
1391 {
1392         MovieClip *clip = oldmain->movieclip.first;
1393         Scene *sce = oldmain->scene.first;
1394         
1395         fd->movieclipmap = oldnewmap_new();
1396         
1397         for (; clip; clip = clip->id.next) {
1398                 if (clip->cache)
1399                         oldnewmap_insert(fd->movieclipmap, clip->cache, clip->cache, 0);
1400                 
1401                 if (clip->tracking.camera.intrinsics)
1402                         oldnewmap_insert(fd->movieclipmap, clip->tracking.camera.intrinsics, clip->tracking.camera.intrinsics, 0);
1403         }
1404         
1405         for (; sce; sce = sce->id.next) {
1406                 if (sce->nodetree) {
1407                         bNode *node;
1408                         for (node = sce->nodetree->nodes.first; node; node= node->next)
1409                                 if (node->type == CMP_NODE_MOVIEDISTORTION)
1410                                         oldnewmap_insert(fd->movieclipmap, node->storage, node->storage, 0);
1411                 }
1412         }
1413 }
1414
1415 /* set old main movie clips caches to zero if it has been restored */
1416 /* this works because freeing old main only happens after this call */
1417 void blo_end_movieclip_pointer_map(FileData *fd, Main *oldmain)
1418 {
1419         OldNew *entry = fd->movieclipmap->entries;
1420         MovieClip *clip = oldmain->movieclip.first;
1421         Scene *sce = oldmain->scene.first;
1422         int i;
1423         
1424         /* used entries were restored, so we put them to zero */
1425         for (i=0; i < fd->movieclipmap->nentries; i++, entry++) {
1426                 if (entry->nr > 0)
1427                         entry->newp = NULL;
1428         }
1429         
1430         for (; clip; clip = clip->id.next) {
1431                 clip->cache = newmclipadr(fd, clip->cache);
1432                 clip->tracking.camera.intrinsics = newmclipadr(fd, clip->tracking.camera.intrinsics);
1433         }
1434         
1435         for (; sce; sce = sce->id.next) {
1436                 if (sce->nodetree) {
1437                         bNode *node;
1438                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1439                                 if (node->type == CMP_NODE_MOVIEDISTORTION)
1440                                         node->storage = newmclipadr(fd, node->storage);
1441                 }
1442         }
1443 }
1444
1445 static void insert_packedmap(FileData *fd, PackedFile *pf)
1446 {
1447         oldnewmap_insert(fd->packedmap, pf, pf, 0);
1448         oldnewmap_insert(fd->packedmap, pf->data, pf->data, 0);
1449 }
1450
1451 void blo_make_packed_pointer_map(FileData *fd, Main *oldmain)
1452 {
1453         Image *ima;
1454         VFont *vfont;
1455         bSound *sound;
1456         Library *lib;
1457         
1458         fd->packedmap = oldnewmap_new();
1459         
1460         for (ima = oldmain->image.first; ima; ima = ima->id.next)
1461                 if (ima->packedfile)
1462                         insert_packedmap(fd, ima->packedfile);
1463                         
1464         for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next)
1465                 if (vfont->packedfile)
1466                         insert_packedmap(fd, vfont->packedfile);
1467         
1468         for (sound = oldmain->sound.first; sound; sound = sound->id.next)
1469                 if (sound->packedfile)
1470                         insert_packedmap(fd, sound->packedfile);
1471         
1472         for (lib = oldmain->library.first; lib; lib = lib->id.next)
1473                 if (lib->packedfile)
1474                         insert_packedmap(fd, lib->packedfile);
1475
1476 }
1477
1478 /* set old main packed data to zero if it has been restored */
1479 /* this works because freeing old main only happens after this call */
1480 void blo_end_packed_pointer_map(FileData *fd, Main *oldmain)
1481 {
1482         Image *ima;
1483         VFont *vfont;
1484         bSound *sound;
1485         Library *lib;
1486         OldNew *entry = fd->packedmap->entries;
1487         int i;
1488         
1489         /* used entries were restored, so we put them to zero */
1490         for (i=0; i < fd->packedmap->nentries; i++, entry++) {
1491                 if (entry->nr > 0)
1492                         entry->newp = NULL;
1493         }
1494         
1495         for (ima = oldmain->image.first; ima; ima = ima->id.next)
1496                 ima->packedfile = newpackedadr(fd, ima->packedfile);
1497         
1498         for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next)
1499                 vfont->packedfile = newpackedadr(fd, vfont->packedfile);
1500
1501         for (sound = oldmain->sound.first; sound; sound = sound->id.next)
1502                 sound->packedfile = newpackedadr(fd, sound->packedfile);
1503                 
1504         for (lib = oldmain->library.first; lib; lib = lib->id.next)
1505                 lib->packedfile = newpackedadr(fd, lib->packedfile);
1506 }
1507
1508
1509 /* undo file support: add all library pointers in lookup */
1510 void blo_add_library_pointer_map(ListBase *mainlist, FileData *fd)
1511 {
1512         Main *ptr = mainlist->first;
1513         ListBase *lbarray[MAX_LIBARRAY];
1514         
1515         for (ptr = ptr->next; ptr; ptr = ptr->next) {
1516                 int i = set_listbasepointers(ptr, lbarray);
1517                 while (i--) {
1518                         ID *id;
1519                         for (id = lbarray[i]->first; id; id = id->next)
1520                                 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
1521                 }
1522         }
1523 }
1524
1525
1526 /* ********** END OLD POINTERS ****************** */
1527 /* ********** READ FILE ****************** */
1528
1529 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
1530 {
1531         int blocksize, nblocks;
1532         char *data;
1533         
1534         data = (char *)(bhead+1);
1535         blocksize = filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
1536         
1537         nblocks = bhead->nr;
1538         while (nblocks--) {
1539                 DNA_struct_switch_endian(filesdna, bhead->SDNAnr, data);
1540                 
1541                 data += blocksize;
1542         }
1543 }
1544
1545 static void *read_struct(FileData *fd, BHead *bh, const char *blockname)
1546 {
1547         void *temp = NULL;
1548         
1549         if (bh->len) {
1550                 /* switch is based on file dna */
1551                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1552                         switch_endian_structs(fd->filesdna, bh);
1553                 
1554                 if (fd->compflags[bh->SDNAnr]) {        /* flag==0: doesn't exist anymore */
1555                         if (fd->compflags[bh->SDNAnr] == 2) {
1556                                 temp = DNA_struct_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
1557                         }
1558                         else {
1559                                 temp = MEM_mallocN(bh->len, blockname);
1560                                 memcpy(temp, (bh+1), bh->len);
1561                         }
1562                 }
1563         }
1564
1565         return temp;
1566 }
1567
1568 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
1569 {
1570         Link *ln, *prev;
1571         
1572         if (lb->first == NULL) return;
1573         
1574         lb->first = newdataadr(fd, lb->first);
1575         ln = lb->first;
1576         prev = NULL;
1577         while (ln) {
1578                 ln->next = newdataadr(fd, ln->next);
1579                 ln->prev = prev;
1580                 prev = ln;
1581                 ln = ln->next;
1582         }
1583         lb->last = prev;
1584 }
1585
1586 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
1587 {
1588         Link *ln, *prev;
1589         void *poin;
1590
1591         if (lb->first == NULL) return;
1592         poin = newdataadr(fd, lb->first);
1593         if (lb->first) {
1594                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1595         }
1596         lb->first = poin;
1597         
1598         ln = lb->first;
1599         prev = NULL;
1600         while (ln) {
1601                 poin = newdataadr(fd, ln->next);
1602                 if (ln->next) {
1603                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1604                 }
1605                 ln->next = poin;
1606                 ln->prev = prev;
1607                 prev = ln;
1608                 ln = ln->next;
1609         }
1610         lb->last = prev;
1611 }
1612
1613 static void test_pointer_array(FileData *fd, void **mat)
1614 {
1615         int64_t *lpoin, *lmat;
1616         int *ipoin, *imat;
1617         size_t len;
1618
1619                 /* manually convert the pointer array in
1620                  * the old dna format to a pointer array in
1621                  * the new dna format.
1622                  */
1623         if (*mat) {
1624                 len = MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1625                         
1626                 if (fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1627                         ipoin=imat= MEM_mallocN(len * 4, "newmatar");
1628                         lpoin= *mat;
1629                         
1630                         while (len-- > 0) {
1631                                 if ((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1632                                         BLI_endian_switch_int64(lpoin);
1633                                 *ipoin = (int)((*lpoin) >> 3);
1634                                 ipoin++;
1635                                 lpoin++;
1636                         }
1637                         MEM_freeN(*mat);
1638                         *mat = imat;
1639                 }
1640                 
1641                 if (fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1642                         lpoin = lmat = MEM_mallocN(len * 8, "newmatar");
1643                         ipoin = *mat;
1644                         
1645                         while (len-- > 0) {
1646                                 *lpoin = *ipoin;
1647                                 ipoin++;
1648                                 lpoin++;
1649                         }
1650                         MEM_freeN(*mat);
1651                         *mat= lmat;
1652                 }
1653         }
1654 }
1655
1656 /* ************ READ ID Properties *************** */
1657
1658 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1659 static void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1660
1661 static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData *fd)
1662 {
1663         IDProperty *array;
1664         int i;
1665         
1666         /* since we didn't save the extra buffer, set totallen to len */
1667         prop->totallen = prop->len;
1668         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1669
1670         array = (IDProperty *)prop->data.pointer;
1671         
1672         /* note!, idp-arrays didn't exist in 2.4x, so the pointer will be cleared
1673          * theres not really anything we can do to correct this, at least don't crash */
1674         if (array == NULL) {
1675                 prop->len = 0;
1676                 prop->totallen = 0;
1677         }
1678         
1679         
1680         for (i = 0; i < prop->len; i++)
1681                 IDP_DirectLinkProperty(&array[i], switch_endian, fd);
1682 }
1683
1684 static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *fd)
1685 {
1686         IDProperty **array;
1687         int i;
1688         
1689         /* since we didn't save the extra buffer, set totallen to len */
1690         prop->totallen = prop->len;
1691         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1692         
1693         if (prop->subtype == IDP_GROUP) {
1694                 test_pointer_array(fd, prop->data.pointer);
1695                 array = prop->data.pointer;
1696                 
1697                 for (i = 0; i < prop->len; i++)
1698                         IDP_DirectLinkProperty(array[i], switch_endian, fd);
1699         }
1700         else if (prop->subtype == IDP_DOUBLE) {
1701                 if (switch_endian) {
1702                         BLI_endian_switch_double_array(prop->data.pointer, prop->len);
1703                 }
1704         }
1705         else {
1706                 if (switch_endian) {
1707                         /* also used for floats */
1708                         BLI_endian_switch_int32_array(prop->data.pointer, prop->len);
1709                 }
1710         }
1711 }
1712
1713 static void IDP_DirectLinkString(IDProperty *prop, FileData *fd)
1714 {
1715         /*since we didn't save the extra string buffer, set totallen to len.*/
1716         prop->totallen = prop->len;
1717         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1718 }
1719
1720 static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, FileData *fd)
1721 {
1722         ListBase *lb = &prop->data.group;
1723         IDProperty *loop;
1724         
1725         link_list(fd, lb);
1726         
1727         /*Link child id properties now*/
1728         for (loop=prop->data.group.first; loop; loop=loop->next) {
1729                 IDP_DirectLinkProperty(loop, switch_endian, fd);
1730         }
1731 }
1732
1733 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd)
1734 {
1735         switch (prop->type) {
1736                 case IDP_GROUP:
1737                         IDP_DirectLinkGroup(prop, switch_endian, fd);
1738                         break;
1739                 case IDP_STRING:
1740                         IDP_DirectLinkString(prop, fd);
1741                         break;
1742                 case IDP_ARRAY:
1743                         IDP_DirectLinkArray(prop, switch_endian, fd);
1744                         break;
1745                 case IDP_IDPARRAY:
1746                         IDP_DirectLinkIDPArray(prop, switch_endian, fd);
1747                         break;
1748                 case IDP_DOUBLE:
1749                         /* erg, stupid doubles.  since I'm storing them
1750                          * in the same field as int val; val2 in the
1751                          * IDPropertyData struct, they have to deal with
1752                          * endianness specifically
1753                          *
1754                          * in theory, val and val2 would've already been swapped
1755                          * if switch_endian is true, so we have to first unswap
1756                          * them then reswap them as a single 64-bit entity.
1757                          */
1758                         
1759                         if (switch_endian) {
1760                                 BLI_endian_switch_int32(&prop->data.val);
1761                                 BLI_endian_switch_int32(&prop->data.val2);
1762                                 BLI_endian_switch_int64((int64_t *)&prop->data.val);
1763                         }
1764                         
1765                         break;
1766         }
1767 }
1768
1769 /* stub function */
1770 static void IDP_LibLinkProperty(IDProperty *UNUSED(prop), int UNUSED(switch_endian), FileData *UNUSED(fd))
1771 {
1772 }
1773
1774 /* ************ READ ID *************** */
1775
1776 static void direct_link_id(FileData *fd, ID *id)
1777 {
1778         /*link direct data of ID properties*/
1779         if (id->properties) {
1780                 id->properties = newdataadr(fd, id->properties);
1781                 if (id->properties) { /* this case means the data was written incorrectly, it should not happen */
1782                         IDP_DirectLinkProperty(id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1783                 }
1784         }
1785 }
1786
1787 /* ************ READ CurveMapping *************** */
1788
1789 /* cuma itself has been read! */
1790 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
1791 {
1792         int a;
1793         
1794         /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
1795         cumap->flag &= ~CUMA_PREMULLED;
1796         
1797         for (a = 0; a < CM_TOT; a++) {
1798                 cumap->cm[a].curve = newdataadr(fd, cumap->cm[a].curve);
1799                 cumap->cm[a].table = NULL;
1800                 cumap->cm[a].premultable = NULL;
1801         }
1802 }
1803
1804 /* ************ READ Brush *************** */
1805 /* library brush linking after fileread */
1806 static void lib_link_brush(FileData *fd, Main *main)
1807 {
1808         Brush *brush;
1809         
1810         /* only link ID pointers */
1811         for (brush = main->brush.first; brush; brush = brush->id.next) {
1812                 if (brush->id.flag & LIB_NEED_LINK) {
1813                         brush->id.flag -= LIB_NEED_LINK;
1814                         
1815                         brush->mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mtex.tex);
1816                         brush->clone.image = newlibadr_us(fd, brush->id.lib, brush->clone.image);
1817                 }
1818         }
1819 }
1820
1821 static void direct_link_brush(FileData *fd, Brush *brush)
1822 {
1823         /* brush itself has been read */
1824
1825         /* fallof curve */
1826         brush->curve = newdataadr(fd, brush->curve);
1827         if (brush->curve)
1828                 direct_link_curvemapping(fd, brush->curve);
1829         else
1830                 BKE_brush_curve_preset(brush, CURVE_PRESET_SHARP);
1831
1832         brush->preview = NULL;
1833         brush->icon_imbuf = NULL;
1834 }
1835
1836 static void direct_link_script(FileData *UNUSED(fd), Script *script)
1837 {
1838         script->id.us = 1;
1839         SCRIPT_SET_NULL(script);
1840 }
1841
1842
1843 /* ************ READ PACKEDFILE *************** */
1844
1845 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
1846 {
1847         PackedFile *pf = newpackedadr(fd, oldpf);
1848         
1849         if (pf) {
1850                 pf->data = newpackedadr(fd, pf->data);
1851         }
1852         
1853         return pf;
1854 }
1855
1856 /* ************ READ IMAGE PREVIEW *************** */
1857
1858 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
1859 {
1860         PreviewImage *prv = newdataadr(fd, old_prv);
1861         
1862         if (prv) {
1863                 int i;
1864                 for (i = 0; i < NUM_ICON_SIZES; ++i) {
1865                         if (prv->rect[i]) {
1866                                 prv->rect[i] = newdataadr(fd, prv->rect[i]);
1867                         }
1868                 }
1869         }
1870         
1871         return prv;
1872 }
1873
1874 /* ************ READ ANIMATION STUFF ***************** */
1875
1876 /* Legacy Data Support (for Version Patching) ----------------------------- */
1877
1878 // XXX deprecated - old animation system
1879 static void lib_link_ipo(FileData *fd, Main *main)
1880 {
1881         Ipo *ipo;
1882         
1883         for (ipo = main->ipo.first; ipo; ipo = ipo->id.next) {
1884                 if (ipo->id.flag & LIB_NEED_LINK) {
1885                         IpoCurve *icu;
1886                         for (icu = ipo->curve.first; icu; icu = icu->next) {
1887                                 if (icu->driver)
1888                                         icu->driver->ob = newlibadr(fd, ipo->id.lib, icu->driver->ob);
1889                         }
1890                         ipo->id.flag -= LIB_NEED_LINK;
1891                 }
1892         }
1893 }
1894
1895 // XXX deprecated - old animation system
1896 static void direct_link_ipo(FileData *fd, Ipo *ipo)
1897 {
1898         IpoCurve *icu;
1899
1900         link_list(fd, &(ipo->curve));
1901         
1902         for (icu = ipo->curve.first; icu; icu = icu->next) {
1903                 icu->bezt = newdataadr(fd, icu->bezt);
1904                 icu->bp = newdataadr(fd, icu->bp);
1905                 icu->driver = newdataadr(fd, icu->driver);
1906         }
1907 }
1908
1909 // XXX deprecated - old animation system
1910 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1911 {
1912         bActionStrip *strip;
1913         bActionModifier *amod;
1914         
1915         for (strip=striplist->first; strip; strip=strip->next) {
1916                 strip->object = newlibadr(fd, id->lib, strip->object);
1917                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1918                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1919                 for (amod = strip->modifiers.first; amod; amod = amod->next)
1920                         amod->ob = newlibadr(fd, id->lib, amod->ob);
1921         }
1922 }
1923
1924 // XXX deprecated - old animation system
1925 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
1926 {
1927         bActionStrip *strip;
1928         
1929         link_list(fd, strips);
1930         
1931         for (strip = strips->first; strip; strip = strip->next)
1932                 link_list(fd, &strip->modifiers);
1933 }
1934
1935 // XXX deprecated - old animation system
1936 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1937 {
1938         bConstraintChannel *chan;
1939
1940         for (chan=chanbase->first; chan; chan=chan->next) {
1941                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1942         }
1943 }
1944
1945 /* Data Linking ----------------------------- */
1946
1947 static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list)
1948 {
1949         FModifier *fcm;
1950         
1951         for (fcm = list->first; fcm; fcm = fcm->next) {
1952                 /* data for specific modifiers */
1953                 switch (fcm->type) {
1954                         case FMODIFIER_TYPE_PYTHON:
1955                         {
1956                                 FMod_Python *data = (FMod_Python *)fcm->data;
1957                                 data->script = newlibadr(fd, id->lib, data->script);
1958                         }
1959                                 break;
1960                 }
1961         }
1962 }
1963
1964 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) 
1965 {
1966         FCurve *fcu;
1967         
1968         if (list == NULL)
1969                 return;
1970         
1971         /* relink ID-block references... */
1972         for (fcu = list->first; fcu; fcu = fcu->next) {
1973                 /* driver data */
1974                 if (fcu->driver) {
1975                         ChannelDriver *driver = fcu->driver;
1976                         DriverVar *dvar;
1977                         
1978                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
1979                                 DRIVER_TARGETS_LOOPER(dvar)
1980                                 {
1981                                         /* only relink if still used */
1982                                         if (tarIndex < dvar->num_targets)
1983                                                 dtar->id = newlibadr(fd, id->lib, dtar->id); 
1984                                         else
1985                                                 dtar->id = NULL;
1986                                 }
1987                                 DRIVER_TARGETS_LOOPER_END
1988                         }
1989                 }
1990                 
1991                 /* modifiers */
1992                 lib_link_fmodifiers(fd, id, &fcu->modifiers);
1993         }
1994 }
1995
1996
1997 /* NOTE: this assumes that link_list has already been called on the list */
1998 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
1999 {
2000         FModifier *fcm;
2001         
2002         for (fcm = list->first; fcm; fcm = fcm->next) {
2003                 /* relink general data */
2004                 fcm->data  = newdataadr(fd, fcm->data);
2005                 fcm->edata = NULL;
2006                 
2007                 /* do relinking of data for specific types */
2008                 switch (fcm->type) {
2009                         case FMODIFIER_TYPE_GENERATOR:
2010                         {
2011                                 FMod_Generator *data = (FMod_Generator *)fcm->data;
2012                                 
2013                                 data->coefficients = newdataadr(fd, data->coefficients);
2014                                 
2015                                 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2016                                         BLI_endian_switch_float_array(data->coefficients, data->arraysize);
2017                                 }
2018                         }
2019                                 break;
2020                         case FMODIFIER_TYPE_ENVELOPE:
2021                         {
2022                                 FMod_Envelope *data=  (FMod_Envelope *)fcm->data;
2023                                 
2024                                 data->data= newdataadr(fd, data->data);
2025                         }
2026                                 break;
2027                         case FMODIFIER_TYPE_PYTHON:
2028                         {
2029                                 FMod_Python *data = (FMod_Python *)fcm->data;
2030                                 
2031                                 data->prop = newdataadr(fd, data->prop);
2032                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2033                         }
2034                                 break;
2035                 }
2036         }
2037 }
2038
2039 /* NOTE: this assumes that link_list has already been called on the list */
2040 static void direct_link_fcurves(FileData *fd, ListBase *list)
2041 {
2042         FCurve *fcu;
2043         
2044         /* link F-Curve data to F-Curve again (non ID-libs) */
2045         for (fcu = list->first; fcu; fcu = fcu->next) {
2046                 /* curve data */
2047                 fcu->bezt = newdataadr(fd, fcu->bezt);
2048                 fcu->fpt = newdataadr(fd, fcu->fpt);
2049                 
2050                 /* rna path */
2051                 fcu->rna_path = newdataadr(fd, fcu->rna_path);
2052                 
2053                 /* group */
2054                 fcu->grp = newdataadr(fd, fcu->grp);
2055                 
2056                 /* clear disabled flag - allows disabled drivers to be tried again ([#32155]),
2057                  * but also means that another method for "reviving disabled F-Curves" exists
2058                  */
2059                 fcu->flag &= ~FCURVE_DISABLED;
2060                 
2061                 /* driver */
2062                 fcu->driver= newdataadr(fd, fcu->driver);
2063                 if (fcu->driver) {
2064                         ChannelDriver *driver= fcu->driver;
2065                         DriverVar *dvar;
2066                         
2067                         /* compiled expression data will need to be regenerated (old pointer may still be set here) */
2068                         driver->expr_comp = NULL;
2069                         
2070                         /* give the driver a fresh chance - the operating environment may be different now 
2071                          * (addons, etc. may be different) so the driver namespace may be sane now [#32155]
2072                          */
2073                         driver->flag &= ~DRIVER_FLAG_INVALID;
2074                         
2075                         /* relink variables, targets and their paths */
2076                         link_list(fd, &driver->variables);
2077                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
2078                                 DRIVER_TARGETS_LOOPER(dvar)
2079                                 {
2080                                         /* only relink the targets being used */
2081                                         if (tarIndex < dvar->num_targets)
2082                                                 dtar->rna_path = newdataadr(fd, dtar->rna_path);
2083                                         else
2084                                                 dtar->rna_path = NULL;
2085                                 }
2086                                 DRIVER_TARGETS_LOOPER_END
2087                         }
2088                 }
2089                 
2090                 /* modifiers */
2091                 link_list(fd, &fcu->modifiers);
2092                 direct_link_fmodifiers(fd, &fcu->modifiers);
2093         }
2094 }
2095
2096
2097 static void lib_link_action(FileData *fd, Main *main)
2098 {
2099         bAction *act;
2100         bActionChannel *chan;
2101
2102         for (act = main->action.first; act; act = act->id.next) {
2103                 if (act->id.flag & LIB_NEED_LINK) {
2104                         act->id.flag -= LIB_NEED_LINK;
2105                         
2106 // XXX deprecated - old animation system <<<
2107                         for (chan=act->chanbase.first; chan; chan=chan->next) {
2108                                 chan->ipo = newlibadr_us(fd, act->id.lib, chan->ipo);
2109                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
2110                         }
2111 // >>> XXX deprecated - old animation system
2112                         
2113                         lib_link_fcurves(fd, &act->id, &act->curves);
2114                 }
2115         }
2116 }
2117
2118 static void direct_link_action(FileData *fd, bAction *act)
2119 {
2120         bActionChannel *achan; // XXX deprecated - old animation system
2121         bActionGroup *agrp;
2122
2123         link_list(fd, &act->curves);
2124         link_list(fd, &act->chanbase); // XXX deprecated - old animation system
2125         link_list(fd, &act->groups);
2126         link_list(fd, &act->markers);
2127
2128 // XXX deprecated - old animation system <<<
2129         for (achan = act->chanbase.first; achan; achan=achan->next) {
2130                 achan->grp = newdataadr(fd, achan->grp);
2131                 
2132                 link_list(fd, &achan->constraintChannels);
2133         }
2134 // >>> XXX deprecated - old animation system
2135
2136         direct_link_fcurves(fd, &act->curves);
2137         
2138         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
2139                 agrp->channels.first= newdataadr(fd, agrp->channels.first);
2140                 agrp->channels.last= newdataadr(fd, agrp->channels.last);
2141         }
2142 }
2143
2144 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
2145 {
2146         NlaStrip *strip;
2147         
2148         for (strip = list->first; strip; strip = strip->next) {
2149                 /* check strip's children */
2150                 lib_link_nladata_strips(fd, id, &strip->strips);
2151                 
2152                 /* check strip's F-Curves */
2153                 lib_link_fcurves(fd, id, &strip->fcurves);
2154                 
2155                 /* reassign the counted-reference to action */
2156                 strip->act = newlibadr_us(fd, id->lib, strip->act);
2157                 
2158                 /* fix action id-root (i.e. if it comes from a pre 2.57 .blend file) */
2159                 if ((strip->act) && (strip->act->idroot == 0))
2160                         strip->act->idroot = GS(id->name);
2161         }
2162 }
2163
2164 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
2165 {
2166         NlaTrack *nlt;
2167         
2168         /* we only care about the NLA strips inside the tracks */
2169         for (nlt = list->first; nlt; nlt = nlt->next) {
2170                 lib_link_nladata_strips(fd, id, &nlt->strips);
2171         }
2172 }
2173
2174 /* This handles Animato NLA-Strips linking 
2175  * NOTE: this assumes that link_list has already been called on the list 
2176  */
2177 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
2178 {
2179         NlaStrip *strip;
2180         
2181         for (strip = list->first; strip; strip = strip->next) {
2182                 /* strip's child strips */
2183                 link_list(fd, &strip->strips);
2184                 direct_link_nladata_strips(fd, &strip->strips);
2185                 
2186                 /* strip's F-Curves */
2187                 link_list(fd, &strip->fcurves);
2188                 direct_link_fcurves(fd, &strip->fcurves);
2189                 
2190                 /* strip's F-Modifiers */
2191                 link_list(fd, &strip->modifiers);
2192                 direct_link_fmodifiers(fd, &strip->modifiers);
2193         }
2194 }
2195
2196 /* NOTE: this assumes that link_list has already been called on the list */
2197 static void direct_link_nladata(FileData *fd, ListBase *list)
2198 {
2199         NlaTrack *nlt;
2200         
2201         for (nlt = list->first; nlt; nlt = nlt->next) {
2202                 /* relink list of strips */
2203                 link_list(fd, &nlt->strips);
2204                 
2205                 /* relink strip data */
2206                 direct_link_nladata_strips(fd, &nlt->strips);
2207         }
2208 }
2209
2210 /* ------- */
2211
2212 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
2213 {
2214         KeyingSet *ks;
2215         KS_Path *ksp;
2216         
2217         /* here, we're only interested in the ID pointer stored in some of the paths */
2218         for (ks = list->first; ks; ks = ks->next) {
2219                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2220                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
2221                 }
2222         }
2223 }
2224
2225 /* NOTE: this assumes that link_list has already been called on the list */
2226 static void direct_link_keyingsets(FileData *fd, ListBase *list)
2227 {
2228         KeyingSet *ks;
2229         KS_Path *ksp;
2230         
2231         /* link KeyingSet data to KeyingSet again (non ID-libs) */
2232         for (ks = list->first; ks; ks = ks->next) {
2233                 /* paths */
2234                 link_list(fd, &ks->paths);
2235                 
2236                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2237                         /* rna path */
2238                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
2239                 }
2240         }
2241 }
2242
2243 /* ------- */
2244
2245 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
2246 {
2247         if (adt == NULL)
2248                 return;
2249         
2250         /* link action data */
2251         adt->action= newlibadr_us(fd, id->lib, adt->action);
2252         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
2253         
2254         /* fix action id-roots (i.e. if they come from a pre 2.57 .blend file) */
2255         if ((adt->action) && (adt->action->idroot == 0))
2256                 adt->action->idroot = GS(id->name);
2257         if ((adt->tmpact) && (adt->tmpact->idroot == 0))
2258                 adt->tmpact->idroot = GS(id->name);
2259         
2260         /* link drivers */
2261         lib_link_fcurves(fd, id, &adt->drivers);
2262         
2263         /* overrides don't have lib-link for now, so no need to do anything */
2264         
2265         /* link NLA-data */
2266         lib_link_nladata(fd, id, &adt->nla_tracks);
2267 }
2268
2269 static void direct_link_animdata(FileData *fd, AnimData *adt)
2270 {
2271         /* NOTE: must have called newdataadr already before doing this... */
2272         if (adt == NULL)
2273                 return;
2274         
2275         /* link drivers */
2276         link_list(fd, &adt->drivers);
2277         direct_link_fcurves(fd, &adt->drivers);
2278         
2279         /* link overrides */
2280         // TODO...
2281         
2282         /* link NLA-data */
2283         link_list(fd, &adt->nla_tracks);
2284         direct_link_nladata(fd, &adt->nla_tracks);
2285         
2286         /* relink active strip - even though strictly speaking this should only be used
2287          * if we're in 'tweaking mode', we need to be able to have this loaded back for
2288          * undo, but also since users may not exit tweakmode before saving (#24535)
2289          */
2290         // TODO: it's not really nice that anyone should be able to save the file in this
2291         //              state, but it's going to be too hard to enforce this single case...
2292         adt->actstrip = newdataadr(fd, adt->actstrip);
2293 }       
2294
2295 /* ************ READ MOTION PATHS *************** */
2296
2297 /* direct data for cache */
2298 static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
2299 {
2300         /* sanity check */
2301         if (mpath == NULL)
2302                 return;
2303         
2304         /* relink points cache */
2305         mpath->points = newdataadr(fd, mpath->points);
2306 }
2307
2308 /* ************ READ NODE TREE *************** */
2309
2310 /* singe node tree (also used for material/scene trees), ntree is not NULL */
2311 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
2312 {
2313         bNode *node;
2314         
2315         if (ntree->adt) lib_link_animdata(fd, &ntree->id, ntree->adt);
2316         
2317         ntree->gpd = newlibadr_us(fd, id->lib, ntree->gpd);
2318         
2319         for (node = ntree->nodes.first; node; node = node->next)
2320                 node->id = newlibadr_us(fd, id->lib, node->id);
2321 }
2322
2323 /* library ntree linking after fileread */
2324 static void lib_link_nodetree(FileData *fd, Main *main)
2325 {
2326         bNodeTree *ntree;
2327         
2328         /* only link ID pointers */
2329         for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2330                 if (ntree->id.flag & LIB_NEED_LINK) {
2331                         ntree->id.flag -= LIB_NEED_LINK;
2332                         lib_link_ntree(fd, &ntree->id, ntree);
2333                 }
2334         }
2335 }
2336
2337 static void do_versions_socket_default_value(bNodeSocket *sock)
2338 {
2339         bNodeSocketValueFloat *valfloat;
2340         bNodeSocketValueVector *valvector;
2341         bNodeSocketValueRGBA *valrgba;
2342         
2343         if (sock->default_value)
2344                 return;
2345         
2346         switch (sock->type) {
2347                 case SOCK_FLOAT:
2348                         valfloat = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueFloat), "default socket value");
2349                         valfloat->value = sock->ns.vec[0];
2350                         valfloat->min = sock->ns.min;
2351                         valfloat->max = sock->ns.max;
2352                         valfloat->subtype = PROP_NONE;
2353                         break;
2354                 case SOCK_VECTOR:
2355                         valvector = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueVector), "default socket value");
2356                         copy_v3_v3(valvector->value, sock->ns.vec);
2357                         valvector->min = sock->ns.min;
2358                         valvector->max = sock->ns.max;
2359                         valvector->subtype = PROP_NONE;
2360                         break;
2361                 case SOCK_RGBA:
2362                         valrgba = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueRGBA), "default socket value");
2363                         copy_v4_v4(valrgba->value, sock->ns.vec);
2364                         break;
2365         }
2366 }
2367
2368 void blo_do_versions_nodetree_default_value(bNodeTree *ntree)
2369 {
2370         bNode *node;
2371         bNodeSocket *sock;
2372         for (node=ntree->nodes.first; node; node=node->next) {
2373                 for (sock=node->inputs.first; sock; sock=sock->next)
2374                         do_versions_socket_default_value(sock);
2375                 for (sock=node->outputs.first; sock; sock=sock->next)
2376                         do_versions_socket_default_value(sock);
2377         }
2378         for (sock=ntree->inputs.first; sock; sock=sock->next)
2379                 do_versions_socket_default_value(sock);
2380         for (sock=ntree->outputs.first; sock; sock=sock->next)
2381                 do_versions_socket_default_value(sock);
2382 }
2383
2384 static void lib_nodetree_init_types_cb(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
2385 {
2386         bNode *node;
2387         
2388         ntreeInitTypes(ntree);
2389         
2390         /* need to do this here instead of in do_versions, otherwise next function can crash */
2391         blo_do_versions_nodetree_default_value(ntree);
2392         
2393         /* XXX could be replaced by do_versions for new nodes */
2394         for (node=ntree->nodes.first; node; node=node->next)
2395                 node_verify_socket_templates(ntree, node);
2396 }
2397
2398 /* updates group node socket own_index so that
2399  * external links to/from the group node are preserved.
2400  */
2401 static void lib_node_do_versions_group_indices(bNode *gnode)
2402 {
2403         bNodeTree *ngroup = (bNodeTree*)gnode->id;
2404         bNode *intnode;
2405         bNodeSocket *sock, *gsock, *intsock;
2406         int found;
2407         
2408         for (sock=gnode->outputs.first; sock; sock=sock->next) {
2409                 int old_index = sock->to_index;
2410                 for (gsock=ngroup->outputs.first; gsock; gsock=gsock->next) {
2411                         if (gsock->link && gsock->link->fromsock->own_index == old_index) {
2412                                 sock->own_index = gsock->own_index;
2413                                 break;
2414                         }
2415                 }
2416         }
2417         for (sock=gnode->inputs.first; sock; sock=sock->next) {
2418                 int old_index = sock->to_index;
2419                 /* can't use break in double loop */
2420                 found = 0;
2421                 for (intnode=ngroup->nodes.first; intnode && !found; intnode=intnode->next) {
2422                         for (intsock=intnode->inputs.first; intsock; intsock=intsock->next) {
2423                                 if (intsock->own_index == old_index && intsock->link) {
2424                                         sock->own_index = intsock->link->fromsock->own_index;
2425                                         found = 1;
2426                                         break;
2427                                 }
2428                         }
2429                 }
2430         }
2431 }
2432
2433 /* updates external links for all group nodes in a tree */
2434 static void lib_nodetree_do_versions_group_indices_cb(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
2435 {
2436         bNode *node;
2437         
2438         for (node = ntree->nodes.first; node; node = node->next) {
2439                 if (node->type == NODE_GROUP) {
2440                         bNodeTree *ngroup = (bNodeTree*)node->id;
2441                         if (ngroup && (ngroup->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE))
2442                                 lib_node_do_versions_group_indices(node);
2443                 }
2444         }
2445 }
2446
2447 /* make an update call for the tree */
2448 static void lib_nodetree_do_versions_update_cb(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
2449 {
2450         if (ntree->update)
2451                 ntreeUpdateTree(ntree);
2452 }
2453
2454 /* verify types for nodes and groups, all data has to be read */
2455 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
2456  * typedefs */
2457 static void lib_verify_nodetree(Main *main, int UNUSED(open))
2458 {
2459         bNodeTree *ntree;
2460         int i;
2461         bNodeTreeType *ntreetype;
2462         
2463         /* this crashes blender on undo/redo */
2464 #if 0
2465                 if (open == 1) {
2466                         reinit_nodesystem();
2467                 }
2468 #endif
2469         
2470         /* set node->typeinfo pointers */
2471         for (i = 0; i < NUM_NTREE_TYPES; ++i) {
2472                 ntreetype = ntreeGetType(i);
2473                 if (ntreetype && ntreetype->foreach_nodetree)
2474                         ntreetype->foreach_nodetree(main, NULL, lib_nodetree_init_types_cb);
2475         }
2476         for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next)
2477                 lib_nodetree_init_types_cb(NULL, NULL, ntree);
2478         
2479         {
2480                 int has_old_groups = 0;
2481                 /* XXX this should actually be part of do_versions, but since we need
2482                  * finished library linking, it is not possible there. Instead in do_versions
2483                  * we have set the NTREE_DO_VERSIONS flag, so at this point we can do the
2484                  * actual group node updates.
2485                  */
2486                 for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2487                         if (ntree->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE) {
2488                                 /* this adds copies and links from all unlinked internal sockets to group inputs/outputs. */
2489                                 node_group_expose_all_sockets(ntree);
2490                                 has_old_groups = 1;
2491                         }
2492                 }
2493                 
2494                 if (has_old_groups) {
2495                         for (i = 0; i < NUM_NTREE_TYPES; ++i) {
2496                                 ntreetype = ntreeGetType(i);
2497                                 if (ntreetype && ntreetype->foreach_nodetree)
2498                                         ntreetype->foreach_nodetree(main, NULL, lib_nodetree_do_versions_group_indices_cb);
2499                         }
2500                 }
2501                 
2502                 for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next)
2503                         ntree->flag &= ~NTREE_DO_VERSIONS_GROUP_EXPOSE;
2504         }
2505                 
2506         /* verify all group user nodes */
2507         for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2508                 ntreeVerifyNodes(main, &ntree->id);
2509         }
2510         
2511         /* make update calls where necessary */
2512         {
2513                 for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next)
2514                         if (ntree->update)
2515                                 ntreeUpdateTree(ntree);
2516                 
2517                 for (i = 0; i < NUM_NTREE_TYPES; i++) {
2518                         ntreetype = ntreeGetType(i);
2519                         if (ntreetype && ntreetype->foreach_nodetree)
2520                                 ntreetype->foreach_nodetree(main, NULL, lib_nodetree_do_versions_update_cb);
2521                 }
2522         }
2523 }
2524
2525 static void direct_link_node_socket(FileData *fd, bNodeSocket *sock)
2526 {
2527         sock->link = newdataadr(fd, sock->link);
2528         sock->storage = newdataadr(fd, sock->storage);
2529         sock->default_value = newdataadr(fd, sock->default_value);
2530         sock->cache = NULL;
2531 }
2532
2533 /* ntree itself has been read! */
2534 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
2535 {
2536         /* note: writing and reading goes in sync, for speed */
2537         bNode *node;
2538         bNodeSocket *sock;
2539         bNodeLink *link;
2540         
2541         ntree->init = 0;                /* to set callbacks and force setting types */
2542         ntree->progress = NULL;
2543         ntree->execdata = NULL;
2544         
2545         ntree->adt = newdataadr(fd, ntree->adt);
2546         direct_link_animdata(fd, ntree->adt);
2547         
2548         ntree->id.flag &= ~(LIB_ID_RECALC|LIB_ID_RECALC_DATA);
2549
2550         link_list(fd, &ntree->nodes);
2551         for (node = ntree->nodes.first; node; node = node->next) {
2552                 node->typeinfo = NULL;
2553                 
2554                 link_list(fd, &node->inputs);
2555                 link_list(fd, &node->outputs);
2556                 
2557                 link_list(fd, &node->internal_links);
2558                 for (link = node->internal_links.first; link; link = link->next) {
2559                         link->fromnode = newdataadr(fd, link->fromnode);
2560                         link->fromsock = newdataadr(fd, link->fromsock);
2561                         link->tonode = newdataadr(fd, link->tonode);
2562                         link->tosock = newdataadr(fd, link->tosock);
2563                 }
2564                 
2565                 if (node->type == CMP_NODE_MOVIEDISTORTION) {
2566                         node->storage = newmclipadr(fd, node->storage);
2567                 }
2568                 else
2569                         node->storage = newdataadr(fd, node->storage);
2570                 
2571                 if (node->storage) {
2572                         /* could be handlerized at some point */
2573                         if (ntree->type==NTREE_SHADER) {
2574                                 if (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB) {
2575                                         direct_link_curvemapping(fd, node->storage);
2576                                 }
2577                                 else if (node->type==SH_NODE_SCRIPT) {
2578                                         NodeShaderScript *nss = (NodeShaderScript *) node->storage;
2579                                         nss->bytecode = newdataadr(fd, nss->bytecode);
2580                                         nss->prop = newdataadr(fd, nss->prop);
2581                                         if (nss->prop)
2582                                                 IDP_DirectLinkProperty(nss->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2583                                 }
2584                         }
2585                         else if (ntree->type==NTREE_COMPOSIT) {
2586                                 if (ELEM4(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
2587                                         direct_link_curvemapping(fd, node->storage);
2588                                 else if (ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
2589                                         ((ImageUser *)node->storage)->ok = 1;
2590                         }
2591                         else if ( ntree->type==NTREE_TEXTURE) {
2592                                 if (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME)
2593                                         direct_link_curvemapping(fd, node->storage);
2594                                 else if (node->type==TEX_NODE_IMAGE)
2595                                         ((ImageUser *)node->storage)->ok = 1;
2596                         }
2597                 }
2598         }
2599         link_list(fd, &ntree->links);
2600         
2601         /* external sockets */
2602         link_list(fd, &ntree->inputs);
2603         link_list(fd, &ntree->outputs);
2604         
2605         /* and we connect the rest */
2606         for (node = ntree->nodes.first; node; node = node->next) {
2607                 node->parent = newdataadr(fd, node->parent);
2608                 node->preview = newimaadr(fd, node->preview);
2609                 node->lasty = 0;
2610                 
2611                 for (sock = node->inputs.first; sock; sock = sock->next)
2612                         direct_link_node_socket(fd, sock);
2613                 for (sock = node->outputs.first; sock; sock = sock->next)
2614                         direct_link_node_socket(fd, sock);
2615         }
2616         for (sock = ntree->inputs.first; sock; sock = sock->next)
2617                 direct_link_node_socket(fd, sock);
2618         for (sock = ntree->outputs.first; sock; sock = sock->next)
2619                 direct_link_node_socket(fd, sock);
2620         
2621         for (link = ntree->links.first; link; link= link->next) {
2622                 link->fromnode = newdataadr(fd, link->fromnode);
2623                 link->tonode = newdataadr(fd, link->tonode);
2624                 link->fromsock = newdataadr(fd, link->fromsock);
2625                 link->tosock = newdataadr(fd, link->tosock);
2626         }
2627         
2628         /* type verification is in lib-link */
2629 }
2630
2631 /* ************ READ ARMATURE ***************** */
2632
2633 /* temp struct used to transport needed info to lib_link_constraint_cb() */
2634 typedef struct tConstraintLinkData {
2635         FileData *fd;
2636         ID *id;
2637 } tConstraintLinkData;
2638 /* callback function used to relink constraint ID-links */
2639 static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, short isReference, void *userdata)
2640 {
2641         tConstraintLinkData *cld= (tConstraintLinkData *)userdata;
2642         
2643         /* for reference types, we need to increment the usercounts on load... */
2644         if (isReference) {
2645                 /* reference type - with usercount */
2646                 *idpoin = newlibadr_us(cld->fd, cld->id->lib, *idpoin);
2647         }
2648         else {
2649                 /* target type - no usercount needed */
2650                 *idpoin = newlibadr(cld->fd, cld->id->lib, *idpoin);
2651         }
2652 }
2653
2654 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
2655 {
2656         tConstraintLinkData cld;
2657         bConstraint *con;
2658         
2659         /* legacy fixes */
2660         for (con = conlist->first; con; con=con->next) {
2661                 /* patch for error introduced by changing constraints (dunno how) */
2662                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
2663                 if (con->data == NULL) {
2664                         con->type = CONSTRAINT_TYPE_NULL;
2665                 }
2666                 /* own ipo, all constraints have it */
2667                 con->ipo = newlibadr_us(fd, id->lib, con->ipo); // XXX deprecated - old animation system
2668         }
2669         
2670         /* relink all ID-blocks used by the constraints */
2671         cld.fd = fd;
2672         cld.id = id;
2673         
2674         BKE_id_loop_constraints(conlist, lib_link_constraint_cb, &cld);
2675 }
2676
2677 static void direct_link_constraints(FileData *fd, ListBase *lb)
2678 {
2679         bConstraint *con;
2680         
2681         link_list(fd, lb);
2682         for (con=lb->first; con; con=con->next) {
2683                 con->data = newdataadr(fd, con->data);
2684                 
2685                 switch (con->type) {
2686                         case CONSTRAINT_TYPE_PYTHON:
2687                         {
2688                                 bPythonConstraint *data= con->data;
2689                                 
2690                                 link_list(fd, &data->targets);
2691                                 
2692                                 data->prop = newdataadr(fd, data->prop);
2693                                 if (data->prop)
2694                                         IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2695                         }
2696                                 break;
2697                         case CONSTRAINT_TYPE_SPLINEIK:
2698                         {
2699                                 bSplineIKConstraint *data= con->data;
2700                                 
2701                                 data->points= newdataadr(fd, data->points);
2702                         }
2703                                 break;
2704                         case CONSTRAINT_TYPE_KINEMATIC:
2705                         {
2706                                 bKinematicConstraint *data = con->data;
2707
2708                                 con->lin_error = 0.f;
2709                                 con->rot_error = 0.f;
2710
2711                                 /* version patch for runtime flag, was not cleared in some case */
2712                                 data->flag &= ~CONSTRAINT_IK_AUTO;
2713                         }
2714                         case CONSTRAINT_TYPE_CHILDOF:
2715                         {
2716                                 /* XXX version patch, in older code this flag wasn't always set, and is inherent to type */
2717                                 if (con->ownspace == CONSTRAINT_SPACE_POSE)
2718                                         con->flag |= CONSTRAINT_SPACEONCE;
2719                         }
2720                                 break;
2721                 }
2722         }
2723 }
2724
2725 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
2726 {
2727         bPoseChannel *pchan;
2728         bArmature *arm = ob->data;
2729         int rebuild;
2730         
2731         if (!pose || !arm)
2732                 return;
2733         
2734         
2735         /* always rebuild to match proxy or lib changes */
2736         rebuild = ob->proxy || (ob->id.lib==NULL && arm->id.lib);
2737         
2738         if (ob->proxy) {
2739                 /* sync proxy layer */
2740                 if (pose->proxy_layer)
2741                         arm->layer = pose->proxy_layer;
2742                 
2743                 /* sync proxy active bone */
2744                 if (pose->proxy_act_bone[0]) {
2745                         Bone *bone = BKE_armature_find_bone_name(arm, pose->proxy_act_bone);
2746                         if (bone)
2747                                 arm->act_bone = bone;
2748                 }
2749         }
2750         
2751         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2752                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
2753                 
2754                 /* hurms... loop in a loop, but yah... later... (ton) */
2755                 pchan->bone = BKE_armature_find_bone_name(arm, pchan->name);
2756                 
2757                 pchan->custom = newlibadr_us(fd, arm->id.lib, pchan->custom);
2758                 if (pchan->bone == NULL)
2759                         rebuild= 1;
2760                 else if (ob->id.lib==NULL && arm->id.lib) {
2761                         /* local pose selection copied to armature, bit hackish */
2762                         pchan->bone->flag &= ~BONE_SELECTED;
2763                         pchan->bone->flag |= pchan->selectflag;
2764                 }
2765         }
2766         
2767         if (rebuild) {
2768                 ob->recalc = (OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
2769                 pose->flag |= POSE_RECALC;
2770         }
2771 }
2772
2773 static void lib_link_armature(FileData *fd, Main *main)
2774 {
2775         bArmature *arm;
2776         
2777         for (arm = main->armature.first; arm; arm = arm->id.next) {
2778                 if (arm->id.flag & LIB_NEED_LINK) {
2779                         if (arm->adt) lib_link_animdata(fd, &arm->id, arm->adt);
2780                         arm->id.flag -= LIB_NEED_LINK;
2781                 }
2782         }
2783 }
2784
2785 static void direct_link_bones(FileData *fd, Bone *bone)
2786 {
2787         Bone *child;
2788         
2789         bone->parent = newdataadr(fd, bone->parent);
2790         bone->prop = newdataadr(fd, bone->prop);
2791         if (bone->prop)
2792                 IDP_DirectLinkProperty(bone->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2793                 
2794         bone->flag &= ~BONE_DRAW_ACTIVE;
2795         
2796         link_list(fd, &bone->childbase);
2797         
2798         for (child=bone->childbase.first; child; child=child->next)
2799                 direct_link_bones(fd, child);
2800 }
2801
2802 static void direct_link_armature(FileData *fd, bArmature *arm)
2803 {
2804         Bone *bone;
2805         
2806         link_list(fd, &arm->bonebase);
2807         arm->edbo = NULL;
2808         arm->sketch = NULL;
2809         
2810         arm->adt = newdataadr(fd, arm->adt);
2811         direct_link_animdata(fd, arm->adt);
2812         
2813         for (bone = arm->bonebase.first; bone; bone = bone->next) {
2814                 direct_link_bones(fd, bone);
2815         }
2816         
2817         arm->act_bone = newdataadr(fd, arm->act_bone);
2818         arm->act_edbone = NULL;
2819 }
2820
2821 /* ************ READ CAMERA ***************** */
2822
2823 static void lib_link_camera(FileData *fd, Main *main)
2824 {
2825         Camera *ca;
2826         
2827         for (ca = main->camera.first; ca; ca = ca->id.next) {
2828                 if (ca->id.flag & LIB_NEED_LINK) {
2829                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
2830                         
2831                         ca->ipo = newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX deprecated - old animation system
2832                         
2833                         ca->dof_ob = newlibadr_us(fd, ca->id.lib, ca->dof_ob);
2834                         
2835                         ca->id.flag -= LIB_NEED_LINK;
2836                 }
2837         }
2838 }
2839
2840 static void direct_link_camera(FileData *fd, Camera *ca)
2841 {
2842         ca->adt = newdataadr(fd, ca->adt);
2843         direct_link_animdata(fd, ca->adt);
2844 }
2845
2846
2847 /* ************ READ LAMP ***************** */
2848
2849 static void lib_link_lamp(FileData *fd, Main *main)
2850 {
2851         Lamp *la;
2852         MTex *mtex;
2853         int a;
2854         
2855         for (la = main->lamp.first; la; la = la->id.next) {
2856                 if (la->id.flag & LIB_NEED_LINK) {
2857                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
2858                         
2859                         for (a = 0; a < MAX_MTEX; a++) {
2860                                 mtex = la->mtex[a];
2861                                 if (mtex) {
2862                                         mtex->tex = newlibadr_us(fd, la->id.lib, mtex->tex);
2863                                         mtex->object = newlibadr(fd, la->id.lib, mtex->object);
2864                                 }
2865                         }
2866                         
2867                         la->ipo = newlibadr_us(fd, la->id.lib, la->ipo); // XXX deprecated - old animation system
2868                         
2869                         if (la->nodetree)
2870                                 lib_link_ntree(fd, &la->id, la->nodetree);
2871                         
2872                         la->id.flag -= LIB_NEED_LINK;
2873                 }
2874         }
2875 }
2876
2877 static void direct_link_lamp(FileData *fd, Lamp *la)
2878 {
2879         int a;
2880         
2881         la->adt = newdataadr(fd, la->adt);
2882         direct_link_animdata(fd, la->adt);
2883         
2884         for (a=0; a<MAX_MTEX; a++) {
2885                 la->mtex[a] = newdataadr(fd, la->mtex[a]);
2886         }
2887         
2888         la->curfalloff = newdataadr(fd, la->curfalloff);
2889         if (la->curfalloff)
2890                 direct_link_curvemapping(fd, la->curfalloff);
2891
2892         la->nodetree= newdataadr(fd, la->nodetree);
2893         if (la->nodetree) {
2894                 direct_link_id(fd, &la->nodetree->id);
2895                 direct_link_nodetree(fd, la->nodetree);
2896         }
2897         
2898         la->preview = direct_link_preview_image(fd, la->preview);
2899 }
2900
2901 /* ************ READ keys ***************** */
2902
2903 static void do_versions_key_uidgen(Key *key)
2904 {
2905         KeyBlock *block;
2906
2907         key->uidgen = 1;
2908         for (block = key->block.first; block; block = block->next) {
2909                 block->uid = key->uidgen++;
2910         }
2911 }
2912
2913 static void lib_link_key(FileData *fd, Main *main)
2914 {
2915         Key *key;
2916         
2917         for (key = main->key.first; key; key = key->id.next) {
2918                 /*check if we need to generate unique ids for the shapekeys*/
2919                 if (!key->uidgen) {
2920                         do_versions_key_uidgen(key);
2921                 }
2922                 
2923                 if (key->id.flag & LIB_NEED_LINK) {
2924                         if (key->adt) lib_link_animdata(fd, &key->id, key->adt);
2925                         
2926                         key->ipo = newlibadr_us(fd, key->id.lib, key->ipo); // XXX deprecated - old animation system
2927                         key->from = newlibadr(fd, key->id.lib, key->from);
2928                         
2929                         key->id.flag -= LIB_NEED_LINK;
2930                 }
2931         }
2932 }
2933
2934 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
2935 {
2936         int elemsize, a, b;
2937         char *data, *poin, *cp;
2938         
2939         elemsize = key->elemsize;
2940         data = kb->data;
2941         
2942         for (a = 0; a < kb->totelem; a++) {
2943                 cp = key->elemstr;
2944                 poin = data;
2945                 
2946                 while (cp[0]) {  /* cp[0] == amount */
2947                         switch (cp[1]) {  /* cp[1] = type */
2948                                 case IPO_FLOAT:
2949                                 case IPO_BPOINT:
2950                                 case IPO_BEZTRIPLE:
2951                                         b = cp[0];
2952                                         BLI_endian_switch_float_array((float *)poin, b);
2953                                         poin += sizeof(float) * b;
2954                                         break;
2955                         }
2956                         
2957                         cp += 2;
2958                 }
2959                 data += elemsize;
2960         }
2961 }
2962
2963 static void direct_link_key(FileData *fd, Key *key)
2964 {
2965         KeyBlock *kb;
2966         
2967         link_list(fd, &(key->block));
2968         
2969         key->adt = newdataadr(fd, key->adt);
2970         direct_link_animdata(fd, key->adt);
2971                 
2972         key->refkey= newdataadr(fd, key->refkey);
2973         
2974         for (kb = key->block.first; kb; kb = kb->next) {
2975                 kb->data = newdataadr(fd, kb->data);
2976                 
2977                 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2978                         switch_endian_keyblock(key, kb);
2979         }
2980 }
2981
2982 /* ************ READ mball ***************** */
2983
2984 static void lib_link_mball(FileData *fd, Main *main)
2985 {
2986         MetaBall *mb;
2987         int a;
2988         
2989         for (mb = main->mball.first; mb; mb = mb->id.next) {
2990                 if (mb->id.flag & LIB_NEED_LINK) {
2991                         if (mb->adt) lib_link_animdata(fd, &mb->id, mb->adt);
2992                         
2993                         for (a = 0; a < mb->totcol; a++) 
2994                                 mb->mat[a] = newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2995                         
2996                         mb->ipo = newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX deprecated - old animation system
2997                         
2998                         mb->id.flag -= LIB_NEED_LINK;
2999                 }
3000         }
3001 }
3002
3003 static void direct_link_mball(FileData *fd, MetaBall *mb)
3004 {
3005         mb->adt = newdataadr(fd, mb->adt);
3006         direct_link_animdata(fd, mb->adt);
3007         
3008         mb->mat = newdataadr(fd, mb->mat);
3009         test_pointer_array(fd, (void **)&mb->mat);
3010         
3011         link_list(fd, &(mb->elems));
3012         
3013         mb->disp.first = mb->disp.last = NULL;
3014         mb->editelems = NULL;
3015         mb->bb = NULL;
3016 /*      mb->edit_elems.first= mb->edit_elems.last= NULL;*/
3017         mb->lastelem = NULL;
3018 }
3019
3020 /* ************ READ WORLD ***************** */
3021
3022 static void lib_link_world(FileData *fd, Main *main)
3023 {
3024         World *wrld;
3025         MTex *mtex;
3026         int a;
3027         
3028         for (wrld = main->world.first; wrld; wrld = wrld->id.next) {
3029                 if (wrld->id.flag & LIB_NEED_LINK) {
3030                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
3031                         
3032                         wrld->ipo = newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX deprecated - old animation system
3033                         
3034                         for (a=0; a < MAX_MTEX; a++) {
3035                                 mtex = wrld->mtex[a];
3036                                 if (mtex) {
3037                                         mtex->tex = newlibadr_us(fd, wrld->id.lib, mtex->tex);
3038                                         mtex->object = newlibadr(fd, wrld->id.lib, mtex->object);
3039                                 }
3040                         }
3041                         
3042                         if (wrld->nodetree)
3043                                 lib_link_ntree(fd, &wrld->id, wrld->nodetree);
3044                         
3045                         wrld->id.flag -= LIB_NEED_LINK;
3046                 }
3047         }
3048 }
3049
3050 static void direct_link_world(FileData *fd, World *wrld)
3051 {
3052         int a;
3053         
3054         wrld->adt = newdataadr(fd, wrld->adt);
3055         direct_link_animdata(fd, wrld->adt);
3056         
3057         for (a = 0; a < MAX_MTEX; a++) {
3058                 wrld->mtex[a] = newdataadr(fd, wrld->mtex[a]);
3059         }
3060         
3061         wrld->nodetree = newdataadr(fd, wrld->nodetree);
3062         if (wrld->nodetree) {
3063                 direct_link_id(fd, &wrld->nodetree->id);
3064                 direct_link_nodetree(fd, wrld->nodetree);
3065         }
3066         
3067         wrld->preview = direct_link_preview_image(fd, wrld->preview);
3068 }
3069
3070
3071 /* ************ READ VFONT ***************** */
3072
3073 static void lib_link_vfont(FileData *UNUSED(fd), Main *main)
3074 {
3075         VFont *vf;
3076         
3077         for (vf = main->vfont.first; vf; vf = vf->id.next) {
3078                 if (vf->id.flag & LIB_NEED_LINK) {
3079                         vf->id.flag -= LIB_NEED_LINK;
3080                 }
3081         }
3082 }
3083
3084 static void direct_link_vfont(FileData *fd, VFont *vf)
3085 {
3086         vf->data = NULL;
3087         vf->temp_pf = NULL;
3088         vf->packedfile = direct_link_packedfile(fd, vf->packedfile);
3089 }
3090
3091 /* ************ READ TEXT ****************** */
3092
3093 static void lib_link_text(FileData *UNUSED(fd), Main *main)
3094 {
3095         Text *text;
3096         
3097         for (text = main->text.first; text; text = text->id.next) {
3098                 if (text->id.flag & LIB_NEED_LINK) {
3099                         text->id.flag -= LIB_NEED_LINK;
3100                 }
3101         }
3102 }
3103
3104 static void direct_link_text(FileData *fd, Text *text)
3105 {
3106         TextLine *ln;
3107         
3108         text->name = newdataadr(fd, text->name);
3109         
3110         text->undo_pos = -1;
3111         text->undo_len = TXT_INIT_UNDO;
3112         text->undo_buf = MEM_mallocN(text->undo_len, "undo buf");
3113         
3114         text->compiled = NULL;
3115         
3116 #if 0
3117         if (text->flags & TXT_ISEXT) {
3118                 BKE_text_reload(text);
3119                 }
3120                 /* else { */
3121 #endif
3122         
3123         link_list(fd, &text->lines);
3124         
3125         text->curl = newdataadr(fd, text->curl);
3126         text->sell = newdataadr(fd, text->sell);
3127         
3128         for (ln = text->lines.first; ln; ln = ln->next) {
3129                 ln->line = newdataadr(fd, ln->line);
3130                 ln->format = NULL;
3131                 
3132                 if (ln->len != (int) strlen(ln->line)) {
3133                         printf("Error loading text, line lengths differ\n");
3134                         ln->len = strlen(ln->line);
3135                 }
3136         }
3137         
3138         text->flags = (text->flags) & ~TXT_ISEXT;
3139         
3140         text->id.us = 1;
3141 }
3142
3143 /* ************ READ IMAGE ***************** */
3144
3145 static void lib_link_image(FileData *fd, Main *main)
3146 {
3147         Image *ima;
3148         
3149         for (ima = main->image.first; ima; ima = ima->id.next) {
3150                 if (ima->id.flag & LIB_NEED_LINK) {
3151                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3152                         
3153                         ima->id.flag -= LIB_NEED_LINK;
3154                 }
3155         }
3156 }
3157
3158 static void link_ibuf_list(FileData *fd, ListBase *lb)
3159 {
3160         Link *ln, *prev;
3161         
3162         if (lb->first == NULL) return;
3163         
3164         lb->first = newimaadr(fd, lb->first);
3165         ln = lb->first;
3166         prev = NULL;
3167         while (ln) {
3168                 ln->next = newimaadr(fd, ln->next);
3169                 ln->prev = prev;
3170                 prev = ln;
3171                 ln = ln->next;
3172         }
3173         lb->last = prev;
3174 }
3175
3176 static void direct_link_image(FileData *fd, Image *ima)
3177 {
3178         /* for undo system, pointers could be restored */
3179         if (fd->imamap)
3180                 link_ibuf_list(fd, &ima->ibufs);
3181         else
3182                 ima->ibufs.first = ima->ibufs.last = NULL;
3183
3184         /* if not restored, we keep the binded opengl index */
3185         if (ima->ibufs.first == NULL) {
3186                 ima->bindcode = 0;
3187                 ima->tpageflag &= ~IMA_GLBIND_IS_DATA;
3188                 ima->gputexture = NULL;
3189         }
3190         
3191         ima->anim = NULL;
3192         ima->rr = NULL;
3193         ima->repbind = NULL;
3194         
3195         /* undo system, try to restore render buffers */
3196         if (fd->imamap) {
3197                 int a;
3198                 
3199                 for (a = 0; a < IMA_MAX_RENDER_SLOT; a++)
3200                         ima->renders[a] = newimaadr(fd, ima->renders[a]);
3201         }
3202         else {
3203                 memset(ima->renders, 0, sizeof(ima->renders));
3204                 ima->last_render_slot = ima->render_slot;
3205         }
3206         
3207         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
3208         ima->preview = direct_link_preview_image(fd, ima->preview);
3209         ima->ok = 1;
3210 }
3211
3212
3213 /* ************ READ CURVE ***************** */
3214
3215 static void lib_link_curve(FileData *fd, Main *main)
3216 {
3217         Curve *cu;
3218         int a;
3219         
3220         for (cu = main->curve.first; cu; cu = cu->id.next) {
3221                 if (cu->id.flag & LIB_NEED_LINK) {
3222                         if (cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
3223                         
3224                         for (a = 0; a < cu->totcol; a++) 
3225                                 cu->mat[a] = newlibadr_us(fd, cu->id.lib, cu->mat[a]);
3226                         
3227                         cu->bevobj = newlibadr(fd, cu->id.lib, cu->bevobj);
3228                         cu->taperobj = newlibadr(fd, cu->id.lib, cu->taperobj);
3229                         cu->textoncurve = newlibadr(fd, cu->id.lib, cu->textoncurve);
3230                         cu->vfont = newlibadr_us(fd, cu->id.lib, cu->vfont);
3231                         cu->vfontb = newlibadr_us(fd, cu->id.lib, cu->vfontb);
3232                         cu->vfonti = newlibadr_us(fd, cu->id.lib, cu->vfonti);