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