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