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