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