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