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