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