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