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