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