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