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