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