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