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