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